diff --git a/CONTENTS.md b/CONTENTS.md index 7e1ed90ac5..a174602698 100644 --- a/CONTENTS.md +++ b/CONTENTS.md @@ -1,6 +1,6 @@ # Mathematics manuscript collection -**721 manuscripts covering 373 result families.** +**722 manuscripts covering 374 result families.** [**Read the overview PDF**](overview.pdf). @@ -9162,6 +9162,22 @@ We prove a uniform interior $`C^{1,\alpha_d}`$ estimate for bounded infinity-har We give a deterministic algorithm for exactly counting the satisfying assignments of an arbitrary $`k`$-CNF formula. For every fixed $`k\ge2`$, on a formula with $`n`$ variables and $`m`$ clauses, our algorithm uses space polynomial in $`n`$ and $`m`$ and runs in time $`(n+m)^{O_k(1)}2^{n/(\log n)^{1/2+o(1)}}`$. Our algorithm refutes the Exponential Time Hypothesis (ETH), which postulates that deciding 3-SAT on $`n`$ variables requires $`2^{\Omega(n)}`$ time in the worst case. + + + + + +**379. Separation of VP and VNP over every field.** An explicit VNP family requires border arithmetic circuits of size at least $`\exp(\Omega((\log n)^{5/4}))`$ over every field. The same bound holds for the directed Hamiltonian cycle polynomial over every field and for the permanent outside characteristic two. ([Lean](lean/docs/379.md)) + + + + + + + [VP and VNP are different](preprints/VP-and-VNP-are-different-November-23-2026/paper.pdf) + +We prove that VP differs from VNP over every field. The lower bound holds for border circuits and is superpolynomial, of the form $`\exp(\Omega((\log n)^{5/4}))`$. In particular it applies to the permanent outside characteristic two. The proof trades two kinds of hardness against one another: the rigidity of tensor networks priced in Euclidean space, and the ability to diagonalize even against degenerating nonuniform circuits by replaying their computations inside a wire budget. + diff --git a/README.md b/README.md index cc5b0a03bc..144c757cb1 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ In our view, these manuscripts are best understood as a form of raw research dat ## Navigating the collection -The current catalogue contains 721 manuscripts organized into 373 families. A family groups related papers, which may include a principal result, companion arguments, consequences, or alternative proofs. Each family is classified by mathematical discipline. +The current catalogue contains 722 manuscripts organized into 374 families. A family groups related papers, which may include a principal result, companion arguments, consequences, or alternative proofs. Each family is classified by mathematical discipline. - Start with the [overview](overview.pdf) for descriptions of the families. - Use the [manuscript map](CONTENTS.md) to find individual papers and their supporting materials. diff --git a/history.md b/history.md index ce3d4ca015..2a8ff2e0b6 100644 --- a/history.md +++ b/history.md @@ -2,6 +2,12 @@ For any withdrawn papers, their README files explain the gap and link to the retracted manuscript. For any updated papers, previously published editions remain accessible through the version notes in their README. +## November 23, 2026 + +**New Results Added** + +- *VP and VNP are different*. This result was obtained on November 6, 2026. + ## October 29, 2026 **Formalization Fix** diff --git a/lean/ComparatorChallenges/VPVNP.json b/lean/ComparatorChallenges/VPVNP.json new file mode 100644 index 0000000000..b55ae410b7 --- /dev/null +++ b/lean/ComparatorChallenges/VPVNP.json @@ -0,0 +1,14 @@ +{ + "challenge_module": "ComparatorChallenges.VPVNP", + "solution_module": "OAI.Computability.VPVNP.ClassSeparation", + "theorem_names": [ + "OAI.Computability.VPVNP.Standalone.vp_ne_vnp" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ], + "enable_nanoda": false +} diff --git a/lean/ComparatorChallenges/VPVNP.lean b/lean/ComparatorChallenges/VPVNP.lean new file mode 100644 index 0000000000..617a845fc5 --- /dev/null +++ b/lean/ComparatorChallenges/VPVNP.lean @@ -0,0 +1,59 @@ +import Mathlib + +/-! # Exact VP and VNP over every field -/ + +namespace OAI + +namespace Computability.VPVNP.Valiant.Project + +open scoped Classical + +/-- A table of `s` binary gates computes `p`. Variables and scalars are free, and the +output and later gates may reuse any previously available value. -/ +def Computes {F σ : Type*} [Field F] (s : ℕ) (p : MvPolynomial σ F) : Prop := + ∃ v : Fin s → MvPolynomial σ F, + let available (k : ℕ) (x : MvPolynomial σ F) := + (∃ j : σ, MvPolynomial.X j = x) ∨ (∃ a : F, MvPolynomial.C a = x) ∨ + ∃ j : Fin s, j.val < k ∧ v j = x + available s p ∧ ∀ i : Fin s, ∃ a b, available i.val a ∧ available i.val b ∧ + (v i = a + b ∨ v i = a - b ∨ v i = a * b) + +/-- A polynomial bound uniform in all sufficiently large indices. -/ +def PolynomiallyBounded (f : ℕ → ℕ) : Prop := ∃ A d N : ℕ, ∀ n ≥ N, f n ≤ A * n ^ d + +/-- At each index a family has its own finite type of indeterminates. -/ +abbrev Family (F : Type*) [Field F] (σ : ℕ → Type) := (n : ℕ) → MvPolynomial (σ n) F + +variable {F : Type*} [Field F] {σ : ℕ → Type} [∀ n, Fintype (σ n)] + +/-- Arity and total degree grow at most polynomially with the index. -/ +def PFamily (p : Family F σ) : Prop := + PolynomiallyBounded (fun n => Fintype.card (σ n)) ∧ + PolynomiallyBounded (fun n => (p n).totalDegree) + +/-- VP consists of polynomial families computed by polynomial-size exact circuits. -/ +def IsVP (p : Family F σ) : Prop := + PFamily p ∧ ∃ s : ℕ → ℕ, PolynomiallyBounded s ∧ ∀ n, Computes (s n) (p n) + +/-- A VNP family sums a VP verifier over all Boolean assignments to its witness variables. -/ +def IsVNP (p : Family F σ) : Prop := + PFamily p ∧ ∃ (W : ℕ → Type) (inst : ∀ n, Fintype (W n)) (g : Family F (fun n => σ n ⊕ W n)), + PolynomiallyBounded (fun n => @Fintype.card _ (inst n)) ∧ IsVP g ∧ ∀ n, + p n = ∑ y : W n → Bool, MvPolynomial.eval₂Hom MvPolynomial.C + (Sum.elim MvPolynomial.X (fun i => MvPolynomial.C (if y i then 1 else 0))) (g n) + +end Computability.VPVNP.Valiant.Project + +namespace Computability.VPVNP.Standalone + +universe u + +/-- The two nonuniform classes differ over each field. -/ +theorem vp_ne_vnp (F : Type u) [Field F] : + (Valiant.Project.IsVP : Valiant.Project.Family F (fun n => Fin n × Bool) → Prop) ≠ + Valiant.Project.IsVNP := by + sorry + +end Computability.VPVNP.Standalone + +end OAI diff --git a/lean/OAI/Computability/VPVNP/AdviceBitLookup.lean b/lean/OAI/Computability/VPVNP/AdviceBitLookup.lean new file mode 100644 index 0000000000..53fe0c1568 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AdviceBitLookup.lean @@ -0,0 +1,131 @@ +import OAI.Computability.VPVNP.RAMTapeRoutinePorts + +/-! # Reading a bit at a unary address in circuit advice + +The instruction stream starts with one `true` per skipped value and a terminating +`false`. The routine saves the skipped prefix, copies the addressed bit to the +result stack, and restores the valuation stack in its original order. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace RAMTape.AdviceBitLookup + +/-- The four stacks used to consume a unary address, inspect the valuation, save its skipped +prefix, and return the selected bit. -/ +inductive Port where + | stream | values | scratch | result + deriving DecidableEq + +instance : Fintype Port := + ⟨{.stream, .values, .scratch, .result}, fun p => by cases p <;> simp⟩ + +/-- Finite control for skipping valuation bits, reading the addressed bit, and restoring the +skipped prefix in its original order. -/ +inductive State where + | index | skip | save (b : Bool) | read | replace (b : Bool) | write (b : Bool) + | restore | put (b : Bool) | done | reject + deriving DecidableEq, Fintype + +/-- Fixed finite control. A missing delimiter or an out-of-bounds address rejects. -/ +def code : StackCode Port State + | .index => .pop .stream fun b => b.elim .reject fun v => if v then .skip else .read + | .skip => .pop .values fun b => b.elim .reject .save + | .save b => .push .scratch b .index + | .read => .pop .values fun b => b.elim .reject .replace + | .replace b => .push .values b (.write b) + | .write b => .push .result b .restore + | .restore => .pop .scratch fun b => b.elim .done .put + | .put b => .push .values b .restore + | .done => .halt true + | .reject => .halt false + +/-- Assign the supplied instruction stream, valuation, saved prefix, and output to their +respective lookup stacks. -/ +def store (stream values scratch result : List Bool) : Stacks Port + | .stream => stream + | .values => values + | .scratch => scratch + | .result => result + +private theorem update_store (a v s r xs : List Bool) (p : Port) : + Function.update (store a v s r) p xs = match p with + | .stream => store xs v s r + | .values => store a xs s r + | .scratch => store a v xs r + | .result => store a v s xs := by + funext q + cases p <;> cases q <;> simp [store, Function.update] + +local macro "lookup_step" : tactic => `(tactic| + (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_) + <;> simp only [update_store, store, List.head?_cons, List.tail_cons, + List.head?_nil, List.tail_nil, Option.elim_some, Option.elim_none, ite_true, ite_false, + Bool.false_eq_true, Bool.true_eq_false, not_false_eq_true]) + +private theorem scan (pre : List Bool) (bit : Bool) (rest stream saved result : List Bool) : + StackRuns code (3 * pre.length + 4) .index + (store (List.replicate pre.length true ++ false :: stream) (pre ++ bit :: rest) saved result) + .restore (store stream (bit :: rest) (pre.reverse ++ saved) (bit :: result)) := by + induction pre generalizing saved with + | nil => + simp only [List.length_nil, Nat.mul_zero, Nat.zero_add, List.replicate_zero, List.nil_append, + List.reverse_nil] + lookup_step; lookup_step; lookup_step; lookup_step + exact .nil .. + | cons a pre ih => + simp only [List.length_cons, Nat.mul_succ, List.replicate_succ, List.cons_append, + List.reverse_cons, List.append_assoc] + lookup_step; lookup_step; lookup_step + exact ih (a :: saved) + +private theorem restore (stream values saved result : List Bool) : + StackRuns code (2 * saved.length + 1) .restore (store stream values saved result) + .done (store stream (saved.reverse ++ values) [] result) := by + induction saved generalizing values with + | nil => + lookup_step + exact .nil .. + | cons a saved ih => + simp only [List.length_cons, Nat.mul_succ, List.reverse_cons, List.append_assoc, + List.singleton_append] + lookup_step; lookup_step + exact ih (a :: values) + +/-- A lookup takes exactly five instructions per skipped bit and five fixed +instructions. Both the remaining advice and the old result tail are preserved. -/ +theorem lookup_runs (values streamTail resultTail : List Bool) (k : ℕ) (hk : k < values.length) : + StackRuns code (5 * k + 5) .index + (store (List.replicate k true ++ false :: streamTail) values [] resultTail) + .done (store streamTail values [] (values[k] :: resultTail)) := by + have length_pre : (values.take k).length = k := by simp [hk.le] + have split : values.take k ++ values[k] :: values.drop (k + 1) = values := by + rw [← List.drop_eq_getElem_cons hk, List.take_append_drop] + have fwd := scan (values.take k) values[k] (values.drop (k + 1)) streamTail [] resultTail + have rev := restore streamTail (values[k] :: values.drop (k + 1)) (values.take k).reverse + (values[k] :: resultTail) + simp only [length_pre, split, List.append_nil] at fwd + simp only [List.length_reverse, List.reverse_reverse, length_pre, split] at rev + simpa only [show 3 * k + 4 + (2 * k + 1) = 5 * k + 5 by omega] using fwd.trans rev + +/-- A normal lookup returns to its caller. The malformed-input halt still rejects. -/ +def routine : FiniteRoutine Port := FiniteRoutine.ofStackCode code id .index (fun q => decide (q = .done)) + +theorem routine_runs (values streamTail resultTail : List Bool) (k : ℕ) (hk : k < values.length) : + routine.Runs (5 * k + 5) + (store (List.replicate k true ++ false :: streamTail) values [] resultTail) + (store streamTail values [] (values[k] :: resultTail)) := by + apply FiniteRoutine.runs_ofStackCode_framed Function.injective_id rfl rfl + (fun q h => by simp only [decide_eq_true_eq] at h; subst q; rfl) (lookup_runs ..) + · exact fun _ => rfl + · exact fun _ => rfl + · intro q h + exact (h q rfl).elim + +end RAMTape.AdviceBitLookup + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AdviceCircuitCompiler.lean b/lean/OAI/Computability/VPVNP/AdviceCircuitCompiler.lean new file mode 100644 index 0000000000..1e610812ec --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AdviceCircuitCompiler.lean @@ -0,0 +1,153 @@ +import OAI.Computability.VPVNP.AdviceCircuitProgram +import OAI.Computability.VPVNP.BooleanTranscript + +/-! +# Translating coefficient verifiers to bit-stack interpreter advice + +The initial valuation stack holds zero, one, the query word, and the candidate +witness, in that order. A gate pushes its result, so a reference to an earlier +gate is addressed from the newest gate backwards. Two final NOT instructions +copy the designated output to the top, including for circuits with no gates. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AdviceCircuit + +variable {u w n : ℕ} + +/-- Initial valuation in stack order, with false and true followed by the query bits and the +candidate witness bits. -/ +def inputs (x : Fin u → Bool) (bits : Fin w → Bool) : List Bool := + false :: true :: (List.ofFn x ++ List.ofFn bits) + +private def valuation (x : Fin u → Bool) (bits : Fin w → Bool) (gates : Fin n → Bool) : + List Bool := (List.ofFn gates).reverse ++ inputs x bits + +/-- Address in the valuation stack after `n` instructions. -/ +def address : Ref Bool (Fin u ⊕ Fin w) n → ℕ + | .const b => n + b.toNat + | .var (.inl i) => n + 2 + i.val + | .var (.inr j) => n + 2 + u + j.val + | .gate i => n - 1 - i.val + +private theorem address_lt (r : Ref Bool (Fin u ⊕ Fin w) n) : + address r < n + 2 + u + w := by + cases r with + | var i => cases i with + | inl i => dsimp [address]; have := i.isLt; omega + | inr i => dsimp [address]; have := i.isLt; omega + | const b => cases b <;> simp [address] <;> omega + | gate i => dsimp [address]; omega + +private theorem read_address (x : Fin u → Bool) (bits : Fin w → Bool) (g : Fin n → Bool) + (r : Ref Bool (Fin u ⊕ Fin w) n) : + (valuation x bits g)[address r]? = some (r.read id (Sum.elim x bits) g) := by + cases r with + | const b => + cases b <;> simp [valuation, address, inputs, Ref.read] + | var z => + cases z with + | inl i => + simp only [valuation, address, Ref.read, Sum.elim_inl] + rw [show n + 2 + i.val = n + (i.val + 1 + 1) by omega, + List.getElem?_append_right (by simp)] + simp [inputs, List.getElem?_append, i.isLt] + | inr j => + simp only [valuation, address, Ref.read, Sum.elim_inr] + rw [show n + 2 + u + j.val = n + (u + j.val + 1 + 1) by omega, + List.getElem?_append_right (by simp)] + simp [inputs] + | gate i => + have hi : n-1-i.val < n := by have := i.isLt; omega + have hr : n-1-(n-1-i.val) = i.val := by have := i.isLt; omega + simp [valuation, address, List.getElem?_append, hi, hr, Ref.read] + +private def emit : BooleanTranscript.Gate (Fin u ⊕ Fin w) n → Instruction + | .not a => .not (address a) + | .and a b => .and (address a) (address b) + +private theorem emit_value (x : Fin u → Bool) (bits : Fin w → Bool) (g : Fin n → Bool) + (a : BooleanTranscript.Gate (Fin u ⊕ Fin w) n) : + (emit a).value (valuation x bits g) = some (a.eval (Sum.elim x bits) g) := by + cases a <;> simp [emit, Instruction.value, read_address, BooleanTranscript.Gate.eval] + +/-- Compile the gates of a Boolean transcript program into unary-address instructions in gate +order. -/ +def instructions : {n : ℕ} → BooleanTranscript.Program (Fin u ⊕ Fin w) n → List Instruction + | _, .nil => [] + | _, .snoc p g => instructions p ++ [emit g] + +private theorem valuation_snoc (x : Fin u → Bool) (bits : Fin w → Bool) (g : Fin n → Bool) (b : Bool) : + valuation x bits (Fin.snoc g b) = b :: valuation x bits g := by + simp only [valuation, List.ofFn_succ', Fin.snoc_castSucc, Fin.snoc_last, List.concat_eq_append, + List.reverse_append, List.reverse_singleton, List.cons_append, List.nil_append] + +theorem instructions_run (p : BooleanTranscript.Program (Fin u ⊕ Fin w) n) + (x : Fin u → Bool) (bits : Fin w → Bool) : + run (instructions p) (inputs x bits) = some (valuation x bits (p.run (Sum.elim x bits))) := by + induction p with + | nil => simp [instructions, valuation] + | snoc p g ih => + simp only [instructions, run_append, ih, Option.bind_some, BooleanTranscript.Program.run, + valuation_snoc] + exact run_cons (emit_value x bits _ g) + +/-- Compile all gates and copy the designated output to the top. -/ +def compile (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) n) : List Instruction := + instructions c.program ++ [.not (address c.output), .not 0] + +theorem compile_run (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) n) + (x : Fin u → Bool) (bits : Fin w → Bool) : + ∃ tail, run (compile c) (inputs x bits) = some (c.eval (Sum.elim x bits) :: tail) := by + let g := c.program.run (Sum.elim x bits) + let b := c.eval (Sum.elim x bits) + have first : (Instruction.not (address c.output)).value (valuation x bits g) = some (!b) := by + simp [Instruction.value, read_address, b, g, BooleanTranscript.Circuit.eval] + have second : (Instruction.not 0).value ((!b) :: valuation x bits g) = some b := by simp [Instruction.value] + refine ⟨(!b) :: valuation x bits g, ?_⟩ + rw [compile, run_append, instructions_run, Option.bind_some, run_cons first, run_cons second, run_nil] + +@[simp] theorem instructions_length (p : BooleanTranscript.Program (Fin u ⊕ Fin w) n) : + (instructions p).length = n := by induction p <;> simp_all [instructions] + +@[simp] theorem compile_length (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) n) : + (compile c).length = n + 2 := by simp [compile] + +private theorem emit_length (a : BooleanTranscript.Gate (Fin u ⊕ Fin w) n) : + (emit a).encode.length ≤ 2*(n+u+w+2)+3 := by + cases a with + | not r => have := address_lt r; simp [emit, Instruction.encode, unary]; omega + | and r s => have := address_lt r; have := address_lt s; simp [emit, Instruction.encode, unary]; omega + +private theorem instructions_size (p : BooleanTranscript.Program (Fin u ⊕ Fin w) n) : + (encode (instructions p)).length ≤ n*(2*(n+u+w+2)+3) := by + induction p with + | nil => simp [encode, instructions] + | @snoc n p g ih => + have hs := emit_length g + have hm := Nat.mul_le_mul_left n (show 2*(n+u+w+2)+3 ≤ 2*(n+1+u+w+2)+3 by omega) + simp only [instructions, encode, List.flatMap_append, List.flatMap_cons, List.flatMap_nil, + List.append_nil, List.length_append] + change (encode (instructions p)).length + (emit g).encode.length ≤ (n+1)*(2*(n+1+u+w+2)+3) + rw [Nat.succ_mul] + omega + +/-- Unary addresses make the bit length quadratic in the combined input and gate bound. -/ +theorem compile_size (c : BooleanTranscript.Circuit (Fin u ⊕ Fin w) n) : + (encode (compile c)).length ≤ (n+2)*(2*(n+u+w+2)+3) := by + have hg := instructions_size c.program + have ho := address_lt c.output + simp only [compile, encode, List.flatMap_append, List.flatMap_cons, List.flatMap_nil, + List.append_nil, List.length_append] + change (encode (instructions c.program)).length + _ ≤ _ + simp [Instruction.encode, unary, Nat.add_mul] + omega + +end AdviceCircuit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AdviceCircuitProgram.lean b/lean/OAI/Computability/VPVNP/AdviceCircuitProgram.lean new file mode 100644 index 0000000000..f68aba7d8f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AdviceCircuitProgram.lean @@ -0,0 +1,79 @@ +import Mathlib.Data.List.Defs + +/-! +# Boolean circuit instructions for the coefficient-query interpreter + +Each instruction reads unary addresses counted from the top of the valuation stack. +The newly computed gate value is prepended. A variable or a constant can be read +from the initial valuation stack, and all earlier gate values remain accessible. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AdviceCircuit + +/-- An advice instruction that computes NOT or AND from addresses counted from the top of the +current valuation stack. -/ +inductive Instruction where + | not (addr : ℕ) + | and (left right : ℕ) + deriving DecidableEq + +/-- Encode an address as one true bit per valuation entry to skip followed by a false +terminator. -/ +def unary (a : ℕ) : List Bool := List.replicate a true ++ [false] + +/-- Encode a gate with a false tag for NOT or a true tag for AND, followed by one unary address +per operand. -/ +def Instruction.encode : Instruction → List Bool + | .not a => false :: unary a + | .and a b => true :: (unary a ++ unary b) + +/-- Concatenate the encodings of all instructions in execution order to form the circuit advice +stream. -/ +def encode (p : List Instruction) : List Bool := p.flatMap Instruction.encode + +/-- Evaluate one gate against a valuation list, returning none if any operand address falls +outside the list. -/ +def Instruction.value (v : List Bool) : Instruction → Option Bool + | .not a => v[a]?.map (!·) + | .and a b => do return (← v[a]?) && (← v[b]?) + +/-- Execute the instruction list, prepending each new gate value to the valuation used by the +remaining instructions. -/ +def run : List Instruction → List Bool → Option (List Bool) + | [], v => some v + | a :: p, v => do run p ((← a.value v) :: v) + +@[simp] theorem run_nil (v : List Bool) : run [] v = some v := rfl + +theorem run_cons {a : Instruction} {p : List Instruction} {v : List Bool} {b : Bool} + (h : a.value v = some b) : run (a :: p) v = run p (b :: v) := by simp [run, h] + +theorem run_append (p q : List Instruction) (v : List Bool) : + run (p ++ q) v = (run p v).bind (run q) := by + induction p generalizing v with + | nil => rfl + | cons a p ih => + cases h : a.value v <;> simp [run, h, ih] + +theorem length_run {p : List Instruction} {v u : List Bool} (hu : run p v = some u) : + u.length = p.length + v.length := by + induction p generalizing v with + | nil => simpa [run] using congrArg (Option.map List.length) hu.symm + | cons a p ih => + cases h : a.value v with + | none => simp [run, h] at hu + | some b => + rw [run_cons h] at hu + have hh := ih hu + simp only [List.length_cons] at * + omega + +end AdviceCircuit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AdviceCountAdapter.lean b/lean/OAI/Computability/VPVNP/AdviceCountAdapter.lean new file mode 100644 index 0000000000..e7f7d0bae3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AdviceCountAdapter.lean @@ -0,0 +1,154 @@ +import OAI.Computability.VPVNP.AdviceInterpreter +import OAI.Computability.VPVNP.AdviceCircuitCompiler +import OAI.Computability.VPVNP.AdviceReturnBit +import OAI.Computability.VPVNP.RAMTapeSuccessorRecord +import OAI.Computability.VPVNP.UniversalCountStack + +/-! # Using the circuit-advice interpreter as a counting verifier + +Each invocation copies the persistent advice, query, and current witness into +the interpreter's work stacks. After evaluation it transfers just the designated +output to the enumeration flag and empties the valuation stack. This restores +the state required for the next witness without copying the count itself. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace RAMTape.AdviceCountAdapter + +open UniversalCountStack AdviceCircuit + +/-- Ports for the persistent query and advice, the circuit interpreter’s work stacks, and the +scratch stack used to copy its inputs. -/ +inductive AuxPort where + | query | advice | vmStream | vmValues | vmScratch | vmResult | copyTmp + deriving DecidableEq + +instance : Fintype AuxPort := derive_fintype% _ + +/-- The witness counter’s ports extended by the query, advice, and working stacks for the +Boolean circuit verifier. -/ +abbrev Port := UniversalCountStack.Port AuxPort + +private def workspace (query advice stream values : List Bool) : Stacks AuxPort + | .query => query + | .advice => advice + | .vmStream => stream + | .vmValues => values + | _ => [] + +/-- Persistent strings with every private work stack empty. -/ +def inputs (query advice : List Bool) : Stacks AuxPort := workspace query advice [] [] + +private def vmPort : AdviceBitLookup.Port → Port + | .stream => .aux .vmStream + | .values => .aux .vmValues + | .scratch => .aux .vmScratch + | .result => .aux .vmResult + +private theorem vmPort_injective : Function.Injective vmPort := by + intro x y h + cases x <;> cases y <;> simp_all [vmPort] + +private def copy (src dst : Port) : FiniteRoutine Port := + SuccessorFields.prependCopy src dst (.aux .copyTmp) + +private def pushValue (bit : Bool) : FiniteRoutine Port := + FiniteRoutine.ofRoutine (Routine.push (.aux .vmValues) bit) + +private def prepare : FiniteRoutine Port := + ((((copy (.aux .advice) (.aux .vmStream)).followedBy (copy .choice (.aux .vmValues))).followedBy + (copy (.aux .query) (.aux .vmValues))).followedBy (pushValue true)).followedBy (pushValue false) + +/-- The verifier called by `UniversalCountStack.enumerate`. -/ +def verify : FiniteRoutine Port := + (prepare.followedBy (AdviceInterpreter.routine.onPorts vmPort)).followedBy + (AdviceReturnBit.takeTopAndClear (.aux .vmValues) .flag) + +private abbrev bankState (q a c t x v flag : List Bool) : Stacks Port := + bank (workspace q a x v) c t [] flag + +private theorem update_stream (q a c t x v f xs : List Bool) : + Function.update (bankState q a c t x v f) (.aux .vmStream) xs = bankState q a c t xs v f := by + funext p + cases p with + | aux j => cases j <;> simp [bankState, bank, workspace, Function.update] + | _ => simp [bankState, bank, Function.update] + +private theorem update_values (q a c t x v f xs : List Bool) : + Function.update (bankState q a c t x v f) (.aux .vmValues) xs = bankState q a c t x xs f := by + funext p + cases p with + | aux j => cases j <;> simp [bankState, bank, workspace, Function.update] + | _ => simp [bankState, bank, Function.update] + +private theorem update_flag (q a c t x v f xs : List Bool) : + Function.update (bankState q a c t x v f) .flag xs = bankState q a c t x v xs := by + funext p + cases p <;> simp [bankState, bank, Function.update] + +private theorem prepare_runs (q a c t : List Bool) : + prepare.Runs (5 * (a.length + c.length + q.length) + 8) (bankState q a c t [] [] []) + (bankState q a c t a (false :: true :: (q ++ c)) []) := by + have ha := SuccessorFields.prependCopy_runs (K := Port) (.aux .advice) (.aux .vmStream) + (.aux .copyTmp) (by decide) (by decide) (by decide) (bankState q a c t [] [] []) rfl + have hc := SuccessorFields.prependCopy_runs (K := Port) .choice (.aux .vmValues) + (.aux .copyTmp) (by decide) (by decide) (by decide) (bankState q a c t a [] []) rfl + have hq := SuccessorFields.prependCopy_runs (K := Port) (.aux .query) (.aux .vmValues) + (.aux .copyTmp) (by decide) (by decide) (by decide) (bankState q a c t a c []) rfl + have push (v : List Bool) (b : Bool) : (pushValue b).Runs 1 (bankState q a c t a v []) + (bankState q a c t a (b :: v) []) := by + have step := Routine.runs_push (.aux .vmValues : Port) b (bankState q a c t a v []) + rw [update_values] at step + exact step + rw [update_stream] at ha + rw [update_values] at hc hq + change (copy (.aux .advice) (.aux .vmStream)).Runs (5 * a.length + 2) _ + (bankState q a c t (a ++ []) [] []) at ha + change (copy .choice (.aux .vmValues)).Runs (5 * c.length + 2) _ + (bankState q a c t a (c ++ []) []) at hc + change (copy (.aux .query) (.aux .vmValues)).Runs (5 * q.length + 2) _ + (bankState q a c t a (q ++ c) []) at hq + rw [List.append_nil] at ha hc + have result := (((ha.followedBy hc).followedBy hq).followedBy (push _ true)).followedBy (push _ false) + rw [show 5 * (a.length + c.length + q.length) + 8 = + (5*a.length + 2) + (5*c.length + 2) + (5*q.length + 2) + 1 + 1 by omega] + exact result + +/-- A successful advice program returns its first valuation bit to the flag, +restoring the complete persistent input and both counter registers. -/ +theorem verify_runs (p : List Instruction) (query choice total : List Bool) + {ok : Bool} {tail : List Bool} + (hu : run p (false :: true :: (query ++ choice)) = some (ok :: tail)) : + ∃ ticks ≤ 32 * ((encode p).length + p.length + query.length + choice.length + 1), + verify.Runs ticks (bank (inputs query (encode p)) choice total [] []) + (bank (inputs query (encode p)) choice total [] [ok]) := by + let a := encode p + let v := false :: true :: (query ++ choice) + obtain ⟨u, htime, hv⟩ := AdviceInterpreter.routine_runs p v (ok :: tail) hu + have hvm : (AdviceInterpreter.routine.onPorts vmPort).Runs u + (bankState query a choice total a v []) (bankState query a choice total [] (ok :: tail) []) := by + apply FiniteRoutine.runs_onPorts_framed _ vmPort_injective hv + · intro j; cases j <;> rfl + · intro j; cases j <;> rfl + · intro j hj + cases j with + | aux i => cases i <;> first | rfl | exact (hj .stream rfl).elim | exact (hj .values rfl).elim + | _ => rfl + have hout := AdviceReturnBit.takeTopAndClear_runs (K := Port) (src := .aux .vmValues) + (dst := .flag) (by decide) (bankState query a choice total [] (ok :: tail) []) ok tail rfl + rw [update_values, update_flag] at hout + have hh := ((prepare_runs query a choice total).followedBy hvm).followedBy hout + refine ⟨_, ?_, hh⟩ + have hlen := AdviceCircuit.length_run hu + simp only [List.length_cons, List.length_append] at hlen + dsimp only [a] + omega + +end RAMTape.AdviceCountAdapter + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AdviceInterpreter.lean b/lean/OAI/Computability/VPVNP/AdviceInterpreter.lean new file mode 100644 index 0000000000..6a23928127 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AdviceInterpreter.lean @@ -0,0 +1,153 @@ +import OAI.Computability.VPVNP.AdviceBitLookup +import OAI.Computability.VPVNP.AdviceCircuitProgram +import OAI.Computability.VPVNP.StructuredStackLoop + +/-! +# A fixed bit-stack interpreter for Boolean circuit advice + +The stream contains a gate tag followed by one or two unary operand addresses. +Each lookup preserves the valuation stack. The gate body removes its operand +bits from scratch and prepends its result to the valuation stack. The control +and the four stacks are fixed independently of the circuit, input and gate count. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace RAMTape.AdviceInterpreter + +open AdviceCircuit +open AdviceBitLookup (Port store) + +private def reject : Routine Port Unit := Routine.halt false +private def put (v : Bool) : Routine Port Unit := Routine.push .values v + +private def unaryBody := Routine.popCase .result reject (put true) (put false) +private def second (v : Bool) := Routine.popCase .result reject (put false) (put v) +private def binaryBody := Routine.popCase .result reject (second false) (second true) + +private def unaryGate : FiniteRoutine Port := + AdviceBitLookup.routine.followedBy (.ofRoutine unaryBody) + +private def binaryGate : FiniteRoutine Port := + (AdviceBitLookup.routine.followedBy AdviceBitLookup.routine).followedBy (.ofRoutine binaryBody) + +/-- Executable instruction loop. An exhausted advice stream returns to the caller. -/ +def routine : FiniteRoutine Port := + .ofRoutine (Routine.popLoop .stream (fun _ ↦ true) unaryGate.body binaryGate.body) + +private theorem update_stream (a v s r t : List Bool) : + Function.update (store a v s r) .stream t = store t v s r := by funext i; cases i <;> simp [store] + +private theorem update_values (a v s r t : List Bool) : + Function.update (store a v s r) .values t = store a t s r := by funext i; cases i <;> simp [store] + +private theorem update_result (a v s r t : List Bool) : + Function.update (store a v s r) .result t = store a v s t := by funext i; cases i <;> simp [store] + +private theorem put_runs (b : Bool) (s v : List Bool) : + (put b).Runs 1 (store s v [] []) (store s (b :: v) [] []) := by + simpa only [put, update_values, store] using Routine.runs_push Port.values b (store s v [] []) + +private theorem unary_runs (b : Bool) (s v : List Bool) : + unaryBody.Runs 2 (store s v [] [b]) (store s ((!b) :: v) [] []) := by + cases b + · apply Routine.runs_popCase_false (s := store s v [] [false]) (t := 1) .result reject + (put true) (put false) rfl + rw [update_result]; exact put_runs _ _ _ + · apply Routine.runs_popCase_true (s := store s v [] [true]) (t := 1) .result reject + (put true) (put false) rfl + rw [update_result]; exact put_runs _ _ _ + +private theorem second_runs (a b : Bool) (s v : List Bool) : + (second b).Runs 2 (store s v [] [a]) (store s ((a && b) :: v) [] []) := by + cases a + · apply Routine.runs_popCase_false (s := store s v [] [false]) (t := 1) .result reject + (put false) (put b) rfl + rw [update_result]; exact put_runs _ _ _ + · apply Routine.runs_popCase_true (s := store s v [] [true]) (t := 1) .result reject + (put false) (put b) rfl + rw [update_result]; exact put_runs _ _ _ + +private theorem binary_runs (a b : Bool) (s v : List Bool) : + binaryBody.Runs 3 (store s v [] [b,a]) (store s ((a && b) :: v) [] []) := by + cases b + · apply Routine.runs_popCase_false (s := store s v [] [false, a]) (t := 2) .result reject + (second false) (second true) rfl + rw [update_result]; exact second_runs _ _ _ _ + · apply Routine.runs_popCase_true (s := store s v [] [true, a]) (t := 2) .result reject + (second false) (second true) rfl + rw [update_result]; exact second_runs _ _ _ _ + +private theorem unaryGate_runs (a : ℕ) (s v : List Bool) (ha : a < v.length) : + unaryGate.Runs (5*a+7) (store (unary a ++ s) v [] []) (store s ((!v[a]) :: v) [] []) := by + simpa only [unaryGate, unary, List.append_assoc, List.singleton_append, Nat.add_assoc] using + FiniteRoutine.Runs.followedBy (AdviceBitLookup.routine_runs v s [] a ha) + (show (FiniteRoutine.ofRoutine unaryBody).Runs 2 _ _ from unary_runs v[a] s v) + +private theorem binaryGate_runs (a b : ℕ) (s v : List Bool) (ha : a < v.length) (hb : b < v.length) : + binaryGate.Runs (5*a+5+(5*b+5)+3) (store (unary a ++ unary b ++ s) v [] []) + (store s ((v[a] && v[b]) :: v) [] []) := by + simpa only [binaryGate, unary, List.append_assoc, List.singleton_append, List.cons_append, List.nil_append] using + FiniteRoutine.Runs.followedBy + (FiniteRoutine.Runs.followedBy (AdviceBitLookup.routine_runs v (unary b ++ s) [] a ha) + (by simpa only [unary, List.append_assoc, List.singleton_append] using + AdviceBitLookup.routine_runs v s [v[a]] b hb)) + (show (FiniteRoutine.ofRoutine binaryBody).Runs 3 _ _ from binary_runs v[a] v[b] s v) + +/-- A successful abstract execution is implemented by at most sixteen stack +instructions per advice bit, including the final end-of-stream test. -/ +theorem routine_runs (p : List Instruction) (v u : List Bool) (hu : run p v = some u) : + ∃ t ≤ 16 * ((encode p).length + 1), routine.Runs t (store (encode p) v [] []) (store [] u [] []) := by + induction p generalizing v with + | nil => + obtain rfl : v = u := Option.some.inj hu + refine ⟨1, by simp [encode], ?_⟩ + change (Routine.popLoop Port.stream (fun _ ↦ true) unaryGate.body binaryGate.body).Runs + 1 (store [] v [] []) (store [] v [] []) + exact Routine.Runs.popLoop_empty (s := store [] v [] []) Port.stream (fun _ ↦ true) + unaryGate.body binaryGate.body rfl + | cons i p ih => + cases i with + | not a => + by_cases ha : a < v.length + · have val : (Instruction.not a).value v = some (!v[a]) := by + simp [Instruction.value, List.getElem?_eq_getElem ha] + rw [run_cons val] at hu + obtain ⟨t, ht, hh⟩ := ih _ hu + refine ⟨1+(5*a+7)+t, ?_, ?_⟩ + · simp only [encode, List.flatMap_cons, Instruction.encode, unary, List.length_append, + List.length_cons, List.length_nil, List.length_replicate] at * + omega + · refine Routine.Runs.popLoop_false_continue (s := store (encode (.not a :: p)) v [] []) + (tail := unary a ++ encode p) .stream (fun _ ↦ true) unaryGate.body binaryGate.body + rfl rfl ?_ hh + rw [update_stream] + exact unaryGate_runs a (encode p) v ha + · simp [run, Instruction.value, List.getElem?_eq_none_iff.mpr (by omega : v.length ≤ a)] at hu + | and a b => + by_cases ha : a < v.length + · by_cases hb : b < v.length + · have val : (Instruction.and a b).value v = some (v[a] && v[b]) := by + simp [Instruction.value, List.getElem?_eq_getElem ha, List.getElem?_eq_getElem hb] + rw [run_cons val] at hu + obtain ⟨t, ht, hh⟩ := ih _ hu + refine ⟨1+(5*a+5+(5*b+5)+3)+t, ?_, ?_⟩ + · simp only [encode, List.flatMap_cons, Instruction.encode, unary, List.length_append, + List.length_cons, List.length_nil, List.length_replicate] at * + omega + · refine Routine.Runs.popLoop_true_continue (s := store (encode (.and a b :: p)) v [] []) + (tail := (unary a ++ unary b) ++ encode p) .stream (fun _ ↦ true) unaryGate.body binaryGate.body + rfl rfl ?_ hh + rw [update_stream] + exact binaryGate_runs a b (encode p) v ha hb + · simp [run, Instruction.value, List.getElem?_eq_getElem ha, + List.getElem?_eq_none_iff.mpr (by omega : v.length ≤ b)] at hu + · simp [run, Instruction.value, List.getElem?_eq_none_iff.mpr (by omega : v.length ≤ a)] at hu + +end RAMTape.AdviceInterpreter + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AdviceReturnBit.lean b/lean/OAI/Computability/VPVNP/AdviceReturnBit.lean new file mode 100644 index 0000000000..cefb49a511 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AdviceReturnBit.lean @@ -0,0 +1,66 @@ +import OAI.Computability.VPVNP.RAMTapeISAPorts + +/-! +# Returning the result bit of a circuit evaluation + +The interpreter leaves the last gate value on top of the stack of intermediate +values. The caller needs that one bit on its result stack and the valuation +stack empty for the next evaluation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace RAMTape.AdviceReturnBit + +private inductive Control where + | read | drain (bit : Bool) | write (bit : Bool) | reject + deriving Fintype + +variable {K : Type} + +private def body (src dst : K) : Routine K Control where + entry := .read + code + | .read => .pop src fun b => some (b.elim .reject .drain) + | .drain bit => .pop src fun b => some (b.elim (.write bit) fun _ => .drain bit) + | .write bit => .push dst bit none + | .reject => .halt false + +/-- Save the head bit, drain the source stack and prepend that bit to the +destination. An empty source rejects. -/ +def takeTopAndClear (src dst : K) : FiniteRoutine K := .ofRoutine (body src dst) + +variable [DecidableEq K] {src dst : K} + +private theorem drain_runs (hne : src ≠ dst) (s : Stacks K) (bit : Bool) (tail : List Bool) : + StackRuns (body src dst).standalone (tail.length + 2) (some (.drain bit)) + (Function.update s src tail) none (Function.update (Function.update s src []) dst (bit :: s dst)) := by + induction tail with + | nil => + apply StackRuns.cons (.pop rfl) + simp only [Function.update_self, List.head?_nil, List.tail_nil, Option.elim_none, Function.update_idem] + simpa only [List.length_nil, Function.update_of_ne hne.symm] using + (StackRuns.cons (StackStep.push (code := (body src dst).standalone) (s := Function.update s src []) + (q := some (.write bit)) rfl) (.nil ..)) + | cons b tail ih => + apply StackRuns.cons (.pop rfl) + simpa only [List.length_cons, Function.update_self, List.head?_cons, List.tail_cons, Option.elim_some, + Function.update_idem] using ih + +/-- Each discarded bit costs one pop. The other three steps read the answer, +test the empty source and push the answer on the destination. -/ +theorem takeTopAndClear_runs (hne : src ≠ dst) (s : Stacks K) (bit : Bool) (tail : List Bool) + (hsrc : s src = bit :: tail) : + (takeTopAndClear src dst).Runs (tail.length + 3) s + (Function.update (Function.update s src []) dst (bit :: s dst)) := by + change StackRuns (body src dst).standalone _ (some .read) s none _ + apply StackRuns.cons (.pop rfl) + simpa only [hsrc, List.head?_cons, List.tail_cons, Option.elim_some] using drain_runs hne s bit tail + +end RAMTape.AdviceReturnBit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffinePinBlocks.lean b/lean/OAI/Computability/VPVNP/AffinePinBlocks.lean new file mode 100644 index 0000000000..8b26ffc2ab --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffinePinBlocks.lean @@ -0,0 +1,191 @@ +import OAI.Computability.VPVNP.AffinePinExponents +import OAI.Computability.VPVNP.MacaulayExponentPack +import OAI.Computability.VPVNP.SliceGeometryProjection + +/-! # Recovering the pin coefficient from its physical bit pattern -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AffinePin + +open RAMTape BurstRAM +open Exponents (Kind classify) +open RadicalCertificate.MonomialIndex +open UniversalCountStack (digits) + +namespace Blocks + +/-- Contiguous equal-width rows, in order of their `Fin` index. -/ +def table {t : ℕ} (rows : Fin t → List Bool) : List Bool := (List.ofFn rows).flatten + +theorem length {t : ℕ} (rows : Fin t → List Bool) (stride : ℕ) + (h : ∀ j, (rows j).length = stride) : (table rows).length = t*stride := by + induction t with + | zero => simp [table] + | succ t ih => + rw [table, List.ofFn_succ, List.flatten_cons, List.length_append, h, Nat.succ_mul] + rw [← table, ih _ (fun i => h i.succ), Nat.add_comm] + +theorem cell {t : ℕ} (rows : Fin t → List Bool) (w : ℕ) (h : ∀ j, (rows j).length = w) + (i : Fin t) : ((table rows).drop (i.val*w)).take w = rows i := by + induction t with + | zero => exact i.elim0 + | succ t ih => + refine Fin.cases ?_ (fun k => ?_) i + · simp only [table, List.ofFn_succ, List.flatten_cons, Fin.val_zero, Nat.zero_mul, List.drop_zero] + rw [List.take_append_of_le_length (h 0).ge, List.take_of_length_le (h 0).le] + · simp only [table, List.ofFn_succ, List.flatten_cons, Fin.val_succ, Nat.succ_mul] + rw [show k.val*w+w=(rows 0).length+k.val*w by rw [h, Nat.add_comm], List.drop_length_add_append] + exact ih _ (fun j => h j.succ) k + +theorem exponent_table {t : ℕ} (w : ℕ) (d : Fin t → ℕ) : + ExponentPack.packed w (List.ofFn d) = table (fun j => digits w (d j)) := by + simp [ExponentPack.packed, table, List.flatMap_def, Function.comp_def] + +theorem packed_injective {t w : ℕ} {d d' : Fin t → ℕ} + (h : ∀ i, d i < 2^w) (h' : ∀ i, d' i < 2^w) + (he : ExponentPack.packed w (List.ofFn d) = ExponentPack.packed w (List.ofFn d')) : d = d' := by + rw [exponent_table, exponent_table] at he + funext i + have e := congrArg (fun xs : List Bool => (xs.drop (i.val*w)).take w) he + simp only [cell _ w (fun j => UniversalCountStack.length_digits _ _) i] at e + have hv := congrArg TapeWord.value e + simpa only [UniversalCountStack.value_digits, Nat.mod_eq_of_lt (h i), Nat.mod_eq_of_lt (h' i)] using hv + +theorem zeros (t w : ℕ) : table (fun _ : Fin t => digits w 0) = List.replicate (t*w) false := by + induction t with + | zero => simp [table] + | succ t ih => + rw [table, List.ofFn_succ, List.flatten_cons, ← table, + ih, UniversalCountStack.digits_zero, ← List.replicate_add, Nat.succ_mul, Nat.add_comm] + +theorem one (w : ℕ) (hw : 0 < w) : digits w 1 = true :: List.replicate (w-1) false := by + apply TapeWord.eq_of_length_value + · simp; omega + · rw [UniversalCountStack.value_digits, Nat.mod_eq_of_lt (one_lt_pow₀ (by decide) hw.ne')] + simp [TapeWord.value] + +theorem singleton {t : ℕ} (i : Fin t) (w : ℕ) (hw : 0 < w) : + table (fun j => digits w (if j=i then 1 else 0)) = + List.replicate (i.val*w) false ++ true :: List.replicate (t*w-i.val*w-1) false := by + induction t with + | zero => exact i.elim0 + | succ t ih => + refine Fin.cases ?_ (fun k => ?_) i + · simp only [table, List.ofFn_succ, List.flatten_cons, ite_true, Fin.succ_ne_zero, ite_false, + Fin.val_zero, Nat.zero_mul, List.replicate_zero, List.nil_append, Nat.sub_zero] + rw [one _ hw, List.cons_append, ← table, zeros, ← List.replicate_add, Nat.succ_mul] + congr 2; omega + · simp only [table, List.ofFn_succ, List.flatten_cons, Ne.symm (Fin.succ_ne_zero k), ite_false, + Fin.succ_inj, Fin.val_succ, Nat.succ_mul, UniversalCountStack.digits_zero] + rw [← table, ih k, ← List.append_assoc, ← List.replicate_add] + rw [Nat.add_comm w (k.val*w), Nat.add_sub_add_right] + +private theorem all_zero (xs : List Bool) : + true ∉ xs ↔ xs = List.replicate xs.length false := by + induction xs with + | nil => simp + | cons b xs ih => + cases b <;> simp [List.replicate_succ, ih] + +theorem classify_constant (pre : List Bool) (b : Bool) (post : List Bool) : + classify pre b post = .constant ↔ + pre ++ b::post = List.replicate pre.length false ++ false :: List.replicate post.length false := by + have eq : pre ++ b::post = List.replicate pre.length false ++ false :: List.replicate post.length false ↔ + pre = List.replicate pre.length false ∧ b = false ∧ post = List.replicate post.length false := by + constructor + · intro h + obtain ⟨h₁, h₂⟩ := List.append_inj h (by simp) + exact ⟨h₁, List.cons.inj h₂⟩ + · rintro ⟨h₁, h₂, h₃⟩ + exact congrArg₂ List.append h₁ (congrArg₂ List.cons h₂ h₃) + rw [eq, ← all_zero, ← all_zero] + by_cases h : true ∈ pre <;> by_cases h' : true ∈ post <;> cases b <;> + simp [classify, Exponents.tailKind, Exponents.selected, h, h'] + +theorem classify_unit (pre : List Bool) (b : Bool) (post : List Bool) : + classify pre b post = .unit ↔ + pre ++ b::post = List.replicate pre.length false ++ true :: List.replicate post.length false := by + have eq : pre ++ b::post = List.replicate pre.length false ++ true :: List.replicate post.length false ↔ + pre = List.replicate pre.length false ∧ b = true ∧ post = List.replicate post.length false := by + constructor + · intro h + obtain ⟨h₁, h₂⟩ := List.append_inj h (by simp) + exact ⟨h₁, List.cons.inj h₂⟩ + · rintro ⟨h₁, h₂, h₃⟩ + exact congrArg₂ List.append h₁ (congrArg₂ List.cons h₂ h₃) + rw [eq, ← all_zero, ← all_zero] + by_cases h : true ∈ pre <;> by_cases h' : true ∈ post <;> cases b <;> + simp [classify, Exponents.tailKind, Exponents.selected, h, h'] + +/-- The two flags written by the scan select exactly the zero exponent and +the selected unit exponent, including when the selected variable is first or last. -/ +theorem split_packed {t : ℕ} (w : ℕ) (hw : 0 < w) (i : Fin t) (d : Fin t →₀ ℕ) + (hd : ∀ j, d j < 2^w) : + ∃ pre b post, + ExponentPack.packed w (List.ofFn (fun j => d j)) = pre ++ b::post ∧ + pre.length = i.val*w ∧ post.length = t*w-i.val*w-1 ∧ + (classify pre b post = .constant ↔ d = 0) ∧ + (classify pre b post = .unit ↔ d = Finsupp.single i 1) := by + let xs := ExponentPack.packed w (List.ofFn (fun j => d j)) + let k := i.val*w + have len : xs.length = t*w := (congrArg List.length (exponent_table w (fun j => d j))).trans + (length _ w (fun _ => UniversalCountStack.length_digits ..)) + have hk : k < xs.length := len ▸ (Nat.mul_lt_mul_of_pos_right i.isLt hw) + let pre := xs.take k + let b := xs[k] + let post := xs.drop (k+1) + have hsplit : xs = pre ++ b::post := by + rw [← List.take_append_drop k xs, List.drop_eq_getElem_cons hk] + have hpre : pre.length = k := List.length_take.trans (min_eq_left hk.le) + have hpost : post.length = t*w-k-1 := by simp [post, len]; omega + have hz : List.replicate pre.length false ++ false :: List.replicate post.length false = + ExponentPack.packed w (List.ofFn fun _ : Fin t => 0) := by + rw [exponent_table, zeros, ← List.replicate_succ, ← List.replicate_add, hpre, hpost] + have := hk; rw [len] at this + congr 1; omega + have hu : List.replicate pre.length false ++ true :: List.replicate post.length false = + ExponentPack.packed w (List.ofFn fun j => (Finsupp.single i 1 : Fin t →₀ ℕ) j) := by + rw [exponent_table, hpre, hpost, ← singleton i w hw] + apply congrArg table + funext j + simp [Finsupp.single_apply, eq_comm] + refine ⟨pre,b,post,hsplit,hpre,hpost,?_,?_⟩ + · rw [classify_constant, ← hsplit, hz] + constructor + · intro h + exact DFunLike.ext' (packed_injective hd (fun _ => Nat.two_pow_pos _) h) + · rintro rfl; rfl + · rw [classify_unit, ← hsplit, hu] + constructor + · intro h + refine DFunLike.ext' (packed_injective hd (fun j => ?_) h) + rw [Finsupp.single_apply] + split + · exact one_lt_pow₀ (by decide) hw.ne' + · exact Nat.two_pow_pos _ + · rintro rfl; rfl + +end Blocks + +/-- Coefficient of a coordinate equation in the padded presentation of the slice. -/ +theorem coeff_pin {K ι : Type*} [Field K] {t : ℕ} (F : ι → MvPolynomial (Fin t) K) + (pins : Finset (Fin t)) (a : Fin t → K) (i : Fin t) (d : Fin t →₀ ℕ) : + (SliceGeometry.pinnedEquations F pins a (.inr i)).coeff d = + if i ∈ pins then (if d=0 then -a i else if d=Finsupp.single i 1 then 1 else 0) else 0 := by + classical + by_cases h : i ∈ pins + · simp only [SliceGeometry.pinnedEquations, Sum.elim_inr, h, ite_true, MvPolynomial.coeff_sub, + MvPolynomial.coeff_X, MvPolynomial.coeff_C] + by_cases hd : d=0 + · subst d + simp + · by_cases hs : d=Finsupp.single i 1 <;> simp [hd, hs, Ne.symm hd, eq_comm] + · simp [SliceGeometry.pinnedEquations, h] +end AffinePin + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffinePinCoefficient.lean b/lean/OAI/Computability/VPVNP/AffinePinCoefficient.lean new file mode 100644 index 0000000000..8e08441b88 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffinePinCoefficient.lean @@ -0,0 +1,103 @@ +import OAI.Computability.VPVNP.AffinePinQuery + +/-! # Bounded native evaluation of an affine coefficient over the advised field -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AffinePin.Query + +open RAMTape SliceArithmetic RankQuery.Stack RadicalCertificate.MonomialIndex +open UniversalCountStack (digits) + +variable {p e t : ℕ} [Fact p.Prime] [NeZero e] {c : Vector p e} +variable {K ι : Type*} [Field K] [Algebra (ZMod p) K] + +/-- Represent a field element by its power-basis coefficients in the advised extension, using +the specified algebra isomorphism. -/ +noncomputable def encode (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (a : K) : Scalar c := + Scalar.pack c (scalarEncoding φ a) + +@[simp] theorem value_encode (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (x : K) : + φ (Scalar.interpretation c (encode φ x)) = x := by + change φ (SliceArithmetic.value (modulus c) (Scalar.pack c (scalarEncoding φ x)).digits) = x + rw [Scalar.digits_pack, map_scalarEncoding] + +omit [NeZero e] in +/-- Each entry of the immutable pin table uses the same field encoding as the +matrix coefficients. -/ +theorem scalar_encode (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (v : ℕ) (x : K) : + Engine.scalar v (encode φ x) = SliceArithmeticRound.packed v (List.ofFn (scalarEncoding φ x)) := by + simp [Engine.scalar, encode] + +/-- Initial work for a pin-row lookup, containing the binary coordinate index and the +concatenated fixed-width exponent words of the requested monomial. -/ +def entry {w : ℕ} (i : Fin t) (d : Fin t →₀ ℕ) : Stage.Work := + {binary := digits w i.val, exponents := ExponentPack.packed w (List.ofFn (fun j => d j))} + +/-- Initial stack-height allowance for an affine coefficient query, accounting for its pin +mask, scalar table, packed exponent words, and field advice. -/ +def storage (t e w v : ℕ) := w+v+t+t*w+t*(e*v)+e*v+e+1 + +/-- Peak stack-height bound for the affine coefficient query obtained by adding its step budget +to the initial storage allowance. -/ +def space (t e w v : ℕ) := storage t e w v + cost t e w v + +omit [Fact p.Prime] [NeZero e] in +private theorem entry_storage {w v : ℕ} (pins : Finset (Fin t)) (a : Fin t → Scalar c) + (i : Fin t) (d : Fin t →₀ ℕ) (j : Port) : + ((frame (advice w v pins a) c v (entry (w := w) i d)) j).length ≤ storage t e w v := by + have len : (ExponentPack.packed w (List.ofFn (fun j => d j))).length = t*w := by + rw [Blocks.exponent_table] + exact Blocks.length _ _ (fun _ => UniversalCountStack.length_digits ..) + rcases j with j | j + · cases j <;> simp [frame, Stage.frame, advice, entry, len, mask_length, values_length, storage] <;> omega + · rcases j with j | j + · simp [frame, AddCall.clean] + · cases j <;> simp [frame, AddCall.clean, MultiplyCall.external, storage] <;> omega + +/-- Every intermediate stack is bounded by the input-bank capacity plus the +polynomial clock of the call. -/ +theorem bounded {w v : ℕ} (hw : 0 ?_)⟩ + exact Nat.add_le_add (entry_storage pins a i d j) hs + +/-- Transport the scalar returned by the coordinate case split to the actual +pin coefficient over the chosen field. -/ +theorem encode_pin (φ : AdjoinRoot (modulus c) ≃ₐ[ZMod p] K) (F : ι → MvPolynomial (Fin t) K) + (pins : Finset (Fin t)) (a : Fin t → K) (i : Fin t) (d : Fin t →₀ ℕ) : + (if i∈pins then (if d=0 then -encode φ (a i) else if d=Finsupp.single i 1 then 1 else 0) else 0) + = encode φ ((SliceGeometry.pinnedEquations F pins a (.inr i)).coeff d) := by + rw [AffinePin.coeff_pin] + apply (φ.injective.comp (Scalar.interpret_injective c)) + change φ (Scalar.interpretation c _) = φ (Scalar.interpretation c _) + rw [value_encode] + by_cases h : i∈pins <;> by_cases z : d=0 <;> by_cases u : d=Finsupp.single i 1 <;> simp [h, z, u] + +/-- Native affine-row lookup computes the packed coefficient in the actual +advised field at the requested exponent. -/ +theorem coefficient {w v : ℕ} (hw : 0 encode φ (a j)) + let x := (SliceGeometry.pinnedEquations F pins a (.inr i)).coeff d + ∃ steps ≤ cost t e w v, machine.BoundedRun (space t e w v) steps (frame A c v (entry (w := w) i d)) + (frame A c v {value := Engine.scalar v (encode φ x)}) := by + dsimp only + rw [← encode_pin φ F pins a i d] + exact bounded hw hv pins (fun j => encode φ (a j)) i hi d hd + +end AffinePin.Query + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffinePinExponents.lean b/lean/OAI/Computability/VPVNP/AffinePinExponents.lean new file mode 100644 index 0000000000..0b6ce677e2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffinePinExponents.lean @@ -0,0 +1,146 @@ +import OAI.Computability.VPVNP.RAMTapeRoutinePorts + +/-! +# Reading the monomial of an affine pin row from its packed exponent bits + +The low bit of the selected variable has a known offset in the packed +exponent array. A single scan distinguishes the zero vector, the vector +with just this one low bit set, and all other bit patterns. The scan +consumes the exponent scratch buffer and the unary offset. It returns +one bit for each of the two distinguished cases. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AffinePin.Exponents + +open RAMTape + +/-- Input stacks for the packed exponents and unary offset, with output stacks for the constant +and unit-monomial flags. -/ +inductive Port where | exponents | offset | constant | unit + deriving DecidableEq + +instance : Fintype Port := derive_fintype% _ + +/-- Classify the monomial at coordinate `i` as the constant monomial, the variable `X i`, or a +different monomial. -/ +inductive Kind where | constant | unit | other + deriving DecidableEq + +instance : Fintype Kind := derive_fintype% _ + +/-- Control states for scanning to the selected exponent bit, checking the remaining bits, and +emitting the two classification flags. -/ +inductive State where + | before (nonzero : Bool) | skip (nonzero : Bool) | select (nonzero : Bool) + | after (kind : Kind) | writeUnit (kind : Kind) | writeConstant (kind : Kind) | done | reject + deriving DecidableEq, Fintype + +/-- Classify the prefix ending at the low bit of the selected coordinate. A previous nonzero +bit forces the other case. -/ +def selected (before bit : Bool) : Kind := + if before then .other else if bit then .unit else .constant + +/-- Retain the prefix classification when every remaining exponent bit is false, and classify +the monomial as other when a true bit occurs. -/ +def tailKind (kind : Kind) (tail : List Bool) : Kind := if true ∈ tail then .other else kind + +/-- Stack instructions that consume the unary offset and packed exponents and write the +constant and selected-unit flags. -/ +def code : StackCode Port State + | .before b => .pop .offset (fun v => v.elim (.select b) fun t => if t then .skip b else .reject) + | .skip b => .pop .exponents (fun v => v.elim .reject fun t => .before (b || t)) + | .select b => .pop .exponents (fun v => v.elim .reject fun t => .after (selected b t)) + | .after k => .pop .exponents (fun v => v.elim (.writeUnit k) fun t => .after (if t then .other else k)) + | .writeUnit k => .push .unit (decide (k = .unit)) (.writeConstant k) + | .writeConstant k => .push .constant (decide (k = .constant)) .done + | .done => .halt true + | .reject => .halt false + +/-- Place the exponent bit stream, offset markers, and existing flag-stack contents on the four +classifier ports. -/ +def bank (exponents marks zero one : List Bool) : Stacks Port + | .exponents => exponents + | .offset => marks + | .constant => zero + | .unit => one + +private theorem set_bank (a m z u xs : List Bool) (p : Port) : + Function.update (bank a m z u) p xs = match p with + | .exponents => bank xs m z u | .offset => bank a xs z u + | .constant => bank a m xs u | .unit => bank a m z xs := by + cases p <;> funext i <;> cases i <;> rfl + +local macro "pin_step" : tactic => `(tactic| + (first | refine StackRuns.cons (.pop rfl) ?_ | refine StackRuns.cons (.push rfl) ?_) + <;> simp only [bank, set_bank, List.head?_cons, List.head?_nil, List.tail_cons, + List.tail_nil, Option.elim_some, Option.elim_none, ite_true, ite_false]) + +private theorem skip_runs (pre xs z u : List Bool) (b : Bool) : + StackRuns code (2*pre.length+1) (.before b) + (bank (pre++xs) (List.replicate pre.length true) z u) + (.select (b || decide (true ∈ pre))) (bank xs [] z u) := by + induction pre generalizing b with + | nil => + simp only [List.length_nil, Nat.mul_zero, Nat.zero_add, List.nil_append, List.replicate_zero, + List.not_mem_nil, decide_false, Bool.or_false] + pin_step + exact .nil .. + | cons t pre ih => + simp only [List.length_cons, Nat.mul_succ, List.cons_append, List.replicate_succ] + pin_step + pin_step + cases t <;> cases b <;> by_cases ht : true ∈ pre <;> simpa [ht] using ih _ + +private theorem after_runs (xs z u : List Bool) (k : Kind) : + StackRuns code (xs.length+3) (.after k) (bank xs [] z u) .done + (bank [] [] (decide (tailKind k xs = .constant) :: z) (decide (tailKind k xs = .unit) :: u)) := by + induction xs generalizing k with + | nil => + simp only [List.length_nil, Nat.zero_add, tailKind, List.not_mem_nil, ite_false] + pin_step + pin_step + pin_step + exact .nil .. + | cons b xs ih => + simp only [List.length_cons] + pin_step + cases b with + | false => by_cases hx : true ∈ xs <;> simpa [tailKind, hx] using ih k + | true => simpa [tailKind] using ih .other + +/-- Run the packed-exponent classifier from an empty scanned prefix and return after writing +both flags. -/ +def machine : FiniteRoutine Port := .ofStackCode code id (.before false) (· == .done) + +/-- Zero except possibly at the selected bit gives the constant or linear +coefficient. A nonzero bit anywhere else gives the zero coefficient. -/ +def classify (pre : List Bool) (bit : Bool) (post : List Bool) : Kind := + tailKind (selected (decide (true ∈ pre)) bit) post + +theorem machine_runs (pre : List Bool) (bit : Bool) (post z u : List Bool) : + let k := classify pre bit post + machine.Runs (2*pre.length + post.length + 5) + (bank (pre ++ bit::post) (List.replicate pre.length true) z u) + (bank [] [] (decide (k = .constant)::z) (decide (k = .unit)::u)) := by + dsimp only + have skip := skip_runs pre (bit::post) z u false + rw [Bool.false_or] at skip + have low : StackRuns code 1 (.select (decide (true ∈ pre))) (bank (bit::post) [] z u) + (.after (selected (decide (true ∈ pre)) bit)) (bank post [] z u) := by + pin_step + exact .nil .. + have hr := (skip.trans low).trans (after_runs post z u _) + rw [show 2*pre.length + 1 + 1 + (post.length+3) = 2*pre.length + post.length+5 by omega] at hr + exact FiniteRoutine.runs_ofStackCode_framed Function.injective_id rfl rfl + (fun q h => by cases q <;> simp_all [code]) hr (fun _ => rfl) (fun _ => rfl) + (fun j hj => (hj j rfl).elim) + +end AffinePin.Exponents + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffinePinIndex.lean b/lean/OAI/Computability/VPVNP/AffinePinIndex.lean new file mode 100644 index 0000000000..92d8bb540e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffinePinIndex.lean @@ -0,0 +1,87 @@ +import OAI.Computability.VPVNP.RAMTapeSortRowAddressUnary +import OAI.Computability.VPVNP.RAMTapeInputParametersMultiply +import OAI.Computability.VPVNP.EvaluatorRadixDivision + +/-! # Computing packed pin-table offsets from the live binary row index + +The little-endian index is consumed once. Its unary value is multiplied by +the stride of the table on scratch stacks. The multiplication preserves the +unary index and stride for the next table. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AffinePin.Index + +open RAMTape EvaluatorRadixDivision + +/-- The binary input, reversed bit stream, unary output, and scratch stacks for decoding a +coordinate index. -/ +inductive Port where | bits | high | index | tmp + deriving DecidableEq + +instance : Fintype Port := derive_fintype% _ + +/-- Initialize the index decoder with the supplied bit streams, a unary index tally, and empty +scratch. -/ +def bank (bits high : List Bool) (index : ℕ) : Stacks Port + | .bits => bits | .high => high | .index => List.replicate index true | .tmp => [] + +private def unaryPorts : SortRowAddress.Unary.Port → Port + | .bits => .high | .out => .index | .tmp => .tmp + +/-- Reverse the little-endian index bits and decode them into a tally with one true marker per +unit of the index. -/ +def decode : FiniteRoutine Port := + (reverseOnto .bits .high).followedBy (SortRowAddress.Unary.routine.onPorts unaryPorts) + +theorem decode_runs (xs : List Bool) : ∃ k ≤ 7*TapeWord.value xs + 6*xs.length+2, + decode.Runs k (bank xs [] 0) (bank [] [] (TapeWord.value xs)) := by + have rev := reverseOnto_runs (src := Port.bits) (dst := .high) (by decide) + (bank xs [] 0) (bank [] xs.reverse 0) rfl (by simp [bank]) + (by intro j h h'; cases j <;> first | rfl | exact (h rfl).elim | exact (h' rfl).elim) + obtain ⟨k,hk,hr⟩ := SortRowAddress.Unary.runs xs + have dec : (SortRowAddress.Unary.routine.onPorts unaryPorts).Runs k (bank [] xs.reverse 0) + (bank [] [] (TapeWord.value xs)) := by + apply FiniteRoutine.runs_onPorts_framed _ (by decide) hr + · intro j; cases j <;> rfl + · intro j; cases j <;> rfl + · intro j hj; cases j <;> first | rfl | exact (hj .bits rfl).elim | exact (hj .out rfl).elim + refine ⟨_, ?_, rev.followedBy dec⟩ + change 2*xs.length+1+k ≤ _ + omega + +/-- Tally stacks for an index, stride, and accumulated offset together with the two work stacks +for multiplication. -/ +inductive OffsetPort where | index | stride | offset | outer | tmp + deriving DecidableEq + +instance : Fintype OffsetPort := derive_fintype% _ + +/-- Set the index, stride, and offset tallies to the supplied natural numbers and initialize +the two work tallies to zero. -/ +def tallies (index stride offset : ℕ) : Tally.State OffsetPort + | .index => index | .stride => stride | .offset => offset | _ => 0 + +/-- Add the product of the unary index and stride to the offset tally while preserving the +index and stride. -/ +def scale : FiniteRoutine OffsetPort := + .ofRoutine (Tally.mulAdd .index .stride .offset .outer .tmp) + +theorem scale_runs (i w : ℕ) : scale.Runs (i*(5*w+6)+2) + (Tally.encode (tallies i w 0)) (Tally.encode (tallies i w (i*w))) := by + have h := Tally.mulAdd_runs (K := OffsetPort) .index .stride .offset .outer .tmp + (by decide) (tallies i w 0) rfl rfl + have upd : Function.update (tallies i w 0) OffsetPort.offset + ((tallies i w 0) .offset + (tallies i w 0) .index * (tallies i w 0) .stride) = + tallies i w (i*w) := by + funext j; cases j <;> simp [tallies] + rwa [upd] at h + +end AffinePin.Index + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffinePinQuery.lean b/lean/OAI/Computability/VPVNP/AffinePinQuery.lean new file mode 100644 index 0000000000..c5724a8f09 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffinePinQuery.lean @@ -0,0 +1,146 @@ +import OAI.Computability.VPVNP.AffinePinStage +import OAI.Computability.VPVNP.AffinePinScalar +import OAI.Computability.VPVNP.RoutineSpace + +/-! +# Fixed bit-stack program for affine pin coefficients + +The immutable pin mask and table are independent of the row and queried +monomial. The program computes three offsets from the live row index, +classifies the packed exponent, selects the pin, and performs the scalar +operation in the advised power basis. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AffinePin.Query + +open RAMTape SliceArithmetic RankQuery.Stack RadicalCertificate.MonomialIndex +open UniversalCountStack (digits) + +/-- The combined ports for classifying a queried monomial, reading its pin data, and computing +the field coefficient. -/ +abbrev Port := Stage.Port ⊕ AddCall.Port + +private def outputPorts : Output.Port → Port + | .inl (.inr .acc) => .inl .value + | .inl j => .inr j + | .inr .active => .inl .active + | .inr .constant => .inl .constant + | .inr .unit => .inl .unit + | .inr .right => .inl .high + | .inr .tmp => .inl .tmp + +/-- Select the coordinate’s mask bit and field value, classify the requested exponent, and +compute the coefficient of its affine pin equation. -/ +def machine : FiniteRoutine Port := + (Stage.machine.onPorts Sum.inl).followedBy (Output.machine.onPorts outputPorts) + +variable {p e t : ℕ} {c : Vector p e} + +/-- The coordinate-ordered bit vector indicating which variables are pinned. -/ +def mask (pins : Finset (Fin t)) : List Bool := List.ofFn (fun i => decide (i∈pins)) + +/-- Concatenate the pinned-value table in coordinate order, encoding every field element in +limbs of `v` bits. -/ +def values (v : ℕ) (a : Fin t → Scalar c) : List Bool := Blocks.table fun j => Engine.scalar v (a j) + +/-- The fixed exponent width, scalar width, pin mask, and packed field-value table used for +every monomial query of this slice. -/ +def advice (w v : ℕ) (pins : Finset (Fin t)) (a : Fin t → Scalar c) : Stage.Advice := + ⟨w, e*v, mask pins, values v a⟩ + +/-- Combine the pin advice and current lookup state with a clean field-arithmetic bank +containing the packed extension modulus. -/ +def frame (A : Stage.Advice) (c : Vector p e) (v : ℕ) (s : Stage.Work) : Stacks Port := + Sum.elim (Stage.frame A s) (AddCall.clean (MultiplyCall.external p e v (SliceArithmeticRound.packed v (List.ofFn c)) [] [])) + +theorem mask_length (pins : Finset (Fin t)) : (mask pins).length = t := List.length_ofFn + +theorem values_length (v : ℕ) (a : Fin t → Scalar c) : (values v a).length = t*(e*v) := + Blocks.length _ _ (fun j => by simp [Engine.scalar]) + +theorem extra_length (v : ℕ) (pins : Finset (Fin t)) (a : Fin t → Scalar c) : + (mask pins ++ values v a).length = t + t*(e*v) := by rw [List.length_append, mask_length, values_length] + +private theorem mask_cell (pins : Finset (Fin t)) (i : Fin t) : + ((mask pins).drop i.val).take 1 = [decide (i∈pins)] := by + have hl : i.val < (mask pins).length := (mask_length pins).symm ▸ i.isLt + rw [List.drop_eq_getElem_cons hl] + simp [mask] + +private theorem values_cell (v : ℕ) (a : Fin t → Scalar c) (i : Fin t) : + ((values v a).drop (i.val*(e*v))).take (e*v) = Engine.scalar v (a i) := + Blocks.cell _ _ (fun _ => by simp [Engine.scalar]) i + +/-- Uniform step bound over the `t` coordinate rows for decoding an index, scanning the +exponents, reading the pin table, and returning a scalar. -/ +def cost (t e w v : ℕ) := Stage.cost w t w (e*v) (t*w) + Output.cost e v + +private theorem cost_le {i t e w v : ℕ} (hi : i ≤ t) : + Stage.cost w i w (e*v) (t*w) + Output.cost e v ≤ cost t e w v := by + unfold cost Stage.cost Reader.cost EvaluatorDigitLookup.lookupTicks + gcongr + +variable [Fact p.Prime] [NeZero e] + +/-- Return the canonical scalar for the indexed row and queried exponent. +All temporary stacks are clean at the return. -/ +theorem machine_runs {w v : ℕ} (hw : 0 d j))} + let ans : Scalar c := if i∈pins then (if d=0 then -a i else if d=Finsupp.single i 1 then 1 else 0) else 0 + ∃ steps ≤ cost t e w v, machine.Runs steps (frame A c v entry) (frame A c v {value := Engine.scalar v ans}) := by + dsimp only + let A := advice w v pins a + let entry : Stage.Work := {binary := digits w i.val, exponents := ExponentPack.packed w (List.ofFn (fun j => d j))} + let act := decide (i∈pins) + let zero := decide (d=0) + let unit := decide (d=Finsupp.single i 1) + let got : Stage.Work := {active := [act], constant := [zero], unit := [unit], value := Engine.scalar v (a i)} + let ans := Output.result (a i) act zero unit + let final : Stage.Work := {value := Engine.scalar v ans} + obtain ⟨pre,b,post,hp,hl,_,hz,hu⟩ := Blocks.split_packed w hw i d hd + have hm : i.val+1 ≤ A.mask.length := (mask_length pins).symm ▸ i.isLt + have hval : i.val*A.scalarWidth+A.scalarWidth ≤ A.values.length := by + change i.val*(e*v)+e*v ≤ (values v a).length + rw [values_length, ← Nat.succ_mul] + exact Nat.mul_le_mul_right _ i.isLt + obtain ⟨k,hk,run⟩ := Stage.machine_runs A (digits w i.val) pre b post i.val + (by rw [UniversalCountStack.value_digits, Nat.mod_eq_of_lt hi]) hl hm hval + have len : (ExponentPack.packed w (List.ofFn (fun j => d j))).length = t*w := by + rw [Blocks.exponent_table]; exact Blocks.length _ _ (fun _ => UniversalCountStack.length_digits ..) + rw [← hp, len, UniversalCountStack.length_digits] at hk + have mcell : (A.mask.drop i.val).take 1 = [act] := mask_cell pins i + have vcell : (A.values.drop (i.val*A.scalarWidth)).take A.scalarWidth = Engine.scalar v (a i) := values_cell v a i + simp only [← hp, mcell, vcell, hz, hu] at run + have stage : (Stage.machine.onPorts (Sum.inl : Stage.Port → Port)).Runs k (frame A c v entry) + (frame A c v got) := by + apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective run (fun _ => rfl) (fun _ => rfl) + rintro (j | j) hj + · exact (hj j rfl).elim + · rfl + obtain ⟨l,hh,out⟩ := Output.machine_runs hv (a i) act zero unit + have write : (Output.machine.onPorts outputPorts).Runs l (frame A c v got) (frame A c v final) := by + apply FiniteRoutine.runs_onPorts_framed _ (by decide) out + · rintro ((j | j) | j) <;> first | cases j <;> rfl + · rintro ((j | j) | j) <;> first | cases j <;> rfl + · rintro (j | j) hj + · cases j <;> first | rfl | exact (hj (.inl (.inr .acc)) rfl).elim | exact (hj (.inr .active) rfl).elim | exact (hj (.inr .constant) rfl).elim | exact (hj (.inr .unit) rfl).elim + · rfl + have heq : ans = if i∈pins then (if d=0 then -a i else if d=Finsupp.single i 1 then 1 else 0) else 0 := by + by_cases h : i∈pins <;> by_cases z : d=0 <;> by_cases u : d=Finsupp.single i 1 <;> + simp [ans, Output.result, act, zero, unit, h, z, u] + refine ⟨k+l, (Nat.add_le_add hk hh).trans (cost_le i.isLt.le), ?_⟩ + rw [← heq] + exact stage.followedBy write + +end AffinePin.Query + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffinePinResources.lean b/lean/OAI/Computability/VPVNP/AffinePinResources.lean new file mode 100644 index 0000000000..4ad240643d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffinePinResources.lean @@ -0,0 +1,48 @@ +import OAI.Computability.VPVNP.AffinePinCoefficient +import OAI.Computability.VPVNP.PolynomialBounds + +/-! # Polynomial time, space and advice for the physical pin query -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AffinePin.Query + +open PolynomiallyBounded + +private theorem reader_polynomial {i s : ℕ → ℕ} (hi : PolynomiallyBounded i) (hs : PolynomiallyBounded s) : + PolynomiallyBounded (fun n => Reader.cost (i n) (s n)) := by + exact ((((hi.mul (((const 5).mul hs).add (const 6))).add (const 2)).add + (((const 5).mul hs).add (const 2))).add + ((((const 5).mul (hi.mul hs)).add ((const 8).mul hs)).add (const 4))) + +private theorem addCall_polynomial {e v : ℕ → ℕ} (he : PolynomiallyBounded e) (hv : PolynomiallyBounded v) : + PolynomiallyBounded (fun n => SliceArithmetic.AddCall.callCap (e n) (v n)) := by + have init := ((const 10).mul (((const 5).mul (he.add hv)).add (const 2))).add (const 1) + have body := (((const 200).mul ((hv.add (const 1)).pow 2)).add ((const 17).mul hv)).add (const 8) + have rows := ((he.mul body).add ((const 2).mul (he.mul hv))).add (const 2) + exact (init.add rows).add (((const 9).mul (hv.add (const 1))).add (const 1)) + +theorem resources {t e w v : ℕ → ℕ} (ht : PolynomiallyBounded t) (he : PolynomiallyBounded e) + (hw : PolynomiallyBounded w) (hv : PolynomiallyBounded v) : + PolynomiallyBounded (fun n => cost (t n) (e n) (w n) (v n)) ∧ + PolynomiallyBounded (fun n => space (t n) (e n) (w n) (v n)) ∧ + PolynomiallyBounded (fun n => t n + t n * (e n * v n)) := by + have scalar := he.mul hv + have row := ht.mul hw + have decode := (((const 7).mul ht).add ((const 6).mul hw)).add (const 2) + have offset := (ht.mul (((const 5).mul hw).add (const 6))).add (const 2) + have scan := ((const 2).mul row).add (const 5) + have stage := ((((decode.add offset).add scan).add (reader_polynomial ht (const 1))).add + (reader_polynomial ht scalar)).add (ht.add (const 1)) + have output := ((((const 8).mul scalar).add (const 5)).add (addCall_polynomial he hv)).add (const 3) + have clock := stage.add output + have storage := (((((((hw.add hv).add ht).add row).add (ht.mul scalar)).add scalar).add he).add (const 1)) + exact ⟨clock,storage.add clock,ht.add (ht.mul scalar)⟩ + +end AffinePin.Query + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffinePinScalar.lean b/lean/OAI/Computability/VPVNP/AffinePinScalar.lean new file mode 100644 index 0000000000..cfdc4780d3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffinePinScalar.lean @@ -0,0 +1,139 @@ +import OAI.Computability.VPVNP.SliceArithmeticNeg +import OAI.Computability.VPVNP.SliceArithmeticConstant +import OAI.Computability.VPVNP.RankQueryStackNativeFrames + +/-! # Native scalar output for a coordinate pin -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AffinePin.Output + +open RAMTape SliceArithmetic RankQuery.Stack + +/-- Ports for the active-pin, constant, and unit-monomial bits and the two work stacks used to +write a field literal. -/ +inductive Flag where | active | constant | unit | right | tmp + deriving DecidableEq + +instance : Fintype Flag := derive_fintype% _ + +/-- The field-addition ports and flag ports used to turn a pin value and a monomial +classification into a scalar coefficient. -/ +abbrev Port := AddCall.Port ⊕ Flag + +/-- Initialize field arithmetic from the modulus and accumulator and install the supplied +active, constant, and unit flag stacks. -/ +def frame {p e : ℕ} (c : Vector p e) (v : ℕ) (a z u acc : List Bool) : Stacks Port := + Sum.elim (AddCall.clean (MultiplyCall.external p e v (SliceArithmeticRound.packed v (List.ofFn c)) [] acc)) + (fun | .active => a | .constant => z | .unit => u | _ => []) + +private def literalPorts : TapeWord.ScanPort → Port + | .left => .inl (.inr .coeff) | .right => .inr .right | .tmp => .inr .tmp | .out => .inl (.inr .acc) + +/-- Negate the pin value for the constant term of an active pin. In the remaining cases write +one for its selected variable and zero otherwise. -/ +def operation (active constant unit : Bool) : FiniteRoutine Port := + if active && constant then NegCall.machine.onPorts Sum.inl + else (SliceArithmeticConstant.machine (active && unit)).onPorts literalPorts + +/-- Pop one Boolean flag and run the continuation for that bit, rejecting an empty flag stack. -/ +def branch (port : Port) (f : Bool → FiniteRoutine Port) : FiniteRoutine Port := + .ofRoutine (Routine.popCase port (Routine.halt false) (f false).body (f true).body) + +private theorem branch_runs (port : Port) (f : Bool → FiniteRoutine Port) + {s out : Stacks Port} {b : Bool} {tail : List Bool} {t : ℕ} (hs : s port = b::tail) + (hr : (f b).Runs t (Function.update s port tail) out) : + (branch port f).Runs (t+1) s out := by + cases b + · exact Routine.runs_popCase_false port _ _ _ hs hr + · exact Routine.runs_popCase_true port _ _ _ hs hr + +/-- Read the active, constant, and unit flags in order and execute the corresponding scalar +operation. -/ +def machine : FiniteRoutine Port := + branch (.inr .active) fun a => branch (.inr .constant) fun z => branch (.inr .unit) (operation a z) + +variable {p e : ℕ} [Fact p.Prime] [NeZero e] + +/-- The pin-row coefficient selected by the flags, equal to minus the pin value for the active +constant term, one for the active selected variable, and zero otherwise. -/ +def result {c : Vector p e} (a : Scalar c) (active constant unit : Bool) : Scalar c := + if active && constant then -a else if active && unit then 1 else 0 + +/-- Step bound for reading the three classification flags and producing the packed scalar by +negation or literal output. -/ +def cost (e v : ℕ) := 8*(e*v) + 5 + AddCall.callCap e v + 3 + +omit [NeZero e] in +private theorem literal_digits {c : Vector p e} (b : Bool) : + (if b then (1 : Scalar c) else 0).digits = SliceArithmeticConstant.literal b p e := by + cases b + · exact Scalar.digits_pack (zero p e) + · exact Scalar.digits_pack (one p e) + +omit [NeZero e] in +private theorem neg_digits {c : Vector p e} (a : Scalar c) : (-a).digits = fun i => -a.digits i := by + change (Scalar.pack c (scale (-1) a.digits)).digits = _ + rw [Scalar.digits_pack] + funext i + change (-1 : Fin p) * a.digits i = -a.digits i + exact neg_one_mul _ + +private theorem operation_runs {c : Vector p e} {v : ℕ} (hv : Word.workingWidth p ≤ v) (a : Scalar c) + (active constant unit : Bool) : ∃ k ≤ cost e v - 3, + (operation active constant unit).Runs k (frame c v [] [] [] (Engine.scalar v a)) + (frame c v [] [] [] (Engine.scalar v (result a active constant unit))) := by + by_cases h : (active && constant) = true + · simp only [operation, result, h, ite_true] + obtain ⟨k,hk,run⟩ := NegCall.machine_runs hv a.digits (SliceArithmeticRound.packed v (List.ofFn c)) + refine ⟨k, by unfold cost; omega, ?_⟩ + apply FiniteRoutine.runs_onPorts_framed _ Sum.inl_injective run (fun _ => rfl) + · intro j + rw [Engine.scalar, neg_digits] + rfl + · rintro (j | j) hj + · exact (hj j rfl).elim + · rfl + · simp only [operation, result, ite_eq_right h] + let b := active && unit + have run := SliceArithmeticConstant.machine_runs (NeZero.pos e) hv b c (Engine.scalar v a) + have len : (Engine.scalar v a).length = e*v := by simp [Engine.scalar] + rw [len] at run + refine ⟨e*v + 7*(e*v) + 3, by unfold cost; omega, ?_⟩ + apply FiniteRoutine.runs_onPorts_framed _ (ports := literalPorts) (by decide) run + · intro j; cases j <;> rfl + · intro j; rw [Engine.scalar, literal_digits (c := c) b]; cases j <;> rfl + · rintro (j | j) hj + · rcases j with j | j + · rfl + · cases j <;> first | rfl | exact (hj .out rfl).elim + · cases j <;> rfl + +theorem machine_runs {c : Vector p e} {v : ℕ} (hv : Word.workingWidth p ≤ v) (a : Scalar c) + (active constant unit : Bool) : ∃ k ≤ cost e v, + machine.Runs k (frame c v [active] [constant] [unit] (Engine.scalar v a)) + (frame c v [] [] [] (Engine.scalar v (result a active constant unit))) := by + let S := fun A Z U => frame c v A Z U (Engine.scalar v a) + have ua : Function.update (S [active] [constant] [unit]) (.inr .active) [] = S [] [constant] [unit] := by + funext i; rcases i with j | j <;> first | cases j <;> rfl + have uz : Function.update (S [] [constant] [unit]) (.inr .constant) [] = S [] [] [unit] := by + funext i; rcases i with j | j <;> first | cases j <;> rfl + have uu : Function.update (S [] [] [unit]) (.inr .unit) [] = S [] [] [] := by + funext i; rcases i with j | j <;> first | cases j <;> rfl + obtain ⟨k,hk,hr⟩ := operation_runs hv a active constant unit + refine ⟨k+3, by unfold cost at *; omega, ?_⟩ + apply branch_runs (.inr .active) _ (b := active) (tail := []) rfl + rw [ua] + apply branch_runs (.inr .constant) _ (b := constant) (tail := []) rfl + rw [uz] + apply branch_runs (.inr .unit) _ (b := unit) (tail := []) rfl + rw [uu] + exact hr + +end AffinePin.Output + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffinePinStage.lean b/lean/OAI/Computability/VPVNP/AffinePinStage.lean new file mode 100644 index 0000000000..faae2df42f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffinePinStage.lean @@ -0,0 +1,167 @@ +import OAI.Computability.VPVNP.AffinePinTable +import OAI.Computability.VPVNP.AffinePinBlocks +import OAI.Computability.VPVNP.SliceArithmeticCallClear + +/-! # Reading the pinned coordinate and classifying its exponent -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AffinePin.Stage + +open RAMTape + +/-- Stacks for decoding the row index, computing offsets, reading the pin mask and scalar +table, and classifying the packed exponent. -/ +inductive Port where + | binary | high | index | wordStride | scalarStride | one | offset | outer | tmp | width + | mask | values | saved | reversed | active | value | exponents | constant | unit + deriving DecidableEq + +instance : Fintype Port := derive_fintype% _ + +/-- Immutable lookup data for the affine pin stage, including the two record widths, membership +mask, and packed field values. -/ +structure Advice where + /-- Number of bits in each coordinate’s exponent word in the packed monomial. -/ + w : ℕ + /-- Number of bits per field element in the packed table of coordinate values. -/ + scalarWidth : ℕ + /-- One Boolean flag per coordinate, set precisely for the pinned coordinates in the query + advice. -/ + mask : List Bool + /-- Consecutive fixed-width blocks holding the coordinate values in field representation. -/ + values : List Bool + +/-- Mutable state of a pin-row query, including the coordinate index, offset, exponent stream, +extracted value, and classification flags. -/ +structure Work where + /-- Binary input word identifying the coordinate whose pin row is being queried. -/ + binary : List Bool := [] + /-- Decoded coordinate index, stored as a unary counter and reused for both pin-table reads. -/ + index : ℕ := 0 + /-- Bit offset to the selected exponent's low bit, represented by one unary mark per bit to + skip. -/ + offset : ℕ := 0 + /-- Packed exponent words of the queried monomial, consumed while testing for the constant + and selected-variable monomials. -/ + exponents : List Bool := [] + /-- Output stack for the packed scalar at the selected coordinate in the pin-value table. -/ + value : List Bool := [] + /-- Output stack for the mask bit indicating whether the selected coordinate is pinned. -/ + active : List Bool := [] + /-- Output flag for the constant monomial, set when all bits in the exponent vector are zero. -/ + constant : List Bool := [] + /-- Output flag for the selected variable's monomial, set when its low exponent bit is the + only bit equal to one. -/ + unit : List Bool := [] + +/-- Place the pin mask, scalar values and stride markers on their advice stacks and encode the +mutable work fields on the stage's remaining ports. -/ +def frame (A : Advice) (s : Work) : Stacks Port + | .binary => s.binary | .index => List.replicate s.index true | .offset => List.replicate s.offset true + | .wordStride => List.replicate A.w true | .scalarStride => List.replicate A.scalarWidth true + | .one => [true] | .mask => A.mask | .values => A.values | .value => s.value | .active => s.active + | .exponents => s.exponents | .constant => s.constant | .unit => s.unit | _ => [] + +private def decodePorts : Index.Port → Port + | .bits => .binary | .high => .high | .index => .index | .tmp => .tmp + +private def offsetPorts : Index.OffsetPort → Port + | .index => .index | .stride => .wordStride | .offset => .offset | .outer => .outer | .tmp => .tmp + +private def exponentPorts : Exponents.Port → Port + | .exponents => .exponents | .offset => .offset | .constant => .constant | .unit => .unit + +private def readPorts (scalar : Bool) : Reader.Port → Port + | .index => .index | .stride => if scalar then .scalarStride else .one + | .offset => .offset | .outer => .outer | .tmp => .tmp | .width => .width + | .src => if scalar then .values else .mask | .saved => .saved | .reversed => .reversed + | .out => if scalar then .value else .active + +/-- Decode the coordinate, classify its queried monomial, read its mask bit and packed pin +value, and clear the unary index. -/ +def machine : FiniteRoutine Port := + (((((Index.decode.onPorts decodePorts).followedBy (Index.scale.onPorts offsetPorts)).followedBy + (Exponents.machine.onPorts exponentPorts)).followedBy (Reader.machine.onPorts (readPorts false))).followedBy + (Reader.machine.onPorts (readPorts true))).followedBy (SliceArithmetic.CallClear.clear .index) + +/-- Step bound for a stage call at row `i`, covering its binary decoding, exponent-offset +calculation, scan of `n` exponent bits, two table reads and index cleanup. -/ +def cost (rowWidth i w scalarWidth n : ℕ) : ℕ := + 7*i+6*rowWidth+2 + (i*(5*w+6)+2) + (2*n+5) + Reader.cost i 1 + Reader.cost i scalarWidth + (i+1) + +/-- The tables and width markers are retained. The row word, exponent vector, +unary row index and all other scratch are consumed or reclaimed. -/ +theorem machine_runs (A : Advice) (xs pre : List Bool) (b : Bool) (post : List Bool) (i : ℕ) + (hi : TapeWord.value xs = i) (hpre : pre.length = i*A.w) + (hm : i+1 ≤ A.mask.length) (hv : i*A.scalarWidth+A.scalarWidth ≤ A.values.length) : + let input := pre ++ b::post + let k := Exponents.classify pre b post + let ready : Work := {binary := xs, exponents := input} + let final : Work := { + active := (A.mask.drop i).take 1 + value := (A.values.drop (i*A.scalarWidth)).take A.scalarWidth + constant := [decide (k = .constant)] + unit := [decide (k = .unit)] } + ∃ steps ≤ cost xs.length i A.w A.scalarWidth input.length, machine.Runs steps (frame A ready) (frame A final) := by + dsimp only + let input := pre ++ b::post + let k := Exponents.classify pre b post + let s₀ : Work := {binary := xs, exponents := input} + let s₁ : Work := {index := i, exponents := input} + let s₂ : Work := {s₁ with offset := i*A.w} + let s₃ : Work := {index := i, constant := [decide (k = .constant)], unit := [decide (k = .unit)]} + let s₄ := {s₃ with active := (A.mask.drop i).take 1} + let s₅ := {s₄ with value := (A.values.drop (i*A.scalarWidth)).take A.scalarWidth} + obtain ⟨u,hu,ud⟩ := Index.decode_runs xs + rw [hi] at hu ud + have decode : (Index.decode.onPorts decodePorts).Runs u (frame A s₀) (frame A s₁) := by + apply FiniteRoutine.runs_onPorts_framed _ (by decide) ud + · intro p; cases p <;> rfl + · intro p; cases p <;> rfl + · intro p hp; cases p <;> first | rfl | exact (hp .bits rfl).elim | exact (hp .index rfl).elim + have offset : (Index.scale.onPorts offsetPorts).Runs (i*(5*A.w+6)+2) (frame A s₁) (frame A s₂) := by + apply FiniteRoutine.runs_onPorts_framed _ (by decide) (Index.scale_runs i A.w) + · intro p; cases p <;> rfl + · intro p; cases p <;> rfl + · intro p hp; cases p <;> first | rfl | exact (hp .offset rfl).elim + have classify : (Exponents.machine.onPorts exponentPorts).Runs (2*pre.length+post.length+5) + (frame A s₂) (frame A s₃) := by + have ex := Exponents.machine_runs pre b post [] [] + rw [hpre] at ex + rw [hpre] + apply FiniteRoutine.runs_onPorts_framed _ (by decide) ex + · intro p; cases p <;> rfl + · intro p; cases p <;> rfl + · intro p hp; cases p <;> first | rfl | exact (hp .offset rfl).elim | exact (hp .exponents rfl).elim | exact (hp .constant rfl).elim | exact (hp .unit rfl).elim + have mask : (Reader.machine.onPorts (readPorts false)).Runs (Reader.cost i 1) (frame A s₃) (frame A s₄) := by + have r := Reader.machine_runs A.mask [] i 1 (by simpa using hm) + simp only [Nat.mul_one, List.append_nil] at r + apply FiniteRoutine.runs_onPorts_framed _ (by decide) r + · intro p; cases p <;> rfl + · intro p; cases p <;> rfl + · intro p hp; cases p <;> first | rfl | exact (hp .out rfl).elim + have value : (Reader.machine.onPorts (readPorts true)).Runs (Reader.cost i A.scalarWidth) + (frame A s₄) (frame A s₅) := by + have r := Reader.machine_runs A.values [] i A.scalarWidth hv + rw [List.append_nil] at r + apply FiniteRoutine.runs_onPorts_framed _ (by decide) r + · intro p; cases p <;> rfl + · intro p; cases p <;> rfl + · intro p hp; cases p <;> first | rfl | exact (hp .out rfl).elim + have clear := SliceArithmetic.CallClear.clear_runs Port.index (frame A s₅) + have len : ((frame A s₅) .index).length = i := List.length_replicate + have upd : Function.update (frame A s₅) .index [] = frame A {s₅ with index := 0} := by + funext p; cases p <;> rfl + rw [len, upd] at clear + refine ⟨_, ?_, ((((decode.followedBy offset).followedBy classify).followedBy mask).followedBy value).followedBy clear⟩ + simp only [cost, List.length_append, List.length_cons] + omega + +end AffinePin.Stage + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffinePinTable.lean b/lean/OAI/Computability/VPVNP/AffinePinTable.lean new file mode 100644 index 0000000000..37a84a71c8 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffinePinTable.lean @@ -0,0 +1,77 @@ +import OAI.Computability.VPVNP.AffinePinIndex +import OAI.Computability.VPVNP.EvaluatorDigitLookup +import OAI.Computability.VPVNP.RAMTapeSuccessorRecord + +/-! # Native indexed selection from an immutable packed pin table -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace AffinePin.Reader + +open RAMTape + +/-- Stack addresses for a fixed-stride table lookup, including its unary counters, packed +source, saved prefix, reversed entry and output. -/ +inductive Port where | index | stride | offset | outer | tmp | width | src | saved | reversed | out + deriving DecidableEq + +instance : Fintype Port := derive_fintype% _ + +private def scalePort : Index.OffsetPort → Port + | .index => .index | .stride => .stride | .offset => .offset | .outer => .outer | .tmp => .tmp + +private def readPort : EvaluatorDigitLookup.Port → Port + | .src => .src | .offset => .offset | .width => .width | .saved => .saved + | .revDigit => .reversed | .digit => .out + +/-- Encode the index, stride, offset and width in unary and install the source table and output +stack with empty lookup scratch. -/ +def bank (i stride offset width : ℕ) (src out : List Bool) : Stacks Port + | .index => List.replicate i true | .stride => List.replicate stride true + | .offset => List.replicate offset true | .width => List.replicate width true + | .src => src | .out => out | _ => [] + +/-- Prepend the `stride` bits starting at bit `i * stride` of the source table to the output +stack, restoring the source table after the read. -/ +def machine : FiniteRoutine Port := + ((Index.scale.onPorts scalePort).followedBy (SuccessorFields.prependCopy .stride .width .tmp)).followedBy + (EvaluatorDigitLookup.lookupRoutine.onPorts readPort) + +/-- Exact step count to compute the offset `i * stride`, copy the width marker and retrieve the +full fixed-width table entry at index `i`. -/ +def cost (i stride : ℕ) : ℕ := + i*(5*stride+6)+2 + (5*stride+2) + EvaluatorDigitLookup.lookupTicks (i*stride) stride + +theorem machine_runs (src out : List Bool) (i w : ℕ) (hf : i*w+w ≤ src.length) : + machine.Runs (cost i w) (bank i w 0 0 src out) + (bank i w 0 0 src (((src.drop (i*w)).take w) ++ out)) := by + have scale : (Index.scale.onPorts scalePort).Runs (i*(5*w+6)+2) + (bank i w 0 0 src out) (bank i w (i*w) 0 src out) := by + apply FiniteRoutine.runs_onPorts_framed _ (by decide) (Index.scale_runs i w) + · intro p; cases p <;> rfl + · intro p; cases p <;> rfl + · intro p hp; cases p <;> first | rfl | exact (hp .offset rfl).elim + let s := bank i w (i*w) 0 src out + have copy := SuccessorFields.prependCopy_runs Port.stride .width .tmp + (by decide) (by decide) (by decide) s rfl + have upd : Function.update s Port.width (s .stride ++ s .width) = bank i w (i*w) w src out := by + funext p; cases p <;> simp [s, bank] + have hw : (s .stride).length = w := List.length_replicate + rw [upd, hw] at copy + have read : (EvaluatorDigitLookup.lookupRoutine.onPorts readPort).Runs + (EvaluatorDigitLookup.lookupTicks (i*w) w) (bank i w (i*w) w src out) + (bank i w 0 0 src (((src.drop (i*w)).take w) ++ out)) := by + apply FiniteRoutine.runs_onPorts_framed _ (by decide) + (EvaluatorDigitLookup.lookupRoutine_runs_at src out (i*w) w hf) + · intro p; cases p <;> rfl + · intro p; cases p <;> rfl + · intro p hp; cases p <;> first | rfl | exact (hp .offset rfl).elim | exact (hp .width rfl).elim | exact (hp .digit rfl).elim + exact (scale.followedBy copy).followedBy read + +end AffinePin.Reader + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/AffineSliceQuery.lean b/lean/OAI/Computability/VPVNP/AffineSliceQuery.lean new file mode 100644 index 0000000000..22bc015d9a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/AffineSliceQuery.lean @@ -0,0 +1,93 @@ +import OAI.Computability.VPVNP.MacaulaySliceBasis + +/-! +# Coefficient queries after prime reduction and affine slicing + +A row lookup either asks for one original integer coefficient and casts it +to the base field, or reads the constant and linear coefficients of one of +the supplied affine cuts. This gives the scalar interface used by the +finite-slice coordinate queries of Appendix D. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace RadicalCertificate.MonomialIndex + +open MvPolynomial + +variable {t e s : ℕ} {K E : Type*} [Field K] + +/-- One affine equation, represented by its coefficient words in the slice field. -/ +structure AffineCut (t : ℕ) (K : Type*) where + /-- Coefficient of the constant monomial in the affine slice equation over `K`. -/ + constant : K + /-- Coefficient of each of the `t` coordinate variables in the affine slice equation. -/ + linear : Fin t → K + +namespace AffineCut + +/-- The multivariate polynomial of the affine equation, obtained by adding its constant term to +the weighted sum of the coordinate variables. -/ +noncomputable def polynomial (cut : AffineCut t K) : MvPolynomial (Fin t) K := + C cut.constant + ∑ i, monomial (Finsupp.single i 1) (cut.linear i) + +/-- Read the coefficient of a cut at a numeric exponent tuple. -/ +def getCoeff (cut : AffineCut t K) (a : Fin t → ℕ) : K := + (if ∀ i, a i = 0 then cut.constant else 0) + + ∑ i : Fin t, if ∀ j, a j = (if j = i then 1 else 0) then cut.linear i else 0 + +theorem getCoeff_eq (cut : AffineCut t K) (a : Fin t → ℕ) : + cut.getCoeff a = cut.polynomial.coeff (exponentVector a) := by + have hz : (∀ i, a i = 0) ↔ exponentVector a = 0 := by rw [DFunLike.ext_iff]; rfl + have hs (i : Fin t) : (∀ j, a j = if j = i then 1 else 0) ↔ + Finsupp.single i 1 = exponentVector a := by + rw [DFunLike.ext_iff] + simp [exponentVector, Finsupp.single_apply, eq_comm] + rw [getCoeff, polynomial, AddMonoidAlgebra.coeff_add, Finsupp.add_apply, coeff_C, coeff_sum] + simp only [hz, hs, coeff_monomial, eq_comm (a := exponentVector a) (b := 0)] + +theorem degree_le (cut : AffineCut t K) : cut.polynomial.totalDegree ≤ 1 := by + unfold polynomial + refine (totalDegree_add ..).trans (max_le (by simp) (totalDegree_finsetSum_le ?_)) + intro i _ + exact (totalDegree_monomial_le _ _).trans (by simp) + +end AffineCut + +/-- Base change the integer equations, followed by the affine slice equations. -/ +noncomputable def slicedSystem (F : Fin e → MvPolynomial (Fin t) ℤ) (cuts : Fin s → AffineCut t K) : + Fin (e+s) → MvPolynomial (Fin t) K := + Fin.addCases (fun i => map (Int.castRingHom K) (F i)) (fun i => (cuts i).polynomial) + +/-- Numerical input for the indexed matrix algorithm after prime reduction. -/ +def slicedQueryData (Q d N : ℕ) (read : Fin e → (Fin t → ℕ) → ℤ) (cuts : Fin s → AffineCut t K) : + QueryData t (e+s) K where + fieldOrder := Q + degreeBound := d + pointBound := N + getCoeff := Fin.addCases (fun i a => (read i a : K)) (fun i => (cuts i).getCoeff) + +theorem slicedQueryData_presents [Fintype K] (F : Fin e → MvPolynomial (Fin t) ℤ) (Q d N : ℕ) + (read : Fin e → (Fin t → ℕ) → ℤ) (cuts : Fin s → AffineCut t K) + (hQ : Q = Fintype.card K) (hd : 3 ≤ d) (hF : ∀ i, (F i).totalDegree ≤ d) + (hread : ∀ i a, read i a = (F i).coeff (exponentVector a)) : + (slicedQueryData Q d N read cuts).Presents (slicedSystem F cuts) := by + refine ⟨hQ, hd, ?_, ?_⟩ + · intro j + refine Fin.addCases (fun i => ?_) (fun i => ?_) j + · simp only [slicedSystem, Fin.addCases_left] + exact (Finset.sup_mono (support_map_subset _ _)).trans (hF i) + · simp only [slicedSystem, Fin.addCases_right] + exact (cuts i).degree_le.trans (show 1 ≤ d by omega) + · intro j + refine Fin.addCases (fun i a => ?_) (fun i a => ?_) j + · simp only [slicedQueryData, slicedSystem, Fin.addCases_left, hread, coeff_map, Int.coe_castRingHom] + · simp only [slicedQueryData, slicedSystem, Fin.addCases_right, AffineCut.getCoeff_eq] + +end RadicalCertificate.MonomialIndex + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BalancedCircuit.lean b/lean/OAI/Computability/VPVNP/BalancedCircuit.lean new file mode 100644 index 0000000000..4ded33806b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BalancedCircuit.lean @@ -0,0 +1,130 @@ +import OAI.Computability.VPVNP.BalancedGrammar +import OAI.Computability.VPVNP.BalancedCoefficients +import OAI.Computability.VPVNP.CircuitGrammar +import Mathlib.LinearAlgebra.Matrix.Rank + +/-! +# Balanced rank decompositions of exact circuits + +In Theorem 4.2 of *VP and VNP differ over every field*, a monomial selects one variable +at each of the `ℓ` parties. Its circuit may use arbitrary intermediate monomials. Taking +the queried coefficients of a balanced product expansion yields one matrix on each party +cut. The sum of these matrices recovers the coefficient tensor, and the number of graded +circuit states bounds every matrix rank. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open MvPolynomial ParseGrammar + +variable {I J k : Type*} [Fintype I] [DecidableEq I] [Fintype J] [Field k] {s : ℕ} + +/-- An assignment to the selected parties, viewed as an exponent of the whole polynomial. -/ +noncomputable def cutExponent (S : Finset I) (a : S → J) : (I × J) →₀ ℕ := + ∑ i : S, Finsupp.single (i.val, a i) 1 + +omit [Fintype I] [DecidableEq I] [Fintype J] in +theorem cutExponent_restrict (S : Finset I) (a : I → J) : + cutExponent S (fun i ↦ a i.val) = partyExponent S a := by + simpa only [cutExponent, partyExponent, ← Finset.attach_eq_univ] using + (Finset.sum_attach S fun i ↦ Finsupp.single (i, a i) (1 : ℕ)) + +/-- Matrix of one cut, including the factorization through a finite state index. -/ +structure CutFactors (S : Finset I) (B : Type*) (J k : Type*) where + /-- Left factor of the cut matrix, with one row per assignment of labels in `J` to the + parties of `S` and one column per state in `B`. -/ + left : Matrix (S → J) B k + /-- Right factor of the cut matrix, with one row per state in `B` and one column per + assignment of labels in `J` to the complementary parties. -/ + right : Matrix B (↥(Sᶜ : Finset I) → J) k + +/-- Matrix on assignments to the two sides of the cut, obtained by multiplying the factors and +summing over the shared state index `B`. -/ +noncomputable def CutFactors.matrix {S : Finset I} {B : Type*} [Fintype B] + (F : CutFactors S B J k) : Matrix (S → J) (↥(Sᶜ : Finset I) → J) k := + F.left * F.right + +theorem CutFactors.rank_le {S : Finset I} {B : Type*} [Fintype B] + (F : CutFactors S B J k) : F.matrix.rank ≤ Fintype.card B := + (Matrix.rank_mul_le_left F.left F.right).trans F.left.rank_le_card_width + +/-- The finite index of all balanced states, for a circuit on party-indexed variables. -/ +abbrev Circuit.BalancedStates (I J : Type*) [Fintype I] (s : ℕ) := + BalancedIndex (Fintype.card I) (Circuit.GrammarSlots (I × J) s) (Fintype.card I) + +theorem Circuit.card_balancedStates_le (I J : Type*) [Fintype I] [Fintype J] (s : ℕ) : + Fintype.card (Circuit.BalancedStates I J s) ≤ + Fintype.card I * (Fintype.card I * Fintype.card J + s + 1) := by + classical + simpa only [Fintype.card_prod, Fintype.card_fin, Circuit.card_grammarSlots] using + (Fintype.card_subtype_le + (fun u : Fin (Fintype.card I) × Circuit.GrammarSlots (I × J) s ↦ + Fintype.card I ≤ 3 * (u.1.val + 1) ∧ 3 * (u.1.val + 1) ≤ 2 * Fintype.card I)) + +/-- Every coefficient selecting one variable per party is the sum of factored +cut matrices. An unbalanced cut contributes the zero matrix, and each factorization +uses only the balanced graded states of the given circuit. -/ +theorem Circuit.exists_balanced_cutFactors (c : Circuit k (I × J) s) + (hI : 3 ≤ Fintype.card I) : + ∃ F : (S : Finset I) → CutFactors S (Circuit.BalancedStates I J s) J k, + (∀ a : I → J, c.polynomial.coeff (partyExponent Finset.univ a) = + ∑ S : Finset I, (F S).matrix (fun i ↦ a i.val) (fun i ↦ a i.val)) ∧ + (∀ S, ¬ (Fintype.card I ≤ 3 * S.card ∧ 3 * S.card ≤ 2 * Fintype.card I) → + (F S).matrix = 0) := by + classical + let ℓ := Fintype.card I + let d : Fin ℓ := ⟨ℓ - 1, by dsimp [ℓ]; omega⟩ + have hd : d.val + 1 = ℓ := by dsimp [d, ℓ]; omega + obtain ⟨G, hG⟩ := c.exists_parseGrammar ℓ + obtain ⟨m, hm⟩ := G.exists_balanced_expansion ℓ hI d none (by rw [hd]; omega) + let g (b : Circuit.BalancedStates I J s) := G.eval b.val.1 b.val.2 + let F (S : Finset I) : CutFactors S (Circuit.BalancedStates I J s) J k := + ⟨.of fun x b ↦ (g b).coeff (cutExponent S x), + .of fun b y ↦ (m b).coeff (cutExponent Sᶜ y)⟩ + refine ⟨F, ?_, ?_⟩ + · intro a + have hc := hG d + rw [hd] at hc + have hcoeff : (homogeneousComponent ℓ c.polynomial).coeff (partyExponent Finset.univ a) = + c.polynomial.coeff (partyExponent Finset.univ a) := by + simp only [coeff_homogeneousComponent, degree_partyExponent, Finset.card_univ, ℓ, ite_true] + rw [← hcoeff, ← hc, hm, coeff_sum] + simp_rw [mul_comm (m _) (G.eval _ _), coeff_mul_partyExponent] + rw [Finset.sum_comm] + refine Finset.sum_congr rfl fun S _ ↦ ?_ + simp only [F, CutFactors.matrix, Matrix.mul_apply, Matrix.of_apply, cutExponent_restrict, g] + rfl + · intro S hS + ext x y + change ∑ b, (g b).coeff (cutExponent S x) * (m b).coeff (cutExponent Sᶜ y) = 0 + apply Finset.sum_eq_zero + intro b _ + have hg := G.eval_isHomogeneous b.val.1 b.val.2 + have hdS : (cutExponent S x).degree = S.card := by + simp [cutExponent, Finsupp.degree_single] + have hn : S.card ≠ b.val.1.val + 1 := by + intro h + exact hS (h ▸ b.property) + rw [show (g b).coeff (cutExponent S x) = 0 from + IsWeightedHomogeneous.coeff_eq_zero hg _ (by + change Finsupp.weight (fun _ : I × J ↦ (1 : ℕ)) (cutExponent S x) ≠ _ + rwa [← Finsupp.degree_eq_weight_one, hdS]), + zero_mul] + +/-- Grouping by cut gives the balanced flattening-rank estimate of Theorem 4.2. -/ +theorem Circuit.exists_balanced_matrices (c : Circuit k (I × J) s) (hI : 3 ≤ Fintype.card I) : + ∃ M : (S : Finset I) → Matrix (S → J) (↥(Sᶜ : Finset I) → J) k, + (∀ a : I → J, c.polynomial.coeff (partyExponent Finset.univ a) = + ∑ S : Finset I, M S (fun i ↦ a i.val) (fun i ↦ a i.val)) ∧ + (∀ S, ¬ (Fintype.card I ≤ 3 * S.card ∧ 3 * S.card ≤ 2 * Fintype.card I) → M S = 0) ∧ + ∀ S, (M S).rank ≤ Fintype.card I * (Fintype.card I * Fintype.card J + s + 1) := by + classical + obtain ⟨F, hcoeff, hbal⟩ := c.exists_balanced_cutFactors hI + exact ⟨fun S ↦ (F S).matrix, hcoeff, hbal, + fun S ↦ (F S).rank_le.trans (card_balancedStates_le I J s)⟩ + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BalancedCoefficients.lean b/lean/OAI/Computability/VPVNP/BalancedCoefficients.lean new file mode 100644 index 0000000000..c56309041e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BalancedCoefficients.lean @@ -0,0 +1,77 @@ +import OAI.Computability.VPVNP.ParseCoefficients +import Mathlib.RingTheory.MvPolynomial.Homogeneous + +/-! +# Splitting a coefficient over a cut of the parties + +In §4 of *VP and VNP differ over every field*, a homogeneous product contributes +to the coefficient tensor through a sum of products across party cuts. Choosing one +variable at each party makes the queried monomial squarefree. The degree of the first +factor fixes the size of the first side of the cut. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open MvPolynomial + +variable {I J R : Type*} + +/-- Exponent vector selecting the variable `(i, a i)` for each party `i ∈ S`. -/ +noncomputable def partyExponent (S : Finset I) (a : I → J) : (I × J) →₀ ℕ := + ∑ i ∈ S, Finsupp.single (i, a i) 1 + +/-- An exponent on one side of the cut depends only on assignments on that side. -/ +theorem partyExponent_congr (S : Finset I) {a b : I → J} (h : ∀ i ∈ S, a i = b i) : + partyExponent S a = partyExponent S b := by + exact Finset.sum_congr rfl fun i hi ↦ by rw [h i hi] + +@[simp] theorem degree_partyExponent (S : Finset I) (a : I → J) : + (partyExponent S a).degree = S.card := by + simp [partyExponent, Finsupp.degree_single] + +variable [CommSemiring R] [Fintype I] [DecidableEq I] + +/-- Coefficient of a product on all parties, expressed as a sum over cuts of the +parties themselves. Each term uses the assignments on its respective sides. -/ +theorem coeff_mul_partyExponent (f g : MvPolynomial (I × J) R) (a : I → J) : + (f * g).coeff (partyExponent Finset.univ a) = + ∑ S : Finset I, f.coeff (partyExponent S a) * g.coeff (partyExponent Sᶜ a) := by + classical + let e : I ↪ I × J := ⟨fun i ↦ (i, a i), fun _ _ h ↦ congrArg Prod.fst h⟩ + have hdeg (S : Finset I) : partyExponent S a = squarefreeDegree (S.map e) := by + simp only [partyExponent, squarefreeDegree, Finset.sum_map] + rfl + have hsets : (Finset.univ.map e).powerset = Finset.univ.image (Finset.map e) := by + simp [Finset.map_eq_image, Finset.powerset_image] + congr 1 + funext S + exact (Finset.map_eq_image e S).symm + rw [hdeg, coeff_mul_squarefree, hsets, Finset.sum_image] + · refine Finset.sum_congr rfl fun S _ ↦ ?_ + rw [← Finset.map_sdiff, ← hdeg, ← hdeg] + rfl + · exact fun _ _ _ _ h ↦ Finset.map_injective e h + +/-- If the first factor is homogeneous of degree `d`, only cuts of size `d` +contribute. The product for each such cut is separated across its two sides. -/ +theorem coeff_mul_partyExponent_homogeneous (f g : MvPolynomial (I × J) R) {d : ℕ} + (hf : f.IsHomogeneous d) (a : I → J) : + (f * g).coeff (partyExponent Finset.univ a) = + ∑ S : Finset I with S.card = d, + f.coeff (partyExponent S a) * g.coeff (partyExponent Sᶜ a) := by + classical + rw [coeff_mul_partyExponent, Finset.sum_filter] + refine Finset.sum_congr rfl fun S _ ↦ ?_ + by_cases hS : S.card = d + · simp [hS] + · have hz : f.coeff (partyExponent S a) = 0 := by + apply IsWeightedHomogeneous.coeff_eq_zero hf + change Finsupp.weight (fun _ ↦ 1) (partyExponent S a) ≠ d + rwa [← Finsupp.degree_eq_weight_one, degree_partyExponent] + simp [hS, hz] + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BalancedGrammar.lean b/lean/OAI/Computability/VPVNP/BalancedGrammar.lean new file mode 100644 index 0000000000..b349ab2801 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BalancedGrammar.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.ParseGrammar +import OAI.Computability.VPVNP.GradedComponents +import Mathlib.RingTheory.Ideal.Operations + +/-! # Balanced degree factors of a graded circuit grammar + +Section 4.2 uses the ideal generated by states of degree between one third and +two thirds of the output degree. In a binary production above that interval, at +least one child reaches its lower endpoint. This expresses the output as a sum +of multiples of the balanced states. Homogeneous projection retains only the +complementary degree of each multiplier. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ParseGrammar + +open MvPolynomial + +variable {R V H : Type*} [CommSemiring R] [Fintype V] [Fintype H] {n : ℕ} + +/-- States whose declared degree lies in the balanced interval for `ℓ`. -/ +abbrev BalancedIndex (n : ℕ) (H : Type*) (ℓ : ℕ) := + {s : Fin n × H // ℓ ≤ 3 * (s.1.val + 1) ∧ 3 * (s.1.val + 1) ≤ 2 * ℓ} + +/-- The ideal generated by all balanced states. -/ +noncomputable def balancedIdeal (G : ParseGrammar R V H n) (ℓ : ℕ) : Ideal (MvPolynomial V R) := + Ideal.span (Set.range (fun s : BalancedIndex n H ℓ => G.eval s.val.1 s.val.2)) + +/-- A state at or above the lower endpoint of the interval belongs to the balanced ideal. -/ +theorem eval_mem_balancedIdeal (G : ParseGrammar R V H n) (ℓ : ℕ) (hℓ : 3 ≤ ℓ) + (d : Fin n) (h : H) (hdeg : ℓ ≤ 3 * (d.val + 1)) : G.eval d h ∈ G.balancedIdeal ℓ := by + induction d using (measure (fun d : Fin n => d.val)).wf.induction generalizing h with + | h d ih => + by_cases upper : 3 * (d.val + 1) ≤ 2 * ℓ + · exact Ideal.subset_span ⟨⟨(d, h), hdeg, upper⟩, rfl⟩ + · rw [G.eval_binary (by omega) h] + refine (G.balancedIdeal ℓ).sum_mem (fun b _ => (G.balancedIdeal ℓ).sum_mem + (fun i _ => (G.balancedIdeal ℓ).sum_mem (fun j _ => ?_))) + have sumDeg := split_degrees d b + by_cases left : ℓ ≤ 3 * ((leftDegree d b).val + 1) + · exact (G.balancedIdeal ℓ).mul_mem_right _ + ((G.balancedIdeal ℓ).mul_mem_left _ (ih _ (leftDegree_lt d b) i left)) + · exact (G.balancedIdeal ℓ).mul_mem_left _ (ih _ (rightDegree_lt d b) j (by omega)) + +/-- Explicit linear combination indexed by the balanced states, with polynomial coefficients. -/ +theorem exists_balanced_expansion (G : ParseGrammar R V H n) (ℓ : ℕ) (hℓ : 3 ≤ ℓ) + (d : Fin n) (h : H) (hdeg : ℓ ≤ 3 * (d.val + 1)) : + ∃ m : BalancedIndex n H ℓ → MvPolynomial V R, + G.eval d h = ∑ b, m b * G.eval b.val.1 b.val.2 := by + obtain ⟨m, hm⟩ := Ideal.mem_span_range_iff_exists_fun.mp (G.eval_mem_balancedIdeal ℓ hℓ d h hdeg) + exact ⟨m, hm.symm⟩ + +omit [Fintype V] in +private theorem component_mul_homogeneous {p q : MvPolynomial V R} {j t : ℕ} + (hq : q.IsHomogeneous j) (hjt : j ≤ t) : + homogeneousComponent t (p * q) = homogeneousComponent (t - j) p * q := by + classical + rw [homogeneousComponent_mul, Finset.sum_eq_single (t - j, j)] + · rw [homogeneousComponent_eq_self hq] + · rintro ⟨a, b⟩ hab hneq + have hs : a + b = t := Finset.mem_antidiagonal.mp hab + have hb : b ≠ j := by rintro rfl; apply hneq; congr 1; omega + simp [homogeneousComponent_of_mem hq, hb] + · intro hn + exact (hn (Finset.mem_antidiagonal.mpr (by simpa using Nat.sub_add_cancel hjt))).elim + +/-- Above the balanced interval, each multiplier may be taken homogeneous of +exactly the complementary degree. -/ +theorem exists_homogeneous_balanced_expansion (G : ParseGrammar R V H n) (ℓ : ℕ) (hℓ : 3 ≤ ℓ) + (d : Fin n) (h : H) (high : 2 * ℓ < 3 * (d.val + 1)) : + ∃ m : BalancedIndex n H ℓ → MvPolynomial V R, + (∀ b, (m b).IsHomogeneous (d.val + 1 - (b.val.1.val + 1))) ∧ + G.eval d h = ∑ b, m b * G.eval b.val.1 b.val.2 := by + obtain ⟨m, hm⟩ := G.exists_balanced_expansion ℓ hℓ d h (by omega) + refine ⟨fun b => homogeneousComponent (d.val + 1 - (b.val.1.val + 1)) (m b), + fun _ => homogeneousComponent_isHomogeneous _ _, ?_⟩ + calc + G.eval d h = homogeneousComponent (d.val + 1) (G.eval d h) := + (homogeneousComponent_eq_self (G.eval_isHomogeneous d h)).symm + _ = ∑ b, homogeneousComponent (d.val + 1) (m b * G.eval b.val.1 b.val.2) := by + rw [hm, map_sum] + _ = _ := by + refine Finset.sum_congr rfl fun b _ => component_mul_homogeneous (G.eval_isHomogeneous ..) ?_ + have := b.property.2 + omega + +end ParseGrammar + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BalancedGrowth.lean b/lean/OAI/Computability/VPVNP/BalancedGrowth.lean new file mode 100644 index 0000000000..8c62dbd7f7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BalancedGrowth.lean @@ -0,0 +1,56 @@ +import Mathlib.Analysis.SpecificLimits.Basic +import Mathlib.Analysis.SpecialFunctions.Pow.Real + +/-! # Comparing the exponential growth of finitely many balanced cuts + +In Section 4.2 each cut contributes a fixed multiplicative factor times an +exponential in the tensor-power index. Strictly smaller exponents make their +sum negligible compared with the lower bound for the full tensor power. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open Filter Topology + +variable {ι : Type*} + +/-- After division by the target power, the finite sum tends to zero. -/ +theorem tendsto_weighted_pow_ratio (cuts : Finset ι) (weight base : ι → ℝ) (target : ℝ) + (ht : 0 < target) (hb : ∀ i ∈ cuts, 0 ≤ base i ∧ base i < target) : + Tendsto (fun h : ℕ => (∑ i ∈ cuts, weight i * base i ^ h) / target ^ h) atTop (𝓝 0) := by + have hi (i : ι) (hic : i ∈ cuts) : + Tendsto (fun h : ℕ => weight i * (base i / target) ^ h) atTop (𝓝 0) := by + have lower := div_nonneg (hb i hic).1 ht.le + have upper : base i / target < 1 := (div_lt_one ht).mpr (hb i hic).2 + simpa using (tendsto_pow_atTop_nhds_zero_of_lt_one lower upper).const_mul (weight i) + simpa [div_eq_mul_inv, mul_pow, inv_pow, Finset.sum_mul, mul_assoc] using tendsto_finsetSum cuts hi + +/-- At every sufficiently large power the total cut contribution is less than any +fixed positive fraction of the target power. -/ +theorem eventually_weighted_pow_lt (cuts : Finset ι) (weight base : ι → ℝ) (target ε : ℝ) + (ht : 0 < target) (hε : 0 < ε) (hb : ∀ i ∈ cuts, 0 ≤ base i ∧ base i < target) : + ∀ᶠ h : ℕ in atTop, ∑ i ∈ cuts, weight i * base i ^ h < ε * target ^ h := by + filter_upwards [(tendsto_weighted_pow_ratio cuts weight base target ht hb).eventually_lt_const hε] + with h hlt using (div_lt_iff₀ (pow_pos ht h)).mp hlt + +/-- Strict comparison with the target, in terms of the spectral values themselves. -/ +theorem eventually_weighted_pow_lt_target (cuts : Finset ι) (weight base : ι → ℝ) (target : ℝ) + (ht : 0 < target) (hb : ∀ i ∈ cuts, 0 ≤ base i ∧ base i < target) : + ∀ᶠ h : ℕ in atTop, ∑ i ∈ cuts, weight i * base i ^ h < target ^ h := by + simpa only [one_mul] using eventually_weighted_pow_lt cuts weight base target 1 ht zero_lt_one hb + +/-- A fixed finite collection of cuts whose base-two exponents are all strictly +smaller than `L` cannot account for growth of `(2 ^ L) ^ h` at unbounded powers. -/ +theorem balancedGrowth_threshold (cuts : Finset ι) (weight exponent : ι → ℝ) (L : ℝ) + (gap : ∀ i ∈ cuts, exponent i < L) : + ∃ N : ℕ, ∀ h ≥ N, ∑ i ∈ cuts, weight i * ((2 : ℝ) ^ exponent i) ^ h < ((2 : ℝ) ^ L) ^ h := by + have h := eventually_weighted_pow_lt_target cuts weight (fun i => (2 : ℝ) ^ exponent i) + ((2 : ℝ) ^ L) (by positivity) (fun i hi => + ⟨by positivity, Real.rpow_lt_rpow_of_exponent_lt (by norm_num) (gap i hi)⟩) + exact eventually_atTop.mp h + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BalancedLayoutThreshold.lean b/lean/OAI/Computability/VPVNP/BalancedLayoutThreshold.lean new file mode 100644 index 0000000000..d35fa1fd3c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BalancedLayoutThreshold.lean @@ -0,0 +1,117 @@ +import OAI.Computability.VPVNP.BalancedWireLayout +import OAI.Computability.VPVNP.SpectralInterpolation +import Mathlib.Order.CountableDenseLinearOrder + +/-! +# A common strict threshold for balanced cube layouts + +Theorem 4.2 compares a single star witness with every balanced cut. The +extension places all subset centroids simultaneously. Its terminal wire lengths +and its bridge length can therefore be computed in one filled cube. Finiteness +of the cuts makes the strict savings uniform before the tensor is chosen. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace SpectralGeometry + +/-- Choose one positive saving below the unit-cube star length for every +balanced split of the same dimension, including at the dimension threshold. -/ +theorem balancedCut_uniformGap {n : ℕ} {C : ℝ} (hC : 1 ≤ C) (hdim : 18 * C^2 ≤ n) : + ∃ ε : ℝ, 0 < ε ∧ ∀ s : Finset (Fin n), n ≤ 3*s.card → 3*s.card ≤ 2*n → + C * √((s.card : ℝ)⁻¹ + (sᶜ.card : ℝ)⁻¹) + (starLength s.card + starLength sᶜ.card) < + starLength n - ε := by + classical + let cuts := Finset.univ.filter (fun s : Finset (Fin n) ↦ n ≤ 3*s.card ∧ 3*s.card ≤ 2*n) + let cost (s : Finset (Fin n)) := + C * √((s.card : ℝ)⁻¹ + (sᶜ.card : ℝ)⁻¹) + (starLength s.card + starLength sᶜ.card) + have hcost {s} (hs : s ∈ cuts) : cost s < starLength n := by + obtain ⟨hlo, hhi⟩ := (Finset.mem_filter.mp hs).2 + have h := balancedLayout_strict hC hdim s hlo hhi (basisCentroid n) + rw [subsetCentroid_star_length, subsetCentroid_star_length, + disjoint_subsetCentroids_dist disjoint_compl_right, basisCentroid_star_length] at h + simpa only [cost, starLength, add_comm (C * _) (_ + _)] using h + obtain ⟨t, hbelow, habove⟩ := Order.exists_between_finsets (cuts.image cost) {starLength n} (by + rintro _ hx y hy + obtain ⟨s, hs, rfl⟩ := Finset.mem_image.mp hx + rw [Finset.mem_singleton.mp hy] + exact hcost hs) + refine ⟨starLength n - t, sub_pos.mpr (habove _ (Finset.mem_singleton_self _)), ?_⟩ + intro s hlo hhi + rw [sub_sub_cancel] + exact hbelow _ (Finset.mem_image_of_mem cost (Finset.mem_filter.mpr ⟨Finset.mem_univ _, hlo, hhi⟩)) + +end SpectralGeometry + +namespace WireTensor.SpectralPoint + +open SpectralGeometry +open scoped symmDiff + +variable {k J : Type*} [Field k] [Fintype J] + +/-- The bridge and the sum of terminal distances in a spectral realization of +the two filled side centroids. The boolean side convention agrees with the +two-center circuit factorization. -/ +theorem centroid_wire_costs (F : SpectralPoint k J) {n : ℕ} (corner : Finset (Fin n) → J) + (c : Finset (Fin n) → J) {σ : ℝ} (hσ : 0 ≤ σ) + (hcorner : ∀ A B, F.wireDistance (corner A) (corner B)^2 = σ^2 * (A ∆ B).card) + {X : Type*} [MetricSpace X] (hc : HasCATZeroSegments X) (e : J → X) + (he : ∀ a b, dist (e a) (e b) = F.wireDistance a b) + (hcentroid : ∀ s, e (c s) = filledSubsetCentroid hc (e ∘ corner) s) + (s : Finset (Fin n)) : + F.wireDistance (c s) (c sᶜ) = σ * √((s.card : ℝ)⁻¹ + (sᶜ.card : ℝ)⁻¹) ∧ + (∑ i, F.wireDistance (corner {i}) (if cutSide s i then c sᶜ else c s)) = + σ * (starLength s.card + starLength sᶜ.card) := by + have hf (A B) : dist ((e ∘ corner) A) ((e ∘ corner) B)^2 = σ^2 * (A ∆ B).card := by + rw [Function.comp_apply, Function.comp_apply, he, hcorner] + have hsum (t : Finset (Fin n)) : + (∑ i ∈ t, F.wireDistance (corner {i}) (c t)) = σ * starLength t.card := by + simpa only [← he, hcentroid, Function.comp_apply, starLength] using + filledSubsetCentroid_star_length hc (e ∘ corner) hσ hf t + constructor + · rw [← he, hcentroid, hcentroid] + exact disjoint_filledSubsetCentroids_dist hc (e ∘ corner) hσ hf disjoint_compl_right + · rw [← s.sum_add_sum_compl, mul_add, ← hsum, ← hsum] + congr 1 + · exact Finset.sum_congr rfl fun i hi ↦ by simp [cutSide, hi] + · exact Finset.sum_congr rfl fun i hi ↦ by simp [cutSide, Finset.mem_compl.mp hi] + +variable {J : Type} [Fintype J] + +/-- Extend the marked cube to one spectrum with two centers for each cut, then +choose a threshold strictly between all balanced layouts and the star bound. +The same margin can be used to select the tensor witness in (4.4). -/ +theorem exists_cubeCentroid_layout_threshold (F : SpectralPoint k J) {n : ℕ} + (corner : Finset (Fin n) → J) {σ C : ℝ} (hσ : 0 < σ) + (hcorner : ∀ A B, F.wireDistance (corner A) (corner B)^2 = σ^2 * (A ∆ B).card) + (hC : 1 ≤ C) (hdim : 18 * C^2 ≤ n) + (embedding : ∀ S : ExtendedSpectrum F, ∃ (X : Type) (_ : MetricSpace X) + (_ : HasCATZeroSegments X) (e : S.Parties → X), + ∀ a b, dist (e a) (e b) = S.point.wireDistance a b) : + ∃ (S : ExtendedSpectrum F) (centers : Finset (Fin n) → Bool → S.Parties) (ε : ℝ), + 0 < ε ∧ ∀ s : Finset (Fin n), n ≤ 3*s.card → 3*s.card ≤ 2*n → + C * S.point.wireDistance (centers s false) (centers s true) + + ∑ i, S.point.wireDistance (S.old (corner {i})) (centers s (cutSide s i)) < + σ * (starLength n - ε) := by + obtain ⟨S, c, hcentroid⟩ := F.exists_cubeCentroid_extension corner + obtain ⟨X, hX, hc, e, he⟩ := embedding S + obtain ⟨ε, hε, hgap⟩ := balancedCut_uniformGap hC hdim + refine ⟨S, fun s b ↦ if b then c sᶜ else c s, ε, hε, fun s hlo hhi ↦ ?_⟩ + have hcube (A B) : S.point.wireDistance ((S.old ∘ corner) A) ((S.old ∘ corner) B)^2 = + σ^2 * (A ∆ B).card := by + rw [Function.comp_apply, Function.comp_apply, S.distances, hcorner] + obtain ⟨bridge, outer⟩ := S.point.centroid_wire_costs (S.old ∘ corner) c hσ.le hcube hc e he + (hcentroid X hc e he) s + change C * S.point.wireDistance (c s) (c sᶜ) + + (∑ i, S.point.wireDistance ((S.old ∘ corner) {i}) (if cutSide s i then c sᶜ else c s)) < _ + rw [bridge, outer, mul_left_comm C σ, ← mul_add] + exact mul_lt_mul_of_pos_left (hgap s hlo hhi) hσ + +end WireTensor.SpectralPoint + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BalancedPowerObstruction.lean b/lean/OAI/Computability/VPVNP/BalancedPowerObstruction.lean new file mode 100644 index 0000000000..0c71677d86 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BalancedPowerObstruction.lean @@ -0,0 +1,125 @@ +import OAI.Computability.VPVNP.BalancedWireLayout +import OAI.Computability.VPVNP.BalancedGrowth +import OAI.Computability.VPVNP.PlacedTensor + +/-! +# Tensor powers and the balanced-cut obstruction + +The tensor value of an `h`-fold power is the `h`th power of its initial value. +For a polynomial-size circuit, each balanced layout contributes at most a fixed +constant times its own exponential. If every layout has smaller growth than the +initial tensor, no circuit within the given size bound can compute the coefficients +at any sufficiently large power. This is the comparison at the end of Theorem 4.2. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open MvPolynomial WireTensor Filter + +variable {k : Type*} [Field k] {I J : Type} {P : Type*} + [Fintype I] [DecidableEq I] [Fintype J] [Fintype P] + +omit [DecidableEq I] in +private theorem bridge_dimension_bound {C K s h : ℕ} (hC : 0 < C) + (hq : 0 < Fintype.card J) (hs : s ≤ K * (Fintype.card J ^ h) ^ C) : + Fintype.card (Circuit.BalancedStates I (Fin h → J) s) ≤ + (Fintype.card I * (Fintype.card I + K + 1)) * (Fintype.card J ^ h) ^ C := by + calc + _ ≤ Fintype.card I * (Fintype.card I * Fintype.card J ^ h + s + 1) := by + simpa only [Fintype.card_fun, Fintype.card_fin] using + Circuit.card_balancedStates_le I (Fin h → J) s + _ ≤ Fintype.card I * + (Fintype.card I * (Fintype.card J ^ h)^C + K * (Fintype.card J ^ h)^C + + (Fintype.card J ^ h)^C) := by + apply Nat.mul_le_mul_left + apply Nat.add_le_add + · apply Nat.add_le_add _ hs + exact Nat.mul_le_mul_left _ (Nat.le_self_pow hC.ne' _) + · exact Nat.pow_pos (Nat.pow_pos hq) + _ = _ := by ring + +private theorem power_layout_cost (q M h C : ℕ) (hq : 0 < q) (bridge outer : ℝ) : + ((M * (q ^ h) ^ C : ℕ) : ℝ) ^ bridge * ((q ^ h : ℕ) : ℝ) ^ outer = + (M : ℝ) ^ bridge * ((q : ℝ) ^ ((C : ℝ) * bridge + outer)) ^ h := by + have hq' : 0 < (q : ℝ) := by exact_mod_cast hq + simp only [Nat.cast_mul, Nat.cast_pow, Real.mul_rpow (Nat.cast_nonneg _) (by positivity : 0 ≤ ((q : ℝ)^h)^C)] + rw [← Real.rpow_natCast_mul (by positivity : 0 ≤ (q : ℝ) ^ h), + ← Real.rpow_natCast_mul hq'.le, ← Real.rpow_natCast_mul hq'.le, + mul_assoc, ← Real.rpow_add hq', ← Real.rpow_mul_natCast hq'.le] + congr 2 + ring + +omit [DecidableEq I] in +/-- A placed tensor power has the spectral value of the original coefficient array +raised to the power `h`, with the local digit order explicit. -/ +theorem placed_array_power_value (F : SpectralPoint k P) (place : I → P) + (A : (I → J) → k) (h : ℕ) : + F.value (placedTensor place (fun _ ↦ Fin h → J) + (fun a ↦ ∏ t : Fin h, A (fun i ↦ a i t))) = + F.value (placedTensor place (fun _ ↦ J) A) ^ h := + F.value_placed_tensorPowerFin place h + (Tensor.mk (fun _ : I ↦ J) (fun _ ↦ inferInstance) A) + +/-- Finite spectral upper bound on one concrete power. The multiplicative budget +factor `K` remains explicit, so it can also be chosen polynomially in `h`. -/ +theorem spectral_power_bound (F : SpectralPoint k P) (place : I → P) + (centers : Finset I → Bool → P) (A : (I → J) → k) {C K h s : ℕ} + (hC : 0 < C) (hI : 3 ≤ Fintype.card I) (hJ : 0 < Fintype.card J) + (hs : s ≤ K * (Fintype.card J ^ h)^C) (c : Circuit k (I × (Fin h → J)) s) + (hc : ∀ a, c.polynomial.coeff (partyExponent Finset.univ a) = ∏ t : Fin h, A (fun i ↦ a i t)) : + (F.value (placedTensor place (fun _ ↦ J) A) : ℝ)^h ≤ + ∑ S : Finset I with Fintype.card I ≤ 3*S.card ∧ 3*S.card ≤ 2*Fintype.card I, + ((Fintype.card I * (Fintype.card I + K + 1) : ℕ) : ℝ) ^ + F.wireDistance (centers S false) (centers S true) * + ((Fintype.card J : ℝ) ^ ((C : ℝ)*F.wireDistance (centers S false) (centers S true) + + ∑ i, F.wireDistance (place i) (centers S (cutSide S i))))^h := by + classical + let M := Fintype.card I * (Fintype.card I + K + 1) + have hwidth := bridge_dimension_bound (I := I) hC hJ hs + have hM : 0 < M := by dsimp [M]; positivity + have ub := c.spectralValue_le_balanced_cost hI + (by simpa only [Fintype.card_fun, Fintype.card_fin] using Nat.pow_pos hJ (n := h)) + (Nat.mul_pos hM (Nat.pow_pos (Nat.pow_pos hJ))) hwidth F place centers + rw [funext hc, placed_array_power_value, NNReal.coe_pow] at ub + simp only [Fintype.card_fun, Fintype.card_fin] at ub + apply ub.trans_eq + refine Finset.sum_congr rfl fun S _ ↦ ?_ + exact power_layout_cost (Fintype.card J) M h C hJ _ _ + +/-- If every balanced two-center layout costs less than the tensor's spectral value, +all sufficiently large powers violate the indicated gate budget. Only the selected +formal coefficients of the circuit are prescribed. -/ +theorem eventually_no_balanced_power_circuit (F : SpectralPoint k P) (place : I → P) + (centers : Finset I → Bool → P) (A : (I → J) → k) (C K : ℕ) + (hC : 0 < C) (hI : 3 ≤ Fintype.card I) (hJ : 0 < Fintype.card J) + (hA : 0 < (F.value (placedTensor place (fun _ ↦ J) A) : ℝ)) + (hgap : ∀ S : Finset I, Fintype.card I ≤ 3 * S.card → 3 * S.card ≤ 2 * Fintype.card I → + (Fintype.card J : ℝ) ^ + ((C : ℝ) * F.wireDistance (centers S false) (centers S true) + + ∑ i, F.wireDistance (place i) (centers S (cutSide S i))) < + (F.value (placedTensor place (fun _ ↦ J) A) : ℝ)) : + ∃ N : ℕ, ∀ h ≥ N, ∀ s ≤ K * (Fintype.card J ^ h) ^ C, ∀ c : Circuit k (I × (Fin h → J)) s, + ¬ ∀ a, c.polynomial.coeff (partyExponent Finset.univ a) = ∏ t : Fin h, A (fun i ↦ a i t) := by + classical + let cuts := Finset.univ.filter + (fun S : Finset I ↦ Fintype.card I ≤ 3 * S.card ∧ 3 * S.card ≤ 2 * Fintype.card I) + let M := Fintype.card I * (Fintype.card I + K + 1) + let bridge (S : Finset I) := F.wireDistance (centers S false) (centers S true) + let outer (S : Finset I) := ∑ i, F.wireDistance (place i) (centers S (cutSide S i)) + let base (S : Finset I) := (Fintype.card J : ℝ) ^ ((C : ℝ) * bridge S + outer S) + let weight (S : Finset I) := (M : ℝ) ^ bridge S + let v := (F.value (placedTensor place (fun _ ↦ J) A) : ℝ) + have gap (S : Finset I) (hS : S ∈ cuts) : 0 ≤ base S ∧ base S < v := by + obtain ⟨lo, hi⟩ := (Finset.mem_filter.mp hS).2 + exact ⟨Real.rpow_nonneg (Nat.cast_nonneg _) _, hgap S lo hi⟩ + obtain ⟨N, hN⟩ := eventually_atTop.mp + (eventually_weighted_pow_lt cuts weight base v 1 hA zero_lt_one gap) + refine ⟨N, fun h hn s hs c hc ↦ ?_⟩ + have bound := spectral_power_bound F place centers A hC hI hJ hs c hc + exact (not_lt_of_ge bound) (by simpa only [one_mul] using hN h hn) + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BalancedWireLayout.lean b/lean/OAI/Computability/VPVNP/BalancedWireLayout.lean new file mode 100644 index 0000000000..2bfcbda263 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BalancedWireLayout.lean @@ -0,0 +1,117 @@ +import OAI.Computability.VPVNP.BalancedCircuit +import OAI.Computability.VPVNP.WireSpectrum + +/-! +# Spectral cost of the balanced circuit cuts + +Place the coefficient tensor of an arithmetic circuit at its terminal parties. Each +balanced cut can choose its own two centers. Local contraction of the explicit +factors at those centers realizes the corresponding term, giving the product of wire +values used in the upper bound (4.5). +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open MvPolynomial WireTensor +open scoped NNReal + +variable {k : Type*} [Field k] {I J B : Type} {P : Type*} + [Fintype I] [DecidableEq I] [Fintype J] [Fintype B] [Fintype P] + +/-- Terminals in `S` use the first center, and the rest use the second. -/ +def cutSide (S : Finset I) (i : I) : Bool := decide (i ∉ S) + +/-- Place each party `i` at `place i` and give each joint assignment the cut matrix entry +indexed by its restrictions to `S` and its complement. -/ +noncomputable def CutFactors.placed {S : Finset I} (F : CutFactors S B J k) (place : I → P) : + WireTensor.Tensor k P := + placedTensor place (fun _ ↦ J) fun a ↦ F.matrix (fun i ↦ a i.val) (fun i ↦ a i.val) + +/-- The term on this cut is a local restriction of the terminal and bridge wires. -/ +theorem CutFactors.wire_restricts {S : Finset I} (F : CutFactors S B J k) + (place : I → P) (center : Bool → P) : + Restricts (wireNetwork (cutSource place center) (cutTarget (cutSide S) center) + (cutBasis (fun _ ↦ J) B)) (F.placed place) := by + let L (a : (i : I) → cutSide S i = false → J) (z : B) := + F.left (fun i ↦ a i.val (by simp [cutSide, i.property])) z + let M (a : (i : I) → cutSide S i = true → J) (z : B) := + F.right z (fun i ↦ a i.val (by simpa only [cutSide, decide_eq_true_eq] using + (Finset.mem_compl.mp i.property))) + exact cutFactorization_restricts place (cutSide S) center (fun _ ↦ J) B L M + +theorem CutFactors.spectralValue_le {S : Finset I} (A : CutFactors S B J k) + (F : WireTensor.SpectralPoint k P) (place : I → P) (center : Bool → P) : + F.value (A.placed place) ≤ F.value (wire (center false) (center true) B) * + ∏ i, F.value (wire (place i) (center (cutSide S i)) J) := by + have h := F.monotone (A.wire_restricts place center) + rw [F.value_wireNetwork, Fintype.prod_option] at h + exact h + +/-- Spectral value of the full coefficient tensor, bounded by the wire networks of +the balanced terms only, each with independently chosen centers. -/ +theorem Circuit.spectralValue_le_balanced_wires {s : ℕ} (c : Circuit k (I × J) s) + (hI : 3 ≤ Fintype.card I) (F : WireTensor.SpectralPoint k P) (place : I → P) + (centers : Finset I → Bool → P) : + F.value (placedTensor place (fun _ ↦ J) + (fun a ↦ c.polynomial.coeff (partyExponent Finset.univ a))) ≤ + ∑ S : Finset I with Fintype.card I ≤ 3 * S.card ∧ 3 * S.card ≤ 2 * Fintype.card I, + F.value (wire (centers S false) (centers S true) (Circuit.BalancedStates I J s)) * + ∏ i, F.value (wire (place i) (centers S (cutSide S i)) J) := by + classical + obtain ⟨A, hcoeff, hbal⟩ := c.exists_balanced_cutFactors hI + let cuts := Finset.univ.filter + (fun S : Finset I ↦ Fintype.card I ≤ 3 * S.card ∧ 3 * S.card ≤ 2 * Fintype.card I) + let target := placedTensor place (fun _ ↦ J) + (fun a ↦ c.polynomial.coeff (partyExponent Finset.univ a)) + have hsum : target.coeff = ∑ S ∈ cuts, ((A S).placed place).coeff := by + funext u + let a (i : I) := u (place i) i rfl + change c.polynomial.coeff (partyExponent Finset.univ a) = _ + refine (hcoeff a).trans (Eq.trans ?_ (Finset.sum_apply u cuts + (fun S ↦ ((A S).placed place).coeff)).symm) + dsimp only [cuts] + rw [Finset.sum_filter] + refine Finset.sum_congr rfl fun S _ ↦ ?_ + by_cases hS : Fintype.card I ≤ 3 * S.card ∧ 3 * S.card ≤ 2 * Fintype.card I + · simp only [hS] + rfl + · simp [hS, hbal S hS] + have hs := F.value_sum_le (b := target.finiteBasis) cuts (fun S ↦ ((A S).placed place).coeff) + change F.value target ≤ _ + rw [show target = WireTensor.Tensor.mk target.Basis target.finiteBasis + (∑ S ∈ cuts, ((A S).placed place).coeff) from congrArg _ hsum] + calc + _ ≤ ∑ S ∈ cuts, F.value ((A S).placed place) := hs + _ ≤ _ := Finset.sum_le_sum fun S _ ↦ (A S).spectralValue_le F place (centers S) + +/-- Express the finite spectral estimate using the power law for each wire. Here +`r` is any numerical upper bound on the bridge dimension, and `q` is the terminal +dimension. The outer wire lengths add in the exponent of `q`. -/ +theorem Circuit.spectralValue_le_balanced_cost {s r : ℕ} (c : Circuit k (I × J) s) + (hI : 3 ≤ Fintype.card I) (hJ : 0 < Fintype.card J) (hr : 0 < r) + (hwidth : Fintype.card (Circuit.BalancedStates I J s) ≤ r) + (F : WireTensor.SpectralPoint k P) (place : I → P) (centers : Finset I → Bool → P) : + (F.value (placedTensor place (fun _ ↦ J) + (fun a ↦ c.polynomial.coeff (partyExponent Finset.univ a))) : ℝ) ≤ + ∑ S : Finset I with Fintype.card I ≤ 3 * S.card ∧ 3 * S.card ≤ 2 * Fintype.card I, + (r : ℝ) ^ F.wireDistance (centers S false) (centers S true) * + (Fintype.card J : ℝ) ^ (∑ i, F.wireDistance (place i) (centers S (cutSide S i))) := by + classical + have hb := NNReal.coe_le_coe.mpr (c.spectralValue_le_balanced_wires hI F place centers) + rw [NNReal.coe_sum] at hb + refine hb.trans (Finset.sum_le_sum fun S _ ↦ ?_) + rw [NNReal.coe_mul, NNReal.coe_prod, Real.rpow_sum_of_pos (by exact_mod_cast hJ)] + apply mul_le_mul + · rw [F.value_wire_equiv _ _ (Fintype.equivFin _), ← F.value_wire_eq_rpow _ _ hr] + exact F.wireDimension_monotone _ _ hwidth + · apply le_of_eq + refine Finset.prod_congr rfl fun i _ ↦ ?_ + rw [F.value_wire_equiv _ _ (Fintype.equivFin J), F.value_wire_eq_rpow _ _ hJ] + · exact Finset.prod_nonneg fun _ _ ↦ NNReal.coe_nonneg _ + · positivity + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/Barycenter.lean b/lean/OAI/Computability/VPVNP/Barycenter.lean new file mode 100644 index 0000000000..54041c28a2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/Barycenter.lean @@ -0,0 +1,124 @@ +import Mathlib.Topology.Instances.Real.Lemmas +import Mathlib.Topology.MetricSpace.Cauchy +import Mathlib.Topology.Order.IsLUB +import Mathlib.Tactic.FunProp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +/-! +# Barycenters in the spectral wire geometry + +Section 5.3 of *VP and VNP differ over every field* smooths a configuration by +taking barycenters along the rows of a stochastic matrix. In a complete space +satisfying the CAT(0) inequality (4.2), every finite probability distribution +admits a barycenter with the squared-distance variance bound used in that step. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace SpectralGeometry + +open Filter Topology + +/-- The squared-distance form (4.2) of the CAT(0) geodesic inequality. The +point at fraction `t` along `xy` satisfies the bound for every test point. -/ +def HasCATZeroSegments (X : Type*) [PseudoMetricSpace X] : Prop := + ∀ (x y : X) (t : ℝ), 0 ≤ t → t ≤ 1 → ∃ w : X, ∀ z : X, + dist z w ^ 2 ≤ (1 - t) * dist z x ^ 2 + t * dist z y ^ 2 - + t * (1 - t) * dist x y ^ 2 + +variable {ι X : Type*} [Fintype ι] [PseudoMetricSpace X] + +/-- The mean squared distance to a finite distribution of points. -/ +noncomputable def weightedSquaredDistance (mass : ι → ℝ) (points : ι → X) (z : X) : ℝ := + ∑ i, mass i * dist (points i) z ^ 2 + +private theorem energy_segment (h : HasCATZeroSegments X) (mass : ι → ℝ) + (points : ι → X) (hpos : ∀ i, 0 ≤ mass i) (hsum : ∑ i, mass i = 1) + (x y : X) (t : ℝ) (ht : 0 ≤ t) (ht' : t ≤ 1) : + ∃ w : X, weightedSquaredDistance mass points w ≤ + (1 - t) * weightedSquaredDistance mass points x + + t * weightedSquaredDistance mass points y - t * (1 - t) * dist x y ^ 2 := by + obtain ⟨w, hw⟩ := h x y t ht ht' + refine ⟨w, ?_⟩ + calc + _ ≤ ∑ i, ((1 - t) * (mass i * dist (points i) x ^ 2) + + t * (mass i * dist (points i) y ^ 2) - mass i * (t * (1 - t) * dist x y ^ 2)) := by + apply Finset.sum_le_sum + intro i _ + convert mul_le_mul_of_nonneg_left (hw (points i)) (hpos i) using 1 + ring + _ = _ := by + rw [Finset.sum_sub_distrib, Finset.sum_add_distrib, ← Finset.mul_sum, + ← Finset.mul_sum, ← Finset.sum_mul, hsum, one_mul] + rfl + +/-- Existence and the variance inequality from Section 5.3. At every test +point the energy exceeds its minimum by at least the squared displacement. -/ +theorem exists_barycenter_variance [CompleteSpace X] [Nonempty X] (h : HasCATZeroSegments X) + (mass : ι → ℝ) (points : ι → X) (hpos : ∀ i, 0 ≤ mass i) (hsum : ∑ i, mass i = 1) : + ∃ b : X, ∀ z : X, weightedSquaredDistance mass points b + dist b z ^ 2 ≤ + weightedSquaredDistance mass points z := by + let E := weightedSquaredDistance mass points + have hE : Continuous E := by unfold E weightedSquaredDistance; fun_prop + let m := sInf (Set.range E) + have hbdd : BddBelow (Set.range E) := by + refine ⟨0, ?_⟩ + rintro _ ⟨z, rfl⟩ + exact Finset.sum_nonneg (fun i _ => mul_nonneg (hpos i) (sq_nonneg _)) + have hlow (z : X) : m ≤ E z := csInf_le hbdd ⟨z, rfl⟩ + obtain ⟨a, _, ha, ha'⟩ := exists_seq_tendsto_sInf (Set.range_nonempty E) hbdd + choose u hu using ha' + have hcauchy : CauchySeq u := by + apply Metric.cauchySeq_iff.mpr + intro ε hε + have hnear : ∀ᶠ n in atTop, a n < m + ε ^ 2 / 4 := + ha.eventually_lt_const (by change m < m + ε ^ 2 / 4; linarith [sq_pos_of_pos hε]) + obtain ⟨N, hN⟩ := eventually_atTop.mp hnear + refine ⟨N, fun i hi j hj => ?_⟩ + obtain ⟨w, hw⟩ := energy_segment h mass points hpos hsum (u i) (u j) (1 / 2) + (by norm_num) (by norm_num) + change E w ≤ _ * E (u i) + _ * E (u j) - _ at hw + rw [hu i, hu j] at hw + apply (sq_lt_sq₀ dist_nonneg hε.le).mp + linarith only [hw, hlow w, hN i hi, hN j hj] + obtain ⟨b, hub⟩ := cauchySeq_tendsto_of_complete hcauchy + have huE : E ∘ u = a := funext hu + have hb : E b = m := tendsto_nhds_unique (hE.continuousAt.tendsto.comp hub) + (show Tendsto (E ∘ u) atTop (𝓝 m) by rw [huE]; exact ha) + refine ⟨b, fun z => ?_⟩ + change E b + dist b z ^ 2 ≤ E z + by_contra! hgap + obtain ⟨δ, hδ, hδ'⟩ := exists_pos_mul_lt (sub_pos.mpr hgap) (dist b z ^ 2) + let t := min δ 1 + have ht : 0 < t := lt_min hδ zero_lt_one + have hsmall : dist b z ^ 2 * t < E b + dist b z ^ 2 - E z := + (mul_le_mul_of_nonneg_left (min_le_left δ 1) (sq_nonneg _)).trans_lt hδ' + obtain ⟨w, hw⟩ := energy_segment h mass points hpos hsum b z t ht.le (min_le_right _ _) + change E w ≤ _ * E b + _ * E z - _ at hw + have hneg : E z - E b - (1 - t) * dist b z ^ 2 < 0 := by linarith only [hsmall] + have hbw : E b ≤ E w := hb.trans_le (hlow w) + nlinarith only [mul_neg_of_pos_of_neg ht hneg, hw, hbw] + +/-- In a metric space the barycenter satisfying the variance bound is unique. -/ +theorem existsUnique_barycenter_variance {Y : Type*} [MetricSpace Y] [CompleteSpace Y] + [Nonempty Y] (h : HasCATZeroSegments Y) (mass : ι → ℝ) (points : ι → Y) + (hpos : ∀ i, 0 ≤ mass i) (hsum : ∑ i, mass i = 1) : + ∃! b : Y, ∀ z : Y, weightedSquaredDistance mass points b + dist b z ^ 2 ≤ + weightedSquaredDistance mass points z := by + obtain ⟨b, hb⟩ := exists_barycenter_variance h mass points hpos hsum + refine ⟨b, hb, fun c hc => ?_⟩ + have hcb := hc b + rw [dist_comm c b] at hcb + apply dist_eq_zero.mp + rw [dist_comm c b] + nlinarith only [hcb, hb c, dist_nonneg (x := b) (y := c)] + +end SpectralGeometry + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BitSlotIndex.lean b/lean/OAI/Computability/VPVNP/BitSlotIndex.lean new file mode 100644 index 0000000000..cb260096a5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BitSlotIndex.lean @@ -0,0 +1,47 @@ +import OAI.Computability.VPVNP.SlotPacking +import Mathlib.Data.Fin.Tuple.Basic +import Mathlib.Logic.Equiv.Fin.Basic + +/-! +# Binary numbering of wire slots and tags + +The shrinking step in Appendix C of *VP and VNP differ over every field* +uses a fixed coordinate block to label a power-of-two set of slots. The +first coordinate is the most significant bit. Encoding and decoding recurse +on the tail, so the same numbering works for both slot and tag blocks. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +/-- Read a binary coordinate block in decreasing order of place value. -/ +def bitWordFinEquiv : (n : ℕ) → BitWord n ≃ Fin (2 ^ n) + | 0 => ⟨fun _ ↦ 0, fun _ i ↦ i.elim0, fun _ ↦ Subsingleton.elim _ _, + fun _ ↦ @Subsingleton.elim (Fin 1) _ _ _⟩ + | n + 1 => + (Fin.consEquiv (fun _ : Fin (n + 1) ↦ ZMod 2)).symm.trans + (((Equiv.refl (Fin 2)).prodCongr (bitWordFinEquiv n)).trans + (finProdFinEquiv.trans (finCongr (pow_succ' 2 n).symm))) + +/-- Encoding the head and tail as a single ordinary binary integer. -/ +theorem bitWordFinEquiv_val (n : ℕ) (w : BitWord (n + 1)) : + (bitWordFinEquiv (n + 1) w).val = + (bitWordFinEquiv n (Fin.tail w)).val + 2 ^ n * (w 0).val := rfl + +/-- Decoding the most significant coordinate divides by the tail's range. -/ +theorem bitWordFinEquiv_symm_head (n : ℕ) (i : Fin (2 ^ (n + 1))) : + ((bitWordFinEquiv (n + 1)).symm i 0).val = i.val / 2 ^ n := rfl + +/-- The remaining coordinates decode the residue modulo the size of the tail. -/ +theorem bitWordFinEquiv_symm_tail (n : ℕ) (i : Fin (2 ^ (n + 1))) : + Fin.tail ((bitWordFinEquiv (n + 1)).symm i) = + (bitWordFinEquiv n).symm ⟨i.val % 2 ^ n, Nat.mod_lt _ (Nat.two_pow_pos n)⟩ := rfl + +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BitSlotXor.lean b/lean/OAI/Computability/VPVNP/BitSlotXor.lean new file mode 100644 index 0000000000..7bacd21231 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BitSlotXor.lean @@ -0,0 +1,75 @@ +import OAI.Computability.VPVNP.BitSlotIndex +import OAI.Computability.VPVNP.RAMProgram + +/-! +# Binary tag arithmetic on the private RAM + +Appendix C's greedy tag assignment uses the additive group of binary vectors. +With the slot numbering of `BitSlotIndex`, vector addition is one native XOR +instruction, including when the tag occupies only the low bits of a RAM word. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +open VPVNP.BurstRAM VPVNP.BurstRAM.PrivateRAM + +private theorem xor_head_tail {n a b : ℕ} (ha : a < 2 ^ n) (hb : b < 2 ^ n) + (i j : ℕ) : + (a + 2 ^ n * i) ^^^ (b + 2 ^ n * j) = (a ^^^ b) + 2 ^ n * (i ^^^ j) := by + rw [← Nat.mod_add_div ((a + 2 ^ n * i) ^^^ (b + 2 ^ n * j)) (2 ^ n)] + simp only [Nat.xor_mod_two_pow, Nat.xor_div_two_pow, Nat.add_mul_mod_self_left, + Nat.add_mul_div_left _ _ (Nat.two_pow_pos n), Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hb, + Nat.div_eq_of_lt ha, Nat.div_eq_of_lt hb, zero_add] + +private theorem binary_digit_add (a b : ZMod 2) : (a + b).val = a.val ^^^ b.val := by + decide +revert + +/-- The binary numbering takes coordinatewise addition to XOR of the numbers. -/ +theorem bitWordFinEquiv_add_val {j : ℕ} (x y : BitWord j) : + (bitWordFinEquiv j (x + y)).val = (bitWordFinEquiv j x).val ^^^ (bitWordFinEquiv j y).val := by + induction j with + | zero => + change 0 = (0 : ℕ) ^^^ 0 + simp + | succ j ih => + rw [bitWordFinEquiv_val, bitWordFinEquiv_val j x, bitWordFinEquiv_val j y, + xor_head_tail (bitWordFinEquiv j (Fin.tail x)).isLt (bitWordFinEquiv j (Fin.tail y)).isLt] + change (bitWordFinEquiv j (Fin.tail x + Fin.tail y)).val + 2 ^ j * (x 0 + y 0).val = _ + rw [ih, binary_digit_add] + +variable {j w : ℕ} + +/-- Store a binary tag in the low bits of a RAM word, zero-extending its number. -/ +def tagWord (hw : j ≤ w) (x : BitWord j) : Word w := + Fin.castLE (Nat.pow_le_pow_right (by decide) hw) (bitWordFinEquiv j x) + +@[simp] theorem tagWord_val (hw : j ≤ w) (x : BitWord j) : + (tagWord hw x).val = (bitWordFinEquiv j x).val := rfl + +theorem tagWord_injective (hw : j ≤ w) : Function.Injective (tagWord hw) := + (Fin.castLE_injective _).comp (bitWordFinEquiv j).injective + +@[simp] theorem tagWord_zero (hw : j ≤ w) : tagWord hw 0 = 0 := by + apply Fin.ext + simpa using bitWordFinEquiv_add_val (0 : BitWord j) 0 + +@[simp] theorem tagWord_neg (hw : j ≤ w) (x : BitWord j) : tagWord hw (-x) = tagWord hw x := by + congr 1 + exact funext fun i ↦ CharTwo.neg_eq (x i) + +/-- Evaluating the native bitwise instruction computes tag addition exactly. -/ +@[simp] theorem tagWord_xor (hw : j ≤ w) (x y : BitWord j) : + BinaryOp.bitXor.eval (tagWord hw x) (tagWord hw y) = tagWord hw (x + y) := by + apply Fin.ext + simp only [BinaryOp.eval, Fin.val_ofNat, tagWord_val, bitWordFinEquiv_add_val] + exact Nat.mod_eq_of_lt (Nat.xor_lt_two_pow (tagWord hw x).isLt (tagWord hw y).isLt) + +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/BooleanTranscript.lean b/lean/OAI/Computability/VPVNP/BooleanTranscript.lean new file mode 100644 index 0000000000..b39c2df5b8 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/BooleanTranscript.lean @@ -0,0 +1,145 @@ +import OAI.Computability.VPVNP.Circuits +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Data.Fin.Tuple.Basic + +/-! +# Boolean gate transcripts + +Section 1.1 of *VP and VNP differ over every field* represents a deterministic +Boolean verifier by summing a product of local consistency tests over all gate +values. Each gate in the verifier may reuse any previously computed gate. On +Boolean inputs the product singles out its unique transcript over every field. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace BooleanTranscript + +variable {σ R S : Type*} {n : ℕ} + +/-- Encode a Boolean value by the corresponding ring element. -/ +def bit [Zero R] [One R] (b : Bool) : R := if b then 1 else 0 + +/-- Equality test on two Boolean-valued elements of a ring. -/ +def equalBit [CommRing R] (a b : R) : R := a * b + (1 - a) * (1 - b) + +theorem equalBit_bits [CommRing R] (a b : Bool) : + equalBit (bit a : R) (bit b) = if a = b then 1 else 0 := by + cases a <;> cases b <;> simp [equalBit, bit] + +/-- AND and NOT with topologically ordered references, a complete Boolean gate basis. -/ +inductive Gate (σ : Type*) (n : ℕ) where + | and (a b : Ref Bool σ n) + | not (a : Ref Bool σ n) + +/-- Compute the Boolean result of an AND or NOT gate from its referenced inputs and earlier +wires. -/ +def Gate.eval (input : σ → Bool) (wires : Fin n → Bool) : Gate σ n → Bool + | .and a b => a.read id input wires && b.read id input wires + | .not a => !(a.read id input wires) + +/-- Interpret AND as multiplication and NOT as subtraction from one in the coefficient ring. -/ +def Gate.arith [CommRing R] (input : σ → R) (wires : Fin n → R) : Gate σ n → R + | .and a b => a.read bit input wires * b.read bit input wires + | .not a => 1 - a.read bit input wires + +private theorem read_bits [CommRing R] (input : σ → Bool) (w : Fin n → Bool) (r : Ref Bool σ n) : + r.read (bit (R := R)) (bit ∘ input) (bit ∘ w) = bit (r.read id input w) := by + cases r <;> rfl + +theorem Gate.arith_bits [CommRing R] (input : σ → Bool) (w : Fin n → Bool) (g : Gate σ n) : + g.arith (bit ∘ input) (bit ∘ w) = (bit (g.eval input w) : R) := by + cases g with + | and a b => + simp only [Gate.arith, Gate.eval, read_bits] + cases a.read id input w <;> cases b.read id input w <;> simp [bit] + | not a => + simp only [Gate.arith, Gate.eval, read_bits] + cases a.read id input w <;> simp [bit] + +/-- A Boolean program built by adjoining one gate at a time. Each new gate can refer to all +preceding gates. -/ +inductive Program (σ : Type*) : ℕ → Type _ where + | nil : Program σ 0 + | snoc {n : ℕ} (p : Program σ n) (g : Gate σ n) : Program σ (n + 1) + +/-- The Boolean value at each gate after running the program on the given inputs. -/ +def Program.run (input : σ → Bool) : {n : ℕ} → Program σ n → Fin n → Bool + | _, .nil => Fin.elim0 + | _, .snoc p g => Fin.snoc (p.run input) (g.eval input (p.run input)) + +/-- Product of all gate tests, evaluated on a proposed transcript. -/ +def Program.check [CommRing R] (input : σ → R) : {n : ℕ} → Program σ n → (Fin n → R) → R + | _, .nil, _ => 1 + | k + 1, .snoc p g, w => + p.check input (Fin.init w) * equalBit (g.arith input (Fin.init w)) (w (Fin.last k)) + +/-- The gate tests have value one at the true transcript and zero at every other +Boolean transcript. This is an identity over any commutative ring. -/ +theorem Program.check_bits [CommRing R] (input : σ → Bool) (p : Program σ n) (w : Fin n → Bool) : + p.check (bit ∘ input) (bit ∘ w) = if w = p.run input then (1 : R) else 0 := by + induction p with + | nil => simp [Program.check, Subsingleton.elim w (Program.nil.run input)] + | @snoc k p g ih => + obtain ⟨⟨b, v⟩, rfl⟩ := (Fin.snocEquiv (fun _ : Fin (k + 1) => Bool)).surjective w + change (p.snoc g).check (bit ∘ input) (bit ∘ Fin.snoc v b) = + if Fin.snoc v b = (p.snoc g).run input then (1 : R) else 0 + simp only [Program.check, Program.run, ← Fin.comp_init, Fin.init_snoc, + Function.comp_apply, Fin.snoc_last, ih, Gate.arith_bits, equalBit_bits, Fin.snoc_inj] + by_cases h : v = p.run input + · subst v + simp [eq_comm] + · simp [h] + +/-- A Boolean program together with the reference whose bit is returned to the verifier. -/ +structure Circuit (σ : Type*) (n : ℕ) where + /-- The ordered gates whose computed bits form the transcript. -/ + program : Program σ n + /-- The input, Boolean constant, or gate bit chosen as the circuit's result. -/ + output : Ref Bool σ n + +/-- Evaluate the program on the Boolean input and read its designated output bit. -/ +def Circuit.eval (c : Circuit σ n) (input : σ → Bool) : Bool := + c.output.read id input (c.program.run input) + +/-- The transcript tests multiplied by the acceptance indicator. -/ +def Circuit.weight [CommRing R] (c : Circuit σ n) (input : σ → R) (w : Fin n → R) : R := + c.program.check input w * c.output.read bit input w + +/-- Summing over gate assignments recovers the Boolean verifier's answer. -/ +theorem Circuit.sum_weight_bits [CommRing R] (c : Circuit σ n) (input : σ → Bool) : + ∑ w : Fin n → Bool, c.weight (bit ∘ input) (bit ∘ w) = (bit (c.eval input) : R) := by + simp [Circuit.weight, Program.check_bits, ite_mul, read_bits, Circuit.eval] + +private theorem read_hom [CommRing R] [CommRing S] (f : R →+* S) (input : σ → R) + (w : Fin n → R) (r : Ref Bool σ n) : + f (r.read bit input w) = r.read bit (f ∘ input) (f ∘ w) := by + cases r with + | const b => cases b <;> simp [Ref.read, bit] + | var | gate => rfl + +private theorem Gate.arith_hom [CommRing R] [CommRing S] (f : R →+* S) (input : σ → R) + (w : Fin n → R) (g : Gate σ n) : + f (g.arith input w) = g.arith (f ∘ input) (f ∘ w) := by + cases g <;> simp [Gate.arith, read_hom] + +theorem Program.check_hom [CommRing R] [CommRing S] (f : R →+* S) (input : σ → R) + (p : Program σ n) (w : Fin n → R) : + f (p.check input w) = p.check (f ∘ input) (f ∘ w) := by + induction p with + | nil => simp [Program.check] + | snoc p g ih => simp [Program.check, equalBit, ih, Gate.arith_hom, Fin.comp_init] + +theorem Circuit.weight_hom [CommRing R] [CommRing S] (f : R →+* S) (c : Circuit σ n) + (input : σ → R) (w : Fin n → R) : + f (c.weight input w) = c.weight (f ∘ input) (f ∘ w) := by + simp [Circuit.weight, Program.check_hom, read_hom] + +end BooleanTranscript + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CATZeroEquality.lean b/lean/OAI/Computability/VPVNP/CATZeroEquality.lean new file mode 100644 index 0000000000..7885e23a41 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CATZeroEquality.lean @@ -0,0 +1,83 @@ +import OAI.Computability.VPVNP.CATZeroPoint + +/-! +# Equality in CAT(0) comparison along a segment + +The difference between the Euclidean comparison quadratic and the squared +distance to a fixed test point is a nonnegative concave function of the +segment parameter. Vanishing at an interior parameter forces it to vanish +along the entire segment. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace SpectralGeometry + +variable {X : Type*} [MetricSpace X] + +private theorem exists_fraction_through (s t : Set.Icc (0 : ℝ) 1) + (hs₀ : 0 < (s : ℝ)) (hs₁ : (s : ℝ) < 1) : + ∃ e u : Set.Icc (0 : ℝ) 1, (u : ℝ) < 1 ∧ catFraction t e u = s := by + by_cases hts : (t : ℝ) ≤ s + · have ht : 0 < 1 - (t : ℝ) := by linarith + let e : Set.Icc (0 : ℝ) 1 := ⟨1, zero_le_one, le_rfl⟩ + let u : Set.Icc (0 : ℝ) 1 := ⟨(s - (t : ℝ)) / (1 - t), + div_nonneg (sub_nonneg.mpr hts) ht.le, + (div_le_one ht).mpr (by linarith)⟩ + refine ⟨e, u, (div_lt_one ht).mpr (by linarith), Subtype.ext ?_⟩ + change (1 - ((s : ℝ) - t) / (1 - t)) * t + ((s : ℝ) - t) / (1 - t) * 1 = s + field_simp [ht.ne'] + ring + · have ht : 0 < (t : ℝ) := hs₀.trans (lt_of_not_ge hts) + let e : Set.Icc (0 : ℝ) 1 := ⟨0, le_rfl, zero_le_one⟩ + let u : Set.Icc (0 : ℝ) 1 := ⟨((t : ℝ) - s) / t, + div_nonneg (sub_nonneg.mpr (le_of_not_ge hts)) ht.le, + (div_le_one ht).mpr (by linarith)⟩ + refine ⟨e, u, (div_lt_one ht).mpr (by linarith), Subtype.ext ?_⟩ + change (1 - ((t : ℝ) - s) / t) * t + ((t : ℝ) - s) / t * 0 = s + field_simp [ht.ne'] + ring + +/-- If squared CAT(0) comparison with a fixed vertex is an equality at an +interior point of the opposite side, it is an equality at every point of that side. -/ +theorem catPoint_bound_eq_of_interior (h : HasCATZeroSegments X) (a b z : X) + (s : Set.Icc (0 : ℝ) 1) (hs₀ : 0 < (s : ℝ)) (hs₁ : (s : ℝ) < 1) + (hs : dist z (catPoint h a b s) ^ 2 = + (1 - (s : ℝ)) * dist z a ^ 2 + (s : ℝ) * dist z b ^ 2 - + (s : ℝ) * (1 - s) * dist a b ^ 2) + (t : Set.Icc (0 : ℝ) 1) : + dist z (catPoint h a b t) ^ 2 = + (1 - (t : ℝ)) * dist z a ^ 2 + (t : ℝ) * dist z b ^ 2 - + (t : ℝ) * (1 - t) * dist a b ^ 2 := by + let Q (r : ℝ) := (1 - r) * dist z a ^ 2 + r * dist z b ^ 2 - + r * (1 - r) * dist a b ^ 2 + let deficit (r : Set.Icc (0 : ℝ) 1) := Q r - dist z (catPoint h a b r) ^ 2 + have nonneg (r : Set.Icc (0 : ℝ) 1) : 0 ≤ deficit r := + sub_nonneg.mpr (catPoint_bound h a b r z) + obtain ⟨e, u, hu, he⟩ := exists_fraction_through s t hs₀ hs₁ + have hseg := catPoint_bound h (catPoint h a b t) (catPoint h a b e) u z + rw [catPoint_subsegment, dist_catPoint_catPoint, mul_pow, sq_abs] at hseg + have hquadratic : Q (catFraction t e u) = + (1 - (u : ℝ)) * Q t + (u : ℝ) * Q e - + (u : ℝ) * (1 - u) * (((t : ℝ) - e) ^ 2 * dist a b ^ 2) := by + dsimp [Q, catFraction] + ring + have hconc : (1 - (u : ℝ)) * deficit t + (u : ℝ) * deficit e ≤ deficit s := by + rw [← he] + dsimp only [deficit] + rw [hquadratic] + linarith only [hseg] + have hs' : deficit s = 0 := sub_eq_zero.mpr hs.symm + rw [hs'] at hconc + have ht : deficit t ≤ 0 := by + apply nonpos_of_mul_nonpos_right _ (sub_pos.mpr hu) + linarith only [hconc, mul_nonneg u.property.1 (nonneg e)] + exact (sub_eq_zero.mp (le_antisymm ht (nonneg t))).symm + +end SpectralGeometry + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CATZeroPoint.lean b/lean/OAI/Computability/VPVNP/CATZeroPoint.lean new file mode 100644 index 0000000000..c2f2ae30fe --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CATZeroPoint.lean @@ -0,0 +1,127 @@ +import OAI.Computability.VPVNP.Barycenter +import Mathlib.Topology.UnitInterval + +/-! # Fractional points of CAT(0) segments + +The squared-distance comparison of (4.2) determines the point at each +fraction of a segment. These points have constant speed and interpolation +on a subsegment agrees with interpolation on the full segment. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace SpectralGeometry + +open scoped unitInterval + +variable {X : Type*} [MetricSpace X] + +/-- The point at fraction `t` on the segment from `a` to `b`. -/ +noncomputable def catPoint (h : HasCATZeroSegments X) (a b : X) (t : I) : X := + (h a b t t.property.1 t.property.2).choose + +theorem catPoint_bound (h : HasCATZeroSegments X) (a b : X) (t : I) (z : X) : + dist z (catPoint h a b t) ^ 2 ≤ (1 - (t : ℝ)) * dist z a ^ 2 + t * dist z b ^ 2 - + t * (1 - t) * dist a b ^ 2 := + (h a b t t.property.1 t.property.2).choose_spec z + +private theorem catPoint_endpoints (h : HasCATZeroSegments X) (a b : X) (t : I) : + dist a (catPoint h a b t) = (t : ℝ) * dist a b ∧ + dist b (catPoint h a b t) = (1 - (t : ℝ)) * dist a b := by + let x := catPoint h a b t + have h₁ : dist a x ≤ (t : ℝ) * dist a b := by + apply (sq_le_sq₀ dist_nonneg (mul_nonneg t.property.1 dist_nonneg)).mp + have hab := catPoint_bound h a b t a + simp only [dist_self, zero_pow (by decide : 2 ≠ 0), mul_zero, zero_add] at hab + dsimp [x] + linarith only [hab] + have h₂ : dist b x ≤ (1 - (t : ℝ)) * dist a b := by + apply (sq_le_sq₀ dist_nonneg (mul_nonneg (sub_nonneg.mpr t.property.2) dist_nonneg)).mp + have hab := catPoint_bound h a b t b + simp only [dist_self, dist_comm b a, zero_pow (by decide : 2 ≠ 0), mul_zero, add_zero] at hab + dsimp [x] + linarith only [hab] + have h₃ := dist_triangle a x b + rw [dist_comm x b] at h₃ + change dist a x = _ ∧ dist b x = _ + constructor <;> linarith only [h₁, h₂, h₃] + +/-- Distance to the initial endpoint. -/ +theorem dist_left_catPoint (h : HasCATZeroSegments X) (a b : X) (t : I) : + dist a (catPoint h a b t) = (t : ℝ) * dist a b := + (catPoint_endpoints h a b t).1 + +/-- Distance to the final endpoint. -/ +theorem dist_right_catPoint (h : HasCATZeroSegments X) (a b : X) (t : I) : + dist b (catPoint h a b t) = (1 - (t : ℝ)) * dist a b := + (catPoint_endpoints h a b t).2 + +@[simp] theorem catPoint_zero (h : HasCATZeroSegments X) (a b : X) : + catPoint h a b 0 = a := by + symm + exact dist_eq_zero.mp (by + simpa only [Set.Icc.coe_zero, zero_mul] using dist_left_catPoint h a b 0) + +@[simp] theorem catPoint_one (h : HasCATZeroSegments X) (a b : X) : + catPoint h a b 1 = b := by + symm + exact dist_eq_zero.mp (by + simpa only [Set.Icc.coe_one, sub_self, zero_mul] using dist_right_catPoint h a b 1) + +/-- Endpoint distances characterize a fractional point uniquely. -/ +theorem catPoint_unique (h : HasCATZeroSegments X) (a b : X) (t : I) (z : X) + (ha : dist z a = (t : ℝ) * dist a b) (hb : dist z b = (1 - (t : ℝ)) * dist a b) : + z = catPoint h a b t := by + have hd := catPoint_bound h a b t z + rw [ha, hb] at hd + apply dist_eq_zero.mp + nlinarith only [hd, dist_nonneg (x := z) (y := catPoint h a b t)] + +/-- Constant speed along a CAT(0) segment. -/ +theorem dist_catPoint_catPoint (h : HasCATZeroSegments X) (a b : X) (s t : I) : + dist (catPoint h a b s) (catPoint h a b t) = |(s : ℝ) - t| * dist a b := by + apply le_antisymm + · apply (sq_le_sq₀ dist_nonneg (mul_nonneg (abs_nonneg _) dist_nonneg)).mp + have hd := catPoint_bound h a b t (catPoint h a b s) + rw [dist_comm _ a, dist_comm _ b, dist_left_catPoint, dist_right_catPoint] at hd + rw [mul_pow, sq_abs] + linarith only [hd] + · have hd := abs_dist_sub_le (catPoint h a b s) (catPoint h a b t) a + rw [dist_comm _ a, dist_comm _ a, dist_left_catPoint, dist_left_catPoint, ← sub_mul, + abs_mul, abs_of_nonneg dist_nonneg] at hd + exact hd + +/-- Fraction obtained by taking a fraction `u` of the way from `s` to `t`. -/ +def catFraction (s t u : I) : I := + ⟨(1 - (u : ℝ)) * s + u * t, by + constructor + · exact add_nonneg (mul_nonneg (sub_nonneg.mpr u.property.2) s.property.1) + (mul_nonneg u.property.1 t.property.1) + · have hs := mul_le_mul_of_nonneg_left s.property.2 (sub_nonneg.mpr u.property.2) + have ht := mul_le_mul_of_nonneg_left t.property.2 u.property.1 + linarith⟩ + +/-- A segment between two fractional points follows the original segment, including when +the two fractions are in decreasing order. -/ +theorem catPoint_subsegment (h : HasCATZeroSegments X) (a b : X) (s t u : I) : + catPoint h (catPoint h a b s) (catPoint h a b t) u = catPoint h a b (catFraction s t u) := by + symm + apply catPoint_unique + · rw [dist_catPoint_catPoint, dist_catPoint_catPoint] + have hfrac : (catFraction s t u : ℝ) - s = (u : ℝ) * ((t : ℝ) - s) := by + change (1 - (u : ℝ)) * s + u * t - s = _ + ring + rw [hfrac, abs_mul, abs_of_nonneg u.property.1, abs_sub_comm (t : ℝ) s, mul_assoc] + · rw [dist_catPoint_catPoint, dist_catPoint_catPoint] + have hfrac : (catFraction s t u : ℝ) - t = (1 - (u : ℝ)) * ((s : ℝ) - t) := by + change (1 - (u : ℝ)) * s + u * t - t = _ + ring + rw [hfrac, abs_mul, abs_of_nonneg (sub_nonneg.mpr u.property.2), mul_assoc] + +end SpectralGeometry + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CNFNormalization.lean b/lean/OAI/Computability/VPVNP/CNFNormalization.lean new file mode 100644 index 0000000000..cb7377b683 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CNFNormalization.lean @@ -0,0 +1,63 @@ +import OAI.Computability.VPVNP.ExactOneOccurrences +import OAI.Computability.VPVNP.HardnessWeights + +/-! +# Bounding the number of clauses by the number of literals + +A single empty clause rejects every assignment. Replacing an inconsistent +formula containing an empty clause by that clause alone controls its clause +count even when the input length bound counts only literal occurrences. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace HardnessCNF + +variable {k : ℕ} + +/-- Keep a single empty clause when the input contains one. -/ +def normalizeClauses (φ : CNF k) : CNF k := + if [] ∈ φ then [[]] else φ + +@[simp] theorem satisfies_normalizeClauses (φ : CNF k) (x : Fin k → Bool) : + Satisfies (normalizeClauses φ) x ↔ Satisfies φ x := by + by_cases h : [] ∈ φ + · have hfalse : ¬ Satisfies φ x := fun hs => by simpa using hs [] h + rw [iff_false_intro hfalse, normalizeClauses, ite_eq_left h] + simp [Satisfies] + · simp [normalizeClauses, h] + +@[simp] theorem weightedCNF_normalizeClauses {R : Type*} [CommSemiring R] (φ : CNF k) + (w : Fin k → R) : weightedCNF (normalizeClauses φ) w = weightedCNF φ w := by + apply Finset.sum_congr rfl + intro x _ + by_cases hx : Satisfies φ x + · rw [ite_eq_left ((satisfies_normalizeClauses φ x).mpr hx), ite_eq_left hx] + · rw [ite_eq_right (fun h => hx ((satisfies_normalizeClauses φ x).mp h)), ite_eq_right hx] + +theorem literalCount_normalizeClauses_le (φ : CNF k) : + literalCount (normalizeClauses φ) ≤ literalCount φ := by + by_cases h : [] ∈ φ <;> simp [normalizeClauses, h, literalCount] + +theorem length_normalizeClauses_le (φ : CNF k) : + (normalizeClauses φ).length ≤ literalCount φ + 1 := by + by_cases h : [] ∈ φ + · simp [normalizeClauses, h] + · simpa [normalizeClauses, h] using (ExactOne.length_le_literalCount_of_nil_notMem h).trans (Nat.le_succ _) + +/-- For a family bounded in literal occurrences, both normalized size measures +are polynomially bounded. -/ +theorem normalizeClauses_polynomial_bounds {k : ℕ → ℕ} (φ : ∀ n, CNF (k n)) + (h : PolynomiallyBounded fun n => literalCount (φ n)) : + PolynomiallyBounded (fun n => literalCount (normalizeClauses (φ n))) ∧ + PolynomiallyBounded (fun n => (normalizeClauses (φ n)).length) := + ⟨h.of_le (fun n => literalCount_normalizeClauses_le (φ n)), + (h.add (.const 1)).of_le (fun n => length_normalizeClauses_le (φ n))⟩ + +end HardnessCNF + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CertificateReduction.lean b/lean/OAI/Computability/VPVNP/CertificateReduction.lean new file mode 100644 index 0000000000..4770082d06 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CertificateReduction.lean @@ -0,0 +1,210 @@ +import OAI.Computability.VPVNP.GreedyBasis +import OAI.Computability.VPVNP.RankMinors +import OAI.Computability.VPVNP.SmallPrime +import Mathlib.Algebra.Field.ZMod +import Mathlib.LinearAlgebra.Matrix.AbsoluteValue + +/-! +# Reduction of the bounded certificate matrix to prime characteristic + +Section 8.2 of *VP and VNP differ over every field* uses an integer matrix of +coefficient rows and the target row for the constant polynomial one. When the +target raises the rational rank, every prime avoiding a fixed nonzero maximal +minor of the augmented matrix preserves nonmembership in the row span. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CertificateReduction + +open Set VPVNP.Crossing VPVNP.RankQuery + +variable {n m q : ℕ} + +private theorem exists_nonzero_minor {K : Type*} [Field K] (M : Matrix (Fin n) (Fin m) K) : + ∃ I J, compound M.rank M I J ≠ 0 := by + obtain ⟨I, hI, _⟩ := exists_isolatedBasis K M.row M.rank_eq_finrank_span_row + obtain ⟨J, hJ, _⟩ := exists_isolatedBasis K M.col M.rank_eq_finrank_span_cols + exact ⟨I, J, (compound_ne_zero_iff M rfl I J).mpr ⟨hI, hJ⟩⟩ + +/-- An integer coefficient matrix over a specified ring. -/ +abbrev castMatrix (R : Type*) [CommRing R] (M : Matrix (Fin n) (Fin m) ℤ) := + M.map (Int.castRingHom R) + +/-- Add the target coefficient row to the matrix of candidate certificates. -/ +def augment {R : Type*} (M : Matrix (Fin n) (Fin m) R) (v : Fin m → R) : + Matrix (Fin (n + 1)) (Fin m) R := Fin.cons v M + +theorem cast_compound (R : Type*) [CommRing R] (M : Matrix (Fin n) (Fin m) ℤ) + (I : powersetCard (Fin n) q) (J : powersetCard (Fin m) q) : + compound q (castMatrix R M) I J = (compound q M I J : ℤ) := by + exact ((Int.castRingHom R).map_det _).symm + +private theorem order_le_rank_of_minor {K : Type*} [Field K] (M : Matrix (Fin n) (Fin m) K) + (I : powersetCard (Fin n) q) (J : powersetCard (Fin m) q) (h : compound q M I J ≠ 0) : + q ≤ M.rank := le_of_not_gt (fun hlt => h (compound_eq_zero_of_rank_lt M hlt I J)) + +/-- Reduction of an integer matrix modulo a prime cannot increase its rational rank. -/ +theorem rank_mod_le_rat (M : Matrix (Fin n) (Fin m) ℤ) (p : ℕ) [Fact p.Prime] : + (castMatrix (ZMod p) M).rank ≤ (castMatrix ℚ M).rank := by + by_contra! hlt + obtain ⟨I, J, hIJ⟩ := exists_nonzero_minor (castMatrix (ZMod p) M) + have hz := compound_eq_zero_of_rank_lt (castMatrix ℚ M) hlt I J + rw [cast_compound] at hz hIJ + have hint : compound _ M I J = 0 := by exact_mod_cast hz + exact hIJ (by rw [hint, Int.cast_zero]) + +private theorem cast_augment (R : Type*) [CommRing R] (M : Matrix (Fin n) (Fin m) ℤ) + (v : Fin m → ℤ) : + castMatrix R (augment M v) = augment (castMatrix R M) (fun j => (v j : R)) := by + ext i j + refine Fin.cases ?_ (fun i => ?_) i <;> rfl + +/-- A target is outside the row span precisely when adding it raises rank. -/ +theorem rank_lt_augment_iff {K : Type*} [Field K] (M : Matrix (Fin n) (Fin m) K) + (v : Fin m → K) : + M.rank < (augment M v).rank ↔ v ∉ Submodule.span K (range M.row) := by + have hr : range (augment M v).row = insert v (range M.row) := by + ext w + constructor + · rintro ⟨i, rfl⟩ + exact Fin.cases (.inl rfl) (fun k => .inr ⟨k, rfl⟩) i + · rintro (rfl | ⟨i, rfl⟩) + · exact ⟨0, rfl⟩ + · exact ⟨i.succ, rfl⟩ + rw [Matrix.rank_eq_finrank_span_row, Matrix.rank_eq_finrank_span_row, hr] + constructor + · intro hlt hv + rw [Submodule.span_insert_eq_span hv] at hlt + exact hlt.false + · intro hv + apply Submodule.finrank_lt_finrank_of_lt + refine lt_of_le_of_ne (Submodule.span_mono (subset_insert _ _)) (fun he => hv ?_) + rw [he] + exact Submodule.subset_span (mem_insert _ _) + +/-- The explicit good-prime test. A nonvanishing augmented minor whose order +exceeds the original rational rank obstructs row-span membership modulo `p`. -/ +theorem notMem_rowSpan_of_not_dvd_minor (M : Matrix (Fin n) (Fin m) ℤ) (v : Fin m → ℤ) + (hq : (castMatrix ℚ M).rank < q) (I : powersetCard (Fin (n + 1)) q) + (J : powersetCard (Fin m) q) (p : ℕ) [Fact p.Prime] + (hp : ¬ (p : ℤ) ∣ compound q (augment M v) I J) : + (fun j => (v j : ZMod p)) ∉ Submodule.span (ZMod p) (range (castMatrix (ZMod p) M).row) := by + intro hmem + have hn : compound q (castMatrix (ZMod p) (augment M v)) I J ≠ 0 := by + rw [cast_compound] + exact fun h => hp ((ZMod.intCast_zmod_eq_zero_iff_dvd _ _).mp h) + have hle := order_le_rank_of_minor _ I J hn + rw [cast_augment] at hle + exact (rank_lt_augment_iff _ _).mp (((rank_mod_le_rat M p).trans_lt hq).trans_le hle) hmem + +/-- The permutation expansion bounds an integer minor of order `q` by +`q! * L^q` when all entries have absolute value at most `L`. -/ +theorem natAbs_compound_le (M : Matrix (Fin n) (Fin m) ℤ) (L : ℕ) + (hL : ∀ i j, (M i j).natAbs ≤ L) (I : powersetCard (Fin n) q) + (J : powersetCard (Fin m) q) : + (compound q M I J).natAbs ≤ q.factorial * L ^ q := by + let N := M.submatrix (powersetCard.ofFinEmbEquiv.symm I) (powersetCard.ofFinEmbEquiv.symm J) + have hn (i j : Fin q) : AbsoluteValue.abs (N i j) ≤ (L : ℤ) := by + rw [AbsoluteValue.abs_apply, Int.abs_eq_natAbs] + exact_mod_cast hL _ _ + have h := Matrix.det_le hn + simp only [AbsoluteValue.abs_apply, Int.abs_eq_natAbs, Fintype.card_fin, nsmul_eq_mul] at h + change N.det.natAbs ≤ q.factorial * L ^ q + exact_mod_cast h + +/-- With at most `2^a` columns and entries bounded by `2^b`, a prime of at +most `2 * (a + clog 2 (a+b+2)) + 2` bits preserves the obstruction. +No restriction on the number of rows is needed. -/ +theorem exists_bounded_good_prime (M : Matrix (Fin n) (Fin m) ℤ) (v : Fin m → ℤ) + (a b : ℕ) (hm : m ≤ 2 ^ a) (hentry : ∀ i j, (augment M v i j).natAbs ≤ 2 ^ b) + (h : (castMatrix ℚ M).rank < (castMatrix ℚ (augment M v)).rank) : + ∃ p : ℕ, p.Prime ∧ p ≤ 2 ^ (2 * (a + Nat.clog 2 (a + b + 2)) + 1) ∧ + (fun j => (v j : ZMod p)) ∉ Submodule.span (ZMod p) (range (castMatrix (ZMod p) M).row) := by + let q := (castMatrix ℚ (augment M v)).rank + have hq : q ≤ 2 ^ a := (by simpa [q] using (castMatrix ℚ (augment M v)).rank_le_card_width : + q ≤ m).trans hm + obtain ⟨I, J, hn⟩ := exists_nonzero_minor (castMatrix ℚ (augment M v)) + let D := compound q (augment M v) I J + have hD : D ≠ 0 := by + intro hz + apply hn + rw [cast_compound] + change (D : ℚ) = 0 + rw [hz, Int.cast_zero] + have hsize : D.natAbs ≤ 2 ^ ((a + b) * q) := calc + D.natAbs ≤ q.factorial * (2 ^ b) ^ q := natAbs_compound_le _ _ hentry I J + _ ≤ (2 ^ a) ^ q * (2 ^ b) ^ q := Nat.mul_le_mul_right _ + (q.factorial_le_pow.trans (Nat.pow_le_pow_left hq q)) + _ = 2 ^ ((a + b) * q) := by rw [← mul_pow, ← pow_add, pow_mul] + obtain ⟨p, prime, hp, hndvd⟩ := exists_small_prime_not_dvd_int hD hsize + let : Fact p.Prime := ⟨prime⟩ + refine ⟨p, prime, hp.trans ?_, notMem_rowSpan_of_not_dvd_minor M v h I J p hndvd⟩ + have hbase : (a + b) * q + 2 ≤ 2 ^ (a + Nat.clog 2 (a + b + 2)) := calc + (a + b) * q + 2 ≤ (a + b) * 2 ^ a + 2 := Nat.add_le_add_right (Nat.mul_le_mul_left _ hq) 2 + _ ≤ (a + b + 2) * 2 ^ a := by + rw [Nat.add_mul (a + b) 2]; exact Nat.add_le_add_left (Nat.le_mul_of_pos_right 2 (by positivity)) _ + _ ≤ 2 ^ Nat.clog 2 (a + b + 2) * 2 ^ a := + Nat.mul_le_mul_right _ (Nat.le_pow_clog (by decide) _) + _ = _ := by rw [← pow_add, Nat.add_comm] + calc + 2 * ((a + b) * q + 2) ^ 2 ≤ 2 * (2 ^ (a + Nat.clog 2 (a + b + 2))) ^ 2 := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hbase 2) + _ = _ := by rw [← pow_mul, Nat.mul_comm (a + _), pow_succ, Nat.mul_comm] + +/-- Every rational rank-raising target remains outside the certificate row span +in some prime characteristic. -/ +theorem exists_good_prime (M : Matrix (Fin n) (Fin m) ℤ) (v : Fin m → ℤ) + (h : (castMatrix ℚ M).rank < (castMatrix ℚ (augment M v)).rank) : + ∃ p : ℕ, p.Prime ∧ (fun j => (v j : ZMod p)) ∉ + Submodule.span (ZMod p) (range (castMatrix (ZMod p) M).row) := by + let b := Finset.univ.sup (fun ij : Fin (n + 1) × Fin m => (augment M v ij.1 ij.2).natAbs) + have hb (i : Fin (n + 1)) (j : Fin m) : (augment M v i j).natAbs ≤ 2 ^ b := + (Finset.le_sup (f := fun ij : Fin (n + 1) × Fin m => (augment M v ij.1 ij.2).natAbs) + (Finset.mem_univ (i, j))).trans Nat.lt_two_pow_self.le + obtain ⟨p, hp, _, hspan⟩ := exists_bounded_good_prime M v m b Nat.lt_two_pow_self.le hb h + exact ⟨p, hp, hspan⟩ + +private theorem row_mem_reindex_iff {K : Type*} [CommRing K] {I J I' J' : Type*} + (M : Matrix I J K) (v : J → K) (rows : I' ≃ I) (cols : J' ≃ J) : + v ∘ cols ∈ Submodule.span K (range (M.submatrix rows cols).row) ↔ + v ∈ Submodule.span K (range M.row) := by + let e := LinearEquiv.funCongrLeft K K cols + change e v ∈ Submodule.span K (range ((e ∘ M.row) ∘ rows)) ↔ _ + rw [rows.surjective.range_comp, range_comp] + change e v ∈ Submodule.span K (e.toLinearMap '' range M.row) ↔ _ + rw [← Submodule.map_span] + constructor + · rintro ⟨w, hw, he⟩ + exact e.injective he ▸ hw + · exact fun hv => ⟨v, hv, rfl⟩ + +/-- The bounded good-prime criterion on arbitrary finite index types, with the +rational hypothesis expressed directly as nonmembership in the row span. -/ +theorem exists_bounded_good_prime_of_notMem {I J : Type*} [Fintype I] [Fintype J] + (M : Matrix I J ℤ) (v : J → ℤ) (a b : ℕ) (hJ : Fintype.card J ≤ 2 ^ a) + (hM : ∀ i j, (M i j).natAbs ≤ 2 ^ b) (hv : ∀ j, (v j).natAbs ≤ 2 ^ b) + (h : (fun j => (v j : ℚ)) ∉ Submodule.span ℚ (range (M.map (Int.castRingHom ℚ)).row)) : + ∃ p : ℕ, p.Prime ∧ p ≤ 2 ^ (2 * (a + Nat.clog 2 (a + b + 2)) + 1) ∧ + (fun j => (v j : ZMod p)) ∉ + Submodule.span (ZMod p) (range (M.map (Int.castRingHom (ZMod p))).row) := by + classical + let rows := (Fintype.equivFin I).symm + let cols := (Fintype.equivFin J).symm + let N := M.submatrix rows cols + let w := v ∘ cols + have h' : (castMatrix ℚ N).rank < (castMatrix ℚ (augment N w)).rank := by + rw [cast_augment, rank_lt_augment_iff] + exact fun hmem => h ((row_mem_reindex_iff (M.map (Int.castRingHom ℚ)) (fun j => (v j : ℚ)) rows cols).mp hmem) + have hentry (i) (j) : (augment N w i j).natAbs ≤ 2 ^ b := + Fin.cases (hv _) (fun k => hM (rows k) (cols j)) i + obtain ⟨p, hp, hsize, hspan⟩ := exists_bounded_good_prime N w a b hJ hentry h' + exact ⟨p, hp, hsize, fun hm => hspan ((row_mem_reindex_iff (M.map (Int.castRingHom (ZMod p))) (fun j => (v j : ZMod p)) rows cols).mpr hm)⟩ + +end CertificateReduction + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ChainAssignments.lean b/lean/OAI/Computability/VPVNP/ChainAssignments.lean new file mode 100644 index 0000000000..cfdc0ace45 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ChainAssignments.lean @@ -0,0 +1,169 @@ +import OAI.Computability.VPVNP.PairedChain + +/-! # Reindexing all shared bits of the live and primed chains + +Groups and cuts are indexed consecutively. A bit on an even cut is an exterior +bit of the adjacent pairs. Bits on an odd cut and the send bits of its two +groups belong to just one pair. The bijection below makes the regrouping in +(9.2)–(9.5) independent of the bit values and the site computations. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ChainAssignments + +open CutSchedule ExponentTrace +open scoped Classical + +/-- Identify pair `i` and side `g` with group `2*i+g` in the chain of `2^(h+1)` groups. -/ +def group (h : ℕ) : Fin (2^h) × Fin 2 ≃ Fin (2^(h+1)) where + toFun a := ⟨2 * a.1.val + a.2.val, by have := a.1.isLt; have := a.2.isLt; rw [pow_succ]; omega⟩ + invFun j := (⟨j.val / 2, by have := j.isLt; have := pow_succ (2 : ℕ) h; omega⟩, ⟨j.val % 2, by omega⟩) + left_inv a := by + obtain ⟨i, j⟩ := a + apply Prod.ext <;> apply Fin.ext <;> dsimp <;> omega + right_inv j := by apply Fin.ext; dsimp; omega + +/-- Index `2*i` of exterior cut `i` after grouping the chain into adjacent pairs, including the +two end cuts. -/ +def evenCut (h : ℕ) (i : Fin (2^h+1)) : Fin (2^(h+1)+1) := + ⟨2*i.val, by have := i.isLt; rw [pow_succ]; omega⟩ + +/-- Index `2*i+1` of the cut between the two groups of pair `i`. -/ +def oddCut (h : ℕ) (i : Fin (2^h)) : Fin (2^(h+1)+1) := + ⟨2*i.val+1, by have := i.isLt; rw [pow_succ]; omega⟩ + +/-- Partition all cuts of the unpaired chain into the even cuts bounding pairs and the odd cuts +internal to individual pairs. -/ +def cut (h : ℕ) : Fin (2^h+1) ⊕ Fin (2^h) ≃ Fin (2^(h+1)+1) where + toFun := Sum.elim (evenCut h) (oddCut h) + invFun j := if hj : j.val % 2 = 0 then .inl ⟨j.val/2, by have := j.isLt; have := pow_succ (2 : ℕ) h; omega⟩ + else .inr ⟨j.val/2, by have := j.isLt; have := pow_succ (2 : ℕ) h; omega⟩ + left_inv a := by + rcases a with i | i + · simp [evenCut] + · simp [oddCut, Nat.mul_add_div] + right_inv j := by + dsimp only + split <;> apply Fin.ext <;> dsimp [evenCut, oddCut] <;> omega + +/-- An assignment of a bit string of the prescribed width to each of the `2^(h+1)+1` cuts of +the chain. -/ +abbrev AllCuts (h Δ : ℕ) := (j : Fin (2^(h+1)+1)) → Bits (width (h+1) Δ j.val) + +/-- A full assignment of chain cut strings together with a Boolean value for every shared RAM +bit of every group. -/ +abbrev Shared (h Δ r bucket w : ℕ) := + AllCuts h Δ × (Fin (2^(h+1)) → RAMLayout.SharedBit r bucket w → Bool) + +variable {h Δ a r bucket w n : ℕ} + +private def cutFields : AllCuts h Δ ≃ Exterior h Δ × + ((i : Fin (2^h)) → Bits (width (h+1) Δ (2*i.val+1))) := + (Equiv.piCongrLeft (fun j : Fin (2^(h+1)+1) => Bits (width (h+1) Δ j.val)) + (cut h)).symm.trans (Equiv.sumPiEquivProdPi _) + +private def groupFields : + (Fin (2^(h+1)) → RAMLayout.SharedBit r bucket w → Bool) ≃ + ((i : Fin (2^h)) → Fin 2 → RAMLayout.SharedBit r bucket w → Bool) := + ((group h).symm.arrowCongr (Equiv.refl _)).trans (Equiv.curry _ _ _) + +private def pairFields : (((i : Fin (2^h)) → Bits (width (h+1) Δ (2*i.val+1))) × + ((i : Fin (2^h)) → Fin 2 → RAMLayout.SharedBit r bucket w → Bool)) ≃ + ((i : Fin (2^h)) → PairedChain.PairBits h Δ a r bucket w i) where + toFun x i := Sum.elim (x.1 i) fun p => x.2 i p.1 p.2 + invFun x := (fun i b => x i (.inl b), fun i g b => x i (.inr (g,b))) + left_inv _ := rfl + right_inv x := by funext i b; rcases b with b | ⟨g,b⟩ <;> rfl + +/-- Each physical assignment supplies exactly one exterior assignment and one +independent internal assignment per pair, and conversely. -/ +def split : Shared h Δ r bucket w ≃ + Exterior h Δ × ((i : Fin (2^h)) → PairedChain.PairBits h Δ a r bucket w i) := + (cutFields.prodCongr groupFields).trans ((Equiv.prodAssoc _ _ _).trans + ((Equiv.refl _).prodCongr pairFields)) + +@[simp] theorem split_even (data : Shared h Δ r bucket w) (i : Fin (2^h+1)) : + ((split (a := a)) data).1 i = data.1 (evenCut h i) := rfl + +@[simp] theorem split_odd (data : Shared h Δ r bucket w) (i : Fin (2^h)) + (b : Fin (width (h+1) Δ (2*i.val+1))) : + ((split (a := a)) data).2 i (.inl b) = data.1 (oddCut h i) b := rfl + +@[simp] theorem split_send (data : Shared h Δ r bucket w) (i : Fin (2^h)) + (g : Fin 2) (b : RAMLayout.SharedBit r bucket w) : + ((split (a := a)) data).2 i (.inr (g,b)) = data.2 (group h (i,g)) b := rfl + +/-- Read an index, advice, or cut field at the site address. Unused +endpoints and addresses beyond the field length are clamped to zero. -/ +def distributedBit {d : ℕ} (bits : Bits d) (addr : ℕ) : Bool := + if h : addr < d then bits ⟨addr, h⟩ else false + +/-- Form processor `v`'s header for group `j` from its distributed bits of the one-based group +number, advice, and left and right cut strings. -/ +def physicalHeader (advice : Bits a) (cuts : AllCuts h Δ) + (j : Fin (2^(h+1))) (v : Fin (2^r)) : BurstRAM.ProcessorInput.Header := + let number : BurstRAM.Word (h+2) := ⟨j.val + 1, by + have := j.isLt + have : 2^(h+2) = 2^(h+1) * 2 := pow_succ 2 (h+1) + have := Nat.two_pow_pos (h+1) + omega⟩ + BurstRAM.ProcessorInput.header + (distributedBit (RAMSerialization.wordBits _ number) v.val) + (distributedBit advice v.val) + (distributedBit (cuts j.castSucc) v.val) + (distributedBit (cuts j.succ) v.val) + +/-- An actual tape in the unpaired chain. Consecutive groups read the same +cut field, and a receive port reads the bit of its physical send endpoint. -/ +def physicalInput (p : UniversalMachine.Program) + (hf : BurstRAM.ProcessorInput.Fits p n r bucket w) (advice : Bits a) + (data : Shared h Δ r bucket w) (j : Fin (2^(h+1))) (v : Fin (2^r)) : Fin n → Bool := + BurstRAM.ProcessorInput.encode p n v (physicalHeader advice data.1 j v) + (fun u => (RAMLayout.assignmentEquiv r bucket w (data.2 j)).val + (v, (RAMLayout.offset r bucket w).symm u)) hf + +theorem physicalInput_at_pair (p : UniversalMachine.Program) + (hf : BurstRAM.ProcessorInput.Fits p n r bucket w) (advice : Bits a) + (data : Shared h Δ r bucket w) (i : Fin (2^h)) (g : Fin 2) (v : Fin (2^r)) : + physicalInput p hf advice data (group h (i,g)) v = + PairedChain.siteInput p hf advice ((split (a := a)) data).1 i + (((split (a := a)) data).2 i) (g,v) := by + unfold physicalInput PairedChain.siteInput PrimedInputRAM.input + congr 1 + funext j + fin_cases g <;> fin_cases j <;> + simp [physicalHeader, BurstRAM.ProcessorInput.header, PrimedInputRAM.siteHeader, + PrimedInputRAM.headerRef, PairedChain.lengths, distributedBit, + PrimedInputRAM.Ref.value, PairedChain.headers, group, evenCut, PairedChain.groupIndex, + Nat.mul_succ] <;> + split_ifs <;> simp only [*, ↓reduceDIte] <;> rfl + +/-- The full contraction written with one variable for each physical shared bit, +one factor per group, and one factor per site in the group. -/ +noncomputable def unpaired (p : UniversalMachine.Program) + (hf : BurstRAM.ProcessorInput.Fits p n r bucket w) (advice : Bits a) : ℕ := + ∑ data : Shared h Δ r bucket w, ∏ j : Fin (2^(h+1)), ∏ v : Fin (2^r), + acceptingCount (physicalInput p hf advice data j v) + +/-- Pairing consecutive factors preserves the integer contraction. -/ +theorem unpaired_eq_original (p : UniversalMachine.Program) + (hf : BurstRAM.ProcessorInput.Fits p n r bucket w) (advice : Bits a) : + unpaired (h := h) (Δ := Δ) p hf advice = PairedChain.original (h := h) (Δ := Δ) p hf advice := by + unfold unpaired PairedChain.original Diagonal.originalContraction + rw [← (split (h := h) (Δ := Δ) (a := a) (r := r) (bucket := bucket) (w := w)).symm.sum_comp, + Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro ξ _ + apply Finset.sum_congr rfl + intro b _ + rw [← (group h).prod_comp] + simp only [Fintype.prod_prod_type, physicalInput_at_pair, Equiv.apply_symm_apply] + +end ChainAssignments + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ChainModeProduct.lean b/lean/OAI/Computability/VPVNP/ChainModeProduct.lean new file mode 100644 index 0000000000..1327979cfc --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ChainModeProduct.lean @@ -0,0 +1,149 @@ +import OAI.Computability.VPVNP.ChainAssignments + +/-! +# The two live modes in the physical chain contraction + +A unit-mode group accepts only zero strings on its incident cuts. An +evaluation-mode group reads a true mode bit on each incident interior cut. +Neighboring groups therefore cannot contribute in different modes to a +nonzero product. The unit-mode product counts the unique all-zero assignment. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ChainAssignments + +open CutSchedule +open scoped Classical + +variable {h Δ : ℕ} + +/-- The unit group accepts exactly once when both incident cut fields are zero. -/ +noncomputable def unitGroupCount (cuts : AllCuts h Δ) (i : Fin (2 ^ (h+1))) : ℕ := + if cuts i.castSucc = (fun _ => false) ∧ cuts i.succ = (fun _ => false) then 1 else 0 + +/-- The first bit on an interior cut selects evaluation mode. Endpoints carry no bits. -/ +def evalCutMode (cuts : AllCuts h Δ) (j : Fin (2 ^ (h+1) + 1)) : Prop := + 0 < j.val → j.val < 2 ^ (h+1) → distributedBit (cuts j) 0 = true + +/-- Every interior cut has its evaluation-mode bit, the bit at distributed position zero, set +to true. -/ +def activeCuts (cuts : AllCuts h Δ) : Prop := ∀ j, evalCutMode cuts j + +private theorem prod_modes {N : ℕ} (hn : 0 < N) (u e : Fin N → ℕ) + (adj : ∀ i j : Fin N, i.val+1 = j.val → u i * e j = 0 ∧ e i * u j = 0) : + (∏ i, (u i + e i)) = (∏ i, u i) + ∏ i, e i := by + cases N with + | zero => omega + | succ k => + induction k with + | zero => simp + | succ k ih => + have hprefix := ih (by omega) (fun i => u i.castSucc) (fun i => e i.castSucc) + (fun i j he => adj i.castSucc j.castSucc he) + let last := Fin.last (k+1) + have ⟨h₁, h₂⟩ := adj (Fin.last k).castSucc last rfl + have cross (f : Fin (k+1) → ℕ) (b : ℕ) (hb : f (Fin.last k) * b = 0) : + (∏ i, f i) * b = 0 := by + rw [Fin.prod_univ_castSucc f, mul_assoc, hb, mul_zero] + have hcross₁ := cross (fun i => u i.castSucc) (e last) h₁ + have hcross₂ := cross (fun i => e i.castSucc) (u last) h₂ + rw [Fin.prod_univ_castSucc (fun i => u i + e i), Fin.prod_univ_castSucc u, + Fin.prod_univ_castSucc e, hprefix, add_mul, mul_add, mul_add, hcross₁, hcross₂, add_zero, zero_add] + +private theorem prod_unit (cuts : AllCuts h Δ) : + (∏ i, unitGroupCount cuts i) = if cuts = (fun _ _ => false) then 1 else 0 := by + have allZero : (∀ i : Fin (2^(h+1)), cuts i.castSucc = (fun _ => false) ∧ + cuts i.succ = (fun _ => false)) ↔ cuts = (fun _ _ => false) := by + constructor + · intro hz + funext j + apply Fin.cases (motive := fun j => cuts j = fun _ => false) _ (fun i => (hz i).2) j + exact (hz ⟨0, Nat.two_pow_pos _⟩).1 + · rintro rfl + simp + simp only [unitGroupCount, Fintype.prod_ite_zero, Finset.prod_const_one] + split_ifs <;> tauto + +variable (eval : AllCuts h Δ → Fin (2^(h+1)) → ℕ) +variable (mode : ∀ cuts i, eval cuts i ≠ 0 → evalCutMode cuts i.castSucc ∧ evalCutMode cuts i.succ) + +include mode + +/-- At fixed cuts every mixed-mode term vanishes, including terms switching +modes across the midpoint. -/ +theorem group_mode_product (cuts : AllCuts h Δ) : + (∏ i, (unitGroupCount cuts i + eval cuts i)) = + (if cuts = (fun _ _ => false) then 1 else 0) + ∏ i, eval cuts i := by + rw [← prod_unit cuts] + apply prod_modes (Nat.two_pow_pos _) + intro i j hij + have he : i.succ = j.castSucc := Fin.ext hij + have hi : 0 < i.succ.val := Nat.succ_pos _ + have hj : j.castSucc.val < 2^(h+1) := j.isLt + have falseBit {d : ℕ} (bits : Bits d) (hz : bits = fun _ => false) : distributedBit bits 0 = false := by + subst bits + simp [distributedBit] + constructor + · by_cases hu : cuts i.castSucc = (fun _ => false) ∧ cuts i.succ = (fun _ => false) + · have ez : eval cuts j = 0 := by + by_contra hne + have htrue := (mode cuts j hne).1 (he ▸ hi) hj + rw [← he, falseBit _ hu.2] at htrue + contradiction + simp [ez] + · unfold unitGroupCount + split_ifs with hit + · exact (hu hit).elim + · simp + · by_cases hu : cuts j.castSucc = (fun _ => false) ∧ cuts j.succ = (fun _ => false) + · have ez : eval cuts i = 0 := by + by_contra hne + have htrue := (mode cuts i hne).2 hi (he.symm ▸ hj) + rw [he, falseBit _ hu.1] at htrue + contradiction + simp [ez] + · unfold unitGroupCount + split_ifs with hit + · exact (hu hit).elim + · simp + +/-- A zero evaluation-mode bit on any interior cut kills the whole evaluation product. -/ +theorem eval_product_zero_of_inactive (cuts : AllCuts h Δ) (bad : ¬activeCuts cuts) : + (∏ i, eval cuts i) = 0 := by + by_contra hn + apply bad + intro j _ hlt + let i : Fin (2^(h+1)) := ⟨j.val, hlt⟩ + have hmode := (mode cuts i (Finset.prod_ne_zero_iff.mp hn i (Finset.mem_univ _))).1 + exact hmode ‹0 < j.val› hlt + +/-- Summing the physical products counts one unit execution and the full +contraction of evaluation-mode groups. -/ +theorem sum_groupCount_eq_one_add_eval (groups : AllCuts h Δ → Fin (2^(h+1)) → ℕ) + (localCount : ∀ cuts i, groups cuts i = unitGroupCount cuts i + eval cuts i) : + (∑ cuts, ∏ i, groups cuts i) = 1 + ∑ cuts, ∏ i, eval cuts i := by + simp_rw [localCount, group_mode_product eval mode] + rw [Finset.sum_add_distrib] + simp + +/-- The evaluation sum in the live-mode identity can be restricted to cut +assignments with true mode bits on every interior cut. -/ +theorem sum_groupCount_eq_one_add_active (groups : AllCuts h Δ → Fin (2^(h+1)) → ℕ) + (localCount : ∀ cuts i, groups cuts i = unitGroupCount cuts i + eval cuts i) : + (∑ cuts, ∏ i, groups cuts i) = 1 + ∑ cuts, if activeCuts cuts then ∏ i, eval cuts i else 0 := by + rw [sum_groupCount_eq_one_add_eval eval mode groups localCount] + congr 1 + apply Finset.sum_congr rfl + intro cuts _ + by_cases ok : activeCuts cuts + · simp [ok] + · simp [ok, eval_product_zero_of_inactive eval mode cuts ok] + +end ChainAssignments + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CharacteristicThreshold.lean b/lean/OAI/Computability/VPVNP/CharacteristicThreshold.lean new file mode 100644 index 0000000000..1cdd3497a1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CharacteristicThreshold.lean @@ -0,0 +1,62 @@ +import OAI.Computability.VPVNP.HamiltonianHardness +import OAI.Computability.VPVNP.PermanentHardness +import Mathlib.FieldTheory.IsAlgClosed.AlgebraicClosure +import Mathlib.RingTheory.Algebraic.Cardinality + +/-! # The order of quantifiers in the characteristic-dependent threshold + +For a fixed characteristic, an infinite collection of exceptional lengths +over possibly different fields gives infinitely many small circuits over a +single countable algebraically closed field. The field is chosen before the +exceptional lengths. This is the initial reduction in §1.2. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open MvPolynomial + +universe u + +theorem countable_algebraicClosure (K : Type) [Field K] [Countable K] : + Countable (AlgebraicClosure K) := + Cardinal.mk_le_aleph0_iff.mp ((Algebra.IsAlgebraic.cardinalMk_le_max K (AlgebraicClosure K)).trans + (max_le Cardinal.mk_le_aleph0 le_rfl)) + +/-- A prime characteristic, including the characteristic-zero case, admits +a single countable algebraically closed representative. -/ +theorem exists_countable_algClosed_of_characteristic {q : ℕ} (hq : q.Prime ∨ q = 0) : + ∃ (K : Type) (_ : Field K) (_ : IsAlgClosed K), Countable K ∧ CharP K q := by + rcases hq with hp | rfl + · let : Fact q.Prime := ⟨hp⟩ + exact ⟨AlgebraicClosure (ZMod q), inferInstance, inferInstance, + countable_algebraicClosure _, inferInstance⟩ + · exact ⟨AlgebraicClosure ℚ, inferInstance, inferInstance, + countable_algebraicClosure _, inferInstance⟩ + +/-- Infinitely many exceptional lengths anywhere in a fixed characteristic +produce infinitely many small circuits over the same chosen closure. -/ +theorem unbounded_small_of_failure_of_uniform_bound + {σ : ℕ → Type*} (p : (n : ℕ) → MvPolynomial (σ n) ℤ) (q C : ℕ) + (h : ¬ ∃ N, ∀ n ≥ N, ∀ (F : Type u) [Field F] [CharP F q], + n^C < circuitSize (map (Int.castRingHom F) (p n))) : + ∃ (K : Type) (_ : Field K) (_ : IsAlgClosed K) (_ : Countable K) (_ : CharP K q), + ∀ N, ∃ n ≥ N, circuitSize (map (Int.castRingHom K) (p n)) ≤ n^C := by + classical + have hq : q.Prime ∨ q = 0 := by + by_contra hq + exact h ⟨0, fun _ _ F _ _ => False.elim (hq (CharP.char_is_prime_or_zero F q))⟩ + obtain ⟨K, iK, hK, cnt, ch⟩ := exists_countable_algClosed_of_characteristic hq + let := iK + let := hK + let := ch + refine ⟨K, iK, hK, cnt, ch, ?_⟩ + by_contra hnone + push Not at hnone + obtain ⟨N, hN⟩ := hnone + exact h ⟨N, circuitSize_intCast_uniform_bound (K := K) p q C N hN⟩ + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ChoiceWitness.lean b/lean/OAI/Computability/VPVNP/ChoiceWitness.lean new file mode 100644 index 0000000000..ef10e5540c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ChoiceWitness.lean @@ -0,0 +1,152 @@ +import OAI.Computability.VPVNP.UniversalMachine +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Data.Fin.Tuple.Basic + +/-! +# Canonical accepting-path witnesses + +For the counting polynomial in §1.1 of *VP and VNP differ over every field*, we use +one Boolean choice for every machine step. This is the combinatorial counting identity +that lets the VNP summand verify one candidate path deterministically. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace UniversalMachine + +/-- One choice bit per step. A single transition consumes zero, and an early halt +accepts only the all-zero unused suffix. The two instructions in a branch have +separate bits even when they induce the same successor configuration. -/ +def acceptsChoices (p : Program) : (t : ℕ) → Config p.extra → (Fin t → Bool) → Bool + | 0, c, _ => decide (c.state.val = 1) + | t + 1, c, w => + if c.state.val = 1 then decide (w = fun _ => false) else if c.state.val = 0 then false else + match branches p c with + | .stop => false + | .one a => !w 0 && acceptsChoices p t (advance c a) (Fin.tail w) + | .two a b => acceptsChoices p t (advance c (if w 0 then b else a)) (Fin.tail w) + +/-- Enter rejection without further tape operations. -/ +def reject {extra : ℕ} (c : Config extra) : Config extra := { c with state := 0 } + +/-- Consume a single witness bit. Invalid choices enter the rejecting state, which is +absorbing. An accepting halt survives precisely the zero padding of a canonical witness. -/ +def choiceStep (p : Program) (c : Config p.extra) (bit : Bool) : Config p.extra := + if c.state.val = 1 then if bit then reject c else c + else if c.state.val = 0 then c + else match branches p c with + | .stop => reject c + | .one a => if bit then reject c else advance c a + | .two a b => advance c (if bit then b else a) + +private theorem acceptsChoices_of_accept (p : Program) (t : ℕ) (c : Config p.extra) + (ha : c.state.val = 1) (w : Fin t → Bool) : + acceptsChoices p t c w = decide (w = fun _ => false) := by + cases t with + | zero => simp [acceptsChoices, ha, Subsingleton.elim w (fun _ => false)] + | succ t => simp [acceptsChoices, ha] + +private theorem acceptsChoices_of_reject (p : Program) (t : ℕ) (c : Config p.extra) + (hr : c.state.val = 0) (w : Fin t → Bool) : acceptsChoices p t c w = false := by + cases t <;> simp [acceptsChoices, hr] + +private theorem all_zero_succ {t : ℕ} (w : Fin (t + 1) → Bool) : + (w = fun _ => false) ↔ w 0 = false ∧ Fin.tail w = fun _ => false := by + constructor + · rintro rfl + exact ⟨rfl, rfl⟩ + · rintro ⟨h₀, ht⟩ + funext i + refine Fin.cases h₀ (fun j => ?_) i + exact congrFun ht j + +/-- Consuming the leading bit agrees with one deterministic machine transition. -/ +theorem acceptsChoices_succ (p : Program) (t : ℕ) (c : Config p.extra) (w : Fin (t + 1) → Bool) : + acceptsChoices p (t + 1) c w = acceptsChoices p t (choiceStep p c (w 0)) (Fin.tail w) := by + have reject_bit := acceptsChoices_of_reject p t (reject c) rfl (Fin.tail w) + by_cases ha : c.state.val = 1 + · cases hb : w 0 <;> + simp [acceptsChoices, choiceStep, ha, hb, all_zero_succ, acceptsChoices_of_accept p t c ha, + reject_bit] + by_cases hr : c.state.val = 0 + · simp [acceptsChoices, choiceStep, hr, acceptsChoices_of_reject p t c hr] + cases h : branches p c with + | stop => simp [acceptsChoices, choiceStep, ha, hr, h, reject_bit] + | one a => cases hb : w 0 <;> simp [acceptsChoices, choiceStep, ha, hr, h, hb, reject_bit] + | two a b => simp [acceptsChoices, choiceStep, ha, hr, h] + +/-- The final state of the fixed-length simulation determines the verifier's answer. -/ +theorem acceptsChoices_eq_foldl (p : Program) (t : ℕ) (c : Config p.extra) (w : Fin t → Bool) : + acceptsChoices p t c w = decide (((List.ofFn w).foldl (choiceStep p) c).state.val = 1) := by + induction t generalizing c with + | zero => simp [acceptsChoices] + | succ t ih => + rw [acceptsChoices_succ, List.ofFn_succ, List.foldl_cons] + exact ih _ _ + +private theorem sum_choice_succ {t : ℕ} (f : (Fin (t + 1) → Bool) → ℕ) : + ∑ w, f w = (∑ v, f (Fin.cons false v)) + ∑ v, f (Fin.cons true v) := by + rw [← (Fin.consEquiv (fun _ : Fin (t + 1) => Bool)).sum_comp f, + Fintype.sum_prod_type, Fintype.sum_bool, add_comm] + rfl + +/-- Counting accepting strings of fixed length recovers the number of accepting paths +of the encoded machine within the step bound, with each halted path counted once. -/ +theorem paths_eq_sum_choices (p : Program) (t : ℕ) (c : Config p.extra) : + paths p t c = ∑ w, if acceptsChoices p t c w then 1 else 0 := by + induction t generalizing c with + | zero => simp [paths, acceptsChoices] + | succ t ih => + rw [paths] + by_cases ha : c.state.val = 1 + · simp [ha, acceptsChoices] + by_cases hr : c.state.val = 0 + · simp [hr, acceptsChoices] + simp only [ha, hr, ite_false] + cases h : branches p c with + | stop => simp [ha, hr, h, acceptsChoices] + | one a => rw [sum_choice_succ]; simp [acceptsChoices, ha, hr, h, ih] + | two a b => rw [sum_choice_succ]; simp [acceptsChoices, ha, hr, h, ih] + +/-- The cardinality form of the fixed-length witness identity. -/ +theorem paths_eq_card_choices (p : Program) (t : ℕ) (c : Config p.extra) : + paths p t c = (Finset.univ.filter (fun w => acceptsChoices p t c w)).card := by + rw [paths_eq_sum_choices] + simpa only [Nat.cast_id] using + (Finset.sum_boole (R := ℕ) (fun w => acceptsChoices p t c w = true) Finset.univ) + +end UniversalMachine + +section + +open UniversalMachine + +/-- A candidate for the coefficient indexed by `x` consists of one bit per clock tick. -/ +def verifiesInput {n : ℕ} (x : Fin n → Bool) (w : Fin (n ^ clockExponent) → Bool) : Bool := + let input := List.ofFn x + match decode input with + | none => false + | some p => acceptsChoices p (n ^ clockExponent) (initial p input) w + +/-- The number of canonical witnesses is the coefficient `U_n(x)` from equation (1.1). -/ +theorem acceptingCount_eq_card_witnesses {n : ℕ} (x : Fin n → Bool) : + acceptingCount x = (Finset.univ.filter (fun w => verifiesInput x w)).card := by + cases h : decode (List.ofFn x) with + | none => simp [acceptingCount, verifiesInput, h] + | some p => simp [acceptingCount, verifiesInput, h, paths_eq_card_choices] + +/-- The Boolean witness sum gives the same coefficient in every target semiring. -/ +theorem acceptingCount_eq_sum_witnesses {R : Type*} [Semiring R] {n : ℕ} + (x : Fin n → Bool) : + (acceptingCount x : R) = ∑ w, if verifiesInput x w then 1 else 0 := by + rw [acceptingCount_eq_card_witnesses] + exact Finset.natCast_card_filter _ _ + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CircuitComposition.lean b/lean/OAI/Computability/VPVNP/CircuitComposition.lean new file mode 100644 index 0000000000..8385aee2ca --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CircuitComposition.lean @@ -0,0 +1,77 @@ +import OAI.Computability.VPVNP.Circuits + +/-! # Composition of exact arithmetic circuits + +Concatenating two topologically ordered programs preserves their internal wires. A final +binary gate then computes the chosen operation on the two designated outputs. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +variable {R σ A : Type*} {n m : ℕ} + +/-- Renumber the gate references while preserving scalar and variable inputs. -/ +def Ref.reindex (f : Fin n → Fin m) : Ref R σ n → Ref R σ m + | .var x => .var x + | .const r => .const r + | .gate i => .gate (f i) + +private theorem Ref.read_reindex (f : Fin n → Fin m) (s : R → A) (x : σ → A) + (w : Fin m → A) (r : Ref R σ n) : + (r.reindex f).read s x w = r.read s x (w ∘ f) := by cases r <;> rfl + +/-- Append the gates of the second program after those of the first program. -/ +def Program.append (p : Program R σ n) : {m : ℕ} → Program R σ m → Program R σ (n + m) + | _, .nil => p + | _, .snoc q op a b => + .snoc (p.append q) op (a.reindex (Fin.natAdd n)) (b.reindex (Fin.natAdd n)) + +private theorem Program.run_append_left [Ring A] (s : R → A) (x : σ → A) + (p : Program R σ n) (q : Program R σ m) : + (p.append q).run s x ∘ Fin.castAdd m = p.run s x := by + funext i + induction q with + | nil => rfl + | snoc q op a b ih => + simp only [Function.comp_apply, Program.append, Program.run, ← Fin.castSucc_castAdd, + Fin.lastCases_castSucc] + exact ih + +private theorem Program.run_append_right [Ring A] (s : R → A) (x : σ → A) + (p : Program R σ n) (q : Program R σ m) : + (p.append q).run s x ∘ Fin.natAdd n = q.run s x := by + induction q with + | nil => funext i; exact i.elim0 + | snoc q op a b ih => + funext i + refine Fin.lastCases ?_ (fun j => ?_) i + · simp only [Function.comp_apply, Program.append, Program.run, Fin.natAdd_last, + Fin.lastCases_last, Ref.read_reindex, ih] + exact Fin.lastCases_last + · simpa only [Function.comp_apply, Program.append, Program.run, Fin.natAdd_castSucc, + Fin.lastCases_castSucc] using congrFun ih j + +/-- Combine the outputs of two circuits using one additional binary gate. -/ +def Circuit.combine (op : BinOp) (c : Circuit R σ n) (d : Circuit R σ m) : + Circuit R σ (n + m + 1) where + program := .snoc (c.program.append d.program) op + (c.output.reindex (Fin.castAdd m)) (d.output.reindex (Fin.natAdd n)) + output := .gate (Fin.last (n + m)) + +theorem Circuit.eval_combine [Ring A] (op : BinOp) (c : Circuit R σ n) + (d : Circuit R σ m) (s : R → A) (x : σ → A) : + (Circuit.combine op c d).eval s x = op.apply (c.eval s x) (d.eval s x) := by + change Program.run s x (.snoc (c.program.append d.program) op _ _) (Fin.last _) = _ + simp only [Program.run, Fin.lastCases_last, Ref.read_reindex, Program.run_append_left, + Program.run_append_right, Circuit.eval] + +theorem Circuit.polynomial_combine [CommRing R] (op : BinOp) (c : Circuit R σ n) + (d : Circuit R σ m) : + (Circuit.combine op c d).polynomial = op.apply c.polynomial d.polynomial := + Circuit.eval_combine op c d MvPolynomial.C MvPolynomial.X + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CircuitDescent.lean b/lean/OAI/Computability/VPVNP/CircuitDescent.lean new file mode 100644 index 0000000000..73f25f25e7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CircuitDescent.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.Circuits +import OAI.Computability.VPVNP.ScalarDescent + +/-! +# Descent without changing the circuit topology + +A circuit for a polynomial defined over a base field `k` can replace every scalar +label with a new value in an algebraically closed extension of `k`. This applies +when the original labels belong to an arbitrary extension of `k`. Binary gate +types, wiring, reuse, the designated output and the gate count all persist. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open MvPolynomial + +variable {R S T σ : Type*} {n : ℕ} + +private def Ref.scalarLabels : Ref R σ n → List R + | .const c => [c] + | .var _ | .gate _ => [] + +private def Program.scalarLabels : {n : ℕ} → Program R σ n → List R + | _, .nil => [] + | _, .snoc p _ a b => p.scalarLabels ++ a.scalarLabels ++ b.scalarLabels + +/-- All scalar occurrences in a circuit, including an output that is a scalar. -/ +def Circuit.scalarLabels (c : Circuit R σ n) : List R := + c.program.scalarLabels ++ c.output.scalarLabels + +private theorem Ref.subst_inl_comp (r : Ref R σ n) (f : R → S) (g : S → T) : + (r.subst Sum.inl f).subst Sum.inl g = r.subst Sum.inl (g ∘ f) := by cases r <;> rfl + +private theorem Program.subst_inl_comp (p : Program R σ n) (f : R → S) (g : S → T) : + (p.subst Sum.inl f).subst Sum.inl g = p.subst Sum.inl (g ∘ f) := by + induction p with + | nil => rfl + | snoc p op a b ih => simp only [Program.subst, ih, Ref.subst_inl_comp] + +theorem Circuit.mapConstants_comp (c : Circuit R σ n) (f : R → S) (g : S → T) : + (c.mapConstants f).mapConstants g = c.mapConstants (g ∘ f) := by + simp only [Circuit.mapConstants, Circuit.subst, Ref.subst_inl_comp, Program.subst_inl_comp] + +private theorem Ref.subst_inl_self (r : Ref R σ n) (f : R → R) + (hf : ∀ x ∈ r.scalarLabels, f x = x) : r.subst Sum.inl f = r := by + cases r with + | const x => simp [Ref.subst, hf x (by simp [Ref.scalarLabels])] + | var | gate => rfl + +private theorem Program.subst_inl_self (p : Program R σ n) (f : R → R) + (hf : ∀ x ∈ p.scalarLabels, f x = x) : p.subst Sum.inl f = p := by + induction p with + | nil => rfl + | snoc p op a b ih => + rw [Program.subst, ih (fun x hx ↦ hf x (by simp [Program.scalarLabels, hx])), + a.subst_inl_self f (fun x hx ↦ hf x (by simp [Program.scalarLabels, hx])), + b.subst_inl_self f (fun x hx ↦ hf x (by simp [Program.scalarLabels, hx]))] + +theorem Circuit.mapConstants_self (c : Circuit R σ n) (f : R → R) + (hf : ∀ x ∈ c.scalarLabels, f x = x) : c.mapConstants f = c := by + simp only [Circuit.mapConstants, Circuit.subst, + c.program.subst_inl_self f (fun x hx ↦ hf x (by simp [Circuit.scalarLabels, hx])), + c.output.subst_inl_self f (fun x hx ↦ hf x (by simp [Circuit.scalarLabels, hx]))] + +/-- Descent of an exact circuit by changing only its scalar labels. The formal target +polynomial is interpreted in the two fields by their respective algebra maps. -/ +theorem Circuit.exists_scalar_relabeling {k F K : Type*} [Field k] [Field F] [Field K] + [Algebra k F] [Algebra k K] [IsAlgClosed K] (c : Circuit F σ n) (p : MvPolynomial σ k) + (hc : c.polynomial = map (algebraMap k F) p) : + ∃ relabel : F → K, (c.mapConstants relabel).polynomial = map (algebraMap k K) p := by + classical + let labels := c.scalarLabels.toFinset + let param (v : F) : MvPolynomial (↥labels) k := + if h : v ∈ labels then X ⟨v, h⟩ else 0 + let generic := c.mapConstants param + let values : (↥labels) → F := Subtype.val + have recover : generic.mapConstants (aeval values).toRingHom = c := by + rw [Circuit.mapConstants_comp] + apply Circuit.mapConstants_self + intro v hv + have hv' : v ∈ labels := List.mem_toFinset.mpr hv + simp [param, values, hv'] + have hs : map (aeval values).toRingHom generic.polynomial = map (algebraMap k F) p := by + rw [← Circuit.map_polynomial, recover, hc] + obtain ⟨b, hb⟩ := formalOutput_descent (K := K) generic.polynomial p values hs + exact ⟨(aeval b).toRingHom ∘ param, by + rw [← Circuit.mapConstants_comp, Circuit.map_polynomial] + exact hb⟩ + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CircuitGrammar.lean b/lean/OAI/Computability/VPVNP/CircuitGrammar.lean new file mode 100644 index 0000000000..358214064f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CircuitGrammar.lean @@ -0,0 +1,104 @@ +import OAI.Computability.VPVNP.CircuitGrammarSpan +import OAI.Computability.VPVNP.ParseGrammar + +/-! +# Graded parse labels for exact circuits + +An exact circuit determines one assignment of the labels of the grammar of Section 8.1 +of *VP and VNP differ over every field*. This assignment works simultaneously for all +homogeneous pieces up to the prescribed cutoff and for all gate, variable and output +states. It allows arbitrary field constants and does not require homogeneous intermediate +gate computations. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open MvPolynomial ParseGrammar + +variable {R V H : Type*} [CommRing R] [Fintype V] [Fintype H] {n D : ℕ} + +omit [Fintype V] in +private theorem Circuit.exists_production_labels (c : Circuit R V n) + (state : H → Circuit.GrammarSlots V n) (surj : Function.Surjective state) + (d : Fin D) (h : H) (hd : d.val ≠ 0) : + ∃ w : Fin d.val → H → H → R, homogeneousComponent (d.val + 1) (c.slotPolynomial (state h)) = + ∑ b, ∑ i, ∑ j, C (w b i j) * + homogeneousComponent ((leftDegree d b).val + 1) (c.slotPolynomial (state i)) * + homogeneousComponent ((rightDegree d b).val + 1) (c.slotPolynomial (state j)) := by + classical + let prod (s : Fin d.val × H × H) : MvPolynomial V R := + homogeneousComponent ((leftDegree d s.1).val + 1) (c.slotPolynomial (state s.2.1)) * + homogeneousComponent ((rightDegree d s.1).val + 1) (c.slotPolynomial (state s.2.2)) + have hmem : homogeneousComponent (d.val + 1) (c.slotPolynomial (state h)) ∈ + Submodule.span R (Set.range prod) := by + apply c.slot_component_mem (by omega) + intro i j a b ha hb hab + obtain ⟨i', rfl⟩ := surj i + obtain ⟨j', rfl⟩ := surj j + let split : Fin d.val := ⟨a - 1, by omega⟩ + have hl : (leftDegree d split).val + 1 = a := by change a - 1 + 1 = a; omega + have hr : (rightDegree d split).val + 1 = b := by + have htotal := split_degrees d split + omega + rw [← hl, ← hr] + exact Submodule.subset_span (Set.mem_range_self (split, i', j') : prod _ ∈ _) + obtain ⟨w, hw⟩ := (Submodule.mem_span_range_iff_exists_fun R).mp hmem + refine ⟨fun b i j ↦ w (b, i, j), ?_⟩ + simpa only [Fintype.sum_prod_type, prod, smul_eq_C_mul, mul_assoc] using hw.symm + +/-- A single assignment of the scalar labels represents the given circuit at every +state and every degree up to `D`. The state list can contain extra copies of any slot. -/ +theorem Circuit.exists_parseGrammar_on (c : Circuit R V n) (D : ℕ) + (state : H → Circuit.GrammarSlots V n) (surj : Function.Surjective state) : + ∃ G : ParseGrammar R V H D, ∀ d h, + G.eval d h = homogeneousComponent (d.val + 1) (c.slotPolynomial (state h)) := by + classical + let binary (d : Fin D) (h : H) : Fin d.val → H → H → R := + if hd : d.val ≠ 0 then (c.exists_production_labels state surj d h hd).choose + else fun _ _ _ ↦ 0 + let G : ParseGrammar R V H D := + ⟨fun h v ↦ (c.slotPolynomial (state h)).coeff (Finsupp.single v 1), binary⟩ + refine ⟨G, G.eval_eq_of_recurrence _ ?_ ?_⟩ + · intro d h hd + simpa only [hd, zero_add] using homogeneousComponent_one_eq_sum (c.slotPolynomial (state h)) + · intro d h hd + simpa only [G, binary, dite_eq_left hd] using + (c.exists_production_labels state surj d h hd).choose_spec + +/-- The start state computes the requested piece of the exact output polynomial. -/ +theorem Circuit.exists_parseGrammar (c : Circuit R V n) (D : ℕ) : + ∃ G : ParseGrammar R V (Circuit.GrammarSlots V n) D, ∀ d, + G.eval d none = homogeneousComponent (d.val + 1) c.polynomial := by + obtain ⟨G, hG⟩ := c.exists_parseGrammar_on D id Function.surjective_id + exact ⟨G, fun d ↦ hG d none⟩ + +/-- The state count is one plus the number of variables and binary gates. -/ +theorem Circuit.card_grammarSlots (V : Type*) [Fintype V] (n : ℕ) : + Fintype.card (Circuit.GrammarSlots V n) = Fintype.card V + n + 1 := by + simp [GrammarSlots] + +/-- The prescribed rectangular table can be padded to any sufficiently large width. +The start slot is number zero (number one in the paper). -/ +theorem Circuit.exists_parseGrammar_fin (c : Circuit R V n) (D S : ℕ) + (hS : Fintype.card V + n + 1 ≤ S) : + ∃ G : ParseGrammar R V (Fin S) D, ∀ d, + G.eval d ⟨0, by omega⟩ = homogeneousComponent (d.val + 1) c.polynomial := by + classical + obtain ⟨e⟩ : Nonempty (Circuit.GrammarSlots V n ↪ Fin S) := + Function.Embedding.nonempty_of_card_le (by simpa only [card_grammarSlots, Fintype.card_fin]) + let start : Fin S := ⟨0, by omega⟩ + let switch := Equiv.swap (e none) start + let state : Fin S → Circuit.GrammarSlots V n := Function.invFun e ∘ switch + have hs : Function.Surjective state := + (Function.leftInverse_invFun e.injective).surjective.comp switch.surjective + obtain ⟨G, hG⟩ := c.exists_parseGrammar_on D state hs + have hstart : state start = none := by + simp only [state, switch, Function.comp_apply, Equiv.swap_apply_right] + exact Function.leftInverse_invFun e.injective none + exact ⟨G, fun d ↦ by simpa only [hstart, slotPolynomial] using hG d start⟩ + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CircuitGrammarSpan.lean b/lean/OAI/Computability/VPVNP/CircuitGrammarSpan.lean new file mode 100644 index 0000000000..c0ee3b0d24 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CircuitGrammarSpan.lean @@ -0,0 +1,129 @@ +import OAI.Computability.VPVNP.Circuits +import OAI.Computability.VPVNP.GradedComponents +import Mathlib.LinearAlgebra.Finsupp.LinearCombination + +/-! +# Eliminating same-degree dependencies in a circuit + +For degrees at least two, every homogeneous piece of a gate lies in the linear span +of products of two positive-degree pieces of circuit nodes. Constants, additions, +subtractions and degree-zero factors can thus be absorbed into the scalar labels +of the graded grammar in Section 8.1 of *VP and VNP differ over every field*. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open MvPolynomial + +variable {R V H : Type*} [CommRing R] {n : ℕ} + +private theorem positive_component_C (a : R) {k : ℕ} (hk : k ≠ 0) : + homogeneousComponent k (C a : MvPolynomial V R) = 0 := by + simp [homogeneousComponent_of_mem (isHomogeneous_C V a), hk] + +/-- The start state, all variable inputs and one state per binary gate. -/ +abbrev Circuit.GrammarSlots (V : Type*) (n : ℕ) := Option (V ⊕ Fin n) + +/-- Read the polynomial at a grammar slot, returning the circuit output at the start slot, `X +v` at a variable slot, or the computed gate polynomial at a gate slot. -/ +noncomputable def Circuit.slotPolynomial (c : Circuit R V n) : + Circuit.GrammarSlots V n → MvPolynomial V R + | none => c.polynomial + | some (.inl v) => X v + | some (.inr j) => c.program.run C X j + +private theorem Ref.read_mem_or_constant {p : Program R V n} (r : Ref R V n) + (v : H → MvPolynomial V R) (hX : ∀ a, X a ∈ Set.range v) + (hp : ∀ j, p.run C X j ∈ Set.range v) : + r.read C X (p.run C X) ∈ Set.range v ∨ ∃ a, r.read C X (p.run C X) = C a := by + cases r with + | const a => exact Or.inr ⟨a, rfl⟩ + | var x => exact Or.inl (hX x) + | gate j => exact Or.inl (hp j) + +private theorem Ref.component_mem {p : Program R V n} (r : Ref R V n) + (M : Submodule R (MvPolynomial V R)) {d : ℕ} (hd : 1 < d) + (hp : ∀ j, homogeneousComponent d (p.run C X j) ∈ M) : + homogeneousComponent d (r.read C X (p.run C X)) ∈ M := by + cases r with + | const a => simp [Ref.read, positive_component_C a (by omega : d ≠ 0)] + | var x => + rw [Ref.read, homogeneousComponent_of_mem (isHomogeneous_X R x)] + split + · omega + · exact M.zero_mem + | gate j => exact hp j + +private theorem component_product_mem {d : ℕ} (p q : MvPolynomial V R) + (M : Submodule R (MvPolynomial V R)) (v : H → MvPolynomial V R) + (hp : homogeneousComponent d p ∈ M) (hq : homogeneousComponent d q ∈ M) + (hpv : p ∈ Set.range v ∨ ∃ a, p = C a) (hqv : q ∈ Set.range v ∨ ∃ a, q = C a) + (hprod : ∀ i j a b, 0 < a → 0 < b → a + b = d → + homogeneousComponent a (v i) * homogeneousComponent b (v j) ∈ M) : + homogeneousComponent d (p * q) ∈ M := by + rw [homogeneousComponent_mul] + apply M.sum_mem + rintro ⟨a, b⟩ hab + have hab' : a + b = d := Finset.mem_antidiagonal.mp hab + by_cases ha : a = 0 + · subst a + simp only [zero_add] at hab' + subst b + simpa only [homogeneousComponent_zero, smul_eq_C_mul] using M.smul_mem (p.coeff 0) hq + by_cases hb : b = 0 + · subst b + simp only [add_zero] at hab' + subst a + simpa only [homogeneousComponent_zero, smul_eq_C_mul, mul_comm] using M.smul_mem (q.coeff 0) hp + rcases hpv with ⟨i, rfl⟩ | ⟨x, rfl⟩ + · rcases hqv with ⟨j, rfl⟩ | ⟨y, rfl⟩ + · exact hprod i j a b (Nat.pos_of_ne_zero ha) (Nat.pos_of_ne_zero hb) hab' + · simp [positive_component_C y hb] + · simp [positive_component_C x ha] + +private theorem Program.components_mem (p : Program R V n) (M : Submodule R (MvPolynomial V R)) + (v : H → MvPolynomial V R) {d : ℕ} (hd : 1 < d) (hX : ∀ a, X a ∈ Set.range v) + (hprod : ∀ i j a b, 0 < a → 0 < b → a + b = d → + homogeneousComponent a (v i) * homogeneousComponent b (v j) ∈ M) + (hp : ∀ j, p.run C X j ∈ Set.range v) : + ∀ j, homogeneousComponent d (p.run C X j) ∈ M := by + induction p with + | nil => exact fun j ↦ j.elim0 + | snoc p op a b ih => + have hprev : ∀ j, p.run C X j ∈ Set.range v := fun j ↦ + by simpa only [Program.run, Fin.lastCases_castSucc] using hp j.castSucc + have ha := a.component_mem M hd (ih hprev) + have hb := b.component_mem M hd (ih hprev) + intro j + refine Fin.lastCases ?_ (fun i ↦ ?_) j + · simp only [Program.run, Fin.lastCases_last] + cases op with + | add => simpa only [BinOp.apply, map_add] using M.add_mem ha hb + | sub => simpa only [BinOp.apply, map_sub] using M.sub_mem ha hb + | mul => + exact component_product_mem _ _ M v ha hb (a.read_mem_or_constant v hX hprev) + (b.read_mem_or_constant v hX hprev) hprod + · simpa only [Program.run, Fin.lastCases_castSucc] using ih hprev i + +/-- Every graded state of degree above one is in the span of lower-degree productions, +using the specified slots for this very circuit, including its output slot. -/ +theorem Circuit.slot_component_mem (c : Circuit R V n) {d : ℕ} (hd : 1 < d) + (M : Submodule R (MvPolynomial V R)) + (hprod : ∀ i j a b, 0 < a → 0 < b → a + b = d → + homogeneousComponent a (c.slotPolynomial i) * homogeneousComponent b (c.slotPolynomial j) + ∈ M) : + ∀ h, homogeneousComponent d (c.slotPolynomial h) ∈ M := by + have hX : ∀ a, X a ∈ Set.range c.slotPolynomial := fun a ↦ ⟨some (.inl a), rfl⟩ + have hp : ∀ j, c.program.run C X j ∈ Set.range c.slotPolynomial := + fun j ↦ ⟨some (.inr j), rfl⟩ + have hgate := c.program.components_mem M c.slotPolynomial hd hX hprod hp + rintro (_ | (a | j)) + · exact c.output.component_mem M hd hgate + · exact (Ref.var a : Ref R V n).component_mem M hd hgate + · exact hgate j + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CircuitSize.lean b/lean/OAI/Computability/VPVNP/CircuitSize.lean new file mode 100644 index 0000000000..dd8076fb86 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CircuitSize.lean @@ -0,0 +1,104 @@ +import OAI.Computability.VPVNP.CircuitComposition +import OAI.Computability.VPVNP.CircuitDescent +import Mathlib.Data.Nat.Find + +/-! +# Minimum exact circuit size + +Every formal polynomial has a division-free arithmetic circuit. Taking the +minimum over topologically ordered circuits therefore defines the gate count +`L_F` of §1, including zero-gate circuits for variables and field constants. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +variable {R σ τ : Type*} [CommRing R] + +/-- A single scalar input is an output of a circuit with no binary gates. -/ +def Circuit.constant (a : R) : Circuit R σ 0 := ⟨.nil, .const a⟩ + +/-- A single variable is an output of a circuit with no binary gates. -/ +def Circuit.variable (i : σ) : Circuit R σ 0 := ⟨.nil, .var i⟩ + +@[simp] theorem Circuit.polynomial_constant (a : R) : + (Circuit.constant a : Circuit R σ 0).polynomial = MvPolynomial.C a := rfl + +@[simp] theorem Circuit.polynomial_variable (i : σ) : + (Circuit.variable i : Circuit R σ 0).polynomial = MvPolynomial.X i := rfl + +/-- Every multivariate polynomial is the formal output of a finite exact circuit. -/ +theorem exists_circuit_polynomial (p : MvPolynomial σ R) : + ∃ n, ∃ c : Circuit R σ n, c.polynomial = p := by + induction p using MvPolynomial.induction_on with + | C a => exact ⟨0, Circuit.constant a, rfl⟩ + | add p q hp hq => + obtain ⟨n, c, rfl⟩ := hp + obtain ⟨m, d, rfl⟩ := hq + exact ⟨n + m + 1, Circuit.combine .add c d, Circuit.polynomial_combine ..⟩ + | mul_X p i hp => + obtain ⟨n, c, rfl⟩ := hp + exact ⟨n + 0 + 1, Circuit.combine .mul c (Circuit.variable i), + Circuit.polynomial_combine ..⟩ + +/-- The least number of binary addition, subtraction and multiplication gates +in a circuit computing `p` as a formal polynomial, with arbitrary scalar inputs. -/ +noncomputable def circuitSize (p : MvPolynomial σ R) : ℕ := by + classical + exact Nat.find (exists_circuit_polynomial p) + +theorem circuitSize_spec (p : MvPolynomial σ R) : + ∃ c : Circuit R σ (circuitSize p), c.polynomial = p := by + classical + exact Nat.find_spec (exists_circuit_polynomial p) + +theorem circuitSize_le_iff {p : MvPolynomial σ R} {n : ℕ} : + circuitSize p ≤ n ↔ ∃ m ≤ n, ∃ c : Circuit R σ m, c.polynomial = p := by + classical + exact Nat.find_le_iff (exists_circuit_polynomial p) n + +theorem circuitSize_le_of_circuit {n : ℕ} (c : Circuit R σ n) : + circuitSize c.polynomial ≤ n := + circuitSize_le_iff.mpr ⟨n, le_rfl, c, rfl⟩ + +@[simp] theorem circuitSize_C (a : R) : circuitSize (MvPolynomial.C (σ := σ) a) = 0 := + Nat.eq_zero_of_le_zero (circuitSize_le_of_circuit (Circuit.constant a)) + +@[simp] theorem circuitSize_X (i : σ) : circuitSize (MvPolynomial.X (R := R) i) = 0 := + Nat.eq_zero_of_le_zero (circuitSize_le_of_circuit (Circuit.variable i)) + +theorem circuitSize_binOp_le (op : BinOp) (p q : MvPolynomial σ R) : + circuitSize (op.apply p q) ≤ circuitSize p + circuitSize q + 1 := by + obtain ⟨c, hc⟩ := circuitSize_spec p + obtain ⟨d, hd⟩ := circuitSize_spec q + simpa only [Circuit.polynomial_combine, hc, hd] using + circuitSize_le_of_circuit (Circuit.combine op c d) + +/-- Replacing variables by variables or constants preserves an upper bound +on the number of binary gates, regardless of the field constants used. -/ +theorem circuitSize_projection_le (φ : Projection R σ τ) (p : MvPolynomial σ R) : + circuitSize (φ.hom p) ≤ circuitSize p := by + obtain ⟨c, hc⟩ := circuitSize_spec p + simpa only [Circuit.project_polynomial, hc] using circuitSize_le_of_circuit (c.subst φ id) + +/-- Applying a scalar homomorphism to the output cannot increase its minimum gate count. -/ +theorem circuitSize_map_le {S : Type*} [CommRing S] (f : R →+* S) (p : MvPolynomial σ R) : + circuitSize (MvPolynomial.map f p) ≤ circuitSize p := by + obtain ⟨c, hc⟩ := circuitSize_spec p + simpa only [Circuit.map_polynomial, hc] using circuitSize_le_of_circuit (c.mapConstants f) + +/-- Section 1's reduction to one algebraically closed field. For a polynomial over +the prime field `k`, a lower bound over its algebraic closure `K` holds with the +same numerical value over every field extension `F` of `k`. -/ +theorem circuitSize_descent_le {k K F : Type*} [Field k] [Field K] [Field F] + [Algebra k K] [Algebra k F] [IsAlgClosed K] (p : MvPolynomial σ k) : + circuitSize (MvPolynomial.map (algebraMap k K) p) ≤ + circuitSize (MvPolynomial.map (algebraMap k F) p) := by + obtain ⟨c, hc⟩ := circuitSize_spec (MvPolynomial.map (algebraMap k F) p) + obtain ⟨f, hf⟩ := c.exists_scalar_relabeling (K := K) p hc + simpa only [hf] using circuitSize_le_of_circuit (c.mapConstants f) + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/Circuits.lean b/lean/OAI/Computability/VPVNP/Circuits.lean new file mode 100644 index 0000000000..35cf1c9970 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/Circuits.lean @@ -0,0 +1,155 @@ +import Mathlib.Algebra.MvPolynomial.Eval + +/-! # Exact arithmetic circuits and projections + +Gates are listed in topological order. Each operand may use any earlier gate, a variable, +or any scalar in the coefficient ring. Only binary operations count toward the size. +The designated output is evaluated in the ring of formal multivariate polynomials. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +/-- A binary addition, subtraction, or multiplication gate in an exact arithmetic circuit. -/ +inductive BinOp where + | add | sub | mul + +/-- Interpret a gate's operation on its two ordered inputs in the target ring. -/ +def BinOp.apply {A : Type*} [Ring A] : BinOp → A → A → A + | .add => (· + ·) + | .sub => (· - ·) + | .mul => (· * ·) + +/-- A reference available after exactly `n` gates have been computed. -/ +inductive Ref (R σ : Type*) (n : ℕ) where + | var : σ → Ref R σ n + | const : R → Ref R σ n + | gate : Fin n → Ref R σ n + +/-- A topologically ordered list of arithmetic gates. The index counts the gates already +available to subsequent operands. -/ +inductive Program (R σ : Type*) : ℕ → Type _ where + | nil : Program R σ 0 + | snoc {n : ℕ} (prev : Program R σ n) (op : BinOp) (a b : Ref R σ n) : Program R σ (n+1) + +/-- An arithmetic program with one designated output. Its size index counts binary operations. -/ +structure Circuit (R σ : Type*) (n : ℕ) where + /-- The sequence of binary gates available to the output reference. -/ + program : Program R σ n + /-- The input variable, ring constant, or previously computed gate selected as the output. -/ + output : Ref R σ n + +variable {R S σ τ A B : Type*} {n : ℕ} + +/-- Resolve an operand using the supplied interpretation of constants, inputs, and earlier gate +values. -/ +def Ref.read (scalar : R → A) (input : σ → A) (wires : Fin n → A) : Ref R σ n → A + | .const r => scalar r + | .var i => input i + | .gate i => wires i + +/-- Evaluate the gates in topological order and return the value at every gate index. -/ +def Program.run [Ring A] (scalar : R → A) (input : σ → A) : + {n : ℕ} → Program R σ n → Fin n → A + | _, .nil => Fin.elim0 + | _, .snoc p op a b => + let wires := p.run scalar input + Fin.lastCases (op.apply (a.read scalar input wires) (b.read scalar input wires)) wires + +/-- Read the designated output after evaluating the circuit with the supplied scalar and +variable assignments. -/ +def Circuit.eval [Ring A] (c : Circuit R σ n) (scalar : R → A) (input : σ → A) : A := + c.output.read scalar input (c.program.run scalar input) + +/-- The formal polynomial computed when each input is its corresponding indeterminate and each +scalar is a constant polynomial. -/ +noncomputable def Circuit.polynomial [CommRing R] (c : Circuit R σ n) : MvPolynomial σ R := + c.eval MvPolynomial.C MvPolynomial.X + +/-- Substitutions allowed in a projection. A variable may become a variable or a scalar. -/ +abbrev Projection (R σ τ : Type*) := σ → τ ⊕ R + +/-- Apply a projection to a variable operand and the supplied scalar map to a constant operand. +A gate reference keeps its index. -/ +def Ref.subst (φ : Projection S σ τ) (f : R → S) : Ref R σ n → Ref S τ n + | .var i => (φ i).elim Ref.var Ref.const + | .const r => .const (f r) + | .gate i => .gate i + +/-- Project the variable operands and map the constants of every gate in the program. -/ +def Program.subst (φ : Projection S σ τ) (f : R → S) : + {n : ℕ} → Program R σ n → Program S τ n + | _, .nil => .nil + | _, .snoc p op a b => .snoc (p.subst φ f) op (a.subst φ f) (b.subst φ f) + +/-- Apply the same variable projection and scalar map to the program and its designated output +reference. -/ +def Circuit.subst (c : Circuit R σ n) (φ : Projection S σ τ) (f : R → S) : Circuit S τ n := + ⟨c.program.subst φ f, c.output.subst φ f⟩ + +/-- Specialize each scalar operand along the given map while retaining the circuit's input +variables. -/ +def Circuit.mapConstants (c : Circuit R σ n) (f : R → S) : Circuit S σ n := + c.subst Sum.inl f + +private theorem Ref.read_subst (φ : Projection S σ τ) (f : R → S) + (s : S → A) (x : τ → A) (w : Fin n → A) (r : Ref R σ n) : + (r.subst φ f).read s x w = r.read (s ∘ f) (fun i => (φ i).elim x s) w := by + cases r with + | var i => cases h : φ i <;> simp [Ref.subst, Ref.read, h] + | const | gate => rfl + +private theorem Program.run_subst [Ring A] (φ : Projection S σ τ) (f : R → S) + (s : S → A) (x : τ → A) (p : Program R σ n) : + (p.subst φ f).run s x = p.run (s ∘ f) (fun i => (φ i).elim x s) := by + induction p with + | nil => rfl + | snoc p op a b ih => simp only [Program.subst, Program.run, ih, Ref.read_subst] + +theorem Circuit.eval_subst [Ring A] (c : Circuit R σ n) (φ : Projection S σ τ) + (f : R → S) (s : S → A) (x : τ → A) : + (c.subst φ f).eval s x = c.eval (s ∘ f) (fun i => (φ i).elim x s) := by + simp only [Circuit.eval, Circuit.subst, Program.run_subst, Ref.read_subst] + +private theorem Ref.read_hom [Ring A] [Ring B] (h : A →+* B) (s : R → A) (x : σ → A) + (w : Fin n → A) (r : Ref R σ n) : + h (r.read s x w) = r.read (h ∘ s) (h ∘ x) (h ∘ w) := by cases r <;> rfl + +private theorem Program.run_hom [Ring A] [Ring B] (h : A →+* B) (s : R → A) (x : σ → A) + (p : Program R σ n) : h ∘ p.run s x = p.run (h ∘ s) (h ∘ x) := by + induction p with + | nil => funext j; exact j.elim0 + | snoc p op a b ih => + funext j + refine Fin.lastCases ?_ (fun i => ?_) j + · simp only [Function.comp_apply, Program.run, Fin.lastCases_last] + cases op <;> simp [BinOp.apply, Ref.read_hom, ih] + · simpa [Program.run, Function.comp_def] using congrFun ih i + +theorem Circuit.eval_hom [Ring A] [Ring B] (c : Circuit R σ n) (h : A →+* B) + (s : R → A) (x : σ → A) : h (c.eval s x) = c.eval (h ∘ s) (h ∘ x) := by + simp only [Circuit.eval, Ref.read_hom, Program.run_hom] + +/-- Scalar specialization preserves every binary gate of the circuit. -/ +theorem Circuit.map_polynomial [CommRing R] [CommRing S] (c : Circuit R σ n) (f : R →+* S) : + (c.mapConstants f).polynomial = MvPolynomial.map f c.polynomial := by + rw [Circuit.mapConstants, Circuit.polynomial, Circuit.eval_subst, Circuit.polynomial, + Circuit.eval_hom] + congr 1 <;> funext i <;> simp + +/-- The coefficient-preserving polynomial semiring homomorphism substituting each source +variable by its prescribed target variable or scalar. -/ +noncomputable def Projection.hom [CommSemiring R] (φ : Projection R σ τ) : + MvPolynomial σ R →+* MvPolynomial τ R := + MvPolynomial.eval₂Hom MvPolynomial.C (fun i => (φ i).elim MvPolynomial.X MvPolynomial.C) + +/-- Projecting a formal polynomial computed with `n` gates gives an `n`-gate circuit. -/ +theorem Circuit.project_polynomial [CommRing R] (c : Circuit R σ n) (φ : Projection R σ τ) : + (c.subst φ id).polynomial = φ.hom c.polynomial := by + rw [Circuit.polynomial, Circuit.eval_subst, Circuit.polynomial, Circuit.eval_hom] + congr 1 <;> funext i <;> simp [Projection.hom] + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ClassSeparation.lean b/lean/OAI/Computability/VPVNP/ClassSeparation.lean new file mode 100644 index 0000000000..513ce5b4c0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ClassSeparation.lean @@ -0,0 +1,29 @@ +import OAI.Computability.VPVNP.Separation +import OAI.Computability.VPVNP.Valiant.Project + +/-! # Exact VP and VNP in the binary gate model -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Standalone + +universe u + +/-- The two nonuniform classes differ over each field. -/ +theorem vp_ne_vnp (F : Type u) [Field F] : + (Valiant.Project.IsVP : Valiant.Project.Family F (fun n => Fin n × Bool) → Prop) ≠ + Valiant.Project.IsVNP := by + intro same + apply VPVNP.vp_ne_vnp F + funext f + apply propext + exact (Valiant.Project.isVP_iff f).symm.trans ((Iff.of_eq (congrFun same f)).trans + (Valiant.Project.isVNP_iff f)) + +end Standalone + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/Classes.lean b/lean/OAI/Computability/VPVNP/Classes.lean new file mode 100644 index 0000000000..14fcf07f78 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/Classes.lean @@ -0,0 +1,74 @@ +import OAI.Computability.VPVNP.CircuitSize +import OAI.Computability.VPVNP.EventualBounds + +/-! # Nonuniform arithmetic complexity classes + +A family is indexed by its length. Its variables may be any finite type at that length. +The bounds are asymptotic, with an exponent and a leading constant independent of the +length. Circuits compute formal polynomials, and only Boolean witness variables are +specialized to field elements in the definition of VNP. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open scoped Classical + +/-- There are fixed natural numbers `A`, `d` and `N` such that `f n ≤ A * n^d` for every `n ≥ +N`. -/ +def PolynomiallyBounded (f : ℕ → ℕ) : Prop := + ∃ A d N : ℕ, ∀ n ≥ N, f n ≤ A * n ^ d + +variable {F : Type*} [Field F] {σ τ : ℕ → Type} [∀ n, Fintype (σ n)] + +/-- A sequence of formal polynomials over `F` whose variable type `σ n` may depend on the index +`n`. -/ +abbrev Family (F : Type*) [CommSemiring F] (σ : ℕ → Type) := + (n : ℕ) → MvPolynomial (σ n) F + +/-- Both the number of variables and the total degree of the indexed polynomials are +polynomially bounded in the family index. -/ +def PFamily (p : Family F σ) : Prop := + PolynomiallyBounded (fun n => Fintype.card (σ n)) ∧ + PolynomiallyBounded (fun n => (p n).totalDegree) + +/-- The family has polynomially bounded variable count and degree, and each member is computed +exactly as a formal polynomial by arithmetic circuits of polynomially bounded size with +arbitrary field constants. -/ +def IsVP (p : Family F σ) : Prop := + PFamily p ∧ PolynomiallyBounded (fun n => circuitSize (p n)) + +/-- Substitution of the bits of a single witness, leaving the output variables formal. -/ +noncomputable def witnessValue {X W : Type} (bits : W → Bool) : + MvPolynomial (X ⊕ W) F →+* MvPolynomial X F := + MvPolynomial.eval₂Hom MvPolynomial.C (Sum.elim MvPolynomial.X + (fun i => MvPolynomial.C (if bits i then 1 else 0))) + +/-- A polynomial family obtained by summing a VP family over all Boolean assignments to a +polynomially bounded number of witness variables, with the output variables left formal. -/ +def IsVNP (p : Family F σ) : Prop := + PFamily p ∧ ∃ (W : ℕ → Type) (inst : ∀ n, Fintype (W n)) + (g : Family F (fun n => σ n ⊕ W n)), + PolynomiallyBounded (fun n => @Fintype.card _ (inst n)) ∧ IsVP g ∧ + ∀ n, p n = ∑ y : W n → Bool, witnessValue y (g n) + +/-- The source index can grow polynomially and need not be monotone. -/ +def PProjects (target : Family F τ) (source : Family F σ) : Prop := + ∃ r : ℕ → ℕ, PolynomiallyBounded r ∧ + ∀ n, ∃ φ : Projection F (σ (r n)) (τ n), φ.hom (source (r n)) = target n + +/-- The family belongs to VNP and every VNP family over the same field is obtained from it by a +polynomially bounded reindexing and substitutions of variables by target variables or field +constants. -/ +def VNPComplete (p : Family F σ) : Prop := + IsVNP p ∧ ∀ (τ : ℕ → Type) [∀ n, Fintype (τ n)] (g : Family F τ), IsVNP g → PProjects g p + +/-- The strict lower bound required in Theorem 1.1 excludes membership in VP. -/ +theorem not_isVP_of_eventual_size {p : Family F σ} + (h : EventuallySuperpolynomial (fun n => circuitSize (p n))) : ¬ IsVP p := + fun hp => h.not_polynomially_bounded hp.2 + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CloudIteration.lean b/lean/OAI/Computability/VPVNP/CloudIteration.lean new file mode 100644 index 0000000000..6f7b22dafc --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CloudIteration.lean @@ -0,0 +1,181 @@ +import OAI.Computability.VPVNP.CloudReplacement +import OAI.Computability.VPVNP.GraphRounding +import OAI.Computability.VPVNP.LayerWalk +import OAI.Computability.VPVNP.PortWalkRealization + +/-! +# Iterating cloud replacement at a fixed degree + +Section 5.3 of *VP and VNP differ over every field* iterates the replacement +starting at a single vertex. All targets in the given family share the same +sequence of integer adjacency matrices. For a port graph with bound `β ≥ 1`, +the explicit bound `444 * β` is preserved when `t ≥ 1776 * β`. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace SpectralGeometry + +variable {V K X : Type*} [Fintype V] [Fintype K] [PseudoMetricSpace X] + +/-- Poincaré bounds are independent of vertex labels. -/ +theorem hasPoincareBound_equiv (e : V ≃ K) (P : Matrix V V ℝ) {γ : ℝ} + (hP : HasPoincareBound X P γ) : + HasPoincareBound X (fun i j ↦ P (e.symm i) (e.symm j)) γ := by + intro x + have hpair : + (∑ i : V, ∑ j : V, dist (x (e i)) (x (e j)) ^ 2) = + ∑ i : K, ∑ j : K, dist (x i) (x j) ^ 2 := by + apply Fintype.sum_equiv e + intro i + exact Fintype.sum_equiv e _ _ fun _ ↦ rfl + have hedge : + walkEnergy P (fun i ↦ x (e i)) = + walkEnergy (fun i j ↦ P (e.symm i) (e.symm j)) x := by + unfold walkEnergy + apply Fintype.sum_equiv e + intro i + apply Fintype.sum_equiv e + simp + simpa only [hpair, Fintype.card_congr e, hedge] using hP (fun i ↦ x (e i)) + +omit [Fintype V] [Fintype K] in +/-- Normalizing the integer replacement by its degree gives the equal mixture +of internal moves and matching moves. -/ +theorem normalize_replacementArcs [DecidableEq V] [DecidableEq K] (H : Matrix K K ℕ) + (σ : Equiv.Perm (V × K)) {h : ℕ} (hh : 0 < h) : + normalizeArcs (replacementArcs H σ h) (2 * h) = cloudWalk (normalizeArcs H h) σ := by + ext p q + have hh' : (h : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr hh.ne' + simp only [normalizeArcs, replacementArcs, cloudWalk, Nat.cast_mul, Nat.cast_ofNat, + eq_comm (a := q.1) (b := p.1), eq_comm (a := q) (b := σ p)] + split_ifs <;> push_cast <;> field_simp <;> ring + +variable {T : Type*} (Y : T → Type*) [∀ a, PseudoMetricSpace (Y a)] + [∀ a, CompleteSpace (Y a)] [∀ a, Nonempty (Y a)] + +/-- One amplification step on integral regular multigraphs. The matching, +hence the resulting graph, works simultaneously for every target. -/ +theorem exists_cloudStep [DecidableEq V] [Nonempty V] {Q h n : ℕ} + (hQ : 0 < Q) (hh : 0 < h) (hn : 0 < n) + (H : Matrix (Fin Q) (Fin Q) ℕ) (hHs : ∀ i j, H i j = H j i) + (hHr : ∀ i, ∑ j, H i j = h) + (G : Matrix V V ℕ) (hGs : ∀ i j, G i j = G j i) + (hGr : ∀ i, ∑ j, G i j = 2 * h) + {β : ℝ} (hβ : 1 ≤ β) (ht : 1776 * β ≤ 2 * (n : ℝ)) + (hdiv : (2 * n) * (2 * (2 * h)) ^ (2 * n) ∣ Q) + (hcat : ∀ a, HasCATZeroSegments (Y a)) + (hH : ∀ a, HasPoincareBound (Y a) (normalizeArcs H h) β) + (hG : ∀ a, HasPoincareBound (Y a) (normalizeArcs G (2 * h)) (444 * β)) : + ∃ G' : Matrix (V × Fin Q) (V × Fin Q) ℕ, (∀ i j, G' i j = G' j i) ∧ + (∀ i, ∑ j, G' i j = 2 * h) ∧ + ∀ a, HasPoincareBound (Y a) (normalizeArcs G' (2 * h)) (444 * β) := by + let : NeZero Q := ⟨hQ.ne'⟩ + have hb : 0 < 2 * h := by omega + have hn' : 0 < 2 * n := by omega + let P := normalizeArcs G (2 * h) + obtain ⟨σ, hi, port, _⟩ := exists_cesaroPortMatching G hb hn' hQ hGs hGr hdiv + refine ⟨replacementArcs H σ h, replacementArcs_symmetric H hHs σ hi h, + replacementArcs_degree H h hHr σ, ?_⟩ + intro a + rw [normalize_replacementArcs H σ hh] + have hpos (v w : V) : 0 ≤ P v w := by unfold P normalizeArcs; positivity + have hrow (v : V) : ∑ w, P v w = 1 := normalizeArcs_row_sum G hb v (hGr v) + have hcol (w : V) : ∑ v, P v w = 1 := by + have sym (v : V) : P v w = P w v := by simp only [P, normalizeArcs, hGs v w] + simp only [sym] + exact hrow w + have hbound := cesaroWalk_hasPoincareBound (hcat a) P hpos hrow hcol + (show 0 ≤ 444 * β by linarith only [hβ]) (hG a) hn + have hmax : max 12 (48 * (444 * β) / (2 * (n : ℝ))) = 12 := by + apply max_eq_left + exact (div_le_iff₀ (by positivity)).mpr (by linarith only [ht]) + rw [hmax] at hbound + have hS : HasPoincareBound (Y a) (portWalk σ) 12 := port ▸ hbound + convert cloudWalk_hasPoincareBound (normalizeArcs H h) σ hβ (by norm_num : (0 : ℝ) ≤ 12) + (hH a) hS using 1 + ring + +/-- Starting with a single vertex and `2h` loops, repeated cloud replacement +gives orders `Q^j`, keeping both degree and Poincaré bound independent of `j`. -/ +theorem exists_iteratedCloudGraph {Q h n : ℕ} (hQ : 0 < Q) (hh : 0 < h) (hn : 0 < n) + (H : Matrix (Fin Q) (Fin Q) ℕ) (hHs : ∀ i j, H i j = H j i) + (hHr : ∀ i, ∑ j, H i j = h) {β : ℝ} (hβ : 1 ≤ β) + (ht : 1776 * β ≤ 2 * (n : ℝ)) (hdiv : (2 * n) * (2 * (2 * h)) ^ (2 * n) ∣ Q) + (hcat : ∀ a, HasCATZeroSegments (Y a)) + (hH : ∀ a, HasPoincareBound (Y a) (normalizeArcs H h) β) (j : ℕ) : + ∃ G : Matrix (Fin (Q ^ j)) (Fin (Q ^ j)) ℕ, (∀ u v, G u v = G v u) ∧ + (∀ u, ∑ v, G u v = 2 * h) ∧ + ∀ a, HasPoincareBound (Y a) (normalizeArcs G (2 * h)) (444 * β) := by + induction j with + | zero => + refine ⟨fun _ _ ↦ 2 * h, fun _ _ ↦ rfl, ?_, ?_⟩ + · intro _ + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, pow_zero, one_nsmul] + intro a x + have hall (i j : Fin (Q ^ 0)) : i = j := by + have hi := i.isLt + have hj := j.isLt + simp only [pow_zero] at hi hj + exact Fin.ext (by omega) + have hd (i j : Fin (Q ^ 0)) : dist (x i) (x j) = 0 := by rw [hall i j, dist_self] + simp only [walkEnergy, hd, zero_pow (by decide : 2 ≠ 0), mul_zero, Finset.sum_const_zero, + zero_div, le_refl] + | succ j ih => + obtain ⟨G, hs, hr, hg⟩ := ih + let : NeZero (Q ^ j) := ⟨(pow_pos hQ j).ne'⟩ + obtain ⟨G', hs', hr', hg'⟩ := + exists_cloudStep Y hQ hh hn H hHs hHr G hs hr hβ ht hdiv hcat hH hg + let e : (Fin (Q ^ j) × Fin Q) ≃ Fin (Q ^ (j + 1)) := + Fintype.equivFinOfCardEq (by simp [pow_succ]) + refine ⟨fun u v ↦ G' (e.symm u) (e.symm v), fun _ _ ↦ hs' _ _, ?_, ?_⟩ + · intro u + exact (Equiv.sum_comp e.symm (G' (e.symm u))).trans (hr' (e.symm u)) + · exact fun a ↦ hasPoincareBound_equiv e _ (hg' a) + +/-- The double cover of each iterated graph has no loops and has a common +Poincaré bound for the entire target family. Its order and degree are twice +those of the iterated graph. -/ +theorem exists_looplessCloudGraph {Q h n : ℕ} (hQ : 0 < Q) (hh : 0 < h) (hn : 0 < n) + (H : Matrix (Fin Q) (Fin Q) ℕ) (hHs : ∀ i j, H i j = H j i) + (hHr : ∀ i, ∑ j, H i j = h) {β : ℝ} (hβ : 1 ≤ β) + (ht : 1776 * β ≤ 2 * (n : ℝ)) (hdiv : (2 * n) * (2 * (2 * h)) ^ (2 * n) ∣ Q) + (hcat : ∀ a, HasCATZeroSegments (Y a)) + (hH : ∀ a, HasPoincareBound (Y a) (normalizeArcs H h) β) (j : ℕ) : + ∃ G : Matrix (Fin (2 * Q ^ j)) (Fin (2 * Q ^ j)) ℕ, (∀ u v, G u v = G v u) ∧ + (∀ u, ∑ v, G u v = 4 * h) ∧ (∀ u, G u u = 0) ∧ + ∀ a, HasPoincareBound (Y a) (normalizeArcs G (4 * h)) (6 + 12 * (444 * β)) := by + obtain ⟨G, hs, hr, hb⟩ := exists_iteratedCloudGraph Y hQ hh hn H hHs hHr hβ ht hdiv hcat hH j + let : NeZero (Q ^ j) := ⟨(pow_pos hQ j).ne'⟩ + let e : (Fin (Q ^ j) × Bool) ≃ Fin (2 * Q ^ j) := Fintype.equivFinOfCardEq (by simp [mul_comm]) + let G' := layerArcs G (2 * h) + refine ⟨fun u v ↦ G' (e.symm u) (e.symm v), fun _ _ ↦ layerArcs_symmetric G hs _ _ _, + ?_, fun _ ↦ layerArcs_no_loops G _ _, ?_⟩ + · intro u + rw [Equiv.sum_comp e.symm (G' (e.symm u))] + exact (layerArcs_degree G _ hr _).trans (by omega) + · intro a + let P := normalizeArcs G (2 * h) + have hnP (i j) : 0 ≤ P i j := by unfold P normalizeArcs; positivity + have hsP (i j) : P i j = P j i := by simp only [P, normalizeArcs, hs i j] + have hcP (j) : ∑ i, P i j = 1 := by + simp only [fun i ↦ hsP i j] + exact normalizeArcs_row_sum G (by omega) j (hr j) + have hnorm : normalizeArcs G' (4 * h) = layerWalk P := by + ext p q + change (layerArcs G (2 * h) p q : ℝ) / (4 * h : ℕ) = + layerWalk (fun u v ↦ (G u v : ℝ) / (2 * h : ℕ)) p q + simp only [Nat.cast_mul, Nat.cast_ofNat] + simpa only [Nat.cast_mul, Nat.cast_ofNat, ← mul_assoc, show (2 : ℝ) * 2 = 4 by norm_num] + using layerArcs_normalize G (show 0 < 2 * h by omega) p q + apply hasPoincareBound_equiv e (normalizeArcs G' (4 * h)) + rw [hnorm] + exact layerWalk_hasPoincareBound P hnP hsP hcP (by linarith only [hβ]) (hb a) + +end SpectralGeometry + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CloudReplacement.lean b/lean/OAI/Computability/VPVNP/CloudReplacement.lean new file mode 100644 index 0000000000..b83267dd1b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CloudReplacement.lean @@ -0,0 +1,179 @@ +import OAI.Computability.VPVNP.WalkEnergy +import Mathlib.Data.Fintype.BigOperators + +/-! +# Cloud replacement in the bounded-degree amplification + +Section 5.3 of *VP and VNP differ over every field* replaces each old vertex +with a copy of a fixed port graph. Half the steps stay in the cloud and half +follow a matching on the ports. The matching realizes an averaged walk on the +old vertices. The estimates below use the same normalization as `walkEnergy`. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace SpectralGeometry + +open scoped BigOperators + +variable {V K X : Type*} [Fintype V] [Fintype K] [PseudoMetricSpace X] + +private theorem sq_dist_le_three_segments (a b c d : X) : + dist a d ^ 2 ≤ 3 * (dist a b ^ 2 + dist b c ^ 2 + dist c d ^ 2) := by + have h := (dist_triangle a b d).trans (add_le_add_right (dist_triangle b c d) _) + have hs := pow_le_pow_left₀ dist_nonneg h 2 + nlinarith [sq_nonneg (dist a b - dist b c), sq_nonneg (dist b c - dist c d), + sq_nonneg (dist c d - dist a b)] + +/-- The energy between the centers of matched clouds is bounded by the matching energy +and twice the squared displacement to a port's center (§5.3). -/ +theorem cloudMatchingEnergy_le (σ : Equiv.Perm (V × K)) (x : V × K → X) (y : V → X) : + (∑ p : V × K, dist (y p.1) (y (σ p).1) ^ 2) ≤ + 3 * (2 * (∑ p : V × K, dist (x p) (y p.1) ^ 2) + + ∑ p : V × K, dist (x p) (x (σ p)) ^ 2) := by + calc + _ ≤ ∑ p : V × K, 3 * (dist (x p) (y p.1) ^ 2 + dist (x p) (x (σ p)) ^ 2 + + dist (x (σ p)) (y (σ p).1) ^ 2) := by + apply Finset.sum_le_sum + intro p _ + simpa only [dist_comm (y p.1) (x p)] using + sq_dist_le_three_segments (y p.1) (x p) (x (σ p)) (y (σ p).1) + _ = _ := by + rw [← Finset.mul_sum, Finset.sum_add_distrib, Finset.sum_add_distrib] + rw [Equiv.sum_comp σ (fun p : V × K => dist (x p) (y p.1) ^ 2)] + ring + +/-- The transition matrix on clouds obtained by following a matching from a +uniformly chosen port. -/ +noncomputable def portWalk [DecidableEq V] (σ : Equiv.Perm (V × K)) : Matrix V V ℝ := + fun v w ↦ ((Finset.univ.filter (fun k : K ↦ (σ (v, k)).1 = w)).card : ℝ) / + Fintype.card K + +/-- The internal transition kernel and the matching transition each have weight one half. -/ +noncomputable def cloudWalk [DecidableEq V] [DecidableEq K] + (H : Matrix K K ℝ) (σ : Equiv.Perm (V × K)) : Matrix (V × K) (V × K) ℝ := + fun p q ↦ ((if p.1 = q.1 then H p.2 q.2 else 0) + (if σ p = q then 1 else 0)) / 2 + +private theorem cloudWalk_energy [DecidableEq V] [DecidableEq K] + (H : Matrix K K ℝ) (σ : Equiv.Perm (V × K)) (x : V × K → X) : + walkEnergy (cloudWalk H σ) x = + ((∑ v, walkEnergy H (fun k ↦ x (v,k))) + ∑ p, dist (x p) (x (σ p)) ^ 2) / 2 := by + have row (p : V × K) : + (∑ q : V × K, (if p.1 = q.1 then H p.2 q.2 else 0) * dist (x q) (x p) ^ 2) = + ∑ k, H p.2 k * dist (x (p.1, k)) (x p) ^ 2 := by + rw [Fintype.sum_prod_type] + simp only [ite_mul, zero_mul, Finset.sum_ite_irrel, Finset.sum_const_zero] + simp + simp only [walkEnergy, cloudWalk, div_mul_eq_mul_div] + simp only [div_eq_mul_inv, ← Finset.sum_mul] + congr 1 + simp only [add_mul, Finset.sum_add_distrib, row] + simp only [ite_mul, one_mul, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + congr 1 + · rw [Fintype.sum_prod_type] + · exact Finset.sum_congr rfl fun p _ ↦ by rw [dist_comm] + +private theorem portWalk_energy [DecidableEq V] [Nonempty K] + (σ : Equiv.Perm (V × K)) (y : V → X) : + (Fintype.card K : ℝ) * walkEnergy (portWalk σ) y = + ∑ p, dist (y p.1) (y (σ p).1) ^ 2 := by + have hK : (Fintype.card K : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero + rw [walkEnergy, Fintype.sum_prod_type, Finset.mul_sum] + apply Finset.sum_congr rfl + intro v _ + rw [Finset.mul_sum] + have term (w : V) : (Fintype.card K : ℝ) * (portWalk σ v w * dist (y w) (y v) ^ 2) = + ∑ k : K, if (σ (v, k)).1 = w then dist (y v) (y w) ^ 2 else 0 := by + rw [Finset.sum_ite, Finset.sum_const_zero, add_zero, Finset.sum_const, + nsmul_eq_mul, portWalk, dist_comm (y w) (y v)] + field_simp + simp_rw [term] + rw [Finset.sum_comm] + simp + +private theorem cloudCenters [Nonempty K] (H : Matrix K K ℝ) + {β : ℝ} (hH : HasPoincareBound X H β) (x : V × K → X) : + ∃ y : V → X, (∑ p : V × K, dist (x p) (y p.1) ^ 2) ≤ + β * ∑ v, walkEnergy H (fun k ↦ x (v,k)) := by + have hK : (0 : ℝ) < Fintype.card K := Nat.cast_pos.mpr Fintype.card_pos + have each (v : V) : ∃ k : K, (∑ l : K, dist (x (v,l)) (x (v,k)) ^ 2) ≤ + β * walkEnergy H (fun l ↦ x (v,l)) := by + have hbound := (div_le_iff₀ hK).mp (hH (fun l ↦ x (v,l))) + rw [Finset.sum_comm] at hbound + have hs : (∑ k : K, ∑ l : K, dist (x (v,l)) (x (v,k)) ^ 2) ≤ + ∑ _k : K, β * walkEnergy H (fun l ↦ x (v,l)) := by + simpa only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, + mul_comm (Fintype.card K : ℝ)] using hbound + obtain ⟨k, _, hk⟩ := Finset.exists_le_of_sum_le Finset.univ_nonempty hs + exact ⟨k, hk⟩ + choose k hk using each + refine ⟨fun v ↦ x (v,k v), ?_⟩ + rw [Fintype.sum_prod_type, Finset.mul_sum] + exact Finset.sum_le_sum fun v _ ↦ hk v + +private theorem lifted_pair_sum (y : V → X) : + (∑ p : V × K, ∑ q : V × K, dist (y p.1) (y q.1) ^ 2) = + (Fintype.card K : ℝ) ^ 2 * ∑ i : V, ∑ j : V, dist (y i) (y j) ^ 2 := by + simp only [Fintype.sum_prod_type, Finset.sum_const, Finset.card_univ, + nsmul_eq_mul, ← Finset.mul_sum] + ring + +/-- The cloud graph amplifies a bound on the induced walk between clouds +using the bound on the internal port graph. -/ +theorem cloudWalk_hasPoincareBound [DecidableEq V] [DecidableEq K] [Nonempty V] [Nonempty K] + (H : Matrix K K ℝ) (σ : Equiv.Perm (V × K)) + {β δ : ℝ} (hβ : 1 ≤ β) (hδ : 0 ≤ δ) (hH : HasPoincareBound X H β) + (hS : HasPoincareBound X (portWalk σ) δ) : + HasPoincareBound X (cloudWalk H σ) (12 * β * (1 + 3 * δ)) := by + intro x + obtain ⟨y, hy⟩ := cloudCenters H hH x + let I := ∑ v, walkEnergy H (fun k ↦ x (v,k)) + let M := ∑ p, dist (x p) (x (σ p)) ^ 2 + let D := ∑ p : V × K, dist (x p) (y p.1) ^ 2 + have hM : 0 ≤ M := Finset.sum_nonneg fun p _ ↦ sq_nonneg _ + have hD : D ≤ β * I := hy + have hV : (0 : ℝ) < Fintype.card V := Nat.cast_pos.mpr Fintype.card_pos + have hK : (0 : ℝ) < Fintype.card K := Nat.cast_pos.mpr Fintype.card_pos + have hcomp := pairVariance_le_displacement_variance x (fun p : V × K ↦ y p.1) + simp only [lifted_pair_sum, Fintype.card_prod, Nat.cast_mul] at hcomp + have hsmall := (div_le_iff₀ hV).mp (hS y) + have hmatch := cloudMatchingEnergy_le σ x y + rw [← portWalk_energy] at hmatch + change (Fintype.card K : ℝ) * walkEnergy (portWalk σ) y ≤ 3 * (2 * D + M) at hmatch + have hmacro : + (Fintype.card K : ℝ) ^ 2 * (∑ i, ∑ j, dist (y i) (y j) ^ 2) ≤ + (Fintype.card V : ℝ) * Fintype.card K * (δ * (3 * (2 * D + M))) := by + calc + _ ≤ (Fintype.card K : ℝ) ^ 2 * + ((δ * walkEnergy (portWalk σ) y) * Fintype.card V) := + mul_le_mul_of_nonneg_left hsmall (sq_nonneg _) + _ = ((Fintype.card V : ℝ) * Fintype.card K * δ) * + ((Fintype.card K : ℝ) * walkEnergy (portWalk σ) y) := by ring + _ ≤ _ := by + convert mul_le_mul_of_nonneg_left hmatch (mul_nonneg (mul_nonneg hV.le hK.le) hδ) using 1 + ring + have coeff : 3 * (2 * D + δ * (3 * (2 * D + M))) ≤ + 12 * β * (1 + 3 * δ) * ((I + M) / 2) := by + have hD' := mul_le_mul_of_nonneg_left hD (show 0 ≤ 6 + 18 * δ by linarith) + have hc : 9 * δ ≤ 6 * β + 18 * β * δ := by + nlinarith only [hβ, hδ, mul_nonneg (sub_nonneg.mpr hβ) hδ] + nlinarith only [hD', mul_le_mul_of_nonneg_right hc hM] + rw [cloudWalk_energy, Fintype.card_prod, Nat.cast_mul] + apply (div_le_iff₀ (mul_pos hV hK)).mpr + change _ ≤ _ * ((I + M) / 2) * ((Fintype.card V : ℝ) * Fintype.card K) + calc + _ ≤ 3 * (2 * ((Fintype.card V : ℝ) * Fintype.card K) * D + + (Fintype.card K : ℝ) ^ 2 * (∑ i, ∑ j, dist (y i) (y j) ^ 2)) := hcomp + _ ≤ 3 * (2 * ((Fintype.card V : ℝ) * Fintype.card K) * D + + (Fintype.card V : ℝ) * Fintype.card K * (δ * (3 * (2 * D + M)))) := by linarith only [hmacro] + _ = (3 * (2 * D + δ * (3 * (2 * D + M)))) * + ((Fintype.card V : ℝ) * Fintype.card K) := by ring + _ ≤ _ := mul_le_mul_of_nonneg_right coeff (mul_nonneg hV.le hK.le) + +end SpectralGeometry + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompleteFieldDescent.lean b/lean/OAI/Computability/VPVNP/CompleteFieldDescent.lean new file mode 100644 index 0000000000..648c5dadbd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompleteFieldDescent.lean @@ -0,0 +1,98 @@ +import OAI.Computability.VPVNP.CircuitSize +import OAI.Computability.VPVNP.Hamiltonian +import OAI.Computability.VPVNP.PermanentPadding +import Mathlib.Algebra.Algebra.ZMod +import Mathlib.Algebra.Field.ZMod + +/-! +# Uniformity across fields of a fixed characteristic + +Section 15.1 of *VP and VNP differ over every field* proves its bounds for the +Hamiltonian cycle and permanent over an algebraic closure of the prime field. +The sums defining these polynomials commute with coefficient maps. Thus the +same threshold and exponent in a bound over that closure apply to every field +of the given characteristic, even when circuits use arbitrary constants. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +open MvPolynomial + +variable {R S : Type*} [CommSemiring R] [CommSemiring S] + +@[simp] theorem map_hamiltonianCyclePolynomial (f : R →+* S) (m : ℕ) : + map f (hamiltonianCyclePolynomial R m) = hamiltonianCyclePolynomial S m := by + simp only [hamiltonianCyclePolynomial, map_sum, map_prod, map_X] + +@[simp] theorem map_permanentPolynomial (f : R →+* S) (m : ℕ) : + map f (permanentPolynomial R m) = permanentPolynomial S m := by + simp only [permanentPolynomial_eq_sum, map_sum, map_prod, map_X] + +variable {K F : Type*} [Field K] [IsAlgClosed K] [Field F] + +/-- Every integer polynomial has minimum gate count over an algebraically closed +field among fields of the same characteristic. This includes characteristic zero. -/ +theorem circuitSize_intCast_descent {σ : Type*} (q : ℕ) [CharP K q] [CharP F q] + (P : MvPolynomial σ ℤ) : + circuitSize (map (Int.castRingHom K) P) ≤ circuitSize (map (Int.castRingHom F) P) := by + have through (k : Type) [Field k] [Algebra k K] [Algebra k F] : + circuitSize (map (Int.castRingHom K) P) ≤ circuitSize (map (Int.castRingHom F) P) := by + have hK : (algebraMap k K).comp (Int.castRingHom k) = Int.castRingHom K := Subsingleton.elim .. + have hF : (algebraMap k F).comp (Int.castRingHom k) = Int.castRingHom F := Subsingleton.elim .. + simpa only [map_map, hK, hF] using + circuitSize_descent_le (K := K) (F := F) (map (Int.castRingHom k) P) + rcases CharP.char_is_prime_or_zero K q with hp | rfl + · have : Fact q.Prime := ⟨hp⟩ + let := ZMod.algebra K q + let := ZMod.algebra F q + exact through (ZMod q) + · have := CharP.charP_to_charZero K + have := CharP.charP_to_charZero F + exact through ℚ + +/-- For an integer family, a lower bound over one algebraically closed field +supplies a single threshold before quantifying over all fields of the characteristic. -/ +theorem circuitSize_intCast_uniform_bound {σ : ℕ → Type*} (P : (n : ℕ) → MvPolynomial (σ n) ℤ) + (q C N : ℕ) [CharP K q] + (h : ∀ n ≥ N, n ^ C < circuitSize (map (Int.castRingHom K) (P n))) : + ∀ n ≥ N, ∀ (F : Type*) [Field F] [CharP F q], + n ^ C < circuitSize (map (Int.castRingHom F) (P n)) := by + intro n hn F _ _ + exact (h n hn).trans_le (circuitSize_intCast_descent q (P n)) + +/-- Comparison of directed Hamiltonian-cycle circuit sizes at the same order. -/ +theorem hamiltonianCyclePolynomial_size_descent (q m : ℕ) [CharP K q] [CharP F q] : + circuitSize (hamiltonianCyclePolynomial K m) ≤ circuitSize (hamiltonianCyclePolynomial F m) := by + simpa only [map_hamiltonianCyclePolynomial] using + circuitSize_intCast_descent (K := K) (F := F) q (hamiltonianCyclePolynomial ℤ m) + +/-- Comparison of permanent circuit sizes at the same order. Scalar descent +applies in every characteristic, including characteristic two. -/ +theorem permanentPolynomial_size_descent (q m : ℕ) [CharP K q] [CharP F q] : + circuitSize (permanentPolynomial K m) ≤ circuitSize (permanentPolynomial F m) := by + simpa only [map_permanentPolynomial] using + circuitSize_intCast_descent (K := K) (F := F) q (permanentPolynomial ℤ m) + +/-- A threshold for Hamiltonian cycles over the algebraic closure works uniformly +for every field of its characteristic. -/ +theorem hamiltonianCyclePolynomial_uniform_bound (q C N : ℕ) [CharP K q] + (h : ∀ m ≥ N, m ^ C < circuitSize (hamiltonianCyclePolynomial K m)) : + ∀ m ≥ N, ∀ (F : Type*) [Field F] [CharP F q], + m ^ C < circuitSize (hamiltonianCyclePolynomial F m) := by + intro m hm F _ _ + exact (h m hm).trans_le (hamiltonianCyclePolynomial_size_descent q m) + +/-- A threshold for the permanent over the algebraic closure works uniformly +for every field of its characteristic. -/ +theorem permanentPolynomial_uniform_bound (q C N : ℕ) [CharP K q] + (h : ∀ m ≥ N, m ^ C < circuitSize (permanentPolynomial K m)) : + ∀ m ≥ N, ∀ (F : Type*) [Field F] [CharP F q], + m ^ C < circuitSize (permanentPolynomial F m) := by + intro m hm F _ _ + exact (h m hm).trans_le (permanentPolynomial_size_descent q m) + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompletePolynomials.lean b/lean/OAI/Computability/VPVNP/CompletePolynomials.lean new file mode 100644 index 0000000000..4ecfd3684c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompletePolynomials.lean @@ -0,0 +1,103 @@ +import OAI.Computability.VPVNP.Classes +import OAI.Computability.VPVNP.HamiltonianPadding +import OAI.Computability.VPVNP.PermanentPadding + +/-! +# Exact circuit sizes of the complete families under padding + +The projections of §15.1 make exact circuit size monotone in matrix order. The +transfer theorem takes as inputs the lower bound for the hard family and its +p-projection from the matrix family. It covers every sufficiently large order, +including the gaps between consecutive orders in the reduction. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +variable {R : Type*} [CommRing R] + +/-- Diagonal padding makes minimum permanent circuit size nondecreasing. -/ +theorem permanentCircuitSize_le_succ (m : ℕ) : + circuitSize (permanentPolynomial R m) ≤ circuitSize (permanentPolynomial R (m + 1)) := by + rw [← permanentPadding_polynomial R m] + exact circuitSize_projection_le _ _ + +/-- Forced-arc subdivision makes minimum Hamiltonian-cycle circuit size +nondecreasing from order two onwards. -/ +theorem hamiltonianCircuitSize_le_succ {m : ℕ} (hm : 2 ≤ m) : + circuitSize (hamiltonianCyclePolynomial R m) ≤ + circuitSize (hamiltonianCyclePolynomial R (m + 1)) := by + let a : Fin m := ⟨0, by omega⟩ + have h : (cyclePaddingProjection R a).hom (hamiltonianCyclePolynomial R (m + 1)) = + hamiltonianCyclePolynomial R m := hamiltonianCyclePolynomial_pad hm a + rw [← h] + exact circuitSize_projection_le _ _ + +/-- Given a polynomially bounded sequence of projection orders and an eventual +hardness bound, monotone padding transfers the bound to all large matrix orders. -/ +private theorem matrixFamily_bound_of_projections {ι : ℕ → Type*} + (hard : (n : ℕ) → MvPolynomial (ι n) R) + (matrixFamily : (m : ℕ) → MvPolynomial (Fin m × Fin m) R) + {q : ℕ → ℕ} {A b n₀ : ℕ} (hA : 0 < A) (hb : 0 < b) + (hhard : EventuallySuperpolynomial fun n => circuitSize (hard n)) + (horder : ∀ n ≥ n₀, q n ≤ A * n ^ b) + (hproj : ∀ n ≥ n₀, ∃ φ : Projection R (Fin (q n) × Fin (q n)) (ι n), + φ.hom (matrixFamily (q n)) = hard n) + (hstep : ∀ m ≥ 2, circuitSize (matrixFamily m) ≤ circuitSize (matrixFamily (m + 1))) + (C : ℕ) : ∃ M : ℕ, ∀ m ≥ M, m ^ C < circuitSize (matrixFamily m) := by + obtain ⟨N, hN⟩ := hhard 1 le_rfl + let S := max (circuitSize (matrixFamily 0)) (circuitSize (matrixFamily 1)) + refine eventualBound_of_polynomialProjection (q := q) (n₀ := max (max n₀ N) S) + hA hb hhard ?_ hstep C + intro n hn + have hn₀ : n₀ ≤ n := ((le_max_left ..).trans (le_max_left ..)).trans hn + have hnN : N ≤ n := ((le_max_right ..).trans (le_max_left ..)).trans hn + have hnS : S ≤ n := (le_max_right ..).trans hn + obtain ⟨φ, hφ⟩ := hproj n hn₀ + have hsize : circuitSize (hard n) ≤ circuitSize (matrixFamily (q n)) := + hφ ▸ circuitSize_projection_le φ _ + refine ⟨?_, horder n hn₀, hsize⟩ + have hbig : S < circuitSize (matrixFamily (q n)) := + hnS.trans_lt ((by simpa using hN n hnN : n < circuitSize (hard n)).trans_le hsize) + by_contra! hsmall + obtain h | h : q n = 0 ∨ q n = 1 := by omega + · rw [h] at hbig + exact hbig.not_ge (le_max_left ..) + · rw [h] at hbig + exact hbig.not_ge (le_max_right ..) + +variable {F : Type*} [Field F] {ι : ℕ → Type} {hard : Family F ι} + +/-- A p-projection onto an eventually hard family forces the same type of bound +at every sufficiently large order of the source family, provided it admits padding. -/ +theorem matrixFamily_bound_of_pProjects + (source : Family F fun m => Fin m × Fin m) (hproj : PProjects hard source) + (hhard : EventuallySuperpolynomial fun n => circuitSize (hard n)) + (hstep : ∀ m ≥ 2, circuitSize (source m) ≤ circuitSize (source (m + 1))) + (C : ℕ) : ∃ M : ℕ, ∀ m ≥ M, m ^ C < circuitSize (source m) := by + obtain ⟨q, ⟨A, b, N, hq⟩, hφ⟩ := hproj + refine matrixFamily_bound_of_projections hard source (q := q) (n₀ := max 1 N) + (Nat.zero_lt_succ A) (Nat.zero_lt_succ b) hhard ?_ (fun n _ => hφ n) hstep C + intro n hn + refine (hq n ((le_max_right ..).trans hn)).trans ?_ + exact Nat.mul_le_mul (Nat.le_succ A) + (Nat.pow_le_pow_right ((le_max_left ..).trans hn) (Nat.le_succ b)) + +/-- The Hamiltonian-cycle implication in §15.1, with the Valiant reduction and +the hard-family lower bound supplied explicitly. -/ +theorem hamiltonian_bound_of_pProjects (hproj : PProjects hard (hamiltonianCyclePolynomial F)) + (hhard : EventuallySuperpolynomial fun n => circuitSize (hard n)) (C : ℕ) : + ∃ M : ℕ, ∀ m ≥ M, m ^ C < circuitSize (hamiltonianCyclePolynomial F m) := + matrixFamily_bound_of_pProjects _ hproj hhard (fun _ hm => hamiltonianCircuitSize_le_succ hm) C + +/-- The permanent implication in §15.1. Its use outside characteristic two +requires the p-projection supplied there by Valiant completeness. -/ +theorem permanent_bound_of_pProjects (hproj : PProjects hard (permanentPolynomial F)) + (hhard : EventuallySuperpolynomial fun n => circuitSize (hard n)) (C : ℕ) : + ∃ M : ℕ, ∀ m ≥ M, m ^ C < circuitSize (permanentPolynomial F m) := + matrixFamily_bound_of_pProjects _ hproj hhard (fun m _ => permanentCircuitSize_le_succ m) C + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompletionReplacement.lean b/lean/OAI/Computability/VPVNP/CompletionReplacement.lean new file mode 100644 index 0000000000..cb8707d982 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompletionReplacement.lean @@ -0,0 +1,74 @@ +import Mathlib.Data.Fin.Tuple.Basic +import Mathlib.LinearAlgebra.LinearIndependent.Basic + +/-! +# Replacing a column of a completion + +When a fresh column extends an independent frame, it can take the place of +any of the completion columns. The original and the modified completions +together span exactly the completion with the fresh column adjoined. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Grassmann + +open Set Submodule + +variable {K V ι : Type*} [Semiring K] [AddCommMonoid V] [Module K V] {s : ℕ} + +/-- Discard the last column of an independent completed frame. -/ +theorem independent_completion_init {v : ι → V} {w : Fin s → V} {x : V} + (h : LinearIndependent K (Sum.elim v (Fin.snoc w x))) : + LinearIndependent K (Sum.elim v w) := by + have h' := h.comp (Sum.map id Fin.castSucc) + (Function.injective_id.sumMap (Fin.castSucc_injective s)) + convert h' using 1 + funext a + rcases a with a | j + · rfl + · simp + +/-- Replace one completion column by the last column of an independent extension. -/ +theorem independent_completion_replacement {v : ι → V} {w : Fin s → V} {x : V} + (i : Fin s) (h : LinearIndependent K (Sum.elim v (Fin.snoc w x))) : + LinearIndependent K (Sum.elim v (Function.update w i x)) := by + let σ := Equiv.swap i.castSucc (Fin.last s) + have h' := h.comp (Sum.map id (σ ∘ Fin.castSucc)) + (Function.injective_id.sumMap (σ.injective.comp (Fin.castSucc_injective s))) + convert h' using 1 + funext a + rcases a with a | j + · rfl + · change Function.update w i x j = Fin.snoc (α := fun _ ↦ V) w x (σ j.castSucc) + by_cases hj : j = i + · subst j + simp [σ] + · rw [Function.update_of_ne hj, Equiv.swap_apply_of_ne_of_ne + ((Fin.castSucc_injective s).ne hj) (Fin.castSucc_ne_last j), Fin.snoc_castSucc] + +/-- The two completions jointly span all the old columns and the new one. -/ +theorem span_completion_sup_replacement (K : Type*) [Semiring K] [Module K V] + (w : Fin s → V) (i : Fin s) (x : V) : + span K (range w) ⊔ span K (range (Function.update w i x)) = span K (range (Fin.snoc w x)) := by + rw [← span_union, Fin.range_snoc] + congr 1 + ext y + constructor + · rintro (hy | ⟨j, rfl⟩) + · exact Or.inr hy + · by_cases hj : j = i + · subst j + exact Or.inl (Function.update_self ..) + · exact Or.inr ⟨j, (Function.update_of_ne hj ..).symm⟩ + · rintro (rfl | hy) + · exact Or.inr ⟨i, Function.update_self ..⟩ + · exact Or.inl hy + +end Grassmann + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ComplexityLib/Bounds.lean b/lean/OAI/Computability/VPVNP/ComplexityLib/Bounds.lean new file mode 100644 index 0000000000..66bea822ab --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ComplexityLib/Bounds.lean @@ -0,0 +1,26 @@ +import OAI.Computability.VPVNP.PolynomialBounds +import Cslib.Foundations.Data.Nat.PolynomialBound + +/-! # Polynomial bounds in the two arithmetic circuit models -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ComplexityLib + +/-- The two polynomial growth conditions agree, including at indices below the +eventual threshold, whose values can be absorbed into a global leading constant. -/ +theorem polynomiallyBounded_iff (f : ℕ → ℕ) : + VPVNP.PolynomiallyBounded f ↔ Cslib.PolynomiallyBounded f := by + rw [Cslib.polynomiallyBounded_iff_le] + constructor + · exact VPVNP.PolynomiallyBounded.exists_global_bound + · rintro ⟨c, d, h⟩ + exact ((PolynomiallyBounded.const c).mul (PolynomiallyBounded.succ.pow d)).of_le h + +end ComplexityLib + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ComplexityLib/Circuit.lean b/lean/OAI/Computability/VPVNP/ComplexityLib/Circuit.lean new file mode 100644 index 0000000000..b8477ce7da --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ComplexityLib/Circuit.lean @@ -0,0 +1,72 @@ +import OAI.Computability.VPVNP.ComplexityLib.ToUpstream +import Complexity.Computability.Circuit.Arithmetic.VP +import OAI.Computability.VPVNP.CircuitSize + +/-! # Simulation of complexitylib arithmetic circuits + +The program below keeps every upstream wire at its original index. Each upstream constant gate +becomes a binary gate adding the given scalar to zero. Thus every designated output has a +project circuit of exactly the upstream size, even when multiple operands use the same gate. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ComplexityLib + +open Cslib.Circuits (Wire Line arithSignature arithInterpretationWith) + +variable {K : Type*} {n g m : ℕ} + +private def wireRef (w : Wire n g) : Ref K (Fin n) g := + w.elim Ref.var Ref.gate + +private theorem read_wireRef {A : Type*} (scalar : K → A) (x : Fin n → A) (v : Fin g → A) + (w : Wire n g) : (wireRef w).read scalar x v = w.elim x v := by + cases w <;> rfl + +variable [CommRing K] + +private def appendLine (p : VPVNP.Program K (Fin n) g) : + Line (arithSignature K) n g → VPVNP.Program K (Fin n) (g + 1) + | ⟨.add, w⟩ => p.snoc .add (wireRef (w 0)) (wireRef (w 1)) + | ⟨.mul, w⟩ => p.snoc .mul (wireRef (w 0)) (wireRef (w 1)) + | ⟨.const k, _⟩ => p.snoc .add (.const k) (.const 0) + +private def ofProgram : {g : ℕ} → Cslib.Circuits.Program (arithSignature K) n g → + VPVNP.Program K (Fin n) g + | _, .empty => .nil + | _, .gate p line => appendLine (ofProgram p) line + +private theorem run_ofProgram (p : Cslib.Circuits.Program (arithSignature K) n g) : + (ofProgram p).run MvPolynomial.C MvPolynomial.X = + p.eval (arithInterpretationWith K MvPolynomial.C) MvPolynomial.X := by + induction p with + | empty => rfl + | gate p line ih => + obtain ⟨op, w⟩ := line + cases op with + | add | mul => + simp only [ofProgram, appendLine, VPVNP.Program.run, Cslib.Circuits.Program.eval, + Line.eval, arithInterpretationWith, BinOp.apply, read_wireRef, Function.comp_apply, ih] + | const k => + simp only [ofProgram, appendLine, VPVNP.Program.run, Cslib.Circuits.Program.eval, + Line.eval, arithInterpretationWith, BinOp.apply, Ref.read, map_zero, add_zero, ih] + +/-- An upstream arithmetic circuit has a project circuit for each designated output with +the same number of gates, evaluated in the formal polynomial ring. -/ +theorem circuitSize_le_upstream (c : Cslib.Circuits.Circuit (arithSignature K) n m) + (j : Fin m) : circuitSize (c.polynomial j) ≤ c.size := by + let d : VPVNP.Circuit K (Fin n) c.size := ⟨ofProgram c.program, wireRef (c.outputs j)⟩ + have hd : d.polynomial = c.polynomial j := by + simp only [d, Circuit.polynomial, Circuit.eval, read_wireRef, run_ofProgram] + rfl + rw [← hd] + exact circuitSize_le_of_circuit d + +end ComplexityLib + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ComplexityLib/Family.lean b/lean/OAI/Computability/VPVNP/ComplexityLib/Family.lean new file mode 100644 index 0000000000..c9fbf6b641 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ComplexityLib/Family.lean @@ -0,0 +1,84 @@ +import OAI.Computability.VPVNP.ComplexityLib.Bounds +import OAI.Computability.VPVNP.ComplexityLib.Circuit +import OAI.Computability.VPVNP.ComplexityLib.Renaming +import OAI.Computability.VPVNP.ComplexityLib.Witness +import Complexity.Foundations.Data.Nat.PolynomialBound.Closure + +/-! +# Finite variable families in the two models + +Numbering the variables preserves the polynomial, its degree, and its minimum +project circuit size. For a VNP verifier, number the visible variables first, +then the witness variables, as required by complexitylib's Boolean sum. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ComplexityLib + +open Cslib.Circuits.Arithmetic + +variable {K : Type*} [Field K] {X : ℕ → Type} [∀ n, Fintype (X n)] {a : ℕ → ℕ} + +/-- The upstream polynomial family obtained by numbering the variables at each length. -/ +noncomputable def numberedFamily (p : Family K X) (e : ∀ n, X n ≃ Fin (a n)) : + PolynomialFamily K where + vars := a + poly n := MvPolynomial.rename (e n) (p n) + +private theorem numbered_isPFamily_iff (p : Family K X) (e : ∀ n, X n ≃ Fin (a n)) : + (numberedFamily p e).IsPFamily ↔ PFamily p := by + have ha : a = fun n => Fintype.card (X n) := by + funext n + simpa using (Fintype.card_congr (e n)).symm + have hd : (fun n => ((numberedFamily p e).poly n).totalDegree) = + (fun n => (p n).totalDegree) := by + funext n + exact MvPolynomial.totalDegree_renameEquiv (e n) (p n) + unfold PolynomialFamily.IsPFamily PFamily + change (Cslib.PolynomiallyBounded a ∧ Cslib.PolynomiallyBounded _) ↔ _ + simp only [hd, ← polynomiallyBounded_iff, ha] + +/-- A family has polynomial-size circuits in one model precisely when its +numbered family has polynomial-size circuits in the other. -/ +theorem numbered_mem_VP_iff (p : Family K X) (e : ∀ n, X n ≃ Fin (a n)) : + numberedFamily p e ∈ VP K ↔ IsVP p := by + constructor + · rintro ⟨hf, c, hc, hpoly⟩ + refine ⟨(numbered_isPFamily_iff p e).mp hf, (polynomiallyBounded_iff _).mpr ?_⟩ + refine hc.mono_of_le fun n => ?_ + rw [← circuitSize_renameEquiv (e n) (p n)] + change circuitSize ((numberedFamily p e).poly n) ≤ _ + rw [← hpoly n] + exact circuitSize_le_upstream (c n) 0 + · rintro ⟨hf, hsize⟩ + choose c hpoly hc using fun n => exists_upstream_circuit ((numberedFamily p e).poly n) + refine ⟨(numbered_isPFamily_iff p e).mpr hf, c, ?_, hpoly⟩ + have hs := (polynomiallyBounded_iff _).mp hsize + refine (((Cslib.PolynomiallyBounded.const 5).mul hs).add + (Cslib.PolynomiallyBounded.const 1)).mono_of_le fun n => ?_ + simpa only [numberedFamily, circuitSize_renameEquiv] using hc n + +/-- A project VNP verifier gives an upstream VNP verifier with the same Boolean +witness length and the same formal polynomial at each index. -/ +theorem numbered_mem_VNP (p : Family K X) (e : ∀ n, X n ≃ Fin (a n)) (hp : IsVNP p) : + numberedFamily p e ∈ VNP K := by + classical + obtain ⟨_, W, iW, g, _, hVP, hsum⟩ := hp + let : ∀ n, Fintype (W n) := iW + let m := fun n => Fintype.card (W n) + let w : ∀ n, W n ≃ Fin (m n) := fun n => Fintype.equivFin _ + let combined := fun n => sumVariables (e n) (w n) + refine ⟨m, fun n => MvPolynomial.rename (combined n) (g n), + (numbered_mem_VP_iff g combined).mpr hVP, fun n => ?_⟩ + change MvPolynomial.rename (e n) (p n) = _ + rw [hsum n] + exact (booleanSum_rename (e n) (w n) (g n)).symm + +end ComplexityLib + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ComplexityLib/PermanentNumbering.lean b/lean/OAI/Computability/VPVNP/ComplexityLib/PermanentNumbering.lean new file mode 100644 index 0000000000..24e29ff93f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ComplexityLib/PermanentNumbering.lean @@ -0,0 +1,26 @@ +import OAI.Computability.VPVNP.ComplexityLib.Family +import OAI.Computability.VPVNP.PermanentPadding +import Complexity.Computability.Circuit.Arithmetic.Determinant + +/-! # Row-major numbering of the generic permanent -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ComplexityLib + +open Cslib.Circuits.Arithmetic + +/-- Numbering the entries of the project's generic matrix in row-major order gives +complexitylib's permanent family, including the member at dimension zero. -/ +theorem numbered_permanent (F : Type*) [Field F] : + numberedFamily (permanentPolynomial F) (fun _ => finProdFinEquiv) = permFamily F := by + simp only [numberedFamily, permFamily, permanentPolynomial, genericMatrix, Matrix.permanent, + Matrix.of_apply, map_sum, map_prod, MvPolynomial.rename_X] + +end ComplexityLib + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ComplexityLib/Renaming.lean b/lean/OAI/Computability/VPVNP/ComplexityLib/Renaming.lean new file mode 100644 index 0000000000..effbc4047d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ComplexityLib/Renaming.lean @@ -0,0 +1,31 @@ +import OAI.Computability.VPVNP.CircuitSize +import Mathlib.Algebra.MvPolynomial.Rename + +/-! # Circuit size under variable renaming -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ComplexityLib + +variable {K X Y : Type*} [CommRing K] + +/-- Renaming variables is a projection and cannot increase the number of binary gates. -/ +private theorem circuitSize_rename_le (f : X → Y) (p : MvPolynomial X K) : + circuitSize (MvPolynomial.rename f p) ≤ circuitSize p := by + rw [MvPolynomial.rename_eq_aeval] + exact circuitSize_projection_le (fun i => Sum.inl (f i)) p + +/-- Relabelling the variables by a bijection preserves the minimum number of binary gates. -/ +theorem circuitSize_renameEquiv (e : X ≃ Y) (p : MvPolynomial X K) : + circuitSize (MvPolynomial.rename e p) = circuitSize p := by + apply le_antisymm (circuitSize_rename_le e p) + simpa only [MvPolynomial.rename_rename, e.symm_comp_self, MvPolynomial.rename_id_apply] using + circuitSize_rename_le e.symm (MvPolynomial.rename e p) + +end ComplexityLib + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ComplexityLib/ToUpstream.lean b/lean/OAI/Computability/VPVNP/ComplexityLib/ToUpstream.lean new file mode 100644 index 0000000000..3741146125 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ComplexityLib/ToUpstream.lean @@ -0,0 +1,102 @@ +import Complexity.Computability.Circuit.Arithmetic.VP +import OAI.Computability.VPVNP.CircuitSize + +/-! # Simulating exact arithmetic circuits in complexitylib + +The induction synthesizes all earlier gates at once, so two references to the +same gate can use the same wire. A binary gate needs at most two additional +gates for its scalar operands. Subtraction uses a constant gate for `-1`, +a multiplication, and an addition. A scalar output needs one final gate. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ComplexityLib + +open Cslib.Circuits (arithInterpretationWith arithSignature inputs Synthesis) +open MvPolynomial (C X) + +variable {K : Type*} [CommRing K] {n g : ℕ} + +/-- A polynomial-valued function of the input wires. -/ +private abbrev WireFunction (K : Type*) [CommRing K] (n : ℕ) := + (Fin n → MvPolynomial (Fin n) K) → MvPolynomial (Fin n) K + +/-- The polynomial-valued functions realized by the gates of a program prefix. -/ +private def gateFunctions (p : Program K (Fin n) g) : Set (WireFunction K n) := + Set.range fun i x => p.run C x i + +/-- Inputs and previously computed gates are available wires. A scalar +operand needs at most one new gate. -/ +private theorem synthesizeRef (p : Program K (Fin n) g) (r : Ref K (Fin n) g) : + Synthesis (arithInterpretationWith K C) (inputs n ∪ gateFunctions p) + {fun x => r.read C x (p.run C x)} 1 := by + cases r with + | var i => + have hi : (fun x : Fin n → MvPolynomial (Fin n) K => x i) ∈ inputs n := ⟨i, rfl⟩ + exact (Synthesis.of_mem (Set.mem_union_left _ hi)).mono + Set.Subset.rfl Set.Subset.rfl (by decide) + | gate i => + have hi : (fun x => p.run C x i) ∈ gateFunctions p := ⟨i, rfl⟩ + exact (Synthesis.of_mem (Set.mem_union_right _ hi)).mono + Set.Subset.rfl Set.Subset.rfl (by decide) + | const k => exact Synthesis.arith_const k + +/-- With the operands available, subtraction costs three gates and the other +two binary operations cost one. -/ +private theorem synthesizeBinOp (op : BinOp) (a b : WireFunction K n) : + Synthesis (arithInterpretationWith K C) {a, b} + {fun x => op.apply (a x) (b x)} 3 := by + have ha : a ∈ ({a, b} : Set (WireFunction K n)) := Set.mem_insert _ _ + have hb : b ∈ ({a, b} : Set (WireFunction K n)) := Set.mem_insert_of_mem _ rfl + cases op with + | add => + exact (Synthesis.arith_add ha hb).mono Set.Subset.rfl Set.Subset.rfl (by decide) + | mul => + exact (Synthesis.arith_mul ha hb).mono Set.Subset.rfl Set.Subset.rfl (by decide) + | sub => + have hneg : Synthesis (arithInterpretationWith K C) {a, b} + {fun x => C (-1 : K) * b x} 2 := + (Synthesis.arith_const (-1 : K)).trans + (Synthesis.arith_mul (Set.mem_union_right _ rfl) (Set.mem_union_left _ hb)) + simpa only [BinOp.apply, map_neg, map_one, neg_one_mul, sub_eq_add_neg] using + hneg.trans (Synthesis.arith_add (Set.mem_union_left _ ha) (Set.mem_union_right _ rfl)) + +/-- The upstream program retains every gate of the simulated prefix at a cost +of at most five upstream gates per project gate. -/ +private theorem synthesizeProgram (p : Program K (Fin n) g) : + Synthesis (arithInterpretationWith K C) (inputs n) (gateFunctions p) (5 * g) := by + induction p with + | nil => + apply Synthesis.of_subset + rintro _ ⟨i, _⟩ + exact i.elim0 + | @snoc g p op a b ih => + have step := (synthesizeRef p a).combine (synthesizeRef p b) + (synthesizeBinOp op _ _) + refine (ih.comp step).mono Set.Subset.rfl ?_ (by omega) + rintro _ ⟨i, rfl⟩ + refine Fin.lastCases ?_ (fun j => ?_) i + · apply Set.mem_union_right + simp only [Program.run, Fin.lastCases_last, Set.mem_singleton_iff] + · apply Set.mem_union_left + exact ⟨j, by simp only [Program.run, Fin.lastCases_castSucc]⟩ + +/-- Every formal polynomial has an upstream circuit whose charged constants +and subtraction expansions cost at most five gates per project binary gate, +plus one gate if the designated output is a scalar. -/ +theorem exists_upstream_circuit (p : MvPolynomial (Fin n) K) : + ∃ c : Cslib.Circuits.Circuit (arithSignature K) n 1, + c.polynomial 0 = p ∧ c.size ≤ 5 * circuitSize p + 1 := by + obtain ⟨c, hc⟩ := circuitSize_spec p + obtain ⟨d, hd, hsize⟩ := ((synthesizeProgram c.program).trans + (synthesizeRef c.program c.output)).exists_circuit_polynomial + exact ⟨d, hd.trans hc, hsize⟩ + +end ComplexityLib + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ComplexityLib/VNPTransport.lean b/lean/OAI/Computability/VPVNP/ComplexityLib/VNPTransport.lean new file mode 100644 index 0000000000..8ba2ebf681 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ComplexityLib/VNPTransport.lean @@ -0,0 +1,54 @@ +import OAI.Computability.VPVNP.ComplexityLib.Family + +/-! # Transport of Boolean-sum verifiers from numbered variables -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ComplexityLib + +open MvPolynomial Cslib.Circuits.Arithmetic + +variable {K : Type*} [Field K] {X : ℕ → Type} [∀ n, Fintype (X n)] {a : ℕ → ℕ} + +/-- Numbering an upstream family's variables by their existing indices recovers the family. -/ +theorem numberedFamily_refl (f : PolynomialFamily K) : + numberedFamily f.poly (fun n => Equiv.refl (Fin (f.vars n))) = f := by + cases f + simp [numberedFamily] + +/-- Relabelling every finite variable type preserves VNP membership in both directions. +The reverse translation separates the visible and witness blocks of an upstream verifier. -/ +theorem numbered_mem_VNP_iff (p : Family K X) (e : ∀ n, X n ≃ Fin (a n)) : + numberedFamily p e ∈ VNP K ↔ IsVNP p := by + classical + refine ⟨?_, numbered_mem_VNP p e⟩ + intro hp + obtain ⟨ha, hd⟩ := VNP.isPFamily hp + have hvars : (fun n => Fintype.card (X n)) = a := + funext fun n => by simpa using Fintype.card_congr (e n) + have hf : PFamily p := by + refine ⟨hvars ▸ (polynomiallyBounded_iff a).mpr ha, (polynomiallyBounded_iff _).mpr ?_⟩ + exact hd.mono_of_le fun n => (totalDegree_renameEquiv (e n) (p n)).symm.le + obtain ⟨m, g, hg, hsum⟩ := hp + let w := fun n => Equiv.refl (Fin (m n)) + let s := fun n => sumVariables (e n) (w n) + let verifier : Family K (fun n => X n ⊕ Fin (m n)) := fun n => rename (s n).symm (g n) + have hrename (n : ℕ) : rename (s n) (verifier n) = g n := + (renameEquiv K (s n)).apply_symm_apply (g n) + have hnumbered : numberedFamily verifier s = (⟨fun n => a n + m n, g⟩ : PolynomialFamily K) := + congrArg (PolynomialFamily.mk _) (funext hrename) + have hm : Cslib.PolynomiallyBounded m := hg.1.1.mono_of_le fun n => Nat.le_add_left _ _ + refine ⟨hf, fun n => Fin (m n), inferInstance, verifier, ?_, + (numbered_mem_VP_iff verifier s).mp (hnumbered ▸ hg), fun n => ?_⟩ + · simpa only [Fintype.card_fin] using (polynomiallyBounded_iff m).mpr hm + · apply rename_injective (e n) (e n).injective + rw [← booleanSum_rename (e n) (w n), hrename n] + exact hsum n + +end ComplexityLib + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/ComplexityLib/Witness.lean b/lean/OAI/Computability/VPVNP/ComplexityLib/Witness.lean new file mode 100644 index 0000000000..063453465a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/ComplexityLib/Witness.lean @@ -0,0 +1,47 @@ +import Complexity.Computability.Circuit.Arithmetic.VNP +import OAI.Computability.VPVNP.Classes +import Mathlib.Logic.Equiv.Fin.Basic + +/-! # Boolean witnesses in the two VNP models + +Number the formal variables first and the witness variables second. With this ordering, +the two Boolean sums agree term by term after reindexing their assignments. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace ComplexityLib + +open MvPolynomial Cslib.Circuits.Arithmetic +open scoped Classical + +/-- Number the output and witness variables in consecutive blocks. -/ +def sumVariables {X W : Type} {a b : ℕ} (x : X ≃ Fin a) (w : W ≃ Fin b) : + X ⊕ W ≃ Fin (a + b) := + (x.sumCongr w).trans finSumFinEquiv + +/-- The Boolean witness sum commutes with numbering both blocks of variables. -/ +theorem booleanSum_rename {K : Type*} [Field K] {X W : Type} [Fintype W] {a b : ℕ} + (x : X ≃ Fin a) (w : W ≃ Fin b) (g : MvPolynomial (X ⊕ W) K) : + booleanSum b (rename (sumVariables x w) g) = + rename x (∑ y : W → Bool, witnessValue y g) := by + rw [booleanSum, map_sum] + refine Fintype.sum_equiv (w.symm.arrowCongr (Equiv.refl Bool)) _ _ fun e => ?_ + change projection (booleanAssignment e) (rename (sumVariables x w) g) = + rename x (witnessValue (e ∘ w) g) + induction g using MvPolynomial.induction_on with + | C c => simp [witnessValue] + | add p q hp hq => simp only [map_add, hp, hq] + | mul_X p i hp => + rw [map_mul, map_mul, map_mul, map_mul, hp, rename_X, projection_X] + rcases i with i | j + · simp [sumVariables, booleanAssignment, witnessValue] + · cases h : e (w j) <;> simp [sumVariables, booleanAssignment, witnessValue, h] + +end ComplexityLib + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressedRAMDegree.lean b/lean/OAI/Computability/VPVNP/CompressedRAMDegree.lean new file mode 100644 index 0000000000..471a1e47fa --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressedRAMDegree.lean @@ -0,0 +1,78 @@ +import OAI.Computability.VPVNP.ExpandedMonomialDegree +import OAI.Computability.VPVNP.CompressionDegreeAssembly + +/-! +# Total exponent of each compressed RAM path + +The accepting choices of the initial validators have exponent zero. Each +subsequent kernel contributes the degrees of its resident template entries. +On the selected branch the number of occurrences and the degree of every +individual entry obey the bounds of Theorem 7.1. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CursorNetwork + +open CursorRouting Compression NetworkKernel BurstRAM BurstRAM.PrivateRAM + +variable {D base lanes a padding w p r k' e : ℕ} [NeZero D] +variable {A : Type*} [CommRing A] {L : Type} [Fintype L] {κ : L → A} + +/-- Every expanded validator path has a selected term chain whose recorded +degrees bound its total parameter exponent. -/ +theorem expandedRAMStateCount_degree {b n : ℕ} (M : Machine w p r k') (fuel : ℕ) + (initial : Word w) (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) + (labels : Fin D ≃ Fin base ⊕ Fin lanes) (hD : 1 < D) (hd : 2 + padding = 2 ^ a) + (E : StateExecution A b n + (cursorState labels hD hd (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ))) + (K : E.MapWitnesses κ) (rec : E.Records) (hrec : E.DegreeCovered K rec) : + let W := expandedRAMStateCount M fuel initial header hw hc labels hD hd + E.history (E.historyWitnesses K) + ∀ c : W.Choice, ∃ z : E.Choices, ∀ B, (E.termChain rec z).AllRecordsLe B → + (∑ l, W.exponents c l) ≤ ∑ v, (E.termChain rec z).occurrences (fun _ => 1) v * B := by + intro W c + let bits := (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ) + let I := cursorStateIso labels hD hd (ramSystemOrder D) bits + let P : Factors Type (paddedNetwork D padding bits) := fun v z => + initialChoices M fuel initial header hw hc v (unpadHalf padding v z) + let inst := I.pushChoiceFintype P fun v z => + initialChoicesFintype M fuel initial header hw hc v (unpadHalf padding v z) + exact (E.history_degreeBound K rec hrec).expandedCount _ _ _ (I.pushFactors P) c + +variable {k : Type*} [Field k] {S : BlockSchedule k} + +/-- The actual path of (12.2) selects a final network. Its total parameter +degree is bounded by its number of sites, the maximum number of local +occurrences, and the largest degree of an individual map entry. -/ +theorem compressedRAMCount_degree (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) + (M : Machine w p r k') (fuel : ℕ) (initial : Word w) (header : ℕ → Word w) + (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) + (labels : Fin D ≃ Fin base ⊕ Fin lanes) (hD : 1 < D) (T : ℕ) (hT : T * S.laneBits ≤ lanes) : + let X := cursorState labels hD (Nat.add_sub_of_le S.degree_bounds.1) + (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ) + let E := B.execute f hf T hT X + let W := compressedRAMCount B f hf M fuel initial header hw hc labels hD T hT + ∀ c : W.Choice, ∃ z : E.Choices, (∑ l, W.exponents c l) ≤ + (E.finalState z).positions * B.growthConstant ^ T * + (B.growthConstant ^ T * (X.maxWireWidth + 1)) := by + intro X E W c + let L := B.growthConstant ^ T * (X.maxWireWidth + 1) + obtain ⟨z, hz⟩ := expandedRAMStateCount_degree M fuel initial header hw hc labels hD + (Nat.add_sub_of_le S.degree_bounds.1) E _ _ (B.execute_degreeCovered f hf T hT X) c + have bounds := B.branch_bounds f hf T hT X z + refine ⟨z, (hz L bounds.2.2.2.2.1).trans ?_⟩ + calc + _ ≤ ∑ _ : (E.finalState z).network.Site, B.growthConstant ^ T * L := + Finset.sum_le_sum fun v _ => Nat.mul_le_mul_right L (bounds.2.2.2.1 v) + _ = (E.finalState z).positions * B.growthConstant ^ T * L := by + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, Nat.mul_assoc] + rfl + +end CursorNetwork + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressedRAMMonomials.lean b/lean/OAI/Computability/VPVNP/CompressedRAMMonomials.lean new file mode 100644 index 0000000000..667b2764bd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressedRAMMonomials.lean @@ -0,0 +1,65 @@ +import OAI.Computability.VPVNP.IteratedCompression +import OAI.Computability.VPVNP.ShrinkProcedureWitness +import OAI.Computability.VPVNP.RefreshProcedureWitness +import OAI.Computability.VPVNP.CursorStateCount + +/-! +# Monomial paths in the iterated compression of the RAM network + +Equation (12.2) sums the parameter monomials of the actual compression +procedure on the padded cursor graph. The two fixed templates determine +all the local witnesses. The chosen term may change both the next state and +its kernel, at every step and in every block. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open NetworkKernel + +variable {k : Type*} [Field k] {S : BlockSchedule k} +variable (B : S.Templates) {A : Type*} [CommRing A] (κ : B.Entry → A) (hκ : B.IsSolution κ) + +/-- Every map entry of the scheduled block has finite monomial witnesses in +the common alphabet of the two templates. -/ +noncomputable def procedureWitnesses : (B.procedure κ hκ).MapWitnesses κ := + S.assembleBlockWitnesses _ _ (B.shrinkProcedureWitnesses κ hκ) (B.refreshProcedureWitnesses κ hκ) + +/-- Local witnesses for the complete history in Theorem 7.1. -/ +noncomputable def executeWitnesses {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) + (X : State (S.degreeExponent 0) n) : + (B.execute κ hκ T h X).history.KernelWitnesses κ := + (B.execute κ hκ T h X).historyWitnesses + (Procedure.repeatWitnesses (B.procedureWitnesses κ hκ) _ T n (Nat.add_sub_of_le h).symm X) + +end Compression.BlockSchedule.Templates + +namespace CursorNetwork + +open CursorRouting Compression NetworkKernel BurstRAM BurstRAM.PrivateRAM + +variable {k : Type*} [Field k] {S : BlockSchedule k} {D e w p r k' base lanes : ℕ} [NeZero D] + +/-- The sum over the expanded paths of the concrete compression is the +integer machine path count specialized to the coefficient ring. A choice +retains the term sequence, final edge values, and all local witnesses. -/ +noncomputable def compressedRAMCount (B : S.Templates) {A : Type*} [CommRing A] + (κ : B.Entry → A) (hκ : B.IsSolution κ) (M : Machine w p r k') (fuel : ℕ) + (initial : Word w) (header : ℕ → Word w) (hw : 2 ≤ w) (hc : 2 ^ D * 2 ^ e < 2 ^ w) + (labels : Fin D ≃ Fin base ⊕ Fin lanes) (hD : 1 < D) (T : ℕ) (hT : T * S.laneBits ≤ lanes) : + MonomialWitness κ (Nat.card (ActualPaths M.program fuel initial + (RAMMemory.initialMemory (2 ^ D) header) (withinCaps (2 ^ D) (2 ^ e))) : A) := + let pad := S.baseDegree - 2 + have hpad : 2 + pad = 2 ^ S.degreeExponent 0 := Nat.add_sub_of_le S.degree_bounds.1 + let X := cursorState labels hD hpad (ramFieldBits (2 ^ e) w : RAMSystem D → ℕ) + expandedRAMStateCount M fuel initial header hw hc labels hD hpad + (B.execute κ hκ T hT X).history (B.executeWitnesses κ hκ T hT X) + +end CursorNetwork + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/Compression.lean b/lean/OAI/Computability/VPVNP/Compression.lean new file mode 100644 index 0000000000..ead50ecec6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/Compression.lean @@ -0,0 +1,88 @@ +import Mathlib.Algebra.Order.Field.GeomSum +import Mathlib.Analysis.Real.Sqrt +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Ring + +/-! +# Iterating the wire energy estimate + +Equation (7.4) of *VP and VNP differ over every field* follows from the +energy estimate for one block and the geometric decrease in the number of +positions. The bound below gives the constant multiplying the initial +position count explicitly. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +open scoped BigOperators + +/-- With positive wire masses of total one, the energy controls total width. -/ +theorem widthSum_le_sqrtEnergy {Wire : Type*} [Fintype Wire] + (width mass : Wire → ℝ) (hpos : ∀ e, 0 < mass e) (htotal : ∑ e, mass e = 1) : + ∑ e, width e ≤ Real.sqrt (∑ e, width e ^ 2 / mass e) := by + apply Real.le_sqrt_of_sq_le + have h := Finset.sq_sum_div_le_sum_sq_div Finset.univ width (fun i _ => hpos i) + simpa only [htotal, div_one] using h + +/-- Multiplication by `4^i` makes the one-block estimates telescope. The term +from block `i` then has ratio `4/κ²` to the corresponding term from block +`i-1`. Only the estimates before the specified horizon are needed. -/ +theorem scaledEnergy_le (L : ℕ → ℝ) (P c κ : ℝ) (T : ℕ) + (hstep : ∀ i < T, L (i + 1) ≤ L i / 4 + c * (P / κ ^ i) ^ 2) : + 4 ^ T * L T ≤ L 0 + 4 * c * P ^ 2 * ∑ i ∈ Finset.range T, (4 / κ ^ 2) ^ i := by + induction T with + | zero => simp + | succ t ih => + have hprev := ih (fun i hi => hstep i (Nat.lt_succ_of_lt hi)) + have hblock := mul_le_mul_of_nonneg_left (hstep t (Nat.lt_succ_self _)) + (by positivity : 0 ≤ (4 : ℝ) ^ (t + 1)) + have hpow : (κ ^ t) ^ 2 = (κ ^ 2) ^ t := by rw [← pow_mul, Nat.mul_comm, pow_mul] + rw [Finset.sum_range_succ, mul_add, ← add_assoc] + refine hblock.trans (le_trans ?_ (add_le_add_left hprev _)) + rw [pow_succ, div_pow, div_pow, hpow] + exact le_of_eq (by ring) + +/-- Equation (7.4), with an error coefficient independent of the number +of blocks. Here `P / κ^i` is the position count at the start of block `i`. -/ +theorem sqrtEnergy_le (L : ℕ → ℝ) {P c κ : ℝ} (T : ℕ) + (hP : 0 ≤ P) (hc : 0 ≤ c) (hκ : 2 < κ) (hinit : 0 ≤ L 0) + (hstep : ∀ i < T, L (i + 1) ≤ L i / 4 + c * (P / κ ^ i) ^ 2) : + Real.sqrt (L T) ≤ (Real.sqrt (L 0) + P * Real.sqrt (4 * c / (1 - 4 / κ ^ 2))) / 2 ^ T := by + let r := 4 / κ ^ 2 + have hr : 0 ≤ r := by dsimp [r]; positivity + have hr' : r < 1 := by + apply (div_lt_iff₀ (by nlinarith : 0 < κ ^ 2)).mpr + nlinarith [sq_nonneg (κ - 2)] + have hsum : ∑ i ∈ Finset.range T, r ^ i ≤ 1 / (1 - r) := by + simpa using (geom_sum_Ico_le_of_lt_one (m := 0) (n := T) hr hr') + have hscaled := scaledEnergy_le L P c κ T hstep + have hbound : 4 ^ T * L T ≤ L 0 + P ^ 2 * (4 * c / (1 - r)) := by + calc + _ ≤ L 0 + 4 * c * P ^ 2 * ∑ i ∈ Finset.range T, r ^ i := hscaled + _ ≤ L 0 + 4 * c * P ^ 2 * (1 / (1 - r)) := + add_le_add_right (mul_le_mul_of_nonneg_left hsum (by positivity)) _ + _ = _ := by ring + have hs : 0 ≤ 4 * c / (1 - r) := div_nonneg (by positivity) (sub_nonneg.mpr hr'.le) + change Real.sqrt (L T) ≤ (Real.sqrt (L 0) + P * Real.sqrt (4 * c / (1 - r))) / 2 ^ T + apply Real.sqrt_le_iff.mpr + refine ⟨by positivity, ?_⟩ + rw [div_pow, ← pow_mul, Nat.mul_comm T 2, pow_mul] + norm_num + apply (le_div_iff₀ (by positivity)).mpr + rw [mul_comm] + calc + _ ≤ L 0 + P ^ 2 * (4 * c / (1 - r)) := hbound + _ ≤ _ := by + rw [add_sq, mul_pow, Real.sq_sqrt hinit, Real.sq_sqrt hs] + linarith [mul_nonneg (Real.sqrt_nonneg (L 0)) + (mul_nonneg hP (Real.sqrt_nonneg (4 * c / (1 - r))))] + +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionBlock.lean b/lean/OAI/Computability/VPVNP/CompressionBlock.lean new file mode 100644 index 0000000000..60baa21192 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionBlock.lean @@ -0,0 +1,111 @@ +import OAI.Computability.VPVNP.CompressionSchedule +import OAI.Computability.VPVNP.CompressionProcedure + +/-! +# Executing one block of scheduled compression + +The shrinking steps are composed in their chosen order. Each step retains +its execution tree for every branch of the preceding exact kernel. The final +refresh restores the initial degree. The procedure consumes the sum of the +scheduled lane lengths, divides the number of positions by their packing +product, and multiplies the leading energy coefficient by the quarter-bound +factor of Section 7.4. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +variable {R : Type*} [CommSemiring R] + +/-- Change the presentation of equal indices without changing the exact procedure. -/ +def Procedure.reindex {a b k p a' b' k' p' : ℕ} {μ μ' : ℝ} (P : Procedure R a b k p μ) + (ha : a = a') (hb : b = b') (hk : k = k') (hp : p = p') (hμ : μ = μ') : + Procedure R a' b' k' p' μ' := ha ▸ hb ▸ hk ▸ hp ▸ hμ ▸ P + +@[simp] theorem Procedure.error_reindex {a b k p a' b' k' p' : ℕ} {μ μ' : ℝ} + (P : Procedure R a b k p μ) (ha : a = a') (hb : b = b') (hk : k = k') + (hp : p = p') (hμ : μ = μ') : (P.reindex ha hb hk hp hμ).error = P.error := by + subst a' b' k' p' μ' + rfl + +namespace BlockSchedule + +variable {k : Type*} [Field k] (S : BlockSchedule k) + +/-- One shrinking procedure per scheduled step, advancing to the next degree exponent with the +prescribed lane consumption, position divisor and shrinking energy multiplier. -/ +abbrev ShrinkProcedures (R : Type*) [CommSemiring R] := + ∀ i : Fin S.steps, Procedure R (S.degreeExponent i.castSucc) (S.degreeExponent i.succ) + (packingLaneBits (S.degreeExponent i.castSucc) 0) + (packingFactor (S.degreeExponent i.castSucc)) shrinkMultiplier + +/-- The final block procedure restoring the initial degree exponent, consuming the final +exponent in lane coordinates and preserving the number of positions with the scheduled +refresh multiplier. -/ +abbrev RefreshProcedure (R : Type*) [CommSemiring R] := + Procedure R (S.degreeExponent (Fin.last S.steps)) (S.degreeExponent 0) + (S.degreeExponent (Fin.last S.steps)) 1 + (refreshMultiplier S.baseDegree (2 ^ S.expanderExponent) S.poincare) + +/-- The first `j` shrinking procedures in the fixed block. -/ +noncomputable def shrinkPrefix (shrink : S.ShrinkProcedures R) (j : ℕ) (hj : j ≤ S.steps) : + Procedure R (S.degreeExponent 0) (S.exponentAt j) + (∑ i ∈ Finset.range j, packingLaneBits (S.exponentAt i) 0) + (∏ i ∈ Finset.range j, packingFactor (S.exponentAt i)) (shrinkMultiplier ^ j) := + match j with + | 0 => (Procedure.id R (S.degreeExponent 0)).reindex rfl + (by unfold exponentAt; apply congrArg S.degreeExponent; ext; simp) (by simp) (by simp) (by simp) + | j + 1 => + let i : Fin S.steps := ⟨j, hj⟩ + let previous := shrinkPrefix shrink j (by omega) + let step := (shrink i).reindex (S.exponentAt_castSucc i).symm + (show S.degreeExponent i.succ = S.exponentAt (j+1) by + simp only [exponentAt, min_eq_left hj]; rfl) + (congrArg (packingLaneBits · 0) (S.exponentAt_castSucc i).symm) + (congrArg packingFactor (S.exponentAt_castSucc i).symm) rfl + (previous.seq step).reindex rfl rfl (by rw [Finset.sum_range_succ]) + (by rw [Finset.prod_range_succ]) (by rw [pow_succ']) + +/-- Run every shrinking procedure and then the refresh, keeping its exact +state execution for every possible term selection. -/ +noncomputable def assembleBlock (shrink : S.ShrinkProcedures R) (refresh : S.RefreshProcedure R) : + Procedure R (S.degreeExponent 0) (S.degreeExponent 0) S.laneBits S.positionFactor + (refreshMultiplier S.baseDegree (2 ^ S.expanderExponent) S.poincare * shrinkMultiplier ^ S.steps) := + let all := (S.shrinkPrefix shrink S.steps le_rfl).reindex rfl + (show S.exponentAt S.steps = S.degreeExponent (Fin.last S.steps) by + simp only [exponentAt, min_self]; rfl) rfl rfl rfl + (all.seq refresh).reindex rfl rfl + (by simp only [laneBits, ← Fin.sum_univ_eq_sum_range, S.exponentAt_castSucc]) + (by simp only [positionFactor, ← Fin.prod_univ_eq_prod_range, S.exponentAt_castSucc, Nat.mul_one]) rfl + +variable {R' : Type*} [CommSemiring R'] + +private theorem shrinkPrefix_error_congr (s : S.ShrinkProcedures R) (s' : S.ShrinkProcedures R') + (hs : ∀ i, (s i).error = (s' i).error) (j : ℕ) (hj : j ≤ S.steps) : + (S.shrinkPrefix s j hj).error = (S.shrinkPrefix s' j hj).error := by + induction j with + | zero => + rw [shrinkPrefix, shrinkPrefix] + erw [Procedure.error_reindex] + | succ j ih => + simp only [shrinkPrefix, Procedure.error_reindex, Procedure.seq, ih (Nat.le_of_succ_le hj), hs] + +/-- When the constituent numerical bounds agree, the additive error of +the whole block agrees across coefficient rings and parameter assignments. -/ +theorem assembleBlock_error_congr (s : S.ShrinkProcedures R) (s' : S.ShrinkProcedures R') + (r : S.RefreshProcedure R) (r' : S.RefreshProcedure R') + (hs : ∀ i, (s i).error = (s' i).error) (hr : r.error = r'.error) : + (S.assembleBlock s r).error = (S.assembleBlock s' r').error := by + unfold assembleBlock + erw [Procedure.error_reindex, Procedure.error_reindex] + simp only [Procedure.seq, Procedure.error_reindex, S.shrinkPrefix_error_congr s s' hs, hr] + +end BlockSchedule +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionBlockHistory.lean b/lean/OAI/Computability/VPVNP/CompressionBlockHistory.lean new file mode 100644 index 0000000000..1765cfffb3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionBlockHistory.lean @@ -0,0 +1,66 @@ +import OAI.Computability.VPVNP.CompressionBlock +import OAI.Computability.VPVNP.CompressionProcedureHistory + +/-! +# Local records for one compression block + +The record list at each site comes from the actual shrinking or refresh +kernel. Composition follows the same indexed schedule as the energy and +position estimates. A maximum over the finitely many substep constants +bounds every local record, and each branch takes at most one step per +shrinking degree followed by one refresh. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +variable {R : Type*} [CommSemiring R] + +/-- Transport the chosen records along equal presentations of a procedure's +degrees, lane length, divisor and energy coefficient. -/ +def Procedure.RecordBounds.reindex {a b k p a' b' k' p' C s : ℕ} {μ μ' : ℝ} + {P : Procedure R a b k p μ} (B : P.RecordBounds C s) + {ha : a = a'} {hb : b = b'} {hk : k = k'} {hp : p = p'} {hμ : μ = μ'} : + (P.reindex ha hb hk hp hμ).RecordBounds C s := by + subst a' b' k' p' μ' + exact B + +namespace BlockSchedule + +variable {k : Type*} [Field k] (S : BlockSchedule k) + +private noncomputable def prefixRecordBounds {C : ℕ} (shrink : S.ShrinkProcedures R) + (hs : ∀ i : Fin S.steps, (shrink i).RecordBounds C 1) (j : ℕ) (hj : j ≤ S.steps) : + (S.shrinkPrefix shrink j hj).RecordBounds C j := + match j with + | 0 => by + rw [shrinkPrefix] + exact (Procedure.RecordBounds.id R _ C).reindex + | j + 1 => by + rw [shrinkPrefix] + apply Procedure.RecordBounds.reindex + apply Procedure.RecordBounds.mono _ (max_le (le_refl C) (le_refl C)) le_rfl + exact (prefixRecordBounds shrink hs j (by omega)).seq (hs ⟨j, hj⟩).reindex + +/-- The bound records the actual kernels passed into `assembleBlock` and +is independent of the network order, widths, and chosen execution path. -/ +noncomputable def assembleBlockRecords (shrink : S.ShrinkProcedures R) + (refresh : S.RefreshProcedure R) {C : Fin S.steps → ℕ} {D : ℕ} + (hs : ∀ i : Fin S.steps, (shrink i).RecordBounds (C i) 1) (hr : refresh.RecordBounds D 1) : + (S.assembleBlock shrink refresh).RecordBounds (max (Finset.univ.sup C) D) (S.steps + 1) := by + unfold assembleBlock + apply Procedure.RecordBounds.reindex + apply Procedure.RecordBounds.seq _ hr + apply Procedure.RecordBounds.reindex + exact S.prefixRecordBounds shrink (fun i ↦ (hs i).mono (Finset.le_sup (Finset.mem_univ i)) le_rfl) + S.steps le_rfl + +end BlockSchedule +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionBoundedBind.lean b/lean/OAI/Computability/VPVNP/CompressionBoundedBind.lean new file mode 100644 index 0000000000..3b731363cd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionBoundedBind.lean @@ -0,0 +1,104 @@ +import OAI.Computability.VPVNP.CompressionHistory + +/-! +# Composition of bounded compressor histories + +When each branch of one compressor execution continues with a second execution, +the records of the combined execution consist of the original records of both +stages. Uniform local bounds are preserved and the selected chain lengths add. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +open NetworkKernel + +variable {R : Type*} [CommSemiring R] {a b g n b' n' : ℕ} {X : State a g} + +/-- A bound on a single pass may be enlarged without changing any records. -/ +theorem StatePass.bounded_mono (p : StatePass R X b n) (rec : p.Records) {C D : ℕ} + (hCD : C ≤ D) (h : p.Bounded rec C) : p.Bounded rec D := by + intro i + obtain ⟨hcount, hwidth, hnext⟩ := h i + exact ⟨fun v ↦ (hcount v).trans hCD, hwidth.trans (Nat.mul_le_mul_right _ hCD), hnext⟩ + +namespace StateExecution + +/-- Enlarge the uniform bound throughout an execution tree. -/ +theorem bounded_mono (E : StateExecution R b n X) (rec : E.Records) {C D : ℕ} + (hCD : C ≤ D) (h : E.Bounded C rec) : E.Bounded D rec := by + induction E with + | done => trivial + | more p tail ih => exact ⟨p.bounded_mono rec.1 hCD h.1, fun i ↦ ih i (rec.2 i) (h.2 i)⟩ + +/-- Append the actual continuation records at each leaf of an execution. -/ +def bindRecords {a g : ℕ} {X : State a g} (E : StateExecution R b n X) + : (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z)) → + E.Records → ((z : E.Choices) → (f z).Records) → (E.bind f).Records := + match E with + | .done _ => fun _ _ after ↦ after () + | .more _ tail => fun f rec after ↦ (rec.1, fun i ↦ (tail i).bindRecords + (fun z ↦ f ⟨i, z⟩) (rec.2 i) (fun z ↦ after ⟨i, z⟩)) + +/-- A common bound on all elementary passes holds on every combined branch. -/ +theorem bounded_bindRecords (E : StateExecution R b n X) + (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z)) + (rec : E.Records) (after : ∀ z, (f z).Records) {C : ℕ} + (hE : E.Bounded C rec) (hAfter : ∀ z, (f z).Bounded C (after z)) : + (E.bind f).Bounded C (E.bindRecords f rec after) := by + induction E with + | done => exact hAfter () + | more p tail ih => + exact ⟨hE.1, fun i ↦ ih i (fun z ↦ f ⟨i, z⟩) (rec.2 i) (fun z ↦ after ⟨i, z⟩) + (hE.2 i) (fun z ↦ hAfter ⟨i, z⟩)⟩ + +omit [CommSemiring R] in +private theorem length_cast {N Y Z : Network} (h : N = Y) (chain : TermChain R Y Z) : + (h.symm ▸ chain : TermChain R N Z).length = chain.length := by cases h; rfl + +/-- Passing through one kernel adds one to the selected continuation length. -/ +theorem length_more {c r : ℕ} (p : StatePass R X c r) + (tail : ∀ i, StateExecution R b n (p.next i)) + (rec : (.more p tail : StateExecution R b n X).Records) + (z : (.more p tail : StateExecution R b n X).Choices) : + ((.more p tail : StateExecution R b n X).termChain rec z).length = + ((tail z.1).termChain (rec.2 z.1) z.2).length + 1 := by + exact congrArg (· + 1) (length_cast (p.output_eq z.1) _) + +/-- Each selected chain has the sum of the lengths of its actual prefix and suffix. -/ +theorem exists_length_bindRecords (E : StateExecution R b n X) + (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z)) + (rec : E.Records) (after : ∀ z, (f z).Records) (w : (E.bind f).Choices) : + ∃ (z : E.Choices) (y : (f z).Choices), + ((E.bind f).termChain (E.bindRecords f rec after) w).length = + (E.termChain rec z).length + ((f z).termChain (after z) y).length := by + induction E with + | done => exact ⟨(), w, (Nat.zero_add _).symm⟩ + | more p tail ih => + obtain ⟨z, y, h⟩ := ih w.1 (fun z ↦ f ⟨w.1,z⟩) (rec.2 w.1) (fun z ↦ after ⟨w.1,z⟩) w.2 + refine ⟨⟨w.1,z⟩, y, ?_⟩ + refine (length_more p (fun i ↦ (tail i).bind (fun z ↦ f ⟨i,z⟩)) + ((more p tail).bindRecords f rec after) w).trans ?_ + refine (congrArg (· + 1) h).trans ((Nat.add_right_comm _ _ 1).trans ?_) + exact congrArg (· + _) (length_more p tail rec ⟨w.1, z⟩).symm + +/-- Uniform bounds on the lengths of the two stages add after dependent continuation. -/ +theorem length_bindRecords_le (E : StateExecution R b n X) + (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z)) + (rec : E.Records) (after : ∀ z, (f z).Records) {m₁ m₂ : ℕ} + (hE : ∀ z, (E.termChain rec z).length ≤ m₁) + (hAfter : ∀ z y, ((f z).termChain (after z) y).length ≤ m₂) + (w : (E.bind f).Choices) : + ((E.bind f).termChain (E.bindRecords f rec after) w).length ≤ m₁ + m₂ := by + obtain ⟨z, y, h⟩ := E.exists_length_bindRecords f rec after w + exact h.trans_le (Nat.add_le_add (hE z) (hAfter z y)) + +end StateExecution +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionBudget.lean b/lean/OAI/Computability/VPVNP/CompressionBudget.lean new file mode 100644 index 0000000000..89cf3c016b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionBudget.lean @@ -0,0 +1,252 @@ +import OAI.Computability.VPVNP.RAMClock +import OAI.Computability.VPVNP.Compression +import OAI.Computability.VPVNP.CompressionParameters +import Mathlib.Analysis.SpecialFunctions.Pow.Real +import Mathlib.Analysis.Asymptotics.Defs + +/-! +# Communication budgets for a compressed pair of groups + +Sections 12 and 13 of *VP and VNP differ over every field* compare the +compressed bit count and the number of external accesses with the budget +of a live group. All bounds below are uniform in the choice of compression +terms, with thresholds depending only on the fixed constants. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +open Filter Asymptotics + +/-- Every fixed power of the binary logarithm is eventually absorbed by any +positive gap between two real power exponents, with any prescribed coefficient. -/ +theorem eventually_absorb_polylog (A : ℝ) (k : ℕ) {a b ε : ℝ} (hab : a < b) (hε : 0 < ε) : + ∀ᶠ n : ℕ in atTop, A * (n : ℝ) ^ a * (n.log2 + 1 : ℝ) ^ k ≤ ε * (n : ℝ) ^ b := by + let D := ⌈(b - a)⁻¹⌉₊ + 1 + let M := ⌈A / ε⌉₊ + have hD : 0 < (D : ℝ) := by dsimp [D]; positivity + have hgap : (D : ℝ)⁻¹ ≤ b - a := by + have hceil := Nat.le_ceil ((b - a)⁻¹) + have hle : (b - a)⁻¹ ≤ (D : ℝ) := by dsimp [D]; push_cast; linarith + simpa only [inv_inv] using (inv_le_inv₀ hD (inv_pos.mpr (sub_pos.mpr hab))).mpr hle + filter_upwards [BurstRAM.eventually_polylog_le (M ^ D) (k * D), eventually_ge_atTop 1] with n hn hn1 + have hbase : 1 ≤ (n : ℝ) := by exact_mod_cast hn1 + have hnpos : 0 < (n : ℝ) := by linarith + have hpoly : ((M : ℝ) * (n.log2 + 1 : ℝ) ^ k) ^ D ≤ n := by + rw [mul_pow, ← pow_mul] + exact_mod_cast hn + have hsmall : (M : ℝ) * (n.log2 + 1 : ℝ) ^ k ≤ (n : ℝ) ^ (b - a) := by + apply le_trans _ (Real.rpow_le_rpow_of_exponent_le hbase hgap) + apply (Real.le_rpow_inv_iff_of_pos (by positivity) hnpos.le hD).mpr + simpa only [Real.rpow_natCast] using hpoly + have hA : A ≤ ε * M := by + have hm := Nat.le_ceil (A / ε) + rwa [div_le_iff₀ hε, mul_comm] at hm + calc + _ ≤ (ε * M) * (n : ℝ) ^ a * (n.log2 + 1 : ℝ) ^ k := by gcongr + _ = ε * (n : ℝ) ^ a * ((M : ℝ) * (n.log2 + 1 : ℝ) ^ k) := by ring + _ ≤ ε * (n : ℝ) ^ a * (n : ℝ) ^ (b - a) := by gcongr + _ = ε * (n : ℝ) ^ b := by rw [mul_assoc, ← Real.rpow_add hnpos]; ring_nf + +/-- The live address exponent can be fixed after the polynomial preparation +exponent. The multiplicative constant and the polylogarithmic power may +still depend on the chosen address exponent. -/ +theorem preparation_isLittleO_processors (A : ℕ → ℝ) (k : ℕ → ℕ) {e B : ℕ} (he : e < B) : + (fun n : ℕ => A B * (n : ℝ) ^ e * (n.log2 + 1 : ℝ) ^ k B) =o[atTop] + (fun n : ℕ => (2 : ℝ) ^ (B * Nat.clog 2 n)) := by + apply IsLittleO.of_bound + intro ε hε + have hsmall := eventually_absorb_polylog |A B| (k B) (show (e : ℝ) < B by exact_mod_cast he) hε + filter_upwards [hsmall] with n h + have hn : (n : ℝ) ^ B ≤ (2 : ℝ) ^ (B * Nat.clog 2 n) := by + rw [Nat.mul_comm, pow_mul] + exact_mod_cast Nat.pow_le_pow_left (Nat.le_pow_clog (by decide : 1 < 2) n) B + simp only [Real.norm_eq_abs, abs_mul, abs_pow, abs_of_nonneg (Nat.cast_nonneg (α := ℝ) n), + abs_of_nonneg (by positivity : 0 ≤ (n.log2 + 1 : ℝ)), abs_of_nonneg (by norm_num : 0 ≤ (2 : ℝ))] + exact (by simpa only [Real.rpow_natCast] using h : _ ≤ ε * (n : ℝ) ^ B).trans + (mul_le_mul_of_nonneg_left hn hε.le) + +/-- Equation (12.1) for every energy sequence satisfying the one-block recurrence. +`P` and `W` are the initial position count and width, and `R` is the live site count. +The eventual threshold is independent of these counts and the term choices. -/ +theorem eventually_finalWidth_le {θ d c κ A B : ℝ} (hθ : 0 < θ) (hd : 0 ≤ d) + (hc : 0 ≤ c) (hκ : 2 < κ) (hA : 0 ≤ A) (s t : ℕ) : + ∀ᶠ n : ℕ in atTop, ∀ (R P W : ℕ) (L : ℕ → ℝ), + (P : ℝ) ≤ A * R * (n : ℝ) ^ (3 / 4 : ℝ) * (n.log2 + 1 : ℝ) ^ s → + (W : ℝ) ≤ B * (n : ℝ) ^ (1 / 4 : ℝ) * (n.log2 + 1 : ℝ) ^ t → + 0 ≤ L 0 → Real.sqrt (L 0) ≤ d * P * W → + (∀ i < blockCount θ n, L (i + 1) ≤ L i / 4 + c * ((P : ℝ) / κ ^ i) ^ 2) → + Real.sqrt (L (blockCount θ n)) ≤ (R : ℝ) * (n : ℝ) ^ (1 - θ / 2) := by + let D := Real.sqrt (4 * c / (1 - 4 / κ ^ 2)) + have hD : 0 ≤ D := Real.sqrt_nonneg _ + have hterm₁ := eventually_absorb_polylog (2 * d * A * B) (s + t) + (show 1 - θ < 1 - θ / 2 by linarith) (show (0 : ℝ) < 1 / 2 by norm_num) + have hterm₂ := eventually_absorb_polylog (2 * A * D) s + (show 3 / 4 - θ < 1 - θ / 2 by linarith) (show (0 : ℝ) < 1 / 2 by norm_num) + filter_upwards [hterm₁, hterm₂, eventually_ge_atTop 1] with n h₁ h₂ hn + intro R P W L hP hW hinit hstart hstep + have hnpos : 0 < (n : ℝ) := by exact_mod_cast hn + calc + _ ≤ (Real.sqrt (L 0) + P * D) / 2 ^ blockCount θ n := + sqrtEnergy_le L _ (by positivity) hc hκ hinit hstep + _ ≤ (d * P * W + P * D) * (2 * (n : ℝ) ^ (-θ)) := by + rw [div_eq_mul_one_div]; gcongr; exact inv_two_pow_blockCount θ hn + _ ≤ (d * (A * R * (n : ℝ) ^ (3 / 4 : ℝ) * (n.log2 + 1 : ℝ) ^ s) * + (B * (n : ℝ) ^ (1 / 4 : ℝ) * (n.log2 + 1 : ℝ) ^ t) + + (A * R * (n : ℝ) ^ (3 / 4 : ℝ) * (n.log2 + 1 : ℝ) ^ s) * D) * + (2 * (n : ℝ) ^ (-θ)) := by gcongr + _ = (R : ℝ) * ((2 * d * A * B) * (n : ℝ) ^ (1 - θ) * (n.log2 + 1 : ℝ) ^ (s + t) + + (2 * A * D) * (n : ℝ) ^ (3 / 4 - θ) * (n.log2 + 1 : ℝ) ^ s) := by + rw [show (1 - θ) = (3 / 4 + 1 / 4) + (-θ) by ring, Real.rpow_add hnpos, Real.rpow_add hnpos, + sub_eq_add_neg, Real.rpow_add hnpos, pow_add] + ring + _ ≤ (R : ℝ) * ((1/2) * (n : ℝ) ^ (1-θ/2) + (1/2) * (n : ℝ) ^ (1-θ/2)) := by gcongr + _ = _ := by ring + +/-- Proposition 13.1's external calls and probes use a vanishing fraction of +`R K`. The hypotheses separate the initial geometry, final bit count and the +per-path operation estimate from this asymptotic comparison. -/ +theorem simulationCost_isLittleO {R P F work : ℕ → ℕ} {θ δ A C : ℝ} {s t : ℕ} + (hθ : 0 < θ) (hθ' : θ < 1 / 100) (hδ : δ < θ / 10) (hC : 0 ≤ C) + (hP : ∀ᶠ n in atTop, (P n : ℝ) ≤ A * R n * (n : ℝ) ^ (3 / 4 : ℝ) * (n.log2 + 1 : ℝ) ^ s) + (hF : ∀ᶠ n in atTop, (F n : ℝ) ≤ R n * (n : ℝ) ^ (1 - θ / 2)) + (hwork : ∀ᶠ n in atTop, (work n : ℝ) ≤ C * + (P n * (n : ℝ) ^ (1 / 100 : ℝ) * (n.log2 + 1 : ℝ) ^ t + F n)) : + (fun n => (work n : ℝ)) =o[atTop] (fun n => (R n : ℝ) * liveBucket δ n) := by + apply IsLittleO.of_bound + intro ε hε + have hs := eventually_absorb_polylog (C * A) (s + t) + (show 3 / 4 + 1 / 100 < 1 - δ by linarith) (half_pos hε) + have hf := eventually_absorb_polylog C 0 + (show 1 - θ / 2 < 1 - δ by linarith) (half_pos hε) + filter_upwards [hP, hF, hwork, hs, hf, eventually_ge_atTop 1] with n hpos hbits hcost hsmall hfinal hn + have hnpos : 0 < (n : ℝ) := by exact_mod_cast hn + simp only [pow_zero, mul_one] at hfinal + rw [Real.norm_eq_abs, Real.norm_eq_abs, abs_of_nonneg (by positivity), abs_of_nonneg (by positivity)] + calc + _ ≤ _ := hcost + _ ≤ C * (A * R n * (n : ℝ) ^ (3 / 4 : ℝ) * (n.log2 + 1 : ℝ) ^ s * + (n : ℝ) ^ (1 / 100 : ℝ) * (n.log2 + 1 : ℝ) ^ t + R n * (n : ℝ) ^ (1 - θ / 2)) := by gcongr + _ = R n * ((C * A) * (n : ℝ) ^ (3 / 4 + 1 / 100 : ℝ) * (n.log2 + 1 : ℝ) ^ (s + t) + + C * (n : ℝ) ^ (1 - θ / 2)) := by rw [Real.rpow_add hnpos, pow_add]; ring + _ ≤ R n * ((ε / 2) * (n : ℝ) ^ (1 - δ) + (ε / 2) * (n : ℝ) ^ (1 - δ)) := by gcongr + _ = ε * ((R n : ℝ) * (n : ℝ) ^ (1 - δ)) := by ring + _ ≤ _ := by gcongr; exact (liveBucket_bounds (by linarith : δ ≤ 1) hn).1 + +/-- Combine the wire-energy and operation estimates for an entire family of paths. +The final bit count is the sum of the actual final arc widths. Only the per-block +recurrence, initial envelopes, and accounting inequality for the simulated path +are required as input. -/ +theorem pairSimulation_budget {Wire : ℕ → Type*} [∀ n, Fintype (Wire n)] + (width : ∀ n, Wire n → ℕ) (mass : ∀ n, Wire n → ℝ) + (hmass : ∀ᶠ n in atTop, ∀ e, 0 < mass n e) (hnorm : ∀ᶠ n in atTop, ∑ e, mass n e = 1) + {R P W work : ℕ → ℕ} {L : ℕ → ℕ → ℝ} {θ δ d c κ A B C : ℝ} {s t k : ℕ} + (hθ : 0 < θ) (hθ' : θ < 1 / 100) (hδ : δ < θ / 10) + (hd : 0 ≤ d) (hc : 0 ≤ c) (hκ : 2 < κ) (hA : 0 ≤ A) (hC : 0 ≤ C) + (hP : ∀ᶠ n in atTop, (P n : ℝ) ≤ A * R n * (n : ℝ) ^ (3/4 : ℝ) * (n.log2 + 1 : ℝ) ^ s) + (hW : ∀ᶠ n in atTop, (W n : ℝ) ≤ B * (n : ℝ) ^ (1/4 : ℝ) * (n.log2 + 1 : ℝ) ^ t) + (hinit : ∀ᶠ n in atTop, 0 ≤ L n 0 ∧ Real.sqrt (L n 0) ≤ d * P n * W n) + (hstep : ∀ᶠ n in atTop, ∀ i < blockCount θ n, + L n (i + 1) ≤ L n i / 4 + c * ((P n : ℝ) / κ ^ i) ^ 2) + (hfinal : ∀ᶠ n in atTop, ∑ e, (width n e : ℝ) ^ 2 / mass n e ≤ L n (blockCount θ n)) + (hwork : ∀ᶠ n in atTop, (work n : ℝ) ≤ C * + (P n * (n : ℝ) ^ (1 / 100 : ℝ) * (n.log2 + 1 : ℝ) ^ k + ↑(∑ e, width n e))) : + (∀ᶠ n in atTop, (∑ e, (width n e : ℝ)) ≤ R n * (n : ℝ) ^ (1 - θ / 2)) ∧ + (fun n => (work n : ℝ)) =o[atTop] (fun n => (R n : ℝ) * liveBucket δ n) := by + have hF : ∀ᶠ n in atTop, (∑ e, (width n e : ℝ)) ≤ R n * (n : ℝ) ^ (1 - θ / 2) := by + filter_upwards [hP, hW, hinit, hstep, hfinal, hmass, hnorm, + eventually_finalWidth_le (B := B) hθ hd hc hκ hA s t] with n hp hw hi hs hf hm hunit hbound + exact (widthSum_le_sqrtEnergy (fun e => (width n e : ℝ)) (mass n) hm hunit).trans + ((Real.sqrt_le_sqrt hf).trans (hbound (R n) (P n) (W n) (L n) hp hw hi.1 hi.2 hs)) + exact ⟨hF, simulationCost_isLittleO (F := fun n => ∑ e, width n e) hθ hθ' hδ hC hP + (by simpa using hF) hwork⟩ + +/-- In a regular network with `P d` arcs of equal mass, bounding each width by `W` +bounds the initial square-root energy by `P d W`, also for an empty network. -/ +theorem regularWire_sqrtEnergy_le {Wire : Type*} [Fintype Wire] (width : Wire → ℕ) + {P d W : ℕ} (hcard : Fintype.card Wire = P * d) (hW : ∀ e, width e ≤ W) : + Real.sqrt (∑ e, (width e : ℝ) ^ 2 / (1 / ((P : ℝ) * d))) ≤ (P : ℝ) * d * W := by + apply Real.sqrt_le_iff.mpr + refine ⟨by positivity, ?_⟩ + calc + _ ≤ ∑ _e : Wire, (W : ℝ) ^ 2 / (1 / ((P : ℝ) * d)) := + Finset.sum_le_sum fun e _ => by gcongr; exact_mod_cast hW e + _ = _ := by simp [hcard, div_eq_mul_inv]; ring + +/-- Field lengths and local monomial degrees satisfy the section 12 exponents +whenever the block growth bound is `C₂^T (W+1)`, with any fixed multiplier. -/ +theorem eventually_fieldGrowth_le {θ C₂ A B : ℝ} (hθ : 0 ≤ θ) (hC : 1 ≤ C₂) + (hexp : θ * Real.logb 2 C₂ ≤ 1 / 100) (hA : 0 ≤ A) (t : ℕ) : + ∀ᶠ n : ℕ in atTop, ∀ W : ℕ, + (W : ℝ) ≤ B * (n : ℝ) ^ (1 / 4 : ℝ) * (n.log2 + 1 : ℝ) ^ t → + A * C₂ ^ blockCount θ n * (W + 1 : ℝ) ≤ (n : ℝ) ^ (3 / 10 : ℝ) ∧ + A * C₂ ^ blockCount θ n * (W + 1 : ℝ) ≤ (n : ℝ) ^ (2 / 5 : ℝ) := by + have hmain := eventually_absorb_polylog (A * (B + 1)) t + (show (1/100 + 1/4 : ℝ) < 3/10 by norm_num) zero_lt_one + filter_upwards [hmain, eventually_ge_atTop 1] with n hmain hn + intro W hW + have hn1 : 1 ≤ (n : ℝ) := by exact_mod_cast hn + have hg : 1 ≤ (n : ℝ) ^ (1 / 4 : ℝ) * (n.log2 + 1 : ℝ) ^ t := + one_le_mul_of_one_le_of_one_le (Real.one_le_rpow hn1 (by norm_num)) + (one_le_pow₀ (by linarith [Nat.cast_nonneg (α := ℝ) n.log2])) + have hw : (W + 1 : ℝ) ≤ (B + 1) * (n : ℝ) ^ (1/4 : ℝ) * (n.log2 + 1 : ℝ) ^ t := by + calc _ ≤ B * (n : ℝ) ^ (1/4 : ℝ) * (n.log2 + 1 : ℝ) ^ t + + (n : ℝ) ^ (1/4 : ℝ) * (n.log2 + 1 : ℝ) ^ t := add_le_add hW hg + _ = _ := by ring + have hlen : A * C₂ ^ blockCount θ n * (W + 1 : ℝ) ≤ (n : ℝ) ^ (3/10 : ℝ) := calc + _ ≤ A * (n : ℝ) ^ (1/100 : ℝ) * ((B + 1) * (n : ℝ) ^ (1/4 : ℝ) * (n.log2 + 1 : ℝ) ^ t) := by + gcongr; exact history_pow_blockCount_le hC hθ hn hexp + _ = A * (B + 1) * (n : ℝ) ^ (1/100 + 1/4 : ℝ) * (n.log2 + 1 : ℝ) ^ t := by + rw [Real.rpow_add (zero_lt_one.trans_le hn1)]; ring + _ ≤ _ := by simpa only [one_mul] using hmain + exact ⟨hlen, hlen.trans (Real.rpow_le_rpow_of_exponent_le hn1 (by norm_num))⟩ + +/-- Fetching the incident bits and history descriptors at one final vertex fits +in a live bucket. The fixed number of counter updates may be included in `A`. -/ +theorem eventually_burst_le {δ : ℝ} (hδ : δ ≤ 1 / 2) (A : ℝ) (k : ℕ) : + ∀ᶠ n : ℕ in atTop, + A * ((n : ℝ) ^ (3/10 : ℝ) + (n : ℝ) ^ (1/100 : ℝ) * (n.log2 + 1 : ℝ) ^ k) ≤ + (n : ℝ) ^ (1/2 : ℝ) ∧ (n : ℝ) ^ (1/2 : ℝ) ≤ liveBucket δ n := by + have h₁ := eventually_absorb_polylog A 0 (show (3/10 : ℝ) < 1/2 by norm_num) + (show (0 : ℝ) < 1/2 by norm_num) + have h₂ := eventually_absorb_polylog A k (show (1/100 : ℝ) < 1/2 by norm_num) + (show (0 : ℝ) < 1/2 by norm_num) + filter_upwards [h₁, h₂, eventually_ge_atTop 1] with n ha hb hn + simp only [pow_zero, mul_one] at ha + constructor + · linarith only [ha, hb] + · exact (Real.rpow_le_rpow_of_exponent_le (by exact_mod_cast hn) (by linarith)).trans + (liveBucket_bounds (by linarith) hn).1 + +/-- With `R ≥ n^5` the total increment from at most `P n^0.01` map occurrences +of degree at most `n^0.4` fits strictly below `R²`, the limit of a `2r`-bit counter. -/ +theorem eventually_counter_lt (A : ℝ) (s : ℕ) : + ∀ᶠ n : ℕ in atTop, ∀ R P : ℕ, n ^ 5 ≤ R → + (P : ℝ) ≤ A * R * (n : ℝ) ^ (3/4 : ℝ) * (n.log2 + 1 : ℝ) ^ s → + (P : ℝ) * (n : ℝ) ^ (1/100 : ℝ) * (n : ℝ) ^ (2/5 : ℝ) < (R : ℝ) ^ 2 := by + have hsmall := eventually_absorb_polylog A s + (show (3/4 + 1/100 + 2/5 : ℝ) < 4 by norm_num) zero_lt_one + filter_upwards [hsmall, eventually_ge_atTop 2] with n hsmall hn + intro R P hR hP + have hn1 : 1 < (n : ℝ) := by exact_mod_cast hn + have hR' : (n : ℝ)^5 ≤ R := by exact_mod_cast hR + have hnpos : 0 < (n : ℝ) := zero_lt_one.trans hn1 + have hpos : 0 < (R : ℝ) := (pow_pos hnpos 5).trans_le hR' + calc + _ ≤ (A * R * (n : ℝ) ^ (3/4 : ℝ) * (n.log2 + 1 : ℝ) ^ s) * + (n : ℝ) ^ (1/100 : ℝ) * (n : ℝ) ^ (2/5 : ℝ) := by gcongr + _ = (R : ℝ) * (A * (n : ℝ) ^ (3/4 + 1/100 + 2/5 : ℝ) * (n.log2 + 1 : ℝ) ^ s) := by + rw [Real.rpow_add hnpos, Real.rpow_add hnpos]; ring + _ ≤ (R : ℝ) * (n : ℝ) ^ (4 : ℕ) := by gcongr; simpa using hsmall + _ < (R : ℝ) * (n : ℝ) ^ (5 : ℕ) := + mul_lt_mul_of_pos_left (pow_lt_pow_right₀ hn1 (by decide)) hpos + _ ≤ _ := by rw [pow_two]; gcongr + +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionDegreeAssembly.lean b/lean/OAI/Computability/VPVNP/CompressionDegreeAssembly.lean new file mode 100644 index 0000000000..f5853c2924 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionDegreeAssembly.lean @@ -0,0 +1,51 @@ +import OAI.Computability.VPVNP.CompressionLocalDegree +import OAI.Computability.VPVNP.CompressedRAMMonomials + +/-! +# Degree coverage for the fixed iterated compressor + +The shrinking and refresh records use the two parts of the common template +alphabet. At every site and on every branch of the actual repeated block, +the degrees in these records bound the degree of its chosen kernel monomial. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) + +theorem shrinkProcedure_degreeCovered (i : Fin S.steps) : + Procedure.DegreeCovered (B.shrinkProcedureWitnesses f hf i) (B.shrinkProcedureRecords f hf i) := + Procedure.DegreeCovered.ofPass _ _ _ _ _ _ _ _ _ + (fun g X => B.shrinkPass_degreeCovered f hf i (packingLaneBits_add _ g) X) + +theorem refreshProcedure_degreeCovered : + Procedure.DegreeCovered (B.refreshProcedureWitnesses f hf) + (B.refreshProcedureRecords f hf) := by + intro g n h X + subst n + exact ⟨B.refreshPass_degreeCovered f hf g X, fun _ => trivial⟩ + +theorem procedure_degreeCovered : + Procedure.DegreeCovered (B.procedureWitnesses f hf) (B.recordBounds f hf) := + S.assemble_degreeCovered _ _ _ _ _ _ (B.shrinkProcedure_degreeCovered f hf) + (B.refreshProcedure_degreeCovered f hf) + +/-- The actual repeated witnesses in the kernel history obey the degree +bound given by the corresponding repeated records. -/ +theorem execute_degreeCovered {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) + (X : State (S.degreeExponent 0) n) : + (B.execute f hf T h X).DegreeCovered + (Procedure.repeatWitnesses (B.procedureWitnesses f hf) _ T n (Nat.add_sub_of_le h).symm X) + (B.records f hf T h X) := + Procedure.repeat_degreeCovered (B.procedure_degreeCovered f hf) _ T n (Nat.add_sub_of_le h).symm X + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionDegreeCoverage.lean b/lean/OAI/Computability/VPVNP/CompressionDegreeCoverage.lean new file mode 100644 index 0000000000..2cf30640ec --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionDegreeCoverage.lean @@ -0,0 +1,158 @@ +import OAI.Computability.VPVNP.CompressionMonomialHistory +import OAI.Computability.VPVNP.CompressionBlockHistory +import OAI.Computability.VPVNP.CompressionPowerHistory + +/-! +# Degrees of map witnesses throughout a compressor execution + +The witnesses and records are indexed by the same pass and selected term. +The sum of the recorded map degrees at a site therefore bounds every local +choice there. This property is preserved by joining procedures, assembling +a scheduled block, and repeating it. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +open NetworkKernel + +variable {R : Type*} [CommRing R] {L : Type} [Fintype L] {κ : L → R} + +/-- The joint degree of a chosen kernel monomial is bounded by the degrees +of all map occurrences at its output site. -/ +def StatePass.DegreeCovered {a g b n : ℕ} {X : State a g} (p : StatePass R X b n) + (W : p.MapWitnesses κ) (rec : p.Records) : Prop := + ∀ i v x z c, (∑ label, (W i v x z).exponents c label) ≤ ∑ j, (rec i v).degree j + +/-- Degree coverage at every site in every branch-dependent substep. -/ +def StateExecution.DegreeCovered {a g b n : ℕ} {X : State a g} : + (E : StateExecution R b n X) → E.MapWitnesses κ → E.Records → Prop + | .done _, _, _ => True + | .more p tail, W, rec => + p.DegreeCovered W.1 rec.1 ∧ ∀ i, (tail i).DegreeCovered (W.2 i) (rec.2 i) + +theorem StateExecution.degreeCovered_bind {a g b n b' n' : ℕ} {X : State a g} + (E : StateExecution R b n X) (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z)) + (W : E.MapWitnesses κ) (V : ∀ z, (f z).MapWitnesses κ) + (u : E.Records) (v : ∀ z, (f z).Records) + (hu : E.DegreeCovered W u) (hv : ∀ z, (f z).DegreeCovered (V z) (v z)) : + (E.bind f).DegreeCovered (E.bindWitnesses f W V) (E.bindRecords f u v) := by + induction E with + | done => exact hv () + | more p tail ih => + exact ⟨hu.1, fun i => ih i _ (W.2 i) _ (u.2 i) _ (hu.2 i) (fun z => hv ⟨i, z⟩)⟩ + +namespace Procedure + +variable {a b l d C m : ℕ} {μ : ℝ} + +/-- The same degree bound for every admissible input state of a procedure. -/ +abbrev DegreeCovered {P : Procedure R a b l d μ} (W : P.MapWitnesses κ) (B : P.RecordBounds C m) := + ∀ g n h X, (P.run g n h X).DegreeCovered (W g n h X) (B.records g n h X) + +namespace DegreeCovered + +theorem id (a C : ℕ) (κ : L → R) : + DegreeCovered (MapWitnesses.id a κ) (RecordBounds.id R a C) := by + intro g n h X + have hn := h.trans (Nat.zero_add g) + subst g + trivial + +theorem ofPass {A : ℝ} (hd : 0 < d) (hμ : 0 ≤ μ) (hA : 0 ≤ A) + (f : ∀ g (X : State a (l + g)), StatePass R X b g) + (hc : ∀ g X (i : (f g X).step.Choice), X.positions = d * ((f g X).next i).positions) + (he : ∀ g X (i : (f g X).step.Choice), + ((f g X).next i).energy ≤ μ * X.energy + A * (X.positions : ℝ) ^ 2) + (W : ∀ g X, (f g X).MapWitnesses κ) + (rec : ∀ g X, (f g X).Records) (hb : ∀ g X, (f g X).Bounded (rec g X) C) + (hcov : ∀ g X, (f g X).DegreeCovered (W g X) (rec g X)) : + DegreeCovered (MapWitnesses.ofPass hd hμ hA f hc he W) + (RecordBounds.ofPass hd hμ hA f hc he rec hb) := by + intro g n h X + subst n + exact ⟨hcov g X, fun _ => trivial⟩ + +theorem seq {c l' d' D n : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} {Q : Procedure R b c l' d' ν} + {W : P.MapWitnesses κ} {V : Q.MapWitnesses κ} + {B : P.RecordBounds C m} {B' : Q.RecordBounds D n} + (h : DegreeCovered W B) (h' : DegreeCovered V B') : + DegreeCovered (W.seq V) (B.seq B') := + fun g n eqn X => + let E := P.run (l' + g) n (eqn.trans (Nat.add_assoc l l' g)) X + E.degreeCovered_bind _ _ _ _ _ (h _ _ _ X) (fun z => h' _ _ _ (E.finalState z)) + +theorem mono {P : Procedure R a b l d μ} {W : P.MapWitnesses κ} + {B : P.RecordBounds C m} {D n : ℕ} (h : DegreeCovered W B) (hC : C ≤ D) (hm : m ≤ n) : + DegreeCovered W (B.mono hC hm) := h + +theorem reindex {a' b' l' d' : ℕ} {μ' : ℝ} {P : Procedure R a b l d μ} {W : P.MapWitnesses κ} + {B : P.RecordBounds C m} (h : DegreeCovered W B) + {ha : a = a'} {hb : b = b'} {hl : l = l'} {hd : d = d'} {hμ : μ = μ'} : + DegreeCovered (W.reindex (ha := ha) (hb := hb) (hl := hl) (hp := hd) (hμ := hμ)) B.reindex := by + subst a' b' l' d' μ' + exact h + +end DegreeCovered + +theorem repeat_degreeCovered {P : Procedure R a a l d μ} {W : P.MapWitnesses κ} + {B : P.RecordBounds C m} (hc : DegreeCovered W B) (g T n : ℕ) (h : n = T * l + g) + (X : State a n) : + (P.repeatExecution g T n h X).DegreeCovered + (repeatWitnesses W g T n h X) (repeatRecords B g T n h X) := by + induction T generalizing n with + | zero => + have hn : n = g := by simpa using h + subst g + trivial + | succ t ih => + let E := P.run (t * l + g) n (by rw [h, Nat.succ_mul]; omega) X + exact E.degreeCovered_bind _ _ _ _ _ (hc _ _ _ X) (fun z => ih _ rfl (E.finalState z)) + +end Procedure + +namespace BlockSchedule + +open private prefixWitnesses from OAI.Computability.VPVNP.CompressionMonomialHistory +open private prefixRecordBounds from OAI.Computability.VPVNP.CompressionBlockHistory + +variable {k : Type*} [Field k] (S : BlockSchedule k) {C : ℕ} + +private theorem prefix_degreeCovered (shrink : S.ShrinkProcedures R) + (W : ∀ i : Fin S.steps, (shrink i).MapWitnesses κ) + (B : ∀ i, (shrink i).RecordBounds C 1) (h : ∀ i, Procedure.DegreeCovered (W i) (B i)) + (j : ℕ) (hj : j ≤ S.steps) : + Procedure.DegreeCovered (prefixWitnesses S shrink W j hj) + (prefixRecordBounds S shrink B j hj) := by + induction j with + | zero => + simp only [prefixRecordBounds, prefixWitnesses, shrinkPrefix] + exact (Procedure.DegreeCovered.id _ C κ).reindex + | succ j ih => + simp only [prefixRecordBounds, prefixWitnesses, shrinkPrefix] + exact (((ih (Nat.le_of_succ_le hj)).seq (h ⟨j, hj⟩).reindex).mono + (max_le le_rfl le_rfl) le_rfl).reindex + +/-- Every shrinking step and the final refresh retain their own degree records +when the block is run on an arbitrary state. -/ +theorem assemble_degreeCovered (shrink : S.ShrinkProcedures R) (refresh : S.RefreshProcedure R) + {D : Fin S.steps → ℕ} (W : ∀ i, (shrink i).MapWitnesses κ) (V : refresh.MapWitnesses κ) + (B : ∀ i, (shrink i).RecordBounds (D i) 1) (B' : refresh.RecordBounds C 1) + (h : ∀ i, Procedure.DegreeCovered (W i) (B i)) (h' : Procedure.DegreeCovered V B') : + Procedure.DegreeCovered (S.assembleBlockWitnesses shrink refresh W V) + (S.assembleBlockRecords shrink refresh B B') := by + unfold assembleBlockWitnesses assembleBlockRecords + apply Procedure.DegreeCovered.reindex + apply Procedure.DegreeCovered.seq _ h' + apply Procedure.DegreeCovered.reindex + exact prefix_degreeCovered S shrink W _ (fun i => h i) S.steps le_rfl + +end BlockSchedule +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionHistory.lean b/lean/OAI/Computability/VPVNP/CompressionHistory.lean new file mode 100644 index 0000000000..6cd8a9c84d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionHistory.lean @@ -0,0 +1,276 @@ +import OAI.Computability.VPVNP.CompressionState +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Data.Finset.Lattice.Fold + +/-! +# Local histories of placed wire kernels + +A term of (7.1) sends each complete old vertex to one new vertex. At a fixed +new vertex the recursive expansion visits precisely this placement fiber and +its local maps and fields. For a selected sequence of terms, Theorem 7.1 bounds +both the occurrence count and the largest field or individual map-entry degree +by exponentiating a constant per compressor block. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace NetworkKernel + +open scoped Classical + +/-- The field and map occurrences of a kernel at one site, with their bit lengths +and monomial degree bounds. Occurrences can have equal lengths or identical values. -/ +structure SiteRecords where + /-- Finite index type of individual bit-field occurrences recorded for a kernel at one output + site. -/ + Field : Type + fieldFintype : Fintype Field + /-- Length in bits of each recorded field occurrence at the site. -/ + width : Field → ℕ + /-- Finite index type of local map occurrences recorded for a kernel at one output site. -/ + Map : Type + mapFintype : Fintype Map + /-- Monomial degree bound attached to each recorded local map occurrence, controlling its + individual entries. -/ + degree : Map → ℕ + +attribute [instance] SiteRecords.fieldFintype SiteRecords.mapFintype + +/-- Count the vertex itself and all its immediate map and field occurrences. -/ +def SiteRecords.count (r : SiteRecords) : ℕ := 1 + Fintype.card r.Map + Fintype.card r.Field + +/-- The largest field length or degree of an individual map entry at this site. -/ +noncomputable def SiteRecords.largest (r : SiteRecords) : ℕ := + max (Finset.univ.sup r.width) (Finset.univ.sup r.degree) + +theorem SiteRecords.width_le_largest (r : SiteRecords) (f : r.Field) : r.width f ≤ r.largest := + (Finset.le_sup (f := r.width) (Finset.mem_univ f)).trans (le_max_left _ _) + +theorem SiteRecords.degree_le_largest (r : SiteRecords) (j : r.Map) : r.degree j ≤ r.largest := + (Finset.le_sup (f := r.degree) (Finset.mem_univ j)).trans (le_max_right _ _) + +variable {k : Type*} {N Y : Network} + +/-- The same finite placement fiber occurs in `Term.pushWitness`. -/ +abbrev Term.Preimage (t : Term k N) (v : t.output.Site) := {u : N.Site // v = t.place u} + +/-- A new vertex visits all local records and each old history in its own fiber once. -/ +noncomputable def Term.pushHistorySize (t : Term k N) (rec : t.output.Site → SiteRecords) + (previous : N.Site → ℕ) (v : t.output.Site) : ℕ := + (rec v).count + ∑ u : t.Preimage v, previous u.val + +theorem Term.pushHistorySize_le (t : Term k N) (rec : t.output.Site → SiteRecords) + (previous : N.Site → ℕ) {M : ℕ} (hM : 1 ≤ M) (hp : ∀ u, previous u ≤ M) + (v : t.output.Site) : t.pushHistorySize rec previous v ≤ + ((rec v).count + Fintype.card (t.Preimage v)) * M := by + rw [Nat.add_mul] + apply Nat.add_le_add (Nat.le_mul_of_pos_right _ hM) + calc + _ ≤ ∑ _ : t.Preimage v, M := Finset.sum_le_sum fun u _ => hp u.val + _ = _ := by simp + +/-- One selected branch with its actual terms, placements and records. -/ +inductive TermChain (k : Type*) : Network → Network → Type _ + | done (N : Network) : TermChain k N N + | more {N Y : Network} (t : Term k N) (rec : t.output.Site → SiteRecords) + (tail : TermChain k t.output Y) : TermChain k N Y + +namespace TermChain + +/-- Number of selected kernel terms along the branch from the initial network to the final +network. -/ +def length {N Y : Network} : TermChain k N Y → ℕ + | .done _ => 0 + | .more _ _ tail => tail.length + 1 + +/-- Count occurrences of the initial vertices and subsequent local records at each final site. -/ +noncomputable def occurrences {N Y : Network} (chain : TermChain k N Y) (initial : N.Site → ℕ) : Y.Site → ℕ := + match chain with + | .done _ => initial + | .more t rec tail => tail.occurrences (t.pushHistorySize rec initial) + +/-- The next length bound includes every field and degree at every output site. -/ +noncomputable def largest {V : Type} [Fintype V] (rec : V → SiteRecords) : ℕ := + Finset.univ.sup fun v => (rec v).largest + +/-- Maximum over the initial stage and all intermediate stages on this branch. -/ +noncomputable def peak {N Y : Network} : TermChain k N Y → ℕ → ℕ + | .done _, W => W + | .more _ rec tail, W => max W (tail.peak (largest rec)) + +theorem le_peak (chain : TermChain k N Y) (W : ℕ) : W ≤ chain.peak W := by + cases chain with + | done => exact le_rfl + | more => exact le_max_left _ _ + +/-- Every bit field and every individual map entry on every intermediate level. -/ +def AllRecordsLe {N Y : Network} : TermChain k N Y → ℕ → Prop + | .done _, _ => True + | .more _ rec tail, B => + (∀ v f, (rec v).width f ≤ B) ∧ (∀ v j, (rec v).degree j ≤ B) ∧ tail.AllRecordsLe B + +theorem allRecordsLe_of_peak (chain : TermChain k N Y) {W B : ℕ} (h : chain.peak W ≤ B) : + chain.AllRecordsLe B := by + induction chain generalizing W with + | done => trivial + | more t rec tail ih => + have ht : tail.peak (largest rec) ≤ B := (le_max_right _ _).trans h + have hl (v : t.output.Site) : (rec v).largest ≤ B := + (Finset.le_sup (f := fun u => (rec u).largest) (Finset.mem_univ v)).trans + ((tail.le_peak _).trans ht) + exact ⟨fun v f => ((rec v).width_le_largest f).trans (hl v), + fun v j => ((rec v).degree_le_largest j).trans (hl v), ih ht⟩ + +/-- Local bounds used at every substep. `W` is a bound on its incoming fields. +The next substep uses the actual largest field or degree from this one. -/ +def Bounded (C : ℕ) {N Y : Network} : TermChain k N Y → ℕ → Prop + | .done _, _ => True + | .more t rec tail, W => + (∀ v, (rec v).count + Fintype.card (t.Preimage v) ≤ C) ∧ + largest rec + 1 ≤ C * (W + 1) ∧ tail.Bounded C (largest rec) + +/-- Iteration bounds both the number of operations at each final site and the +largest field or single-entry degree reached anywhere on the selected branch. -/ +theorem growth {C W M : ℕ} (chain : TermChain k N Y) (hC : 1 ≤ C) + (hb : chain.Bounded C W) (initial : N.Site → ℕ) (hM : 1 ≤ M) (hi : ∀ u, initial u ≤ M) : + (∀ v, chain.occurrences initial v ≤ C ^ chain.length * M) ∧ + chain.peak W + 1 ≤ C ^ chain.length * (W + 1) := by + induction chain generalizing W M with + | done => simp [occurrences, length, peak, hi] + | more t rec tail ih => + obtain ⟨hc, hw, ht⟩ := hb + have hcM : 1 ≤ C * M := Nat.mul_le_mul hC hM + have hp (v : t.output.Site) : t.pushHistorySize rec initial v ≤ C * M := + (t.pushHistorySize_le rec initial hM hi v).trans (Nat.mul_le_mul_right _ (hc v)) + obtain ⟨hcount, hpeak⟩ := ih ht _ hcM hp + constructor + · intro v + simpa only [occurrences, length, pow_succ, Nat.mul_assoc] using hcount v + · simp only [peak, length, ← max_add_add_right, max_le_iff, pow_succ, Nat.mul_assoc] + constructor + · exact Nat.le_mul_of_pos_left _ (Nat.mul_pos (Nat.pow_pos hC) hC) |>.trans_eq (Nat.mul_assoc ..) + · exact hpeak.trans (Nat.mul_le_mul_left _ hw) + +/-- A block with at most `s` elementary substeps costs a fixed factor `C^s`. +The constant in Theorem 7.1 is uniform in the number of blocks and the branch. -/ +theorem blockGrowth {C W s T : ℕ} (chain : TermChain k N Y) (hC : 1 ≤ C) + (hb : chain.Bounded C W) (hlen : chain.length ≤ s * T) : + (∀ v, chain.occurrences (fun _ => 1) v ≤ (C ^ s) ^ T) ∧ + chain.peak W + 1 ≤ (C ^ s) ^ T * (W + 1) := by + obtain ⟨hc, hw⟩ := chain.growth hC hb (fun _ => 1) (M := 1) le_rfl (fun _ => le_rfl) + have hpow : C ^ chain.length ≤ (C ^ s) ^ T := by + rw [← pow_mul]; exact Nat.pow_le_pow_right hC hlen + exact ⟨fun v => (by simpa using hc v : _ ≤ C ^ chain.length).trans hpow, + hw.trans (Nat.mul_le_mul_right _ hpow)⟩ + +end TermChain +end NetworkKernel + +namespace Compression + +open NetworkKernel +open scoped Classical + +variable {a b g n : ℕ} + +/-- The largest actual wire width of a lifted state. -/ +noncomputable def State.maxWireWidth (X : State a g) : ℕ := Finset.univ.sup X.width + +theorem State.width_le_maxWireWidth (X : State a g) (e) : X.width e ≤ X.maxWireWidth := + Finset.le_sup (f := X.width) (Finset.mem_univ e) + +variable {R : Type*} [CommSemiring R] {X : State a g} + +/-- A substep supplies its local records on every branch, even when its topology +and placement depend on the selected terms. -/ +abbrev StatePass.Records (p : StatePass R X b n) := + (i : p.step.Choice) → (p.step.term i).output.Site → SiteRecords + +/-- The substep count and width estimates needed by the history recursion. -/ +def StatePass.Bounded (p : StatePass R X b n) (rec : p.Records) (C : ℕ) : Prop := + ∀ i, (∀ v, (rec i v).count + Fintype.card ((p.step.term i).Preimage v) ≤ C) ∧ + TermChain.largest (rec i) + 1 ≤ C * (X.maxWireWidth + 1) ∧ + (p.next i).maxWireWidth ≤ TermChain.largest (rec i) + +namespace StateExecution + +/-- Local site records for every pass and each branch-dependent continuation of the execution, +with the unit record at a terminal state. -/ +def Records {a g : ℕ} {X : State a g} : StateExecution R b n X → Type 1 + | .done _ => PUnit + | .more p tail => p.Records × ((i : p.step.Choice) → (tail i).Records) + +/-- The recursive data contains exactly the terms selected by this execution path. -/ +noncomputable def termChain {a g : ℕ} {X : State a g} (E : StateExecution R b n X) : + E.Records → (z : E.Choices) → TermChain R X.network (E.finalState z).network := + match E with + | .done _ => fun _ _ => .done _ + | .more p tail => fun rec z => .more (p.step.term z.1) (rec.1 z.1) + ((p.output_eq z.1).symm ▸ (tail z.1).termChain (rec.2 z.1) z.2) + +/-- Every pass on every branch satisfies its local bounds with constant `C`, controlling record +and preimage counts, field widths and map-entry degrees. -/ +def Bounded (C : ℕ) {a g : ℕ} {X : State a g} (E : StateExecution R b n X) : E.Records → Prop := + match E with + | .done _ => fun _ => True + | .more p tail => fun rec => p.Bounded rec.1 C ∧ ∀ i, (tail i).Bounded C (rec.2 i) + +omit [CommSemiring R] in +private theorem chain_input_mono {N Y : Network} (chain : TermChain R N Y) {C W W' : ℕ} + (h : chain.Bounded C W) (hle : W ≤ W') : chain.Bounded C W' := by + cases chain with + | done => trivial + | more t rec tail => + exact ⟨h.1, h.2.1.trans (Nat.mul_le_mul_left _ (Nat.succ_le_succ hle)), h.2.2⟩ + +omit [CommSemiring R] in +private theorem cast_bounded {N Y Z : Network} (h : N = Y) (chain : TermChain R Y Z) {C W : ℕ} + (hb : chain.Bounded C W) : (h.symm ▸ chain : TermChain R N Z).Bounded C W := by + cases h + exact hb + +theorem termChain_bounded (E : StateExecution R b n X) (rec : E.Records) {C : ℕ} + (hb : E.Bounded C rec) (z : E.Choices) : (E.termChain rec z).Bounded C X.maxWireWidth := by + induction E with + | done => trivial + | more p tail ih => + obtain ⟨hpass, htail⟩ := hb + obtain ⟨hc, hw, hnext⟩ := hpass z.1 + exact ⟨hc, hw, cast_bounded (p.output_eq z.1) _ + (chain_input_mono _ (ih z.1 (rec.2 z.1) (htail z.1) z.2) hnext)⟩ + +omit [CommSemiring R] in +private theorem cast_peak {N Y Z : Network} (h : N = Y) (chain : TermChain R Y Z) (W : ℕ) : + (h.symm ▸ chain : TermChain R N Z).peak W = chain.peak W := by cases h; rfl + +/-- The maximum actual final arc width is among the quantities controlled by +this branch's peak, even when the terminal layout depends on all earlier choices. -/ +theorem final_maxWireWidth_le_peak (E : StateExecution R b n X) (rec : E.Records) {C W : ℕ} + (hb : E.Bounded C rec) (hw : X.maxWireWidth ≤ W) (z : E.Choices) : + (E.finalState z).maxWireWidth ≤ (E.termChain rec z).peak W := by + induction E generalizing W with + | done => exact hw + | more p tail ih => + have hh := ih z.1 (rec.2 z.1) (hb.2 z.1) (hb.1 z.1).2.2 z.2 + change _ ≤ max W (((p.output_eq z.1).symm ▸ (tail z.1).termChain (rec.2 z.1) z.2 : + TermChain R (p.step.term z.1).output _).peak (TermChain.largest (rec.1 z.1))) + rw [cast_peak (p.output_eq z.1)] + exact hh.trans (le_max_right _ _) + +/-- Theorem 7.1's local growth conclusion for a chosen branch of an execution +of `T` blocks, each containing at most `s` substeps with bounded local records. -/ +theorem localHistory_bounds (E : StateExecution R b n X) (rec : E.Records) {C s T : ℕ} + (hC : 1 ≤ C) (hb : E.Bounded C rec) (z : E.Choices) + (hlen : (E.termChain rec z).length ≤ s * T) : + (∀ v, (E.termChain rec z).occurrences (fun _ => 1) v ≤ (C ^ s) ^ T) ∧ + (E.termChain rec z).peak X.maxWireWidth + 1 ≤ (C ^ s) ^ T * (X.maxWireWidth + 1) := + (E.termChain rec z).blockGrowth hC (E.termChain_bounded rec hb z) hlen + +end StateExecution +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionLocalDegree.lean b/lean/OAI/Computability/VPVNP/CompressionLocalDegree.lean new file mode 100644 index 0000000000..9d4d1405ce --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionLocalDegree.lean @@ -0,0 +1,140 @@ +import OAI.Computability.VPVNP.CompressionDegreeCoverage +import OAI.Computability.VPVNP.RefreshProcedureRecords +import OAI.Computability.VPVNP.RefreshProcedureWitness +import OAI.Computability.VPVNP.ShrinkProcedureHistory +import OAI.Computability.VPVNP.ShrinkProcedureWitness + +/-! +# Parameter degrees of the local compressor maps + +Every accepted shrinking map reads one label per base repetition, and every +resident occurrence of that map contributes its own record. The refresh +reads the labels of a single motif entry after its two diagonal checks. +This identifies the total parameter multiplicity with the sum of the +degrees stored in the actual records of each selected substep. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.State + +open NetworkKernel MotifBlocks MotifGrid MotifConversion PackingData ShrinkMotif + +variable {a b g : ℕ} {δ factor : ℝ} (X : State a (packingLaneBits a g)) +variable {k : Type*} [Field k] +variable (B : FixedBlock k demandSource demandTarget supply + (realWidths demandMass) (realWidths supplyMass) (31 / 16) factor) +variable {R : Type*} [CommRing R] (κ : (parameterData B).Entry → R) +variable (hκ : (parameterData B).IsSolution κ) +variable (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) + +set_option maxHeartbeats 1200000 in +-- Matching the reindexed kernel unfolds the dyadic state pass. +/-- The recorded resident maps account for all labels of a shrinking-site witness. -/ +theorem shrinkStateKernelWitness_degree_eq (s : X.ShrinkSelection B) (v x z) + (w : (X.shrinkStateKernelWitness B κ hκ ready s v x z).Choice) : + (∑ label, (X.shrinkStateKernelWitness B κ hκ ready s v x z).exponents w label) = + ∑ j, ((X.shrinkStatePass B κ hκ ready).slotRecords + (X.shrinkExtraRecords B κ hκ ready) s v).degree j := by + classical + exact X.packingData.shrinkKernelWitness_totalExponent (two_le_packingColors a) + (Nat.two_pow_pos a) X.shrinkNumber X.shrinkOrder X.packingWidth B κ hκ ready + (X.shrinkStateIndex ready) s v _ _ w + +end Compression.State + +namespace Compression.Refresh + +open NetworkKernel SpectralGeometry DegreeRefresh MotifConversion + +variable {a g a₀ dH : ℕ} {k : Type*} [Field k] {K K' : ℝ} +variable (X : State a (a + g)) (P : RegularArcGraph (Fin (2 ^ a)) dH) (hdH : 0 < dH) + (hconn : (arcSupportGraph P.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply P hdH hconn) (2 ^ a₀) K K') + (hD : 1 < 2 ^ a) (hd : dH + 1 ≤ 2 ^ a₀) +variable {R : Type*} [CommRing R] (κ : (parameterData F).Entry → R) + (hκ : (parameterData F).IsSolution κ) + +set_option maxHeartbeats 1200000 in +-- The recorded degree and accepted entry are in different port coordinates. +/-- The motif entry supplies the full recorded degree of an accepted refresh port. -/ +theorem dyadicRefreshKernelWitness_degree_eq (c : DyadicRefreshChoice X P hdH hconn F) (v x z) + (w : (dyadicRefreshKernelWitness X P hdH hconn F hD hd κ hκ c v x z).Choice) : + (∑ label, (dyadicRefreshKernelWitness X P hdH hconn F hD hd κ hκ c v x z).exponents w label) = + ∑ j, ((dyadicRefreshPass X P hdH hconn F hD hd κ hκ).slotRecords + (refreshLocalRecords X P hdH hconn F hD hd κ hκ) c v).degree j := by + let p := promotedSites.symm v + have h := entryWitness_totalExponent κ (refreshEntryIndices (splitSlots X) + (bitWordFinEquiv a) (splitWidths X) P hdH hconn F hD hd c p _ _) w + refine h.trans ?_ + change _ = ∑ j : Fin 3, if j = 0 then repetitions F _ else 0 + simp [p, promotedSites] + +end Compression.Refresh + +namespace NetworkKernel.MonomialWitness + +variable {L M : Type} [Fintype L] [Fintype M] {R : Type*} [CommRing R] {a : R} + +/-- Using the shrinking summand preserves the total degree. -/ +theorem left_totalExponent (f : L ⊕ M → R) (W : MonomialWitness (f ∘ Sum.inl) a) (w : W.Choice) : + (∑ l, (W.left f).exponents w l) = ∑ l, W.exponents w l := by + simp [left, Fintype.sum_sum_type] + +/-- Using the refresh summand preserves the total degree. -/ +theorem right_totalExponent (f : L ⊕ M → R) (W : MonomialWitness (f ∘ Sum.inr) a) (w : W.Choice) : + (∑ l, (W.right f).exponents w l) = ∑ l, W.exponents w l := by + simp [right, Fintype.sum_sum_type] + +end NetworkKernel.MonomialWitness + +namespace Compression.BlockSchedule.Templates + +open NetworkKernel Refresh +open private recordsAt from OAI.Computability.VPVNP.ShrinkProcedureHistory + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) + +set_option maxHeartbeats 1200000 in +-- The lane equality transports both records and witnesses. +/-- At the scheduled lane count the tagged shrinking witnesses fit their actual records. -/ +theorem shrinkPass_degreeCovered (i : Fin S.steps) {g n : ℕ} + (h : n = packingLaneBits (S.degreeExponent i.castSucc) g) + (X : State (S.degreeExponent i.castSucc) n) : + (B.shrinkPassAt f hf i h X).DegreeCovered (B.shrinkPassWitnesses f hf i h X) + (recordsAt B f hf i h X) := by + subst n + intro s v x z w + let hκ := ((B.solution_iff f).mp hf).1 + let W := X.shrinkStateKernelWitness B.shrink (f ∘ Sum.inl) hκ (S.shrink i) + exact (MonomialWitness.left_totalExponent f (W s v x z) w).le.trans + (X.shrinkStateKernelWitness_degree_eq B.shrink (f ∘ Sum.inl) hκ (S.shrink i) s v x z w).le + +set_option maxHeartbeats 1200000 in +-- The type of the local witness depends on its concrete refresh branch. +/-- Each tagged refresh witness fits the records of its chosen port and branch. -/ +theorem refreshPass_degreeCovered (g : ℕ) (X : State S.portExponent (S.portExponent + g)) : + let conn := (S.port_bound.connected_and_pos S.port_order).1 + let hκ := ((B.solution_iff f).mp hf).2 + let p := dyadicRefreshPass X S.graph (Nat.two_pow_pos _) conn B.refresh S.port_order + S.degree_bounds.2 (f ∘ Sum.inr) hκ + p.DegreeCovered (fun c v x z ↦ MonomialWitness.right f + (dyadicRefreshKernelWitness X S.graph (Nat.two_pow_pos _) conn B.refresh + S.port_order S.degree_bounds.2 (f ∘ Sum.inr) hκ c v x z)) + (p.slotRecords (refreshLocalRecords X S.graph (Nat.two_pow_pos _) conn B.refresh + S.port_order S.degree_bounds.2 (f ∘ Sum.inr) hκ)) := by + intro conn hκ p c v x z w + let W := dyadicRefreshKernelWitness X S.graph (Nat.two_pow_pos _) conn B.refresh + S.port_order S.degree_bounds.2 (f ∘ Sum.inr) hκ + exact (MonomialWitness.right_totalExponent f (W c v x z) w).le.trans + (dyadicRefreshKernelWitness_degree_eq X S.graph (Nat.two_pow_pos _) conn B.refresh + S.port_order S.degree_bounds.2 (f ∘ Sum.inr) hκ c v x z w).le + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionMonomialHistory.lean b/lean/OAI/Computability/VPVNP/CompressionMonomialHistory.lean new file mode 100644 index 0000000000..3b5e249b3d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionMonomialHistory.lean @@ -0,0 +1,172 @@ +import OAI.Computability.VPVNP.NetworkMonomials +import OAI.Computability.VPVNP.CompressionBlock +import OAI.Computability.VPVNP.CompressionPowers + +/-! +# Parameter labels through a compressor execution + +All substeps of Section 7.4 use the same two sets of template labels. A +shrinking entry uses the first alphabet and a refresh entry the second. +The actual branch-dependent composition of passes preserves the witnesses +of every kernel, including through all repetitions of the fixed block. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace NetworkKernel.MonomialWitness + +open Diagonal + +variable {L M : Type} [Fintype L] [Fintype M] {A : Type*} [CommRing A] {x : A} + +/-- Include the labels of a shrinking map in the common template alphabet. -/ +def left (κ : L ⊕ M → A) (W : MonomialWitness (κ ∘ Sum.inl) x) : MonomialWitness κ x where + Choice := W.Choice + choiceFintype := W.choiceFintype + exponents p := Sum.elim (W.exponents p) (fun _ ↦ 0) + evaluates := by simpa [labelMonomial, Fintype.prod_sum_type, Function.comp_def] using W.evaluates + +/-- Include the labels of a refresh map in the common template alphabet. -/ +def right (κ : L ⊕ M → A) (W : MonomialWitness (κ ∘ Sum.inr) x) : MonomialWitness κ x where + Choice := W.Choice + choiceFintype := W.choiceFintype + exponents p := Sum.elim (fun _ ↦ 0) (W.exponents p) + evaluates := by simpa [labelMonomial, Fintype.prod_sum_type, Function.comp_def] using W.evaluates + +end NetworkKernel.MonomialWitness + +namespace Compression + +open NetworkKernel + +variable {R : Type*} [CommRing R] {Label : Type} [Fintype Label] {κ : Label → R} +variable {a b n g : ℕ} {X : State a g} + +/-- Local entry witnesses for every kernel of a pass. -/ +abbrev StatePass.MapWitnesses (p : StatePass R X b n) (κ : Label → R) := + ∀ i v old new, MonomialWitness κ ((p.step.term i).kernel v old new) + +namespace StateExecution + +/-- Witnesses along exactly the nodes reached by the chosen terms. -/ +def MapWitnesses {a g : ℕ} {X : State a g} (κ : Label → R) : StateExecution R b n X → Type 1 + | .done _ => PUnit + | .more p tail => p.MapWitnesses κ × ((i : p.step.Choice) → (tail i).MapWitnesses κ) + +private def transportWitnesses {N M : Network} (e : N = M) (h : History R N) + (W : h.KernelWitnesses κ) : (e ▸ h : History R M).KernelWitnesses κ := by + subst M + exact W + +/-- Use the pass witnesses in the actual kernel history, respecting the +pass's equality of its selected output with the next state. -/ +noncomputable def historyWitnesses (E : StateExecution R b n X) (W : E.MapWitnesses κ) : + E.history.KernelWitnesses κ := by + induction E with + | done => exact PUnit.unit + | more p tail ih => exact ⟨W.1, fun i ↦ transportWitnesses (p.output_eq i).symm _ (ih i (W.2 i))⟩ + +/-- Branch-dependent continuation uses the witnesses of both component +executions, without adding choices at their join. -/ +def bindWitnesses {b' n' : ℕ} {a g : ℕ} {X : State a g} (E : StateExecution R b n X) : + (f : (z : E.Choices) → StateExecution R b' n' (E.finalState z)) → E.MapWitnesses κ → + ((z : E.Choices) → (f z).MapWitnesses κ) → (E.bind f).MapWitnesses κ := + match E with + | .done _ => fun _ _ after ↦ after () + | .more _ tail => fun f W after ↦ ⟨W.1, fun i ↦ (tail i).bindWitnesses + (fun z ↦ f ⟨i,z⟩) (W.2 i) (fun z ↦ after ⟨i,z⟩)⟩ + +end StateExecution + +namespace Procedure + +variable {l p : ℕ} {μ : ℝ} + +/-- A choice of local map witnesses for every input to a fixed procedure. -/ +abbrev MapWitnesses (P : Procedure R a b l p μ) (κ : Label → R) := + ∀ g n h X, (P.run g n h X).MapWitnesses κ + +namespace MapWitnesses + +/-- The empty collection of local map-entry witnesses for the identity procedure, whose +execution ends at its input state. -/ +def id (a : ℕ) (κ : Label → R) : (Procedure.id R a).MapWitnesses κ := by + intro g n h X + have hg : n = g := h.trans (Nat.zero_add g) + subst g + exact PUnit.unit + +/-- Lift witnesses for every local map entry of a pass to the one-step procedure built from +that pass. -/ +def ofPass {C : ℝ} (hp : 0 < p) (hμ : 0 ≤ μ) (hC : 0 ≤ C) + (f : ∀ g (X : State a (l + g)), StatePass R X b g) + (hcount : ∀ g X (i : (f g X).step.Choice), X.positions = p * ((f g X).next i).positions) + (henergy : ∀ g X (i : (f g X).step.Choice), + ((f g X).next i).energy ≤ μ * X.energy + C * (X.positions : ℝ) ^ 2) + (W : ∀ g X, (f g X).MapWitnesses κ) : + (Procedure.ofPass hp hμ hC f hcount henergy).MapWitnesses κ := by + intro g n h X + subst n + exact ⟨W g X, fun _ ↦ PUnit.unit⟩ + +/-- Combine the first procedure's map-entry witnesses with those of the second procedure at the +final state of each first-stage branch. -/ +def seq {c l' p' : ℕ} {ν : ℝ} {P : Procedure R a b l p μ} {Q : Procedure R b c l' p' ν} + (W : P.MapWitnesses κ) (W' : Q.MapWitnesses κ) : (P.seq Q).MapWitnesses κ := + fun g n h X ↦ + let E := P.run (l' + g) n (h.trans (Nat.add_assoc l l' g)) X + E.bindWitnesses (fun z ↦ Q.run g (l' + g) rfl (E.finalState z)) + (W _ _ _ X) (fun z ↦ W' _ _ _ (E.finalState z)) + +/-- Transport local map-entry witnesses along equalities of the procedure's degree, lane, +packing and energy parameters. -/ +def reindex {a' b' l' p' : ℕ} {μ' : ℝ} {P : Procedure R a b l p μ} (W : P.MapWitnesses κ) + {ha : a = a'} {hb : b = b'} {hl : l = l'} {hp : p = p'} {hμ : μ = μ'} : + (P.reindex ha hb hl hp hμ).MapWitnesses κ := by + subst a' b' l' p' μ' + exact W + +end MapWitnesses + +/-- Repeating the block uses the original two label sets at every iteration. -/ +def repeatWitnesses {P : Procedure R a a l p μ} (W : P.MapWitnesses κ) (g : ℕ) : + (T n : ℕ) → (h : n = T * l + g) → (X : State a n) → (P.repeatExecution g T n h X).MapWitnesses κ + | 0, n, h, X => MapWitnesses.id a κ g n (by simpa using h) X + | t + 1, n, h, X => + let E := P.run (t * l + g) n (by rw [h, Nat.succ_mul]; omega) X + E.bindWitnesses (fun z ↦ P.repeatExecution g t (t * l + g) rfl (E.finalState z)) + (W _ _ _ X) (fun z ↦ repeatWitnesses W g t _ rfl (E.finalState z)) + +end Procedure + +namespace BlockSchedule + +variable {k : Type*} [Field k] (S : BlockSchedule k) + +private noncomputable def prefixWitnesses (shrink : S.ShrinkProcedures R) + (W : ∀ i : Fin S.steps, (shrink i).MapWitnesses κ) (j : ℕ) (hj : j ≤ S.steps) : + (S.shrinkPrefix shrink j hj).MapWitnesses κ := + match j with + | 0 => by + rw [shrinkPrefix] + exact (Procedure.MapWitnesses.id _ κ).reindex + | j + 1 => by + rw [shrinkPrefix] + exact ((prefixWitnesses shrink W j (by omega)).seq (W ⟨j, hj⟩).reindex).reindex + +/-- Preserve the concrete per-pass witnesses in the complete scheduled block. -/ +noncomputable def assembleBlockWitnesses (shrink : S.ShrinkProcedures R) + (refresh : S.RefreshProcedure R) + (W : ∀ i : Fin S.steps, (shrink i).MapWitnesses κ) (W' : refresh.MapWitnesses κ) : + (S.assembleBlock shrink refresh).MapWitnesses κ := by + unfold assembleBlock + exact ((S.prefixWitnesses shrink W S.steps le_rfl).reindex.seq W').reindex + +end BlockSchedule +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionParameters.lean b/lean/OAI/Computability/VPVNP/CompressionParameters.lean new file mode 100644 index 0000000000..89ff8448bc --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionParameters.lean @@ -0,0 +1,196 @@ +import Mathlib.Algebra.Order.Floor.Div +import Mathlib.Analysis.SpecialFunctions.Log.Base +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum + +/-! +# Rounded compression and bucket exponents + +Section 9.1 of *VP and VNP differ over every field* chooses the number of +compressor blocks and the sizes of the live and virtual transcript buckets +by rounding multiples of the binary logarithm of the input length. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +/-- Number of compressor blocks used in §12. -/ +noncomputable def blockCount (θ : ℝ) (n : ℕ) : ℕ := ⌊θ * Real.logb 2 n⌋₊ + +/-- Binary exponent of a transcript bucket. -/ +noncomputable def bucketExponent (x : ℝ) (n : ℕ) : ℕ := ⌈x * Real.logb 2 n⌉₊ + +/-- The live group uses buckets of size `K`. -/ +noncomputable def liveBucket (δ : ℝ) (n : ℕ) : ℕ := 2 ^ bucketExponent (1 - δ) n + +/-- The virtual network uses buckets of size `K′`. -/ +noncomputable def virtualBucket (n : ℕ) : ℕ := 2 ^ bucketExponent (1 / 4) n + +/-- Comparing a rounded-down rational exponent requires only an integer power comparison. -/ +theorem le_blockCount_ratio_iff {a b n k : ℕ} (hb : 0 < b) (hn : 1 ≤ n) : + k ≤ blockCount ((a : ℝ) / b) n ↔ 2 ^ (k * b) ≤ n ^ a := by + have hb' : 0 < (b : ℝ) := by exact_mod_cast hb + have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast hn + have hpos : 0 < (n : ℝ) ^ a := pow_pos (zero_lt_one.trans_le hn') _ + have hlog := Real.logb_nonneg (by norm_num : 1 < (2 : ℝ)) hn' + rw [blockCount, Nat.le_floor_iff (mul_nonneg (by positivity) hlog), div_mul_eq_mul_div, + le_div_iff₀ hb', ← Real.logb_pow, ← Nat.cast_mul, + Real.le_logb_iff_rpow_le (by norm_num) hpos, Real.rpow_natCast] + norm_cast + +/-- Comparing a rounded-up rational exponent requires only an integer power comparison. -/ +theorem bucketExponent_ratio_le_iff {a b n k : ℕ} (hb : 0 < b) (hn : 1 ≤ n) : + bucketExponent ((a : ℝ) / b) n ≤ k ↔ n ^ a ≤ 2 ^ (k * b) := by + have hb' : 0 < (b : ℝ) := by exact_mod_cast hb + have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast hn + have hpos : 0 < (n : ℝ) ^ a := pow_pos (zero_lt_one.trans_le hn') _ + rw [bucketExponent, Nat.ceil_le, div_mul_eq_mul_div, div_le_iff₀ hb', + ← Real.logb_pow, ← Nat.cast_mul, Real.logb_le_iff_le_rpow (by norm_num) hpos, + Real.rpow_natCast] + norm_cast + +/-- An executable integer formula for the number of compressor blocks. -/ +theorem blockCount_ratio_eq {a b n : ℕ} (hb : 0 < b) (hn : 1 ≤ n) : + blockCount ((a : ℝ) / b) n = Nat.log 2 (n ^ a) / b := by + apply eq_of_forall_le_iff + intro k + rw [le_blockCount_ratio_iff hb hn, Nat.le_div_iff_mul_le hb, + Nat.le_log_iff_pow_le Nat.one_lt_two (pow_ne_zero _ (by omega))] + +/-- An executable integer formula for the binary exponent of a transcript bucket. -/ +theorem bucketExponent_ratio_eq {a b n : ℕ} (hb : 0 < b) (hn : 1 ≤ n) : + bucketExponent ((a : ℝ) / b) n = (Nat.clog 2 (n ^ a) + b - 1) / b := by + apply eq_of_forall_ge_iff + intro k + rw [bucketExponent_ratio_le_iff hb hn, ← Nat.ceilDiv_eq_add_pred_div, + ceilDiv_le_iff_le_mul hb, Nat.clog_le_iff_le_pow Nat.one_lt_two, Nat.mul_comm b k] + +private theorem two_rpow_mul_logb (x : ℝ) {y : ℝ} (hy : 0 < y) : + (2 : ℝ) ^ (x * Real.logb 2 y) = y ^ x := by + rw [mul_comm, Real.rpow_mul (by norm_num : 0 ≤ (2 : ℝ)), + Real.rpow_logb (by norm_num) (by norm_num) hy] + +/-- Rounding a nonnegative bucket exponent upwards costs at most a factor of two. -/ +theorem bucketExponent_bounds {x : ℝ} {n : ℕ} (hx : 0 ≤ x) (hn : 1 ≤ n) : + (n : ℝ) ^ x ≤ (2 : ℝ) ^ bucketExponent x n ∧ + (2 : ℝ) ^ bucketExponent x n ≤ 2 * (n : ℝ) ^ x := by + have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast hn + have hnpos : 0 < (n : ℝ) := zero_lt_one.trans_le hn' + have hnonneg := mul_nonneg hx (Real.logb_nonneg (by norm_num : 1 < (2 : ℝ)) hn') + rw [← two_rpow_mul_logb x hnpos, bucketExponent, ← Real.rpow_natCast] + constructor + · exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (Nat.le_ceil _) + · calc + _ ≤ (2 : ℝ) ^ (x * Real.logb 2 n + 1) := + Real.rpow_le_rpow_of_exponent_le (by norm_num) (Nat.ceil_lt_add_one hnonneg).le + _ = _ := by rw [Real.rpow_add_one (by norm_num), mul_comm] + +theorem liveBucket_bounds {δ : ℝ} {n : ℕ} (hδ : δ ≤ 1) (hn : 1 ≤ n) : + (n : ℝ) ^ (1 - δ) ≤ (liveBucket δ n : ℝ) ∧ + (liveBucket δ n : ℝ) ≤ 2 * (n : ℝ) ^ (1 - δ) := by + simpa [liveBucket] using bucketExponent_bounds (sub_nonneg.mpr hδ) hn + +theorem virtualBucket_bounds {n : ℕ} (hn : 1 ≤ n) : + (n : ℝ) ^ (1 / 4 : ℝ) ≤ (virtualBucket n : ℝ) ∧ + (virtualBucket n : ℝ) ≤ 2 * (n : ℝ) ^ (1 / 4 : ℝ) := by + simpa [virtualBucket] using bucketExponent_bounds (by norm_num : 0 ≤ (1 / 4 : ℝ)) hn + +/-- Rounding the number of blocks down costs at most a factor of two in +the compression estimate. -/ +theorem inv_two_pow_blockCount (θ : ℝ) {n : ℕ} (hn : 1 ≤ n) : + 1 / (2 : ℝ) ^ blockCount θ n ≤ 2 * (n : ℝ) ^ (-θ) := by + have hn' : 0 < (n : ℝ) := by exact_mod_cast hn + have hfloor := (Nat.lt_floor_add_one (θ * Real.logb 2 n)).le + have h := Real.rpow_le_rpow_of_exponent_le (by norm_num : 1 ≤ (2 : ℝ)) hfloor + rw [two_rpow_mul_logb θ hn', Real.rpow_add_one (by norm_num), Real.rpow_natCast] at h + rw [Real.rpow_neg hn'.le, ← div_eq_mul_inv, div_le_div_iff₀ (by positivity) + (Real.rpow_pos_of_pos hn' θ), one_mul, mul_comm] + exact h + +/-- The growth of histories through all blocks fits the power slack fixed in §9.1. -/ +theorem history_pow_blockCount_le {C₂ θ : ℝ} {n : ℕ} (hC : 1 ≤ C₂) (hθ : 0 ≤ θ) + (hn : 1 ≤ n) (hexp : θ * Real.logb 2 C₂ ≤ 1 / 100) : + C₂ ^ blockCount θ n ≤ (n : ℝ) ^ (1 / 100 : ℝ) := by + have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast hn + have hnpos := zero_lt_one.trans_le hn' + have hnonneg := mul_nonneg hθ (Real.logb_nonneg (by norm_num : 1 < (2 : ℝ)) hn') + rw [blockCount, ← Real.rpow_natCast] + calc + _ ≤ C₂ ^ (θ * Real.logb 2 n) := Real.rpow_le_rpow_of_exponent_le hC (Nat.floor_le hnonneg) + _ = (2 : ℝ) ^ (Real.logb 2 C₂ * (θ * Real.logb 2 n)) := by + rw [Real.rpow_mul (by norm_num : 0 ≤ (2 : ℝ)), + Real.rpow_logb (by norm_num) (by norm_num) (zero_lt_one.trans_le hC)] + _ = (n : ℝ) ^ (θ * Real.logb 2 C₂) := by + rw [mul_left_comm, ← mul_assoc, two_rpow_mul_logb _ hnpos] + _ ≤ _ := Real.rpow_le_rpow_of_exponent_le hn' hexp + +/-- The rational exponents of §9.1 can be chosen for every fixed per-block +growth constant from Theorem 7.1. -/ +theorem exists_compression_exponents (C₂ : ℝ) (hC : 1 ≤ C₂) : + ∃ θ δ : ℚ, 0 < θ ∧ θ < 1 / 100 ∧ 0 < δ ∧ δ < θ / 10 ∧ + (θ : ℝ) * Real.logb 2 C₂ ≤ 1 / 100 := by + have hlog := Real.logb_nonneg (b := 2) (by norm_num) hC + have hpos : 0 < 1 + Real.logb 2 C₂ := by linarith + have hb : 0 < min (1 / 100 : ℝ) ((1 / 100) / (1 + Real.logb 2 C₂)) := + lt_min (by norm_num) (div_pos (by norm_num) hpos) + obtain ⟨θ, hθ, hθb⟩ := exists_rat_btwn hb + obtain ⟨hsmall, hbudget⟩ := lt_min_iff.mp hθb + have hθq : 0 < θ := Rat.cast_pos.mp hθ + refine ⟨θ, θ / 20, hθq, ?_, div_pos hθq (by norm_num), ?_, ?_⟩ + · apply (Rat.cast_lt (K := ℝ)).mp + simpa using hsmall + · linarith + · have hprod := (lt_div_iff₀ hpos).mp hbudget + linarith + +/-- The same fixed pair of rationals gives the required history bound at +every positive input length. -/ +theorem exists_compression_budgets (C₂ : ℝ) (hC : 1 ≤ C₂) : + ∃ θ δ : ℚ, 0 < θ ∧ θ < 1 / 100 ∧ 0 < δ ∧ δ < θ / 10 ∧ + ∀ n : ℕ, 1 ≤ n → C₂ ^ blockCount (θ : ℝ) n ≤ (n : ℝ) ^ (1 / 100 : ℝ) := by + obtain ⟨θ, δ, hθ, hθ', hδ, hδ', hlog⟩ := exists_compression_exponents C₂ hC + exact ⟨θ, δ, hθ, hθ', hδ, hδ', fun _ hn => + history_pow_blockCount_le hC (Rat.cast_nonneg.mpr hθ.le) hn hlog⟩ + +/-- Every positive choice of the block exponent yields arbitrarily many blocks +at sufficiently large input lengths. -/ +theorem tendsto_blockCount {θ : ℝ} (hθ : 0 < θ) : + Filter.Tendsto (blockCount θ) Filter.atTop Filter.atTop := + tendsto_nat_floor_atTop.comp (Filter.Tendsto.const_mul_atTop hθ + ((Real.tendsto_logb_atTop (by norm_num : 1 < (2 : ℝ))).comp tendsto_natCast_atTop_atTop)) + +/-- An address multiplier at least the rounded lane demand per binary +logarithm supplies all lane bits required by the compressor blocks. -/ +theorem laneBits_le_addressWidth {θ : ℝ} {b₀ B n : ℕ} (hθ : 0 ≤ θ) (hn : 1 ≤ n) + (hB : ⌈(b₀ : ℝ) * θ⌉₊ ≤ B) : + b₀ * blockCount θ n ≤ B * Nat.clog 2 n := by + have hn' : 1 ≤ (n : ℝ) := by exact_mod_cast hn + have hlog := Real.logb_nonneg (by norm_num : 1 < (2 : ℝ)) hn' + have hB' : (b₀ : ℝ) * θ ≤ B := (Nat.le_ceil _).trans (by exact_mod_cast hB) + have hclog : Real.logb 2 n ≤ (Nat.clog 2 n : ℝ) := by + rw [← Real.natCeil_logb_natCast 2 n] + exact Nat.le_ceil _ + have hfloor : (blockCount θ n : ℝ) ≤ θ * Real.logb 2 n := Nat.floor_le (mul_nonneg hθ hlog) + have h : (b₀ : ℝ) * (blockCount θ n : ℝ) ≤ (B : ℝ) * (Nat.clog 2 n : ℝ) := calc + _ ≤ (b₀ : ℝ) * (θ * Real.logb 2 n) := mul_le_mul_of_nonneg_left hfloor (Nat.cast_nonneg _) + _ = ((b₀ : ℝ) * θ) * Real.logb 2 n := (mul_assoc ..).symm + _ ≤ _ := mul_le_mul hB' hclog hlog (Nat.cast_nonneg _) + exact_mod_cast h + +/-- Choosing the multiplier of the address width at least five ensures the +processor count dominates the fifth power used in the counter budget. -/ +theorem pow_five_le_processorCount (n : ℕ) {B : ℕ} (hB : 5 ≤ B) : + n ^ 5 ≤ 2 ^ (B * Nat.clog 2 n) := by + calc + n ^ 5 ≤ (2 ^ Nat.clog 2 n) ^ 5 := Nat.pow_le_pow_left (Nat.le_pow_clog Nat.one_lt_two n) _ + _ = 2 ^ (5 * Nat.clog 2 n) := by rw [← pow_mul, Nat.mul_comm] + _ ≤ _ := Nat.pow_le_pow_right (by decide) (Nat.mul_le_mul_right _ hB) + +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionPowerHistory.lean b/lean/OAI/Computability/VPVNP/CompressionPowerHistory.lean new file mode 100644 index 0000000000..abf7604e5a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionPowerHistory.lean @@ -0,0 +1,97 @@ +import OAI.Computability.VPVNP.CompressionPowers +import OAI.Computability.VPVNP.CompressionProcedureHistory + +/-! +# Local records throughout a repeated compressor block + +The term chosen in each substep determines the network for the next substep. +Append the actual local records along this branch-dependent execution. The +fixed per-block bound on substeps then gives the exponential bounds on local +field lengths and occurrences in Theorem 7.1. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.Procedure + +variable {R : Type*} [CommSemiring R] {a k κ C s : ℕ} {μ : ℝ} {P : Procedure R a a k κ μ} + +/-- Keep the records supplied by the same procedure on each branch. -/ +noncomputable def repeatRecords (B : P.RecordBounds C s) (g : ℕ) : + (T n : ℕ) → (h : n = T * k + g) → (X : State a n) → (P.repeatExecution g T n h X).Records + | 0, n, h, X => by + have hn : n = g := by simpa using h + subst g + exact PUnit.unit + | t + 1, n, h, X => + let h₀ : n = k + (t * k + g) := by rw [h, Nat.succ_mul]; omega + let E := P.run (t * k + g) n h₀ X + E.bindRecords (fun z => P.repeatExecution g t (t * k + g) rfl (E.finalState z)) + (B.records _ _ h₀ X) fun z => repeatRecords B g t (t * k + g) rfl (E.finalState z) + +/-- Bounds for every elementary record remain uniform. A repeated execution +contains at most `s*T` substeps on any branch. -/ +theorem repeat_recordBounds (B : P.RecordBounds C s) (g T n : ℕ) (h : n = T * k + g) + (X : State a n) : + let E := P.repeatExecution g T n h X + let data := repeatRecords B g T n h X + E.Bounded C data ∧ ∀ z, (E.termChain data z).length ≤ s * T := by + induction T generalizing n with + | zero => + have hn : n = g := by simpa using h + subst g + exact ⟨trivial, fun _ => Nat.zero_le _⟩ + | succ t ih => + let h₀ : n = k + (t * k + g) := by rw [h, Nat.succ_mul]; omega + let E := P.run (t * k + g) n h₀ X + let f := fun z : E.Choices => P.repeatExecution g t (t * k + g) rfl (E.finalState z) + let r := B.records _ _ h₀ X + let r' := fun z : E.Choices => repeatRecords B g t (t * k + g) rfl (E.finalState z) + have hb z := ih (t * k + g) rfl (E.finalState z) + refine ⟨E.bounded_bindRecords f r r' (B.bounded _ _ h₀ X) (fun z => (hb z).1), fun z => ?_⟩ + have hl := E.length_bindRecords_le f r r' (B.length_le _ _ h₀ X) (fun z => (hb z).2) z + change ((E.bind f).termChain (E.bindRecords f r r') z).length ≤ s * (t + 1) + exact hl.trans_eq (by rw [Nat.mul_succ, Nat.add_comm]) + +/-- Every local expansion has bounded occurrence count and peak field width +with one uniform constant `C^s` per whole block. -/ +theorem repeat_history_growth (B : P.RecordBounds C s) (hC : 1 ≤ C) (g T n : ℕ) + (h : n = T * k + g) (X : State a n) (z : (P.repeatExecution g T n h X).Choices) : + let E := P.repeatExecution g T n h X + let chain := E.termChain (repeatRecords B g T n h X) z + (∀ v, chain.occurrences (fun _ => 1) v ≤ (C ^ s) ^ T) ∧ + chain.peak X.maxWireWidth + 1 ≤ (C ^ s) ^ T * (X.maxWireWidth + 1) := by + obtain ⟨hb, hl⟩ := repeat_recordBounds B g T n h X + exact (P.repeatExecution g T n h X).localHistory_bounds _ hC hb z (hl z) + +/-- Every intermediate field width, individual map degree, and final wire width +obeys the same estimate. Enlarging the coefficient to at least two gives the +constant convention of Theorem 7.1. -/ +theorem repeatWithLanes_history_bounds (B : P.RecordBounds C s) (hC : 1 ≤ C) (T n : ℕ) + (h : T * k ≤ n) (X : State a n) (z : (P.repeatWithLanes T n h X).Choices) : + let E := P.repeatWithLanes T n h X + let records := repeatRecords B (n - T * k) T n (Nat.add_sub_of_le h).symm X + let chain := E.termChain records z + let C₂ := max 2 (C ^ s) + (∀ v, chain.occurrences (fun _ => 1) v ≤ C₂ ^ T) ∧ + chain.AllRecordsLe (C₂ ^ T * (X.maxWireWidth + 1)) ∧ + (E.finalState z).maxWireWidth ≤ C₂ ^ T * (X.maxWireWidth + 1) := by + let eqn := (Nat.add_sub_of_le h).symm + let E := P.repeatWithLanes T n h X + let records := repeatRecords B (n - T * k) T n eqn X + let chain := E.termChain records z + have hg := repeat_history_growth B hC (n - T * k) T n eqn X z + have hpow := Nat.pow_le_pow_left (le_max_right 2 (C ^ s)) T + have hpeak : chain.peak X.maxWireWidth ≤ max 2 (C ^ s) ^ T * (X.maxWireWidth + 1) := + (Nat.le_succ _).trans (hg.2.trans (Nat.mul_le_mul_right _ hpow)) + have hb := (repeat_recordBounds B (n - T * k) T n eqn X).1 + exact ⟨fun v => (hg.1 v).trans hpow, chain.allRecordsLe_of_peak hpeak, + (E.final_maxWireWidth_le_peak records hb le_rfl z).trans hpeak⟩ + +end Compression.Procedure + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionPowers.lean b/lean/OAI/Computability/VPVNP/CompressionPowers.lean new file mode 100644 index 0000000000..b7d4ac0296 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionPowers.lean @@ -0,0 +1,158 @@ +import OAI.Computability.VPVNP.CompressionProcedure + +/-! +# Repeating an exact compressor block + +Theorem 7.1 of *VP and VNP differ over every field* repeats the same block +along every branch of its tensor expansion. For the energy estimate (7.4), +adding a fixed multiple of the squared position count to the energy makes +this quantity contract by a factor of four at each block. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.Procedure + +variable {R : Type*} [CommSemiring R] {a k κ : ℕ} {μ : ℝ} (P : Procedure R a a k κ μ) + +/-- Execute the same block `T` times, consuming `T*k` lanes and retaining +`g` unused lanes. Each continuation receives its own selected output state. -/ +def repeatExecution (g : ℕ) : (T n : ℕ) → n = T * k + g → (X : State a n) → + StateExecution R a g X + | 0, n, h, X => (Procedure.id R a).run g n (by simpa using h) X + | t + 1, n, h, X => + let E := P.run (t * k + g) n (by rw [h, Nat.succ_mul]; omega) X + E.bind fun z => repeatExecution g t (t * k + g) rfl (E.finalState z) + +/-- Every final branch has the exact position count after `T` blocks. -/ +theorem repeat_positions (g T n : ℕ) (h : n = T * k + g) (X : State a n) : + ∀ z, X.positions = κ ^ T * ((P.repeatExecution g T n h X).finalState z).positions := by + induction T generalizing n with + | zero => + intro z + exact (Procedure.id R a).positions g n (by simpa using h) X z + | succ t ih => + let E := P.run (t * k + g) n (by rw [h, Nat.succ_mul]; omega) X + exact E.forall_final_bind + (fun z => P.repeatExecution g t (t * k + g) rfl (E.finalState z)) + (fun Y => X.positions = κ ^ (t + 1) * Y.positions) fun z y => by + rw [P.positions _ _ _ X z, ih _ rfl (E.finalState z) y, pow_succ', Nat.mul_assoc] + +/-- Coefficient of the squared position count in the contracting quantity. -/ +noncomputable def potentialWeight : ℝ := 4 * P.error / (1 - 4 / (κ : ℝ) ^ 2) + +private theorem denominator_pos (hκ : 2 < κ) : 0 < 1 - 4 / (κ : ℝ) ^ 2 := by + have h : (2 : ℝ) < κ := by exact_mod_cast hκ + have hsq := (sq_lt_sq₀ (by norm_num : (0 : ℝ) ≤ 2) (Nat.cast_nonneg κ)).mpr h + apply sub_pos.mpr + apply (div_lt_iff₀ (sq_pos_of_pos (by positivity : (0 : ℝ) < κ))).mpr + linarith only [hsq] + +theorem potentialWeight_nonneg (hκ : 2 < κ) : 0 ≤ P.potentialWeight := + div_nonneg (mul_nonneg (by norm_num) P.error_nonneg) (denominator_pos hκ).le + +private theorem balance (hκ : 2 < κ) : + P.potentialWeight * ((κ : ℝ) ^ 2 - 4) = 4 * P.error * (κ : ℝ) ^ 2 := by + have hpos : (0 : ℝ) < κ := by exact_mod_cast P.divisor_pos + have h := div_mul_cancel₀ (4 * P.error) (denominator_pos hκ).ne' + change P.potentialWeight * (1 - 4 / (κ : ℝ) ^ 2) = 4 * P.error at h + rw [← h, mul_assoc, sub_mul, one_mul, div_mul_cancel₀ _ (pow_ne_zero _ hpos.ne')] + +/-- A single block contracts the energy plus the squared-position correction. -/ +theorem potential_step (hκ : 2 < κ) (hμ : μ ≤ 1 / 4) (g n : ℕ) (h : n = k + g) + (X : State a n) (z : (P.run g n h X).Choices) : + let Y := (P.run g n h X).finalState z + 4 * (Y.energy + P.potentialWeight * (Y.positions : ℝ) ^ 2) ≤ + X.energy + P.potentialWeight * (X.positions : ℝ) ^ 2 := by + let Y := (P.run g n h X).finalState z + have hpos : (X.positions : ℝ) = (κ : ℝ) * Y.positions := by exact_mod_cast P.positions g n h X z + have hen : Y.energy ≤ μ * X.energy + P.error * (X.positions : ℝ) ^ 2 := P.energy g n h X z + have hcoeff := mul_le_mul_of_nonneg_right hμ X.energy_nonneg + change 4 * (Y.energy + P.potentialWeight * (Y.positions : ℝ) ^ 2) ≤ _ + rw [hpos] at hen ⊢ + have hbal := congrArg (fun c : ℝ => c * (Y.positions : ℝ) ^ 2) (P.balance hκ) + nlinarith only [hcoeff, hen, hbal] + +/-- The scaled contracting quantity along the actual branch-dependent execution. -/ +theorem repeat_scaled_potential (hκ : 2 < κ) (hμ : μ ≤ 1 / 4) (g T n : ℕ) (h : n = T * k + g) + (X : State a n) : ∀ z, let Y := (P.repeatExecution g T n h X).finalState z + (4 : ℝ) ^ T * (Y.energy + P.potentialWeight * (Y.positions : ℝ) ^ 2) ≤ + X.energy + P.potentialWeight * (X.positions : ℝ) ^ 2 := by + induction T generalizing n with + | zero => + intro z + let E := (Procedure.id R a).run g n (by simpa using h) X + have hc : X.positions = (E.finalState z).positions := by + simpa only [one_mul] using (Procedure.id R a).positions g n (by simpa using h) X z + have he : (E.finalState z).energy ≤ X.energy := by + have he := (Procedure.id R a).energy g n (by simpa using h) X z + change (E.finalState z).energy ≤ 1 * X.energy + 0 * (X.positions : ℝ) ^ 2 at he + simpa only [one_mul, zero_mul, add_zero] using he + change (4 : ℝ) ^ 0 * ((E.finalState z).energy + + P.potentialWeight * ((E.finalState z).positions : ℝ) ^ 2) ≤ _ + rw [pow_zero, one_mul, ← hc] + exact add_le_add he le_rfl + | succ t ih => + let E := P.run (t * k + g) n (by rw [h, Nat.succ_mul]; omega) X + exact E.forall_final_bind + (fun z => P.repeatExecution g t (t * k + g) rfl (E.finalState z)) + (fun Y => (4 : ℝ) ^ (t + 1) * (Y.energy + P.potentialWeight * (Y.positions : ℝ) ^ 2) ≤ + X.energy + P.potentialWeight * (X.positions : ℝ) ^ 2) fun z y => by + rw [pow_succ', mul_assoc] + exact (mul_le_mul_of_nonneg_left (ih _ rfl (E.finalState z) y) (by norm_num)).trans + (P.potential_step hκ hμ _ _ _ X z) + +/-- Equation (7.4), with the coefficient of the initial position count given +explicitly. The first inequality controls all final shared wire fields. -/ +theorem repeat_totalWidth_le (hκ : 2 < κ) (hμ : μ ≤ 1 / 4) (g T n : ℕ) (h : n = T * k + g) + (X : State a n) (z : (P.repeatExecution g T n h X).Choices) : + let Y := (P.repeatExecution g T n h X).finalState z + (Y.totalWidth : ℝ) ≤ √Y.energy ∧ + √Y.energy ≤ (√X.energy + √P.potentialWeight * X.positions) / (2 : ℝ) ^ T := by + let Y := (P.repeatExecution g T n h X).finalState z + refine ⟨Y.totalWidth_le_sqrt, ?_⟩ + have hstep := P.repeat_scaled_potential hκ hμ g T n h X z + have hB := P.potentialWeight_nonneg hκ + have hscale : (4 : ℝ) ^ T * Y.energy ≤ X.energy + P.potentialWeight * (X.positions : ℝ) ^ 2 := + (mul_le_mul_of_nonneg_left (le_add_of_nonneg_right (mul_nonneg hB (sq_nonneg _))) + (by positivity : 0 ≤ (4 : ℝ) ^ T)).trans hstep + have hsq : ((2 : ℝ) ^ T) ^ 2 = 4 ^ T := by + rw [← pow_mul, Nat.mul_comm, pow_mul]; norm_num + apply (le_div_iff₀ (by positivity : 0 < (2 : ℝ) ^ T)).mpr + apply (sq_le_sq₀ (mul_nonneg (Real.sqrt_nonneg _) (by positivity)) + (add_nonneg (Real.sqrt_nonneg _) (mul_nonneg (Real.sqrt_nonneg _) (Nat.cast_nonneg _)))).mp + rw [mul_pow, Real.sq_sqrt Y.energy_nonneg, hsq, add_sq, mul_pow, + Real.sq_sqrt X.energy_nonneg, Real.sq_sqrt hB] + linarith only [hscale, mul_nonneg (Real.sqrt_nonneg X.energy) + (mul_nonneg (Real.sqrt_nonneg P.potentialWeight) (Nat.cast_nonneg X.positions))] + +/-- The history attached to the repeated execution gives the exact finite +sum of its expanded kernel paths for every assignment of initial factors. -/ +theorem repeat_contract (g T n : ℕ) (h : n = T * k + g) (X : State a n) + (F : NetworkKernel.Factors R X.network) : + let H := (P.repeatExecution g T n h X).history + NetworkKernel.contract X.network F = ∑ path : H.Path, H.weight F path := + (P.repeatExecution g T n h X).history.contract_eq_sum_paths F + +/-- For an input with at least `T*k` lanes, keep exactly the unused suffix. +This is the lane-count convention in Theorem 7.1. -/ +def repeatWithLanes (T n : ℕ) (h : T * k ≤ n) (X : State a n) : + StateExecution R a (n - T * k) X := + P.repeatExecution (n - T * k) T n (Nat.add_sub_of_le h).symm X + +/-- Position count and final wire bound for every term, starting with any +number of lanes that suffices for the chosen repetition count. -/ +theorem repeatWithLanes_bounds (hκ : 2 < κ) (hμ : μ ≤ 1 / 4) (T n : ℕ) (h : T * k ≤ n) + (X : State a n) (z : (P.repeatWithLanes T n h X).Choices) : + let Y := (P.repeatWithLanes T n h X).finalState z + X.positions = κ ^ T * Y.positions ∧ (Y.totalWidth : ℝ) ≤ √Y.energy ∧ + √Y.energy ≤ (√X.energy + √P.potentialWeight * X.positions) / (2 : ℝ) ^ T := + ⟨P.repeat_positions _ _ _ _ X z, P.repeat_totalWidth_le hκ hμ _ _ _ _ X z⟩ + +end Compression.Procedure + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionProcedure.lean b/lean/OAI/Computability/VPVNP/CompressionProcedure.lean new file mode 100644 index 0000000000..716be1746a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionProcedure.lean @@ -0,0 +1,125 @@ +import OAI.Computability.VPVNP.CompressionState + +/-! +# Composing exact compressor procedures + +A procedure consumes a fixed number of lane coordinates and carries bounds +independent of the input widths and network order. Its execution tree +retains the exact local kernel at every substep. The position divisors +multiply under composition, as do the leading energy coefficients. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +variable {R : Type*} [CommSemiring R] + +/-- Uniform cost and output bounds on an exact execution tree. -/ +structure Procedure (R : Type*) [CommSemiring R] (a b k κ : ℕ) (μ : ℝ) where + divisor_pos : 0 < κ + gain_nonneg : 0 ≤ μ + /-- Nonnegative coefficient multiplying the square of the input position count in the energy + bound for every output branch. -/ + error : ℝ + error_nonneg : 0 ≤ error + /-- Construct the execution tree from a state with `n = k + g` lane coordinates. Every + terminal state has degree exponent `b` and `g` lane coordinates. -/ + run (g n : ℕ) (h : n = k + g) (X : State a n) : StateExecution R b g X + positions : ∀ g n h X (z : (run g n h X).Choices), + X.positions = κ * ((run g n h X).finalState z).positions + energy : ∀ g n h X (z : (run g n h X).Choices), + ((run g n h X).finalState z).energy ≤ μ * X.energy + error * (X.positions : ℝ) ^ 2 + +namespace Procedure + +/-- A single exact tensor substep with input-independent energy and count estimates. -/ +def ofPass {a b k κ : ℕ} {μ C : ℝ} (hκ : 0 < κ) (hμ : 0 ≤ μ) (hC : 0 ≤ C) + (f : ∀ g (X : State a (k + g)), StatePass R X b g) + (hcount : ∀ g X (i : (f g X).step.Choice), X.positions = κ * ((f g X).next i).positions) + (henergy : ∀ g X (i : (f g X).step.Choice), + ((f g X).next i).energy ≤ μ * X.energy + C * (X.positions : ℝ) ^ 2) : + Procedure R a b k κ μ where + divisor_pos := hκ + gain_nonneg := hμ + error := C + error_nonneg := hC + run g n h X := by + subst n + exact .more (f g X) fun i => .done ((f g X).next i) + positions g n h X z := by + subst n + exact hcount g X z.1 + energy g n h X z := by + subst n + exact henergy g X z.1 + +private def stop {a g n : ℕ} (h : n = g) (X : State a n) : StateExecution R a g X := by + cases h + exact .done X + +private theorem stop_positions {a g n : ℕ} (h : n = g) (X : State a n) + (z : (stop (R := R) h X).Choices) : ((stop h X).finalState z).positions = X.positions := by + cases h + rfl + +private theorem stop_energy {a g n : ℕ} (h : n = g) (X : State a n) + (z : (stop (R := R) h X).Choices) : ((stop h X).finalState z).energy = X.energy := by + cases h + rfl + +/-- An empty schedule preserves the entire state. -/ +def id (R : Type*) [CommSemiring R] (a : ℕ) : Procedure R a a 0 1 1 where + divisor_pos := one_pos + gain_nonneg := zero_le_one + error := 0 + error_nonneg := le_rfl + run g _ h X := stop (h.trans (Nat.zero_add g)) X + positions g _ h X z := by rw [one_mul, stop_positions (h.trans (Nat.zero_add g)) X z] + energy g _ h X z := by + rw [one_mul, zero_mul, add_zero, stop_energy (h.trans (Nat.zero_add g)) X z] + +/-- The later step's order error is bounded by the squared original order, +since the earlier step has a positive integer position divisor. -/ +def seq {a b c k l p q : ℕ} {μ ν : ℝ} (P : Procedure R a b k p μ) + (Q : Procedure R b c l q ν) : Procedure R a c (k + l) (p * q) (ν * μ) where + divisor_pos := Nat.mul_pos P.divisor_pos Q.divisor_pos + gain_nonneg := mul_nonneg Q.gain_nonneg P.gain_nonneg + error := ν * P.error + Q.error + error_nonneg := add_nonneg (mul_nonneg Q.gain_nonneg P.error_nonneg) Q.error_nonneg + run g n h X := + (P.run (l+g) n (h.trans (Nat.add_assoc k l g)) X).bind fun z => + Q.run g (l+g) rfl ((P.run (l+g) n (h.trans (Nat.add_assoc k l g)) X).finalState z) + positions g n h X := + (P.run (l+g) n (h.trans (Nat.add_assoc k l g)) X).forall_final_bind + (fun z => Q.run g (l+g) rfl ((P.run (l+g) n (h.trans (Nat.add_assoc k l g)) X).finalState z)) + (fun Y => X.positions = p*q*Y.positions) fun z y => by + rw [P.positions _ _ _ X z, Q.positions _ _ _ _ y, Nat.mul_assoc] + energy g n h X := + (P.run (l+g) n (h.trans (Nat.add_assoc k l g)) X).forall_final_bind + (fun z => Q.run g (l+g) rfl ((P.run (l+g) n (h.trans (Nat.add_assoc k l g)) X).finalState z)) + (fun Y => Y.energy ≤ ν*μ*X.energy + (ν*P.error + Q.error) * (X.positions : ℝ)^2) + fun z y => by + let M := (P.run (l+g) n (h.trans (Nat.add_assoc k l g)) X).finalState z + have hM := P.energy _ _ _ X z + have hc : M.positions ≤ X.positions := by + rw [P.positions _ _ _ X z] + exact Nat.le_mul_of_pos_left _ P.divisor_pos + have hc' : (M.positions : ℝ) ≤ X.positions := by exact_mod_cast hc + have hpow := pow_le_pow_left₀ (Nat.cast_nonneg M.positions (α := ℝ)) hc' 2 + calc + _ ≤ ν * M.energy + Q.error * (M.positions : ℝ) ^ 2 := Q.energy _ _ _ _ y + _ ≤ ν * (μ * X.energy + P.error * (X.positions : ℝ) ^ 2) + + Q.error * (X.positions : ℝ) ^ 2 := + add_le_add (mul_le_mul_of_nonneg_left hM Q.gain_nonneg) + (mul_le_mul_of_nonneg_left hpow Q.error_nonneg) + _ = _ := by ring + +end Procedure +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionProcedureHistory.lean b/lean/OAI/Computability/VPVNP/CompressionProcedureHistory.lean new file mode 100644 index 0000000000..1649375c93 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionProcedureHistory.lean @@ -0,0 +1,110 @@ +import OAI.Computability.VPVNP.CompressionBoundedBind +import OAI.Computability.VPVNP.CompressionProcedure + +/-! +# Local history bounds of exact compressor procedures + +The bounds refer to the records attached to each term in the actual execution +tree. Sequential procedures retain both sets of records, including the records +of the continuation selected by each branch. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.Procedure + +open NetworkKernel + +variable {R : Type*} [CommSemiring R] {a b k κ : ℕ} {μ : ℝ} + +/-- Uniform local record and branch length bounds for every execution of a procedure. -/ +structure RecordBounds (P : Procedure R a b k κ μ) (C steps : ℕ) where + /-- The local records for the whole execution tree of each input, used to bound each pass and + the length of every selected branch. -/ + records : ∀ g n h X, (P.run g n h X).Records + bounded : ∀ g n h X, (P.run g n h X).Bounded C (records g n h X) + length_le : ∀ g n h X z, ((P.run g n h X).termChain (records g n h X) z).length ≤ steps + +namespace RecordBounds + +variable {P : Procedure R a b k κ μ} {C D m n : ℕ} + +/-- Enlarge both bounds while keeping the same records. -/ +def mono (B : P.RecordBounds C m) (hC : C ≤ D) (hm : m ≤ n) : P.RecordBounds D n where + records := B.records + bounded g l h X := (P.run g l h X).bounded_mono _ hC (B.bounded g l h X) + length_le g l h X z := (B.length_le g l h X z).trans hm + +/-- The empty schedule has an empty history and depth zero. -/ +def id (R : Type*) [CommSemiring R] (a C : ℕ) : (Procedure.id R a).RecordBounds C 0 where + records g l h X := by + have hl : l = g := h.trans (Nat.zero_add g) + subst g + exact PUnit.unit + bounded g l h X := by + have hl : l = g := h.trans (Nat.zero_add g) + subst g + trivial + length_le g l h X z := by + have hl : l = g := h.trans (Nat.zero_add g) + subst g + exact Nat.zero_le 0 + +/-- Concatenate the two actual execution records. The largest elementary +bound applies throughout, and the two uniform branch lengths add. -/ +def seq {d k' κ' : ℕ} {ν : ℝ} {Q : Procedure R b d k' κ' ν} + (B : P.RecordBounds C m) (B' : Q.RecordBounds D n) : + (P.seq Q).RecordBounds (max C D) (m + n) where + records g l h X := + let E := P.run (k' + g) l (h.trans (Nat.add_assoc k k' g)) X + E.bindRecords (fun z => Q.run g (k' + g) rfl (E.finalState z)) + (B.records _ _ _ X) (fun z => B'.records _ _ _ (E.finalState z)) + bounded g l h X := by + let E := P.run (k' + g) l (h.trans (Nat.add_assoc k k' g)) X + apply E.bounded_bindRecords + · exact E.bounded_mono _ (le_max_left _ _) (B.bounded _ _ _ X) + · intro z + exact (Q.run _ _ _ (E.finalState z)).bounded_mono _ (le_max_right _ _) + (B'.bounded _ _ _ (E.finalState z)) + length_le g l h X z := by + let E := P.run (k' + g) l (h.trans (Nat.add_assoc k k' g)) X + exact E.length_bindRecords_le _ _ _ (B.length_le _ _ _ X) + (fun y => B'.length_le _ _ _ (E.finalState y)) z + +section SinglePass + +variable {A : ℝ} (hκ : 0 < κ) (hμ : 0 ≤ μ) (hA : 0 ≤ A) + (f : ∀ g (X : State a (k + g)), StatePass R X b g) + (hcount : ∀ g X (i : (f g X).step.Choice), X.positions = κ * ((f g X).next i).positions) + (henergy : ∀ g X (i : (f g X).step.Choice), + ((f g X).next i).energy ≤ μ * X.energy + A * (X.positions : ℝ) ^ 2) + +/-- Every branch of a procedure created from one pass has depth exactly one. -/ +theorem ofPass_length (g l : ℕ) (h : l = k + g) (X : State a l) + (rec : ((Procedure.ofPass hκ hμ hA f hcount henergy).run g l h X).Records) + (z : ((Procedure.ofPass hκ hμ hA f hcount henergy).run g l h X).Choices) : + (((Procedure.ofPass hκ hμ hA f hcount henergy).run g l h X).termChain rec z).length = 1 := by + subst l + exact (StateExecution.length_more (f g X) (fun i => .done ((f g X).next i)) rec z) + +/-- Lift the supplied records and elementary bound of a single pass to the +whole procedure. Each selected history contains exactly that pass. -/ +def ofPass (rec : ∀ g X, (f g X).Records) (hrec : ∀ g X, (f g X).Bounded (rec g X) C) : + (Procedure.ofPass hκ hμ hA f hcount henergy).RecordBounds C 1 where + records g l h X := by + subst l + exact (rec g X, fun _ => PUnit.unit) + bounded g l h X := by + subst l + exact ⟨hrec g X, fun _ => trivial⟩ + length_le g l h X z := (ofPass_length hκ hμ hA f hcount henergy g l h X _ z).le + +end SinglePass +end RecordBounds +end Compression.Procedure + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionSchedule.lean b/lean/OAI/Computability/VPVNP/CompressionSchedule.lean new file mode 100644 index 0000000000..b8e1c17945 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionSchedule.lean @@ -0,0 +1,182 @@ +import OAI.Computability.VPVNP.WireExpanders +import OAI.Computability.VPVNP.DegreeRefreshSupply +import OAI.Computability.VPVNP.PackedShrinkStep +import OAI.Computability.VPVNP.PackingLanes + +/-! +# Choosing one fixed compression block + +Section 7.4 chooses the number of shrinking steps before their output +degrees. The refresh multiplier depends only on the common expander bound, +the expander degree and the fixed initial degree. Each subsequent power of +two can therefore be chosen large enough to represent the four supply masses, +and the last one can be an order of the common expander family. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +open SpectralGeometry + +/-- An admissible strict version of the six-party squared-distance bound. -/ +noncomputable def shrinkComparison : ℝ := 63 / 32 + +/-- The relative mass lost in replacing real weights by integral slots. -/ +noncomputable def shrinkLoss : ℝ := 1 / 128 + +/-- Leading energy factor of a shrinking step with the chosen constants. -/ +noncomputable def shrinkMultiplier : ℝ := shrinkComparison / (2 * (1 - shrinkLoss)) + +theorem shrink_constants : + (31 / 16 : ℝ) < shrinkComparison ∧ 0 < shrinkLoss ∧ shrinkLoss < 1 ∧ + shrinkComparison < 2 * (1 - shrinkLoss) ∧ + shrinkMultiplier = 126 / 127 ∧ 0 < shrinkMultiplier ∧ shrinkMultiplier < 1 := by + norm_num [shrinkComparison, shrinkLoss, shrinkMultiplier] + +/-- The exact position-count ratio in the dyadic packing at degree `2^a`. -/ +def packingFactor (a : ℕ) : ℕ := 2 ^ (2 * 2 ^ a + 1) * 2 ^ a + +theorem two_lt_packingFactor (a : ℕ) : 2 < packingFactor a := by + have h₁ := Nat.two_pow_pos a + have h₂ : 2 ≤ 2 * 2 ^ a + 1 := by omega + have hpow := Nat.pow_le_pow_right (by decide : 0 < (2 : ℕ)) h₂ + exact (show 2 < 2 ^ (2 * 2 ^ a + 1) by omega).trans_le + (Nat.le_mul_of_pos_right _ h₁) + +/-- A transition between exponents meets the mass and slot capacity bounds +of the actual regularized shrinking step. -/ +abbrev AllowsShrink (a a' : ℕ) : Prop := + ShrinkMotif.Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ a') shrinkLoss + +private theorem eventually_allowsShrink (a : ℕ) : + ∃ N : ℕ, ∀ a' : ℕ, N ≤ 2 ^ a' → AllowsShrink a a' := by + have hd := Nat.two_pow_pos a + obtain ⟨N, hN⟩ := ShrinkMotif.eventually_ready _ _ hd + (show 2 ≤ 2 * 2 ^ a + 1 by omega) shrink_constants.2.1 shrink_constants.2.2.1 + exact ⟨N, fun a' hn ↦ hN (2 ^ a') hn⟩ + +/-- The leading refresh factor (7.3), independent of the port count. -/ +noncomputable def refreshMultiplier (d₀ dH : ℕ) (γ : ℝ) : ℝ := + d₀ + 2 * (2 * γ * d₀ / dH + 1) + +/-- A fixed block of shrinking degrees followed by an expander refresh. -/ +structure BlockSchedule (k : Type*) [Field k] where + /-- Binary logarithm of the common expander degree used in the final refresh. -/ + expanderExponent : ℕ + /-- Uniform Poincaré bound required of the port graph at the end of the block. -/ + poincare : ℝ + poincare_pos : 0 < poincare + /-- Number of shrinking substeps before the degree refresh. -/ + steps : ℕ + steps_pos : 0 < steps + /-- Base-two degree exponent at each boundary of the shrinking sequence, including its + initial and final boundaries. -/ + degreeExponent : Fin (steps + 1) → ℕ + initial : degreeExponent 0 = expanderExponent + 1 + shrink : ∀ i : Fin steps, AllowsShrink (degreeExponent i.castSucc) (degreeExponent i.succ) + port_order : 2 ≤ 2 ^ degreeExponent (Fin.last steps) + /-- Regular port graph on the final shrinking degree's ports, with degree fixed by + `expanderExponent`. -/ + graph : RegularArcGraph (Fin (2 ^ degreeExponent (Fin.last steps))) (2 ^ expanderExponent) + port_bound : Refresh.SpectralPortBound k graph poincare + quarter : refreshMultiplier (2 ^ degreeExponent 0) (2 ^ expanderExponent) poincare * + shrinkMultiplier ^ steps ≤ 1 / 4 + +variable {k : Type*} [Field k] + +/-- All the constants and the graph in the schedule are selected before +the network, its lane count, and its widths. -/ +theorem exists_blockSchedule (h : HasWireExpanders k) : Nonempty (BlockSchedule k) := by + classical + obtain ⟨e, γ, hγ, graphs⟩ := h + let a₀ := e + 1 + let C := refreshMultiplier (2 ^ a₀) (2 ^ e) γ + have hC : 0 < C := by unfold C refreshMultiplier; positivity + obtain ⟨_, _, _, _, _, hρ, hρlt⟩ := shrink_constants + obtain ⟨n, hn⟩ := exists_pow_lt_of_lt_one (by positivity : 0 < 1 / (4 * C)) hρlt + let steps := n + 1 + have hquarter : C * shrinkMultiplier ^ steps ≤ 1 / 4 := by + have hmono : shrinkMultiplier ^ steps ≤ shrinkMultiplier ^ n := + pow_le_pow_of_le_one hρ.le hρlt.le (by omega) + have hscaled := (lt_div_iff₀ (by positivity : 0 < 4 * C)).mp (hmono.trans_lt hn) + linarith + choose threshold hthreshold using eventually_allowsShrink + choose nextOrder hOrder hexp using fun a : ℕ ↦ graphs (max 2 (threshold a)) + let degree : ℕ → ℕ := Nat.rec (motive := fun _ ↦ ℕ) a₀ (fun _ a ↦ nextOrder a) + have hg := hexp (degree n) + obtain ⟨G, _, hG⟩ := hg + refine ⟨⟨e, γ, hγ, steps, Nat.succ_pos _, fun i ↦ degree i.val, rfl, + fun i ↦ hthreshold _ _ ((le_max_right _ _).trans (hOrder _)), ?_, G, + fun F ↦ hG _ F, hquarter⟩⟩ + exact (le_max_left _ _).trans (hOrder _) + +namespace BlockSchedule + +variable (S : BlockSchedule k) + +/-- Initial and final restored degree. -/ +def baseDegree : ℕ := 2 ^ S.degreeExponent 0 + +/-- Number of lane bits consumed by the whole block, including the port index. -/ +def laneBits : ℕ := (∑ i : Fin S.steps, packingLaneBits (S.degreeExponent i.castSucc) 0) + + S.degreeExponent (Fin.last S.steps) + +/-- Number of old positions per final position; refresh keeps all the positions. -/ +def positionFactor : ℕ := ∏ i : Fin S.steps, packingFactor (S.degreeExponent i.castSucc) + +theorem degree_bounds : 2 ≤ S.baseDegree ∧ 2 ^ S.expanderExponent + 1 ≤ S.baseDegree := by + have h := Nat.two_pow_pos S.expanderExponent + rw [baseDegree, S.initial, pow_succ] + omega + +theorem laneBits_pos : 0 < S.laneBits := by + have h : 0 < S.degreeExponent (Fin.last S.steps) := by + by_contra! hn + have hD := S.port_order + simp [Nat.eq_zero_of_le_zero hn] at hD + exact Nat.add_pos_right _ h + +theorem positionFactor_gt_two : 2 < S.positionFactor := by + let i : Fin S.steps := ⟨0, S.steps_pos⟩ + apply (two_lt_packingFactor (S.degreeExponent i.castSucc)).trans_le + exact Finset.single_le_prod (fun j _ ↦ (two_lt_packingFactor (S.degreeExponent j.castSucc)).le.trans' + (by decide : 1 ≤ 2)) (Finset.mem_univ i) + +/-- The scheduled exponent at an index, with later indices held at the +last exponent. This permits sums over ordinary half-open index ranges. -/ +def exponentAt (i : ℕ) : ℕ := S.degreeExponent ⟨min i S.steps, by omega⟩ + +theorem exponentAt_castSucc (i : Fin S.steps) : + S.exponentAt i.val = S.degreeExponent i.castSucc := by + simp only [exponentAt, min_eq_left i.isLt.le] + rfl + +/-- Lane coordinates required by the suffix starting at shrink `i`. +Extra unused coordinates can be appended to every suffix. -/ +def remainingBits (i : ℕ) : ℕ := + (∑ j ∈ Finset.Ico i S.steps, packingLaneBits (S.exponentAt j) 0) + + S.degreeExponent (Fin.last S.steps) + +theorem remainingBits_zero : S.remainingBits 0 = S.laneBits := by + rw [remainingBits, laneBits, ← Finset.range_eq_Ico, + ← Fin.sum_univ_eq_sum_range (fun j ↦ packingLaneBits (S.exponentAt j) 0)] + simp only [exponentAt_castSucc] + +theorem remainingBits_step (i : Fin S.steps) (extra : ℕ) : + S.remainingBits i.val + extra = + packingLaneBits (S.degreeExponent i.castSucc) (S.remainingBits (i.val + 1) + extra) := by + rw [remainingBits, Finset.sum_eq_sum_Ico_succ_bot i.isLt, S.exponentAt_castSucc] + simp [remainingBits, packingLaneBits, Nat.add_assoc] + +theorem remainingBits_last : S.remainingBits S.steps = S.degreeExponent (Fin.last S.steps) := by + simp [remainingBits] + +end BlockSchedule +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionState.lean b/lean/OAI/Computability/VPVNP/CompressionState.lean new file mode 100644 index 0000000000..edff8c228d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionState.lean @@ -0,0 +1,149 @@ +import OAI.Computability.VPVNP.DegreeRefreshActualStep +import OAI.Computability.VPVNP.PackingLanes +import OAI.Computability.VPVNP.Compression + +/-! +# Degree and lane states of the compressor + +A state retains the actual slots, their binary displacements and the width +of every individual wire. A substep specifies one such output per admitted +term of its local tensor identity. These types let Section 7.4 compose the +shrinking and degree-refresh identities even when the next topology depends +on all term choices made so far. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +open NetworkKernel + +/-- Degree exponent and available binary lane coordinates index a network. -/ +structure State (a g : ℕ) where + /-- Finite type of base vertices whose lifts by the lane bits give the sites of this + compression state. -/ + Base : Type + baseFintype : Fintype Base + baseNonempty : Nonempty Base + /-- Number the base vertices by consecutive finite ordinals for use in the descriptor tables. -/ + baseIndex : Base ≃ Fin (@Fintype.card Base baseFintype) + /-- Directed slots and lane displacements describing the network lifted from the base + vertices. -/ + slots : LiftedSlots Base (2 ^ a) (BitWord g) + /-- Number of bits carried by an individual outgoing wire, indexed by base vertex, port, and + lane. -/ + width : (Base × Fin (2 ^ a)) × BitWord g → ℕ + +attribute [instance] State.baseFintype State.baseNonempty + +variable {a b g n : ℕ} + +namespace State + +/-- The indexed order on a product base. The first component is the +old base address and the second is the promoted tag or port coordinate. -/ +def productIndex {A B : Type*} [Fintype A] [Fintype B] {m n : ℕ} + (e : A ≃ Fin m) (f : B ≃ Fin n) : A × B ≃ Fin (Fintype.card (A × B)) := + ((e.prodCongr f).trans finProdFinEquiv).trans (finCongr (by + rw [Fintype.card_prod, Fintype.card_congr e, Fintype.card_congr f] + simp)) + +/-- The wire tensor uses the finite binary word alphabet on each actual arc. -/ +noncomputable def network (X : State a g) : Network := Refresh.actualWireGraph X.slots X.width + +/-- Number of processor positions, including all lanes at each base vertex. -/ +def positions (X : State a g) : ℕ := Fintype.card (X.Base × BitWord g) + +theorem positions_pos (X : State a g) : 0 < X.positions := Fintype.card_pos + +/-- Energy at the normalized mass of a single directed arc. -/ +noncomputable def energy (X : State a g) : ℝ := + ∑ e, (X.width e : ℝ) ^ 2 / (1 / ((X.positions : ℝ) * (2 ^ a : ℕ))) + +theorem energy_nonneg (X : State a g) : 0 ≤ X.energy := by unfold energy; positivity + +/-- Sum of the widths of all shared fields. -/ +def totalWidth (X : State a g) : ℕ := ∑ e, X.width e + +theorem totalWidth_le_sqrt (X : State a g) : (X.totalWidth : ℝ) ≤ Real.sqrt X.energy := by + let m := 1 / ((X.positions : ℝ) * (2 ^ a : ℕ)) + have hm : 0 < m := by dsimp [m]; positivity [X.positions_pos] + have hsum : ∑ _e : (X.Base × Fin (2 ^ a)) × BitWord g, m = 1 := by + have hc : Fintype.card ((X.Base × Fin (2 ^ a)) × BitWord g) = X.positions * 2 ^ a := by + simp only [positions, Fintype.card_prod, Fintype.card_fin] + ac_rfl + rw [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, hc, Nat.cast_mul] + exact mul_one_div_cancel (mul_pos (Nat.cast_pos.mpr X.positions_pos) + (Nat.cast_pos.mpr (Nat.two_pow_pos a))).ne' + simpa only [totalWidth, Nat.cast_sum, energy] using + widthSum_le_sqrtEnergy (fun e => (X.width e : ℝ)) (fun _ => m) (fun _ => hm) hsum + +end State + +/-- A local tensor identity whose output at each choice has the indicated +degree and lane count. -/ +structure StatePass (R : Type*) [CommSemiring R] (X : State a g) (b n : ℕ) where + /-- The network step expressing each input wire-tensor coefficient as the sum of the term + values at the same half-wire assignment. -/ + step : Step R X.network + /-- Output compression state for the network of each chosen term. -/ + next : step.Choice → State b n + output_eq : ∀ i, (step.term i).output = (next i).network + +/-- An exact computation with the same final degree and remaining lane +count for every sequence of admitted choices. -/ +inductive StateExecution (R : Type*) [CommSemiring R] (b n : ℕ) : + {a g : ℕ} → State a g → Type _ + | done (X : State b n) : StateExecution R b n X + | more {a g a' g'} {X : State a g} (p : StatePass R X a' g') + (tail : ∀ i, StateExecution R b n (p.next i)) : StateExecution R b n X + +namespace StateExecution + +variable {R : Type*} [CommSemiring R] {X : State a g} + +/-- Only the motif choices are part of the path. The kernel contractions +sum over their hidden wire coordinates separately. -/ +def Choices {a g : ℕ} {X : State a g} : StateExecution R b n X → Type + | .done _ => Unit + | .more p tail => (i : p.step.Choice) × (tail i).Choices + +/-- Output topology and widths determined by the choices. -/ +def finalState {a g : ℕ} {X : State a g} (P : StateExecution R b n X) : P.Choices → State b n := + match P with + | .done X => fun _ => X + | .more _ tail => fun z => (tail z.1).finalState z.2 + +/-- The coefficient identity is iterated over exactly these substeps. -/ +noncomputable def history {a g : ℕ} {X : State a g} (P : StateExecution R b n X) : + NetworkKernel.History R X.network := + match P with + | .done _ => .stop + | .more p tail => .branch p.step fun i => (p.output_eq i).symm ▸ (tail i).history + +/-- Continue each admitted term independently. -/ +def bind {b' n' a g : ℕ} {X : State a g} (P : StateExecution R b n X) + (f : (z : P.Choices) → StateExecution R b' n' (P.finalState z)) : + StateExecution R b' n' X := + match P with + | .done _ => f () + | .more p tail => .more p fun i => (tail i).bind fun z => f ⟨i,z⟩ + +/-- Every final state of a continuation is reached by a path of the initial +execution followed by a path of the chosen continuation. -/ +theorem forall_final_bind {b' n' : ℕ} (P : StateExecution R b n X) + (f : (z : P.Choices) → StateExecution R b' n' (P.finalState z)) + (pred : State b' n' → Prop) (h : ∀ z y, pred ((f z).finalState y)) : + ∀ y, pred ((P.bind f).finalState y) := by + induction P with + | done X => exact h () + | more p tail ih => exact fun y => ih y.1 (fun z => f ⟨y.1,z⟩) (fun z => h ⟨y.1,z⟩) y.2 + +end StateExecution +end Compression + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressionTemplates.lean b/lean/OAI/Computability/VPVNP/CompressionTemplates.lean new file mode 100644 index 0000000000..c7d87244c7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressionTemplates.lean @@ -0,0 +1,103 @@ +import OAI.Computability.VPVNP.CompressionSchedule +import OAI.Computability.VPVNP.ShrinkMotif +import OAI.Computability.VPVNP.DegreeRefreshPass +import Mathlib.Algebra.MvPolynomial.Rename + +/-! +# The fixed equations for one compressor block + +The shrinking identities all use the same six-party template, independently +of the base degree. The degree refresh uses one template on the chosen +port graph. Tagging their parameter and equation indices gives a single +finite system over the integers, fixed before the input network or the +number of iterations. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule + +open MotifBlocks MotifGrid MotifConversion + +variable {k : Type*} [Field k] (S : BlockSchedule k) + +/-- Port order exponent at the last shrinking step. -/ +abbrev portExponent := S.degreeExponent (Fin.last S.steps) + +/-- Comparison constant for the internal port demands, before the unit slack. -/ +noncomputable def portComparison : ℝ := 2 * S.poincare * S.baseDegree / (2 ^ S.expanderExponent : ℕ) + +theorem portComparison_pos : 0 < S.portComparison := by + unfold portComparison baseDegree + positivity [S.poincare_pos] + +/-- The expander as the connected supply motif for the fixed refresh graph. -/ +noncomputable abbrev portSupply := Refresh.expanderSupply S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 + +/-- The two families of base maps and all their widths. -/ +structure Templates where + /-- Fixed six-party block used for the local wire identity at each shrinking substep. -/ + shrink : FixedBlock k ShrinkMotif.demandSource ShrinkMotif.demandTarget ShrinkMotif.supply + (realWidths ShrinkMotif.demandMass) (realWidths ShrinkMotif.supplyMass) + (31 / 16) shrinkComparison + /-- Fixed block implementing the refresh identity on the schedule's chosen port graph. -/ + refresh : DegreeRefresh.RefreshBlock k S.portSupply S.baseDegree + S.portComparison (S.portComparison + 1) + +/-- Both templates exist over the field in which the spectral bound was established. -/ +theorem exists_templates : Nonempty S.Templates := by + obtain ⟨A⟩ := ShrinkMotif.exists_block (k := k) shrink_constants.1 + obtain ⟨B⟩ := Refresh.exists_expander_block S.graph (Nat.two_pow_pos _) S.port_order + (show 0 < S.baseDegree from Nat.two_pow_pos _) S.port_bound + exact ⟨⟨A, B⟩⟩ + +namespace Templates + +variable {S} (P : S.Templates) + +/-- Parameter indices of the joint equation system, tagged by the shrinking or refresh block +they belong to. -/ +abbrev Entry := (parameterData P.shrink).Entry ⊕ (parameterData P.refresh).Entry + +/-- Output-equation indices of the joint system, tagged by which of the two fixed blocks +supplies the equation. -/ +abbrev EquationIndex := (parameterData P.shrink).Output ⊕ (parameterData P.refresh).Output + +instance : Finite P.Entry := by unfold Entry; infer_instance +instance : Finite P.EquationIndex := by unfold EquationIndex; infer_instance + +/-- Distinct variable names for the two sets of integral equations. -/ +noncomputable def equation (o : P.EquationIndex) : MvPolynomial P.Entry ℤ := + match o with + | .inl z => MvPolynomial.rename Sum.inl ((parameterData P.shrink).equation z) + | .inr z => MvPolynomial.rename Sum.inr ((parameterData P.refresh).equation z) + +/-- Simultaneous vanishing of the fixed template equations in a coefficient ring. -/ +def IsSolution {R : Type*} [CommRing R] (f : P.Entry → R) : Prop := + ∀ o, MvPolynomial.eval₂Hom (Int.castRingHom R) f (P.equation o) = 0 + +theorem solution_iff {R : Type*} [CommRing R] (f : P.Entry → R) : + P.IsSolution f ↔ (parameterData P.shrink).IsSolution (f ∘ Sum.inl) ∧ + (parameterData P.refresh).IsSolution (f ∘ Sum.inr) := by + constructor + · intro h + exact ⟨fun o => by simpa only [equation, MvPolynomial.eval₂Hom_rename] using h (.inl o), + fun o => by simpa only [equation, MvPolynomial.eval₂Hom_rename] using h (.inr o)⟩ + · rintro ⟨h₁, h₂⟩ (o | o) + · exact (MvPolynomial.eval₂Hom_rename ..).trans (h₁ o) + · exact (MvPolynomial.eval₂Hom_rename ..).trans (h₂ o) + +theorem exists_solution : ∃ f : P.Entry → k, P.IsSolution f := by + obtain ⟨f, hf⟩ := MotifConversion.exists_solution P.shrink + obtain ⟨g, hg⟩ := MotifConversion.exists_solution P.refresh + exact ⟨Sum.elim f g, (P.solution_iff _).2 ⟨hf, hg⟩⟩ + +end Templates +end Compression.BlockSchedule + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBaseAdvice.lean b/lean/OAI/Computability/VPVNP/CompressorBaseAdvice.lean new file mode 100644 index 0000000000..153ad525d4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBaseAdvice.lean @@ -0,0 +1,93 @@ +import OAI.Computability.VPVNP.MacaulayBaseAdvice +import OAI.Computability.VPVNP.CompressorReaderBudgets +import OAI.Computability.VPVNP.RankQueryUniformResources + +/-! # Fixed Macaulay reader advice at an admissible compressor length + +The grammar checker stream, affine pin mask and field values, graded monomial +bounds and row counts are all chosen at the input length. The same bank serves +every coordinate query. Its height bound uses the reader plan fixed before the +prime and slice, including in characteristic zero. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace RankQuery.Stack.MacaulayRead.BaseAdvice + +open RadicalCertificate.MonomialIndex Coordinate.ConcreteResources + +/-- All three immutable row-decoder parameters fit in the plan's physical +address words, even when an equation block is empty. -/ +theorem plan_registers_fit {P : ReaderPlan} {F : Type*} {S : QueryData P.arity (P.equations+P.pins) F} + (h : P.Covers S) {w : ℕ} (hw : P.wordWidth ≤ w) : + P.equations < 2^w ∧ P.pins < 2^w ∧ size P.arity S.multiplierDegree < 2^w := by + have dense : size P.arity S.multiplierDegree ≤ rawSize P.arity P.multiplier := by + rw [size_eq_card] + exact (RadicalCertificate.card_boundedMonomial_le ..).trans ((Nat.le_mul_of_pos_left _ (Nat.succ_pos _)).trans + (ReaderPlan.raw_mono _ h.degrees.2.1)) + have hcap := (Nat.le_pow_clog (by decide : 1<2) P.addressLimit).trans + (Nat.pow_le_pow_right (by decide : 0<2) (P.dispatchWidth.2.1.trans hw)) + change P.addressLimit ≤ 2^w at hcap + unfold ReaderPlan.addressLimit at hcap + omega + +end RankQuery.Stack.MacaulayRead.BaseAdvice + +namespace Compression.BlockSchedule.Templates + +open LabelEvaluator RadicalCertificate.MonomialIndex RankQuery.Stack RAMTape SliceArithmetic +open MacaulayRead (BaseAdvice.RawPort) + +local instance rawAdvicePrime (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩ +/-- Finite enumeration of the ground field used to encode the Macaulay reader's affine pin +values. -/ +noncomputable local instance rawAdviceFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _ +/-- Equality decision for elements of the ground field used in the fixed advice bank. -/ +noncomputable local instance rawAdviceDecidable (p : Nat.Primes) (t d : ℕ) : DecidableEq (Ground p t d) := Classical.decEq _ + +variable {k : Type*} [Field k] {sched : BlockSchedule k} (B : sched.Templates) {p : Nat.Primes} {n c e : ℕ} + (hn : 2 ≤ n) (M : Model p (B.compressorDegree n) (B.compressorEquations hn c)) + (modulus : Vector p.val e) (φ : AdjoinRoot (SliceArithmetic.modulus modulus) ≃ₐ[ZMod p.val] + Ground p (B.compressorLabelCount c n) (B.compressorDegree n)) + +local notation "data" => M.queryData (B.compressorCoeff hn c) +local notation "orig" => (2^n+Fintype.card B.EquationIndex) +local notation "values" => (fun i ↦ AffinePin.Query.encode φ (M.values i)) + +/-- Actual immutable base matrix state before the first call. Its checker +parameters refer to the fixed equation types of both compressor templates. -/ +noncomputable def compressorBaseBank (w v : ℕ) : Stacks MacaulayRead.BaseAdvice.RawPort := + let L := JointScalar.Leaf.layout B.Entry B.EquationIndex B.equation c hn w p.val e v + MacaulayRead.BaseAdvice.initial (orig) (data) L modulus w v M.pins (values) + +/-- The base advice stacks contain the equation data, modulus, affine pins and encoded pin +values for the chosen compressor instance. -/ +noncomputable def compressorBaseReady (w v : ℕ) : Stacks MacaulayRead.BaseAdvice.RawPort → Prop := + let L := JointScalar.Leaf.layout B.Entry B.EquationIndex B.equation c hn w p.val e v + MacaulayRead.BaseAdvice.ready (orig) (data) L modulus w v M.pins (values) + +theorem compressorBaseBank_ready (q w v : ℕ) (hp : q ≠ 0 → p.val = q) + (hz : q = 0 → p.val ≤ 2^B.compressorPrimeBits c n) (hw : (B.compressorReaderPlan q c n).wordWidth ≤ w) : + B.compressorBaseReady hn M modulus φ w v (B.compressorBaseBank hn M modulus φ w v) := by + obtain ⟨covers, _, _⟩ := B.compressorReaderCovers q c hn p M hp hz + obtain ⟨ho, ht, hm⟩ := MacaulayRead.BaseAdvice.plan_registers_fit covers hw + exact MacaulayRead.BaseAdvice.initial_ready _ _ _ _ _ _ _ _ ho ht hm + +/-- The bound is uniform over the advised modulus and every ready state. +The original matrix reader's scratch registers need only satisfy its ready predicate. -/ +theorem compressorBaseReady_length (q w v signedSpace : ℕ) (he : e ≤ B.readerDegreeBudget q c n) + (hv : v ≤ B.readerLimbBudget q c n) + (hs : JointScalar.Leaf.bankSize (JointScalar.Leaf.layout B.Entry B.EquationIndex B.equation c hn w p.val e v) + w (B.compressorLabelCount c n*w) ≤ signedSpace) + (s : Stacks MacaulayRead.BaseAdvice.RawPort) (h : B.compressorBaseReady hn M modulus φ w v s) (j : MacaulayRead.BaseAdvice.RawPort) : + (s j).length ≤ (B.compressorReaderPlan q c n).live (B.readerDegreeBudget q c n) (B.readerLimbBudget q c n) w signedSpace := + MacaulayRead.BaseAdvice.ready_length_uniform (B.compressorReaderPlan q c n) (data) _ modulus M.pins (values) + rfl he hv hs s h j + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockABSliceFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorBlockABSliceFootprint.lean new file mode 100644 index 0000000000..4007ce63f9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockABSliceFootprint.lean @@ -0,0 +1,148 @@ +import OAI.Computability.VPVNP.CompressorBlockABSliceRun +import OAI.Computability.VPVNP.CompressorShrinkABSliceFootprint + +/-! +# Physical footprint of the AB interval calendar inside a block + +The fixed graph input begins at its own scratch-table head. The four read +columns lie between that head and the slice table, and the latter has one +bank for each bundle. Thus the typed chronological walk supplies the progress +and external address evidence of all AB stages inside the allocated interval. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockSlices + +open BurstRAM Compression Compression.PackingData PhaseRecipe ShrinkBlockInputs ShrinkSliceArrays +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) +variable (T : IncidenceDirectory w) (start : ℕ) + +local notation "Z" => ShrinkInput.plan X start +local notation "t" => ShrinkInput.thickBank X T start +local notation "u" => ShrinkInput.cdBank X T start +local notation "p" => ShrinkInput.piecesBank X T start +local notation "ns" => ShrinkBundlePlan.thickCount (a i) +local notation "nt" => ShrinkBundlePlan.cap (a i) +local notation "sites" => Shrink.packedIndex (a := a i) (g := g) X.baseIndex + +private theorem before_width : start ≤ ShrinkInput.widthBase X start := by + let V := Fintype.card X.Base + let d := 2^(a i) + have greedy : ShrinkInput.placementBase X start = + start+V*(6+3*d+4*Greedy.WalkLayout.tagCount d)+1 := GreedyArena.greedyStop_eq .. + change start ≤ (((((ShrinkInput.placementBase X start+_)+_)+_)+_)+_)+_ + omega + +private theorem columns_after {stride : ℕ} (room : ShrinkInput.termEnd X start stride < 2^w) : + start ≤ (t 2).val ∧ start ≤ (t 3).val ∧ start ≤ (p 3).val ∧ start ≤ (p 4).val := by + let W := ShrinkInput.widthBase X start + let q := ShrinkRankSpace.Shape.collectBank Z w + let B := (Z).B + let Q := (Z).Q + have lower : start ≤ W := before_width i X start + have cap : W+6*(B*Q)+2*B < 2^w := by + change (W+6*(B*Q)+2*B)+_+_ < _ at room; omega + have rankFit : (Z).stop < 2^w := by change W < _; omega + have hv : (q 4).val = Q := ((Z).values T (ShrinkInput.placementBank X T start) Fintype.card_pos rankFit).stride + have hW : W < 2^w := rankFit + have tc : (t 2).val = W := by change ((W%(2^w))%(2^w))=W; rw [Nat.mod_mod,Nat.mod_eq_of_lt hW] + have ts : (t 3).val = W+2*(B*Q) := by + change (W+2*(B*(q 4).val))%(2^w) = _ + rw [hv,Nat.mod_eq_of_lt (by omega)] + have pc : (p 3).val = W+2*(B*Q)+2*(B*Q)+2*B := by + change ((W+2*(B*(q 4).val))+2*(B*(q 4).val)+2*B)%(2^w) = _ + rw [hv,Nat.mod_eq_of_lt (by omega)] + have ps : (p 4).val = W+2*(B*Q)+2*(B*Q)+2*B+B*Q := by + change ((W+2*(B*(q 4).val))+2*(B*(q 4).val)+2*B+B*Q)%(2^w) = _ + rw [hv,Nat.mod_eq_of_lt (by omega)] + rw [tc,ts,pc,ps]; omega + +/-- Exact external interval enclosing all reads, including the old widths +and both sets of field starts. -/ +theorem ab_region {first stride : ℕ} (termRoom : ShrinkInput.termEnd X start stride < 2^w) + (fresh : ShrinkInput.stop X start ≤ first) + (room : first+(Z).B*IndexedStarts.capacity ns nt < 2^w) : + ShrinkABSliceRecipe.ReadRegion t p (Z).B ns nt first + (fun x => start ≤ x ∧ x < first+(Z).B*IndexedStarts.capacity ns nt) := by + let L := ab_layout i X T start termRoom fresh room + have lo := columns_after i X T start termRoom + have low : start ≤ first := by + have h := before_width i X start + change ShrinkInput.widthBase X start+_+_ ≤ first at fresh + omega + constructor + · intro j c v hv + obtain ⟨a,b,f,g'⟩ := ShrinkABSliceTable.columns_val L j + have pre := (ShrinkABSliceTable.space L j).reads c + have hb := ShrinkABSliceTable.bank_val L j + have top := Nat.mul_le_mul_right (IndexedStarts.capacity ns nt) j.isLt.le + have lower : start ≤ ((ShrinkABSliceTable.columns t p j.val) c).val := by + fin_cases c + · change start ≤ ((ShrinkABSliceTable.columns t p j.val) 0).val + rw [a]; exact lo.2.1.trans (Nat.le_add_right ..) + · change start ≤ ((ShrinkABSliceTable.columns t p j.val) 1).val + rw [b]; exact lo.1.trans (Nat.le_add_right ..) + · change start ≤ ((ShrinkABSliceTable.columns t p j.val) 2).val + rw [f]; exact lo.2.2.2.trans (Nat.le_add_right ..) + · change start ≤ ((ShrinkABSliceTable.columns t p j.val) 3).val + rw [g']; exact lo.2.2.1.trans (Nat.le_add_right ..) + exact ⟨lower.trans (Nat.le_add_right ..),by omega⟩ + · intro x hx high; exact ⟨low.trans hx,high⟩ + +open private inputs from OAI.Computability.VPVNP.CompressorShrinkABSliceTable + +variable {F : DescriptorSpace.Shape} {origin abArena : Expr} {pub : Fin 5 → Word w} +variable {state : Word w} {ref : Memory w} + +set_option maxHeartbeats 1200000 in +/-- Preserve the real stage inputs and report lists and attach the exact +cursor guards, reads and writes to every stage of the admitted block. -/ +theorem ab_guarded [Nontrivial (Word w)] {first stride : ℕ} (initial : Memory w) + (stored : DemandWidths.Stored X.packingData sites X.packingWidth X.shrinkOrder X.shrinkNumber t u p initial) + (level : ShrinkBundlePlan.Reads X F i.val origin pub state ref start T) + (arena : abArena.eval pub state ref = (first : Word w)) + (termRoom : ShrinkInput.termEnd X start stride < 2^w) (fresh : ShrinkInput.stop X start ≤ first) + (room : first+(Z).B*IndexedStarts.capacity ns nt < 2^w) (widthRoom : nt*X.maxWireWidth < 2^w) + (cap : ℕ) (hcap : 95 ≤ cap) {rs : List (Report w)} + (walk : SourceWalk (ShrinkABSliceRecipe.Source (abInputs i origin abArena) pub state ref (Z).B cap) + (ShrinkABSliceRecipe.phases ns nt) initial rs) : + SourceWalk (ShrinkABSliceRecipe.Guarded (abInputs i origin abArena) pub state ref (Z).B cap + (fun x => start ≤ x ∧ x < first+(Z).B*IndexedStarts.capacity ns nt)) (ShrinkABSliceRecipe.phases ns nt) initial rs := by + let L := ab_layout i X T start termRoom fresh room + have rankFit : (Z).stop < 2^w := by + change ShrinkInput.widthBase X start < _ + change ShrinkInput.widthBase X start+_+_+_+_ < _ at termRoom + omega + let heads := ab_describes i X T start level rankFit arena + let old := fun j => thickWidths X.packingData X.shrinkOrder X.packingWidth ((BundleLists.portIndex sites).symm j) + let new := fun j => abWidths X.packingData X.shrinkNumber X.packingWidth ((BundleLists.portIndex sites).symm j) + have hc := State.two_le_packingColors (a i) + have hd := Nat.two_pow_pos (a i) + have fit := ab_widthFit i X widthRoom + have hs j : (old j).sum < 2^w := (thickWidths_sum X.packingData X.shrinkOrder X.packingWidth _).symm ▸ fit _ + have ht j : (new j).sum < 2^w := by + dsimp only [new] + rw [abWidths,orderedWidths,List.sum_ofFn, + (X.shrinkNumber _).symm.sum_comp (fun z : X.packingData.MotifFiber _ => X.packingData.abWidth X.shrinkNumber X.packingWidth z.1), + X.packingData.sum_abWidth hc hd X.shrinkNumber X.packingWidth _] + exact fit _ + have hpow : 4 ≤ 2^(Shrink.colors (a i)) := Nat.pow_le_pow_right Nat.zero_lt_two hc + have hprod := hpow.trans (Nat.le_mul_of_pos_right (2^(Shrink.colors (a i))) hd) + have qpos : 0 < nt := by change 0 < 3*(2^(Shrink.colors (a i))*2^(a i))/4; omega + have cnt : (Z).B < 2^w := (Nat.le_mul_of_pos_right _ (show 0 < IndexedStarts.capacity ns nt by unfold IndexedStarts.capacity; omega)).trans_lt (by omega) + exact ShrinkABSliceRecipe.guarded_walk (abInputs i origin abArena) pub state ref L heads + (ab_region i X T start termRoom fresh room) cnt old new (fun _ => List.length_ofFn) (fun _ => List.length_ofFn) + hs ht initial (inputs X.packingData sites X.packingWidth X.shrinkOrder X.shrinkNumber t u p initial stored L) + cap hcap walk + +end CompressorRecords.BlockSlices + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockABSliceRun.lean b/lean/OAI/Computability/VPVNP/CompressorBlockABSliceRun.lean new file mode 100644 index 0000000000..a7de3c3f8b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockABSliceRun.lean @@ -0,0 +1,105 @@ +import OAI.Computability.VPVNP.CompressorBlockSlices +import OAI.Computability.VPVNP.CompressorShrinkABSliceCalendar +import OAI.Computability.VPVNP.CompressorShrinkInputTerms + +/-! +# AB interval scans in the block's physical address space + +The level planner reads the same prefix and AB heads that the demand builder +writes. Its four input columns lie below the demand head. An AB interval bank +placed after that head needs only its own rectangular capacity, and every +thick bundle sum fits under the word bound already used to build the prefixes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockSlices + +open BurstRAM Compression Compression.PackingData PhaseRecipe +open ShrinkBlockInputs +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) +variable (T : IncidenceDirectory w) (start : ℕ) + +local notation "Z" => ShrinkInput.plan X start +local notation "t" => ShrinkInput.thickBank X T start +local notation "u" => ShrinkInput.cdBank X T start +local notation "p" => ShrinkInput.piecesBank X T start +local notation "ns" => ShrinkBundlePlan.thickCount (a i) +local notation "nt" => ShrinkBundlePlan.cap (a i) +local notation "sites" => Shrink.packedIndex (a := a i) (g := g) X.baseIndex + +/-- The width builder's four source rectangles all precede the new slice +bank. This uses the common bound on the existing term array and one end +bound on the new interval allocation. -/ +theorem ab_layout {stride first : ℕ} (termRoom : ShrinkInput.termEnd X start stride < 2^w) + (fresh : ShrinkInput.stop X start ≤ first) + (room : first+(Z).B*IndexedStarts.capacity ns nt < 2^w) : + ShrinkABSliceTable.Layout t p (Z).B ns nt first := by + have h := (ShrinkInput.termLayout X T start stride termRoom).2.1 + have le : (ShrinkInput.demandHead (w := w) X start).val ≤ first := + (Nat.mod_le ..).trans fresh + exact ⟨room,h.thickRanks,h.abRanks,h.thickWidths.trans le,h.thickStarts.trans le, + h.abWidths.trans le,h.abStarts.trans le⟩ + +variable {F : DescriptorSpace.Shape} {origin abArena : Expr} {pub : Fin 5 → Word w} +variable {state : Word w} {ref : Memory w} + +open private eval_bundles from OAI.Computability.VPVNP.CompressorShrinkBundlePlan + +/-- Evaluation of the fixed block's eight AB operands in the real directory. -/ +theorem ab_describes {first : ℕ} (level : ShrinkBundlePlan.Reads X F i.val origin pub state ref start T) + (rankFit : (Z).stop < 2^w) (arena : abArena.eval pub state ref = (first : Word w)) : + ShrinkABSliceRecipe.Describes (abInputs i origin abArena) pub state ref t p (Z).B first := by + have thick := ShrinkBundlePlan.prefix_bank X level false rankFit + have pieces := ShrinkBundlePlan.ab_bank X level rankFit + exact ⟨eval_bundles X level,arena,congrFun thick 3,congrFun thick 2,congrFun thick 1, + congrFun pieces 4,congrFun pieces 3,congrFun pieces 1⟩ + +/-- A bundle sum uses at most the sorted thick row count, which is at most +the CD rectangle capacity already charged to the prefix scan. -/ +theorem ab_widthFit (fit : nt*X.maxWireWidth < 2^w) : + ∀ b, X.packingData.bundleWidth X.packingWidth b < 2^w := by + have hsmall : ns ≤ nt := by + change 2^(Shrink.colors (a i))*2^(a i)/4 ≤ pieceCount (2^(a i)) (Shrink.colors (a i)) + unfold pieceCount; omega + intro b + exact ((X.packingData.bundleWidth_le (State.two_le_packingColors _) X.packingWidth + (fun e => X.width_le_maxWireWidth _) b).trans (Nat.mul_le_mul_right X.maxWireWidth hsmall)).trans_lt fit + +set_option maxHeartbeats 900000 in +/-- Execute the actual AB part of the online block calendar in the current +shrinking state. The post-memory has the exact compact lists and interval +records of every assigned bundle and preserves both outside intervals. -/ +theorem ab_run {first stride : ℕ} (initial : Memory w) + (stored : DemandWidths.Stored X.packingData sites X.packingWidth X.shrinkOrder X.shrinkNumber t u p initial) + (level : ShrinkBundlePlan.Reads X F i.val origin pub state ref start T) + (arena : abArena.eval pub state ref = (first : Word w)) + (termRoom : ShrinkInput.termEnd X start stride < 2^w) (fresh : ShrinkInput.stop X start ≤ first) + (room : first+(Z).B*IndexedStarts.capacity ns nt < 2^w) (widthRoom : nt*X.maxWireWidth < 2^w) + (cap : ℕ) (hcap : 95 ≤ cap) : + ∃ rs, SourceWalk (ShrinkABSliceRecipe.Source (abInputs i origin abArena) pub state ref (Z).B cap) + (ShrinkABSliceRecipe.phases ns nt) initial rs ∧ + (∀ b, IndexedStarts.Stored (ShrinkABSliceTable.bank first ns nt (BundleLists.portIndex sites b).val) + (ShrinkSliceArrays.thickWidths X.packingData X.shrinkOrder X.packingWidth b) + (ShrinkSliceArrays.abWidths X.packingData X.shrinkNumber X.packingWidth b) (after initial (eventLog rs))) ∧ + ∀ x, x < first ∨ first+(Z).B*IndexedStarts.capacity ns nt ≤ x → after initial (eventLog rs) x = initial x := by + have rankFit : (Z).stop < 2^w := by + change ShrinkInput.widthBase X start < _ + change ShrinkInput.stop X start + _ + _ < _ at termRoom + change ShrinkInput.widthBase X start + _ + _ + _ + _ < _ at termRoom + omega + exact ShrinkABSliceRecipe.graph_run (abInputs i origin abArena) pub state ref X.packingData sites X.packingWidth + X.shrinkOrder X.shrinkNumber (State.two_le_packingColors _) (Nat.two_pow_pos _) t u p initial stored + (ab_layout i X T start termRoom fresh room) (ab_describes i X T start level rankFit arena) + (ab_widthFit i X widthRoom) cap hcap + +end CompressorRecords.BlockSlices + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockCapacity.lean b/lean/OAI/Computability/VPVNP/CompressorBlockCapacity.lean new file mode 100644 index 0000000000..d41fbfb647 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockCapacity.lean @@ -0,0 +1,108 @@ +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorDescriptorBranchSpace +import OAI.Computability.VPVNP.CompressorDescriptorSquare + +/-! +# Capacity of the concrete online program + +The dimensions used by the static phase compiler cover all of the selected +substeps. The exact chronological directory and its six tables fit within +the polynomial word bound and within the square pair workspace. Both length +thresholds are independent of the coefficient specialization and branch. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockProgram + +open BurstRAM Compression DescriptorSpace CursorBounds CursorNetwork Filter + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +theorem refresh_length : + let s := RefreshBlockPlan.shape B + (refresh B).length = 24 + s.ties + s.ports*s.dH + s.degree := by + intro s + unfold refresh + simp only [List.length_append, BlockHeaderPlan.substep_length, List.length_cons, List.length_nil, + termPointers_length, BlockMetadata.visits] + rw [RefreshBlockPlan.visits_length B (geometry B) S.steps (0 : Fin 6)] + dsimp only [s] + omega + +theorem slots_pos : 0 < (geometry B).slots := + (Nat.two_pow_pos S.portExponent).trans_le (le_max_left _ _) + +theorem field_rates (base positions blocks : ℕ) : + let L := layout B base positions blocks + let n := L.shape.slots*L.shape.fields + ShrinkLevelSpace.tableFactor S ≤ n ∧ refreshRate B ≤ n ∧ residentRate S ≤ n ∧ 3 ≤ n := by + let g := geometry B + have h := Nat.le_mul_of_pos_left g.fields (slots_pos B) + have h₁ := le_max_left (ShrinkLevelSpace.tableFactor S) (max (refreshRate B) (residentRate S)) + have h₂ := le_max_right (ShrinkLevelSpace.tableFactor S) (max (refreshRate B) (residentRate S)) + have h₃ := le_max_left (refreshRate B) (residentRate S) + have h₄ := le_max_right (refreshRate B) (residentRate S) + change max _ _+3 ≤ g.slots*g.fields at h + change _ ≤ g.slots*g.fields ∧ _ ≤ g.slots*g.fields ∧ _ ≤ g.slots*g.fields ∧ _ ≤ g.slots*g.fields + omega + +theorem selected_capacity {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) + {l : ℕ} (T : ℕ) (h : T * S.laneBits ≤ l) (X : State (S.degreeExponent 0) l) (base : ℕ) + (z : (B.execute f hf T h X).Choices) : + let L := layout B base X.positions T + (executeLevels B f hf T h X z).length < L.levels ∧ + ∀ v ∈ executeLevels B f hf T h X z, v.input.positions ≤ L.positions ∧ + v.outputSites ≤ L.positions ∧ v.oldSlots ≤ slotCapacity L ∧ v.outputSlots ≤ slotCapacity L ∧ + v.origin.motifCount ≤ slotCapacity L := by + apply selected_level_capacity + · change (S.steps+1)*T < 1+(S.steps+1)*T; omega + · exact le_rfl + · exact le_rfl + +/-- Runtime-sized addresses with a polynomial suffix fit under a single +threshold. The suffix can include the saved field data of the enclosing +diagonal machine. -/ +theorem eventually_end (b : ℕ) (hb : 1 ≤ b) {θ : ℝ} (hθ : θ ≤ 1) + {start suffix : ℕ → ℕ} (hs : PolynomiallyBounded start) (hf : PolynomiallyBounded suffix) : + ∀ᶠ n : ℕ in atTop, + endAddress (layout B (start n) (initialPositions b n) (blockCount θ n)) + + suffix n < 2^wordBits b n := by + filter_upwards [eventually_cursor_room (allocationShape B) b (S.degreeExponent 0) + S.steps hb hθ hs hf] + with n h + exact (Nat.add_le_add_right (allocation_end B (start n) (initialPositions b n) (blockCount θ n)) + _).trans_lt h.1 + +/-- The square-workspace threshold comes before the coordinate split, the +coefficient solution, and the selected chronological path. -/ +theorem eventually_square (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b) + (K : ℕ) : + ∀ᶠ n : ℕ in atTop, ∀ (start : ℕ) {base lanes : ℕ} (labels : Fin (virtualBits b n) + ≃ Fin base ⊕ Fin lanes) + (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes) + (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f), + let X := pairInput S labels hD + let T := blockCount (u.θ : ℝ) n + ∀ z : (B.execute f hf T hT X).Choices, + let Y := (B.execute f hf T hT X).finalState z + endAddress (layout B start (initialPositions b n) T) + + K*(X.positions+processorCount b n+Y.positions*B.growthConstant^T+Y.totalWidth)+1 < + start+(processorCount b n)^2 := by + filter_upwards [eventually_selected_square (allocationShape B) B u b hb K] with n h + intro start base lanes labels hD hT R _ f hf X T z Y + have upper := h start labels hD hT R f hf z + exact (Nat.add_le_add_right (Nat.add_le_add_right (allocation_end B start (initialPositions b n) + T) _) 1).trans_lt upper + +end CompressorRecords.BlockProgram + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockClock.lean b/lean/OAI/Computability/VPVNP/CompressorBlockClock.lean new file mode 100644 index 0000000000..f45461e85d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockClock.lean @@ -0,0 +1,157 @@ +import OAI.Computability.VPVNP.CompressorPrefixWorkerFit +import OAI.Computability.VPVNP.CompressorShrinkHeaderGreedyPackets +import OAI.Computability.VPVNP.CompressorShrinkBundlePackets +import OAI.Computability.VPVNP.CompressorInitialScriptPackets +import OAI.Computability.VPVNP.CompressorOnlineBranchCut +import OAI.Computability.VPVNP.CompressorScheduledGreedyRates + +/-! +# A common clock for the fixed online descriptor program + +A finite maximum covers the deterministic workers at every scheduled degree. +The motif workers add their bounds at the actual input length. A larger +outer machine clock gives the same controller, launcher, and source budgets. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockClock + +open BurstRAM Compression CursorBounds Schedule SourceOnline Filter +open ShrinkSliceSweep + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +local notation "A" => BlockProgram.script B +local notation "D" => Online.N (BlockPlanner.Script.size (BlockProgram.script B)) + (BlockPlanner.Script.size (BlockProgram.script B)) + +/-- Fuel bound for the header publishers of the degree-refresh pass. -/ +def refreshHeaders := ScheduledRates.headerCap (BlockProgram.geometry B) + (.refresh S.portExponent (S.degreeExponent 0) S.expanderExponent) + +/-- Length-independent fuel allowance covering the deterministic workers, including surviving +slices, refresh headers and shrinking bundle scans. -/ +def fixedFuel := + 95 + (1 + SurvivingNative.ops.length) + refreshHeaders B + + Finset.univ.sup (ShrinkBundlePackets.maxFuel B) + +/-- Length-independent controller allowance for startup, shrinking headers, greedy scans and +online dispatch. -/ +def fixedClock := + InitialScriptPackets.budget (A) (BlockProgram.layout B 0 0 0) (S.degreeExponent 0) + + Finset.univ.sup (ShrinkHeaderGreedyPackets.clock B) + + (30 + 2 * (A).size + 2 * (D) + 5) + + (20 + 6 * (arity (A).catalog + 1) + 2 * (D) + 5) + +/-- Worker fuel at input length `n`, including shrinking prefix preparation and term selection +at the chosen word width. -/ +def workerFuel (b n : ℕ) := fixedFuel B + ShrinkBranch.prefixClock B b n + + SelectedTermWorker.clock B (wordBits b n) + +/-- Common online clock obtained by adding the fixed controller allowance to the scan budget at +the current worker fuel. -/ +def small (b n : ℕ) := fixedClock B + scanCap (A) (workerFuel B b n) + +theorem scan {b n fuel : ℕ} (h : fuel ≤ workerFuel B b n) : + scanCap (A) fuel ≤ small B b n := by + unfold small + apply le_trans _ (Nat.le_add_left ..) + unfold scanCap + omega + +theorem fixed (b n : ℕ) : + scanCap (A) 95 ≤ small B b n ∧ + scanCap (A) (1 + SurvivingNative.ops.length) ≤ small B b n ∧ + scanCap (A) (refreshHeaders B) ≤ small B b n ∧ + ∀ i : Fin S.steps, scanCap (A) (ShrinkBundlePackets.maxFuel B i) ≤ small B b n := by + have simple (j : ℕ) (hj : j ≤ fixedFuel B) := scan B (b := b) (n := n) + (hj.trans (by unfold workerFuel; omega)) + refine ⟨simple 95 ?_, simple _ ?_, simple _ ?_, fun i ↦ simple _ ?_⟩ + · unfold fixedFuel; omega + · unfold fixedFuel; omega + · unfold fixedFuel; omega + · exact (Finset.le_sup (f := ShrinkBundlePackets.maxFuel B) (Finset.mem_univ i)).trans + (Nat.le_add_left ..) + +theorem start (b n base positions blocks : ℕ) : + InitialScriptPackets.budget (A) (BlockProgram.layout B base positions blocks) + (S.degreeExponent 0) ≤ small B b n ∧ + ∀ i : Fin S.steps, ShrinkHeaderGreedyPackets.clock B i ≤ small B b n := by + rw [InitialScriptPackets.budget_fixed B] + unfold small fixedClock + constructor + · omega + · intro i + have := Finset.le_sup (f := ShrinkHeaderGreedyPackets.clock B) (Finset.mem_univ i) + omega + +theorem dynamic (b n : ℕ) : + scanCap (A) (ShrinkBranch.prefixClock B b n) ≤ small B b n ∧ + scanCap (A) (max 64 (SelectedTermWorker.clock B (wordBits b n))) ≤ small B b n := by + constructor + · exact scan B (by unfold workerFuel; omega) + · exact scan B (by unfold workerFuel fixedFuel; omega) + +theorem controls {b n cap : ℕ} (tags : (D) ≤ 2 ^ wordBits b n) (h : small B b n ≤ cap) : + Online.Run.ControlBounds (A).plan cap (w := wordBits b n) := by + have c : fixedClock B ≤ cap := (Nat.le_add_right _ _).trans h + unfold fixedClock at c + refine ⟨tags, ?_, ?_⟩ + · change 30 + 2 * (A).size + 2 * (D) + 5 ≤ cap + omega + · change 20 + 6 * (arity (A).catalog + 1) + 2 * (D) + 5 ≤ cap + omega + +/-- The length dependence is at most quartic in the binary logarithm. -/ +theorem rate (b : ℕ) : ∃ K : ℕ, ∀ n, small B b n ≤ K * (n.log2 + 1) ^ 4 := by + let G := (SelectedTerms.shrinkGrid B).stepConstant + let H := G * ((b + 10) ^ 4 + 2) + 7 + ShrinkDemandGather.cost + 1 + let J := SelectedTerms.stepConstant B + 7 + let F := fixedClock B + fixedFuel B + scanCap (A) 0 + let C := (b + 10) ^ 4 + 2 + refine ⟨F + H + J * (2 * C + 1), fun n ↦ ?_⟩ + let L := (n.log2 + 1) ^ 4 + have hl : 0 < L := Nat.pow_pos (Nat.succ_pos _) + have grow (x : ℕ) := Nat.le_mul_of_pos_right x hl + have word : wordBits b n ≤ C * L := (Nat.le_add_right ..).trans + (show wordBits b n + Nat.clog 2 (0 + 1) + 1 ≤ C * L from word_plus_clog_le b n 0 (by omega)) + have term : SelectedTermWorker.clock B (wordBits b n) ≤ J * (2 * C + 1) * L := by + change J * (2 * wordBits b n + 1) ≤ _ + rw [Nat.mul_assoc] + apply Nat.mul_le_mul_left + nlinarith only [word, hl] + have cap := SourceOnline.scanCap_le (A) (workerFuel B b n) + change fixedClock B + scanCap (A) (workerFuel B b n) ≤ (F + H + J * (2 * C + 1)) * L + apply (Nat.add_le_add_left cap _).trans + change fixedClock B + (fixedFuel B + H * L + SelectedTermWorker.clock B (wordBits b n) + + scanCap (A) 0) ≤ _ + have stable := grow F + unfold F at * + simp only [Nat.add_mul] at stable ⊢ + omega + +/-- A single threshold covers the tag word, the smaller clock, and any fixed +number of further link instructions. -/ +theorem eventually_room (b : ℕ) (hb : 1 ≤ b) (link : ℕ) : ∀ᶠ n : ℕ in atTop, + small B b n + link ≤ n ∧ + ∀ cap, small B b n ≤ cap → Online.Run.ControlBounds (A).plan cap (w := wordBits b n) := by + obtain ⟨K, bound⟩ := rate B b + filter_upwards [eventually_polylog_le (K + link) 4, + CursorRAM.eventual_word_room b hb (PolynomiallyBounded.const (D))] with n hn tags + refine ⟨?_, fun cap enough ↦ controls B tags.le enough⟩ + have pad := Nat.le_mul_of_pos_right link (Nat.pow_pos (n := 4) (Nat.succ_pos n.log2)) + rw [Nat.add_mul] at hn + exact (Nat.add_le_add (bound n) pad).trans hn + +end CompressorRecords.BlockClock + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockCursorPacket.lean b/lean/OAI/Computability/VPVNP/CompressorBlockCursorPacket.lean new file mode 100644 index 0000000000..ea5bf10584 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockCursorPacket.lean @@ -0,0 +1,115 @@ +import OAI.Computability.VPVNP.CompressorBlockHeaderPacket +import OAI.Computability.VPVNP.CompressorBlockHeaderStartup +import OAI.Computability.VPVNP.CompressorRecordsScheduleCursor + +/-! +# Cursor incidence as the third source packet of the block program + +The worker reads its eleven operands from the published first-level frame. +It starts at zero, returns each following row index, and writes all six +incidence columns for the actual cursor state. Every address before the +columns retains its incoming value. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockCursorPacket + +open CursorNetwork BurstRAM BlockPlanner BlockHeaderRun BlockHeaderStartup DescriptorSpace CursorRAM SourceTransport +open scoped Fin.CommRing + +variable {w : ℕ} + +private theorem row_events (p : Fin 11 → Word w) (i : ℕ) (x v : Word w) : + (.read x v : Event w) ∉ events p (Fin.ofNat _ i) ∧ + (.write x v ∈ events p (Fin.ofNat _ i) → (x,v) ∈ rowWrites p i) := by + simp [events,rowWrites,writes] + +private theorem scan_access (p : Fin 11 → Word w) (k n : ℕ) (data : ℕ → Prop) + (ok : ∀ j, k ≤ j → j < k+n → ∀ av ∈ rowWrites p j, data av.1.val) : + Reads (fun _ ↦ False) (eventLog (scanReports p k n)) ∧ Writes data (eventLog (scanReports p k n)) := by + induction n generalizing k with + | zero => exact ⟨fun _ _ h ↦ False.elim (List.not_mem_nil h),fun _ _ h ↦ False.elim (List.not_mem_nil h)⟩ + | succ n ih => + obtain ⟨rd,wr⟩ := ih (k+1) (fun j lo hi av mem ↦ ok j (by omega) (by omega) av mem) + constructor + · intro x v mem + rcases List.mem_append.mp mem with h|h + · exact (row_events p k x v).1 h + · exact rd x v h + · intro x v mem + rcases List.mem_append.mp mem with h|h + · exact ok k le_rfl (by omega) (x,v) ((row_events p k x v).2 h) + · exact wr x v h + +private theorem scan_progress (p : Fin 11 → Word w) (k n : ℕ) (fit : k+n < 2^w) : + SourceOnline.Progress ((k+n : ℕ) : Word w) (Fin.ofNat _ k) (scanReports p k n) := by + induction n generalizing k with + | zero => exact .done le_rfl + | succ n ih => + have bound : (k+1)+n = k+(n+1) := by omega + refine SourceOnline.Progress.next (next := Fin.ofNat _ (k+1)) ?_ rfl ?_ + · apply Fin.lt_def.mpr + rw [Fin.val_ofNat,Fin.val_natCast,Nat.mod_eq_of_lt (show k < 2^w by omega),Nat.mod_eq_of_lt fit] + omega + · exact bound ▸ ih (k+1) (by omega) + +variable {a b l pad : ℕ} {T : Type} [Fintype T] + +open Compression in +/-- The scan follows the two raw header publishers. Its report list certifies +the exact typed outgoing, incoming, displacement and width records, including +the incoming entries written at computed destination indices. -/ +theorem run (L : Layout) (n : ℕ) (base : Word w) (m : Memory w) (s : Word w) + (hD : 1 < b+l) (hd : 2+pad = 2^a) (bits : T → ℕ) + (ready : BlockHeaderStartup.Ready L a b l (∑ t, bits t) n base m) + (room : incidenceStart L 0+6*rowCount b l a ≤ 2^w) (width : (∑ t, bits t) < 2^w) : + let W := ∑ t, bits t + let pub := (Workspace.ports L.shape.arity base).data + let mem := initialFinal a L m + let start := incidenceStart L 0 + let p := publicWords w b l a W start + let N := rowCount b l a + let rs := scanReports p 0 N + let out := after mem (eventLog rs) + let X := cursorState (cursorCoordinateLabels b l) hD hd bits + HeaderPacket.Run L pub s (BlockPlanner.cursor BlockHeaderPlan.persistentFrame) mem rs + (1+visit.length) (List.replicate N []) ∧ + (directory w b l a start).Represents X out ∧ + (∀ x, x < start ∨ start+6*N ≤ x → out x = mem x) ∧ + rs.length = N ∧ RAMBuckets.cost Report.probes rs = 7*N := by + intro W pub mem start p N rs out X + obtain ⟨native,rep,_,len,_,cost,_⟩ := initialize_cursor hD hd bits room width mem + obtain ⟨stop,params⟩ := ready.initial.cursor pub s (ready.first s) ready.count_before ready.frame + change (BlockPlanner.cursor BlockHeaderPlan.persistentFrame).stop.eval pub s mem = (N : Word w) at stop + change (fun j ↦ ((BlockPlanner.cursor BlockHeaderPlan.persistentFrame).params j).eval pub s mem) = p at params + have touched (j : ℕ) (hj : j < N) (av : Word w × Word w) (ha : av ∈ rowWrites p j) : + start ≤ av.1.val ∧ av.1.val < start+6*N := + Schedule.cursor_write_address hD hd bits room hj av ha + obtain ⟨rd,wr⟩ := scan_access p 0 N (fun x ↦ start ≤ x ∧ x < start+6*N) + (fun j _ hj av ha ↦ touched j (by simpa using hj) av ha) + have hstart : levelStart L 0 ≤ start := Nat.le_add_right .. + have hN : N < 2^w := by + change incidenceStart L 0 + 6*N ≤ 2^w at room + have pos : 0 < N := by dsimp [N,rowCount]; positivity + omega + refine ⟨⟨by omega,?_,?_,fun x v hv ↦ (rd x v hv).elim,fun x v hv ↦ hstart.trans (wr x v hv).1⟩, + rep,?_,len,cost⟩ + · let executeBank := fun data : Fin 11 → Word w ↦ + runSegment ((PrimedStackRAM.template CursorRAM.visit 0).instantiate w data).program (1+visit.length) + (some (encode w 0)) mem (List.replicate N []) + exact (congrArg executeBank params).trans native + · rw [stop] + change SourceOnline.Progress (N : Word w) (Fin.ofNat _ 0) (scanReports p 0 N) + simpa only [Nat.zero_add] using scan_progress p 0 N (by simpa only [Nat.zero_add] using hN) + · intro x hx + apply after_outside mem wr + omega + +end CompressorRecords.BlockCursorPacket + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockDataHeads.lean b/lean/OAI/Computability/VPVNP/CompressorBlockDataHeads.lean new file mode 100644 index 0000000000..2c6b3ff4b3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockDataHeads.lean @@ -0,0 +1,62 @@ +import OAI.Computability.VPVNP.CompressorBlockSlices + +/-! +# Cached physical addresses for a shrinking node reader + +After the slot and subdivision visitors finish, the local evaluator needs +direct access to the packed AB and surviving arrays, the chosen arc roles, +and both incidence directories. Fourteen fixed header cells hold these +addresses. The next-level pointer also locates its DFS layer base. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockDataHeads + +open BurstRAM PhaseRecipe BlockPlanner Compression ShrinkBlockInputs + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + (F : DescriptorSpace.Shape) (i : Fin S.steps) + +/-- Offsets 40 through 53 in the old level header. -/ +def values (origin abArena widthArena slotArena : Expr) : Fin 14 → Expr := + let step := i.val + let a := ShrinkBlockInputs.a i + let selected := selectedInputs B F i origin + let slot := SlotLevel.Recipe.counts (slotTemplate i) (slotInputs B F i origin slotArena) + let term := ShrinkBundlePlan.termInputs step a origin + ![LevelFields.atLevel (step+1),slot.inverse,BlockSlices.intervals i widthArena,abArena, + ShrinkBundlePlan.owner step a origin,ShrinkBundlePlan.ranks step a origin,ShrinkBundlePlan.ids + step a origin, + ShrinkTermRecipe.dense a term,ShrinkBundlePlan.sorted step a + origin,ShrinkBundlePlan.prefixStart step a origin, + ShrinkBundlePlan.abStart step a origin,(ShrinkBundlePlan.abParams step a origin) + 4,SelectedPlan.roleBase selected,slot.rows] + +/-- Fourteen visits that publish the shrinking reader's physical addresses at header offsets 40 +through 53. -/ +def visits (origin abArena widthArena slotArena : Expr) : List Visit := + List.ofFn fun j : Fin 14 ↦ BlockPlanner.publish (LevelFields.address i.val (40+j.val)) + (values B F i origin abArena widthArena slotArena j) + +theorem visits_length (origin abArena widthArena slotArena : Expr) : + (visits B F i origin abArena widthArena slotArena).length = 14 := by simp [visits] + +theorem field_visit (origin abArena widthArena slotArena : Expr) (j : Fin 14) : + (visits B F i origin abArena widthArena slotArena)[j.val]'(by simpa only [visits_length] + using j.isLt) = + BlockPlanner.publish (LevelFields.address i.val (40+j.val)) + (values B F i origin abArena widthArena slotArena j) := + List.getElem_ofFn .. + +end CompressorRecords.BlockDataHeads + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockGroups.lean b/lean/OAI/Computability/VPVNP/CompressorBlockGroups.lean new file mode 100644 index 0000000000..ed8a40fa6b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockGroups.lean @@ -0,0 +1,130 @@ +import OAI.Computability.VPVNP.CompressorBlockIndex +import OAI.Computability.VPVNP.CompressorScriptWindow + +/-! +# Windows for source runs in the online descriptor script + +Each native source trace occupies a contiguous range in the fixed block. +The windows identify the worker for each visit and its ordinal among all +the heterogeneous substeps. They can be applied to the source packets +without numbering the repeated instances of the same instruction table by hand. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockGroups + +open PhaseRecipe BlockPlanner Compression + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- The twelve consecutive visit groups of shrinking step `i`, in their order in the compiled +block. -/ +def parts (i : Fin S.steps) : List (List Visit) := + let step := i.val + let a := ShrinkBlockInputs.a i + let F := BlockProgram.geometry B + let arena := BlockProgram.arena B step + let origin := arena 0 + let chosen := ShrinkBlockInputs.selectedInputs B F i origin + let absolute := ShrinkBundlePlan.absoluteCD step a origin + [BlockHeaderPlan.substep F step (.shrink a (ShrinkBlockInputs.b i)), + GreedyLevelPlan.visits F step a origin, + ShrinkBundlePlan.visits F step a origin, + ShrinkBlockInputs.termVisits B i origin, + SelectedPlan.visits chosen a, + ShrinkResidentsPlan.visits chosen (arena 5) (LevelFields.atLevel step) absolute a, + BlockSlices.intersections i origin (arena 1), + BlockSlices.surviving B F i origin (arena 2), + ShrinkBlockInputs.slots B F i origin (arena 3) (arena 2), + BlockMetadata.visits F step B.recordLimit (slotDegree S) .shrink (.shrink a chosen), + BlockProgram.termPointers step chosen.termBase (.lit chosen.termStride) + (SelectedPlan.layout chosen) absolute, + BlockDataHeads.visits B F i origin (arena 1) (arena 2) (arena 3)] + +theorem parts_length (i : Fin S.steps) : (parts B i).length = 12 := rfl + +theorem parts_flatten (i : Fin S.steps) : (parts B i).flatten = BlockProgram.shrink B i := by + simp only [parts,BlockProgram.shrink,ShrinkBlockInputs.beforeSlices,BlockSlices.visits, + List.flatten_cons,List.flatten_nil,List.append_nil,List.append_assoc] + +/-- The seven consecutive groups of the degree refresh, from header publication through the +successor pointer. -/ +def refreshParts : List (List Visit) := + let step := S.steps + let F := BlockProgram.geometry B + let arena := BlockProgram.arena B step + let p := RefreshBlockPlan.input F step (0 : Fin 6) + let s := RefreshBlockPlan.shape B + [BlockHeaderPlan.substep F step (.refresh S.portExponent (S.degreeExponent 0) S.expanderExponent), + (PortRefresh.LevelRecipe.order s).map (RefreshBlockPlan.stage B p), + List.ofFn (RefreshBlockPlan.copyColumn B F step p), + [BlockProgram.refreshPlacement step (arena 4)], + BlockMetadata.visits F step B.recordLimit (slotDegree S) .refresh (.refresh step (arena 4)), + BlockProgram.termPointers step (PortRefresh.LevelRecipe.termStart s p) (.lit s.stride) (.lit 0) + (.lit 0), + [BlockPlanner.publish (LevelFields.address step 40) (LevelFields.atLevel (step+1))]] + +theorem refreshParts_length : (refreshParts B).length = 7 := rfl + +theorem refreshParts_flatten : (refreshParts B).flatten = BlockProgram.refresh B := by + simp only [refreshParts,BlockProgram.refresh,RefreshBlockPlan.visits,List.flatten_cons, + List.flatten_nil,List.append_nil,List.append_assoc] + +private theorem split_groups (ls : List (List Visit)) (j : Fin ls.length) : + ls.flatten = (ls.take j.val).flatten ++ ls[j.val] ++ (ls.drop (j.val+1)).flatten := by + have split : ls = ls.take j.val ++ ls[j.val] :: ls.drop (j.val+1) := by + simpa only [List.drop_eq_getElem_cons j.isLt] using (List.take_append_drop j.val ls).symm + exact (congrArg List.flatten split).trans + (by simp only [List.flatten_append,List.flatten_cons,List.append_assoc]) + +/-- Restrict a script window to its indexed subgroup, moving earlier and later groups into the +surrounding prefix and suffix. -/ +def within {A : Script} {body : List Visit} (W : Window A body) (groups : List (List Visit)) + (h : groups.flatten = body) (j : Fin groups.length) : Window A groups[j.val] where + before := W.before ++ (groups.take j.val).flatten + after := (groups.drop (j.val+1)).flatten ++ W.after + block := by + calc + A.block = W.before ++ body ++ W.after := W.block + _ = W.before ++ groups.flatten ++ W.after := congrArg (fun xs ↦ W.before ++ xs ++ W.after) + h.symm + _ = _ := by rw [split_groups groups j]; simp only [List.append_assoc] + +/-- The window occupied by shrinking step `i` in the complete block script. -/ +def shrinkWindow (i : Fin S.steps) : Window (BlockProgram.script B) (BlockProgram.shrink B i) := + ⟨BlockIndex.earlier B i,BlockIndex.later B i,BlockIndex.split_block B i⟩ + +/-- The terminal window of a block, containing the refresh after all shrinking steps. -/ +def refreshWindow : Window (BlockProgram.script B) (BlockProgram.refresh B) := + ⟨(List.finRange S.steps).flatMap (BlockProgram.shrink B),[],(List.append_nil _).symm⟩ + +/-- Locate one of the twelve visit groups of a shrinking step in the global script. -/ +def shrink (i : Fin S.steps) (j : Fin 12) : Window (BlockProgram.script B) + ((parts B i)[j.val]'j.isLt) := + within (shrinkWindow B i) (parts B i) (parts_flatten B i) j + +/-- Locate one of the seven visit groups of the degree refresh in the global script. -/ +def refresh (j : Fin 7) : Window (BlockProgram.script B) ((refreshParts B)[j.val]'j.isLt) := + within (refreshWindow B) (refreshParts B) (refreshParts_flatten B) j + +theorem shrink_offset (i : Fin S.steps) (j : Fin 12) : + (shrink B i j).before.length = (BlockIndex.earlier B i).length+((parts B i).take + j.val).flatten.length := + List.length_append .. + +theorem refresh_offset (j : Fin 7) : + (refresh B j).before.length = ((List.finRange S.steps).flatMap (BlockProgram.shrink B)).length+ + ((refreshParts B).take j.val).flatten.length := List.length_append .. + +end CompressorRecords.BlockGroups + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockHeadReads.lean b/lean/OAI/Computability/VPVNP/CompressorBlockHeadReads.lean new file mode 100644 index 0000000000..f16c1a147f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockHeadReads.lean @@ -0,0 +1,205 @@ +import OAI.Computability.VPVNP.CompressorBlockHeadStability +import OAI.Computability.VPVNP.CompressorWindowPrepared +import OAI.Computability.VPVNP.CompressorHeaderOperands + +/-! +# Read footprints of the shrinking and refresh head formulas + +The online recipe can read its pitch and the graph data suffix. The four +level scalars and six table pointers lie in that suffix, as does the +selected shrinking layout bit. Arithmetic on these operands makes no +additional external reads. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockHeadReads + +open BurstRAM BurstRAM.PrivateRAM DescriptorSpace PhaseRecipe Schedule BlockPlanner Compression LevelFields +open scoped Fin.CommRing +open private recordsEnd firstRecord from OAI.Computability.VPVNP.CompressorGreedyLevelPlan + +variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {A : Script} {L : Layout} {base state : Word w} {m : Memory w} {first : ℕ} + +local notation "pt" => Workspace.ports (arity A.catalog) base +local notation "pub" => Schedule.Ports.data pt +local notation "D" => Window.operandRegion A L base +local notation "read" => Expr.ReadsFrom D pub state m +local notation "H" => levelStart L 0 + +private theorem add_reads {w : ℕ} (d : ℕ → Prop) (p : Fin 5 → Word w) (s : Word w) (mem : Memory w) + (x y : Expr) : (x.add y).ReadsFrom d p s mem ↔ x.ReadsFrom d p s mem ∧ y.ReadsFrom d p s mem := Iff.rfl + +private theorem mul_reads {w : ℕ} (d : ℕ → Prop) (p : Fin 5 → Word w) (s : Word w) (mem : Memory w) + (x y : Expr) : (x.mul y).ReadsFrom d p s mem ↔ x.ReadsFrom d p s mem ∧ y.ReadsFrom d p s mem := Iff.rfl + +private theorem lit_reads {w : ℕ} (d : ℕ → Prop) (p : Fin 5 → Word w) (s : Word w) (mem : Memory w) (n : ℕ) : + (Expr.lit n).ReadsFrom d p s mem := trivial + +/-- Level arithmetic reads the physical pitch cell allowed by the calendar. -/ +theorem level (step : ℕ) : read (atLevel step) := + ⟨trivial,trivial,⟨trivial,trivial⟩,Or.inr (Or.inl rfl)⟩ + +theorem address (step off : ℕ) : read (LevelFields.address step off) := ⟨level step,trivial⟩ + +private theorem field {step : ℕ} (entry : Entry L first pub state m) (room : levelStart L (first+step)+66 ≤ 2^w) + (j : ℕ) (small : j < 66) : read (scalar step j) := by + refine ⟨address step j,Or.inr (Or.inr ?_)⟩ + rw [eval_address entry,Fin.val_natCast,Nat.mod_eq_of_lt ((Nat.add_lt_add_left small _).trans_le room)] + exact (levelStart_mono L (Nat.zero_le _)).trans (Nat.le_add_right ..) + +private structure Inputs (step : ℕ) (d : ℕ → Prop) (p : Fin 5 → Word w) (s : Word w) (mem : Memory w) : Prop where + vertex : (vertices step).ReadsFrom d p s mem + deg : (degree step).ReadsFrom d p s mem + lane : (lanes step).ReadsFrom d p s mem + residual : (residualLanes step).ReadsFrom d p s mem + arena (j : Fin 6) : (BlockProgram.arena B step j).ReadsFrom d p s mem + +private theorem inputs {step : ℕ} (entry : Entry L first pub state m) (room : levelStart L (first+step)+66 ≤ 2^w) : + Inputs B step D pub state m := + ⟨field entry room 0 (by decide),field entry room 1 (by decide),field entry room 2 (by decide), + field entry room 3 (by decide),fun j => field entry room (54+6+j.val) (by have := j.isLt; omega)⟩ + +variable (i : Fin S.steps) + +local notation "st" => i.val +local notation "a" => ShrinkBlockInputs.a i +local notation "F" => BlockProgram.geometry B +local notation "o" => BlockProgram.arena B st 0 +local notation "c" => ShrinkBlockInputs.selectedInputs B F i o + +section Core + +variable {d : ℕ → Prop} {p : Fin 5 → Word w} +local notation "reads" => Expr.ReadsFrom d p state m + +private theorem bundle_heads (h : Inputs B st d p state m) : + reads (ShrinkBundlePlan.owner st a o) ∧ reads (ShrinkBundlePlan.ranks st a o) ∧ + reads (ShrinkBundlePlan.ids st a o) ∧ reads (ShrinkBundlePlan.sorted st a o) ∧ + reads (ShrinkBundlePlan.prefixStart st a o) ∧ reads (ShrinkBundlePlan.abStart st a o) ∧ + reads (ShrinkBundlePlan.absoluteCD st a o) ∧ reads (ShrinkBundlePlan.blockSize st a) := by + simp only [ShrinkBundlePlan.absoluteCD,ShrinkBundlePlan.prefixStart,ShrinkBundlePlan.abStart, + ShrinkBundlePlan.totalStart,ShrinkBundlePlan.sorted,ShrinkBundlePlan.ranks,ShrinkBundlePlan.gathered, + ShrinkBundlePlan.ids,ShrinkBundlePlan.counts,ShrinkBundlePlan.owner,ShrinkBundlePlan.preliminary, + ShrinkBundlePlan.rectangle,ShrinkBundlePlan.bucketCount,ShrinkBundlePlan.blockSize,ShrinkBundlePlan.bundles, + GreedyLevelPlan.greedyStop,GreedyLevelPlan.zeroAddress,GreedyLevelPlan.shiftBase,GreedyLevelPlan.offsetBase, + recordsEnd,firstRecord,LevelFields.sites,LevelFields.slots,add_reads,mul_reads,lit_reads,h.arena,h.vertex,h.deg,h.lane,h.residual,and_self] + +private theorem selected_heads (h : Inputs B st d p state m) : + reads (c).termBase ∧ reads (ShrinkTermRecipe.dense a (ShrinkBundlePlan.termInputs st a o)) ∧ + reads (SelectedPlan.roleBase c) ∧ reads (SelectedPlan.layoutCell c) ∧ reads (c).newSites ∧ reads (c).motifs := by + have hab := (bundle_heads B i h).2.2.2.2.2.1 + simp only [ShrinkBlockInputs.selectedInputs,ShrinkBlockInputs.newSites,SelectedPlan.roleBase,SelectedPlan.placementBase, + SelectedPlan.layoutCell,SelectedPlan.scoreBase,ShrinkTermRecipe.term,ShrinkTermRecipe.dense,ShrinkTermRecipe.count, + ShrinkTermRecipe.bundles,ShrinkBundlePlan.termInputs,LevelFields.sites,add_reads,mul_reads,lit_reads, + h.vertex,h.deg,h.lane,h.residual,hab,and_self] + +private theorem slot_heads (h : Inputs B st d p state m) : + let z := SlotLevel.Recipe.counts (ShrinkBlockInputs.slotTemplate i) + (ShrinkBlockInputs.slotInputs B F i o (BlockProgram.arena B st 3)) + reads z.rows ∧ reads z.inverse := by + simp only [SlotLevel.Recipe.counts,ShrinkBlockInputs.slotInputs,ShrinkBlockInputs.newSites, + add_reads,mul_reads,lit_reads,h.arena,h.vertex,h.residual,and_self] + +end Core + +/-- The same operand proof applies to a smaller region preserved by the +preceding calls. Only the pitch, four scalars, six table heads and the chosen +layout bit need to be available in that region. -/ +theorem resident_operands_of (d : ℕ → Prop) {p : Fin 5 → Word w} (entry : Entry L first p state m) + (room : levelStart L (first+st)+66 ≤ 2^w) (pitch : d (p 1-1).val) + (scalars : ∀ j : Fin 4, d (levelStart L (first+st)+j.val)) + (tables : ∀ j : Fin 6, d (levelStart L (first+st)+(60+j.val))) + (score : d ((SelectedPlan.layoutCell c).eval p state m).val) : + let reads := Expr.ReadsFrom d p state m + reads (c).newSites ∧ reads (c).motifs ∧ reads (BlockProgram.arena B st 5) ∧ reads (SelectedPlan.roleBase c) ∧ + reads (SelectedPlan.layout c) ∧ reads (ShrinkBundlePlan.absoluteCD st a o) ∧ reads (atLevel st) := by + have lev : (atLevel st).ReadsFrom d p state m := ⟨trivial,trivial,⟨trivial,trivial⟩,pitch⟩ + have cell (j : ℕ) (small : j < 66) (atCell : d (levelStart L (first+st)+j)) : + (scalar st j).ReadsFrom d p state m := by + refine ⟨⟨lev,trivial⟩,?_⟩ + rw [eval_address entry,Fin.val_natCast,Nat.mod_eq_of_lt ((Nat.add_lt_add_left small _).trans_le room)] + exact atCell + have h : Inputs B st d p state m := + ⟨cell 0 (by decide) (scalars 0),cell 1 (by decide) (scalars 1),cell 2 (by decide) (scalars 2), + cell 3 (by decide) (scalars 3),fun j => cell (60+j.val) (by have := j.isLt; omega) (tables j)⟩ + obtain ⟨_,_,roles,layoutAddress,newSites,motifs⟩ := selected_heads B i h + exact ⟨newSites,motifs,h.arena 5,roles,⟨layoutAddress,score⟩,(bundle_heads B i h).2.2.2.2.2.2.1,lev⟩ + +/-- All seven inputs shared by the hidden and map resident windows. -/ +theorem resident_operands (entry : Entry L first pub state m) (room : levelStart L (first+st)+66 ≤ 2^w) + (score : H ≤ ((SelectedPlan.layoutCell c).eval pub state m).val) : + read (c).newSites ∧ read (c).motifs ∧ read (BlockProgram.arena B st 5) ∧ read (SelectedPlan.roleBase c) ∧ + read (SelectedPlan.layout c) ∧ read (ShrinkBundlePlan.absoluteCD st a o) ∧ read (atLevel st) := by + have h := inputs B entry room + obtain ⟨_,_,roles,cell,newSites,motifs⟩ := selected_heads B i h + exact ⟨newSites,motifs,h.arena 5,roles,⟨cell,Or.inr (Or.inr score)⟩, + (bundle_heads B i h).2.2.2.2.2.2.1,level st⟩ + +theorem shrink_terms (entry : Entry L first pub state m) (room : levelStart L (first+st)+66 ≤ 2^w) + (score : H ≤ ((SelectedPlan.layoutCell c).eval pub state m).val) (j : Fin 4) : + read (BlockHeadStability.shrinkTerms B i j) := by + have h := inputs B entry room + obtain ⟨term,_,_,cell,_,_⟩ := selected_heads B i h + fin_cases j + · exact term + · trivial + · exact ⟨cell,Or.inr (Or.inr score)⟩ + · exact (bundle_heads B i h).2.2.2.2.2.2.1 + +theorem shrink_data (entry : Entry L first pub state m) (room : levelStart L (first+st)+66 ≤ 2^w) (j : Fin 14) : + read (BlockDataHeads.values B F i o (BlockProgram.arena B st 1) (BlockProgram.arena B st 2) + (BlockProgram.arena B st 3) j) := by + have h := inputs B entry room + obtain ⟨owner,ranks,ids,sorted,pref,ab,_,size⟩ := bundle_heads B i h + obtain ⟨_,dense,role,_,_,_⟩ := selected_heads B i h + obtain ⟨rows,inverse⟩ := slot_heads B i h + fin_cases j + · exact level (st+1) + · exact inverse + · exact ⟨h.arena 2,⟨trivial,⟨⟨h.vertex,h.lane⟩,h.deg⟩⟩,trivial⟩ + · exact h.arena 1 + · exact owner + · exact ranks + · exact ids + · exact dense + · exact sorted + · exact pref + · exact ab + · exact ⟨ab,size⟩ + · exact role + · exact rows + +theorem refresh_terms (entry : Entry L first pub state m) (room : levelStart L (first+S.steps)+66 ≤ 2^w) (j : Fin 4) : + read (BlockHeadStability.refreshTerms B j) := by + have h := inputs B entry room + fin_cases j + · have arena : read (table F S.steps (0 : Fin 6)) := h.arena 0 + change read (PortRefresh.LevelRecipe.termStart (RefreshBlockPlan.shape B) + (RefreshBlockPlan.input F S.steps (0 : Fin 6))) + simp only [PortRefresh.LevelRecipe.termStart,PortRefresh.LevelRecipe.demandStart,PortRefresh.LevelRecipe.blocks, + PortRefresh.LevelRecipe.segments,PortRefresh.LevelRecipe.sites,RefreshBlockPlan.input,add_reads,mul_reads,lit_reads, + h.vertex,h.residual,arena,and_self] + all_goals trivial + +/-- All operands of the two-word one-shot publisher use the same allowed region. -/ +theorem publish_supported {dest value : Expr} (hd : read dest) (hv : read value) : + HeaderOperands.Supported D pub state m (publish dest value) := by + refine ⟨trivial,trivial,?_⟩ + intro j + fin_cases j + · exact hd + · exact hv + +end CompressorRecords.BlockHeadReads + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockHeadSequence.lean b/lean/OAI/Computability/VPVNP/CompressorBlockHeadSequence.lean new file mode 100644 index 0000000000..a1553f4104 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockHeadSequence.lean @@ -0,0 +1,132 @@ +import OAI.Computability.VPVNP.CompressorBlockHeadWindows +import OAI.Computability.VPVNP.CompressorPublishedScoreRoom + +/-! # Chronological DFS head publications on the allocated graph levels + +The second publication starts from the first group's actual output. The +joined source group records every global ordinal and every emitted report. +For shrinking levels the original graph header and table capacity locate +the selected-layout bit beyond the published scalar fields. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.PublishedHeads + +open BurstRAM DescriptorSpace BlockPlanner PhaseRecipe Schedule Compression +open scoped Fin.CommRing + +variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable (base : Word w) (positions blocks t step cap : ℕ) (m : Memory w) +local notation "prog" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog prog)) base +local notation "pub" => Schedule.Ports.data pt +local notation "first" => Script.levelsPerBlock prog * t +local notation "st" => (levelStart L (first) : Word w) +local notation "here" => levelStart L (first+step) + +variable {N : ℕ} (terms : Fin 4 → Expr) (heads : Fin N → Expr) + (W : Window (BlockProgram.script B) (fieldVisits step 36 terms)) + (V : Window (BlockProgram.script B) (fieldVisits step 40 heads)) +local notation "mid" => image pub st m (here+36) terms + +/-- The two physical publication groups, with the second attached to the +first's exact final memory and immediately succeeding ordinal. -/ +structure Pair : Prop where + termGroup : Installed (N:=4) B base positions blocks t step 36 terms W cap m + dataGroup : Installed (N:=N) B base positions blocks t step 40 heads V cap mid + consecutive : V.before.length = W.before.length+4 + +variable {B base positions blocks t step cap m terms heads W V} + +theorem Pair.online (pair : Pair B base positions blocks t step cap m terms heads W V) : + ∃ ps : List (SourceOnline.Packet prog w), + SourceOnline.Group prog L base cap ((prog).initial.length+t*(prog).block.length+W.before.length) + (directoryRows L) m ps ∧ + ps.map (fun p ↦ p.stage.phase) = W.indices++V.indices ∧ + ps.flatMap SourceWalk.Packet.reports = fieldReports (here+36) pub st m terms ++ fieldReports (here+40) pub st mid heads ∧ + ps.flatMap (fun p ↦ p.stage.choices) = List.replicate (4+N) [] := by + obtain ⟨ps,p,pp,pr,pb⟩ := pair.termGroup.online + obtain ⟨qs,q,qp,qr,qb⟩ := pair.dataGroup.online + have len : ps.length = 4 := by + simpa only [Window.indices,List.length_map,List.length_ofFn,fieldVisits] using congrArg List.length pp + have same : SourceOnline.post m ps = mid := by rw [SourceOnline.post,pr]; rfl + have next : (prog).initial.length+t*(prog).block.length+W.before.length+ps.length = + (prog).initial.length+t*(prog).block.length+V.before.length := by rw [pair.consecutive,len,Nat.add_assoc] + refine ⟨ps++qs,p.append (by rw [same,next]; exact q),?_,?_,?_⟩ + · simp only [List.map_append,pp,qp] + · simp only [List.flatMap_append,pr,qr] + · simp only [List.flatMap_append,pb,qb,List.replicate_add] + +theorem Pair.frame (pair : Pair B base positions blocks t step cap m terms heads W V) (x : ℕ) + (out : x < here+36 ∨ here+40+N ≤ x) : + image pub st mid (here+40) heads x = m x := by + have d := pair.dataGroup.source.outside x (by unfold Outside; omega) + exact d.trans (pair.termGroup.source.outside x (by unfold Outside; omega)) + +theorem pair_charge (ports : Fin 5 → Word w) (state : Word w) (m : Memory w) (start : ℕ) + (terms : Fin 4 → Expr) (heads : Fin N → Expr) : + let nextMem := image ports state m (start+36) terms + RAMBuckets.cost Report.probes (fieldReports (start+36) ports state m terms ++ fieldReports (start+40) ports state nextMem heads) = + 2*(4+N) := by + intro nextMem + have charge {n : ℕ} (head : ℕ) (input : Memory w) (rhs : Fin n → Expr) : + RAMBuckets.cost Report.probes (fieldReports head ports state input rhs) = 2*n := packet_cost ports state input head rhs + rw [RAMBuckets.cost_append,charge,charge,Nat.mul_add] + +private theorem offset_length {α : Type*} (ls : List (List α)) (j : ℕ) (hj : j < ls.length) : + (ls.take (j+1)).flatten.length = (ls.take j).flatten.length + ls[j].length := by + rw [List.take_succ_eq_append_getElem hj,List.flatten_append,List.length_append,List.flatten_cons, + List.flatten_nil,List.append_nil] + +variable (B) (i : Fin S.steps) + +/-- All eighteen shrinking publications on the live table-zero allocation. -/ +theorem shrink_pair (h : Ready B base positions blocks t cap m) {g : ℕ} + (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) (T : IncidenceDirectory w) + (header : ShrinkHeaderReads.Header i X T (tableBase L (first+i.val) (0 : Fin 6)) L (first) m) + (sites : X.positions ≤ positions) : + Pair B base positions blocks t i.val cap m (BlockHeadStability.shrinkTerms B i) (dataValues B i) + (BlockGroups.shrink B i 10) (BlockGroups.shrink B i 11) := by + have level : first+i.val < (L).levels := by + have hb := Nat.mul_le_mul_left (S.steps+1) h.block + change (S.steps+1)*t+i.val < 1+(S.steps+1)*blocks + rw [Nat.mul_succ] at hb + have := i.isLt + omega + have score := PublishedScoreRoom.allocated B i X T base.val positions blocks header + (show LevelFields.Entry L (first) pub st m from ⟨rfl,h.pitch⟩) level sites h.room + have term := shrink_terms_window B i h score + refine ⟨term,shrink_data_window B i (h.after_publication term),?_⟩ + rw [BlockGroups.shrink_offset,BlockGroups.shrink_offset] + have lens := offset_length (BlockGroups.parts B i) 10 (by rw [BlockGroups.parts_length]; decide) + have four : ((BlockGroups.parts B i)[10]'(by rw [BlockGroups.parts_length]; decide)).length = 4 := + BlockProgram.termPointers_length .. + change _+((BlockGroups.parts B i).take 11).flatten.length = _+((BlockGroups.parts B i).take 10).flatten.length+4 + rw [lens,four,Nat.add_assoc] + +/-- The four refresh term pointers are followed by its next-level address. -/ +theorem refresh_pair (h : Ready B base positions blocks t cap m) : + Pair B base positions blocks t S.steps cap m (BlockHeadStability.refreshTerms B) + (fun _ : Fin 1 ↦ LevelFields.atLevel (S.steps+1)) (BlockGroups.refresh B 5) (BlockGroups.refresh B 6) := by + have term := refresh_terms_window B h + refine ⟨term,refresh_next_window B (h.after_publication term),?_⟩ + rw [BlockGroups.refresh_offset,BlockGroups.refresh_offset] + have lens := offset_length (BlockGroups.refreshParts B) 5 (by rw [BlockGroups.refreshParts_length]; decide) + have four : ((BlockGroups.refreshParts B)[5]'(by rw [BlockGroups.refreshParts_length]; decide)).length = 4 := + BlockProgram.termPointers_length .. + change _+((BlockGroups.refreshParts B).take 6).flatten.length = _+((BlockGroups.refreshParts B).take 5).flatten.length+4 + rw [lens,four,Nat.add_assoc] + +end CompressorRecords.PublishedHeads + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockHeadStability.lean b/lean/OAI/Computability/VPVNP/CompressorBlockHeadStability.lean new file mode 100644 index 0000000000..bdc1a05e26 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockHeadStability.lean @@ -0,0 +1,243 @@ +import OAI.Computability.VPVNP.CompressorBlockProgram +import OAI.Computability.VPVNP.CompressorPublishedHeadsRun + +/-! +# Memory read by the published term and DFS heads + +The address formulas use four scalar words of the old level, its table +heads and the block pitch. The selected shrinking layout needs one more +read from the score table. Each of these cells is outside the fields +published at offsets 36 through 53. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockHeadStability + +open BurstRAM BurstRAM.PrivateRAM DescriptorSpace PhaseRecipe LevelFields Compression SourceTransport +open scoped Fin.CommRing + +variable {w : ℕ} {pub : Fin 5 → Word w} {state : Word w} {original mem : Memory w} +variable {L : Layout} {first : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +private abbrev same (pub : Fin 5 → Word w) (state : Word w) (mem original : Memory w) (e : Expr) := + e.eval pub state mem = e.eval pub state original + +private theorem eval_add (p : Fin 5 → Word w) (s : Word w) (m : Memory w) (x y : Expr) : + (x.add y).eval p s m = x.eval p s m + y.eval p s m := rfl + +private theorem eval_mul (p : Fin 5 → Word w) (s : Word w) (m : Memory w) (x y : Expr) : + (x.mul y).eval p s m = x.eval p s m * y.eval p s m := rfl + +private theorem eval_lit (p : Fin 5 → Word w) (s : Word w) (m : Memory w) (n : ℕ) : + (Expr.lit n).eval p s m = (n : Word w) := rfl + +/-- The only old-header reads in the compiled expressions. -/ +private structure Inputs (step : ℕ) (pub : Fin 5 → Word w) (state : Word w) (mem original : Memory w) : Prop where + vertex : same pub state mem original (vertices step) + deg : same pub state mem original (degree step) + lane : same pub state mem original (lanes step) + residual : same pub state mem original (residualLanes step) + arena (j : Fin 6) : same pub state mem original (BlockProgram.arena B step j) + next : same pub state mem original (atLevel (step+1)) + +/-- A block pointer places its pitch cell before every graph header. -/ +theorem pitch_before (first step : ℕ) (dir : pub 1 = ((directoryBase L) : Word w)) + (fit : directoryBase L < 2^w) : (pub 1-1).val < levelStart L (first+step)+36 := by + have pos : 1 ≤ directoryBase L := Nat.le_add_left .. + have wsub : pub 1-1 = ((directoryBase L-1 : ℕ) : Word w) := by rw [dir,Nat.cast_sub pos,Nat.cast_one] + rw [wsub,Fin.val_natCast,Nat.mod_eq_of_lt ((Nat.sub_le ..).trans_lt fit)] + have below : directoryBase L ≤ levelStart L (first+step) := + (Nat.le_add_right .. : directoryBase L ≤ levelsBase L).trans (Nat.le_add_right ..) + omega + +private theorem readInputs {step offset N : ℕ} (entry : Entry L first pub state original) + (room : levelStart L (first+step)+66 ≤ 2^w) (pitch : (pub 1-1).val < levelStart L (first+step)+36) + (lo : 36 ≤ offset) (hi : offset+N ≤ 54) + (frame : Agree (PublishedHeads.Outside (levelStart L (first+step)+offset) N) mem original) : + Inputs B step pub state mem original := by + let base := levelStart L (first+step) + have pitchKeep : mem (pub 1-1).val = original (pub 1-1).val := + frame _ (.inl (pitch.trans_le (Nat.add_le_add_left lo _))) + have afterEntry : Entry L first pub state mem := ⟨entry.pointer,pitchKeep.trans entry.pitch⟩ + have scalarKeep (j : ℕ) (small : j < 66) (apart : j < 36 ∨ 54 ≤ j) : + same pub state mem original (scalar step j) := by + have fits : base+j < 2^w := (Nat.add_lt_add_left small _).trans_le room + rw [same,eval_scalar afterEntry step j fits,eval_scalar entry step j fits] + exact frame _ (apart.imp (fun h => Nat.add_lt_add_left (h.trans_le lo) _) + (fun h => by change base+offset+N ≤ base+j; omega)) + refine ⟨scalarKeep 0 (by decide) (by decide),scalarKeep 1 (by decide) (by decide), + scalarKeep 2 (by decide) (by decide),scalarKeep 3 (by decide) (by decide),fun j => ?_,?_⟩ + · change same pub state mem original (scalar step (54+6+j.val)) + exact scalarKeep _ (by have := j.isLt; omega) (.inr (by omega)) + · exact (eval_atLevel afterEntry (step+1)).trans (eval_atLevel entry (step+1)).symm + +open private recordsEnd firstRecord from OAI.Computability.VPVNP.CompressorGreedyLevelPlan + +variable (i : Fin S.steps) + +private abbrev F := BlockProgram.geometry B +private abbrev origin := BlockProgram.arena B i.val 0 +private abbrev chosen := ShrinkBlockInputs.selectedInputs B (F B) i (origin B i) +private abbrev a := ShrinkBlockInputs.a i + +private theorem bundle_heads (h : Inputs B i.val pub state mem original) : + let st := i.val + let d := a i + let o := origin B i + same pub state mem original (ShrinkBundlePlan.owner st d o) ∧ + same pub state mem original (ShrinkBundlePlan.ranks st d o) ∧ + same pub state mem original (ShrinkBundlePlan.ids st d o) ∧ + same pub state mem original (ShrinkBundlePlan.sorted st d o) ∧ + same pub state mem original (ShrinkBundlePlan.prefixStart st d o) ∧ + same pub state mem original (ShrinkBundlePlan.abStart st d o) ∧ + same pub state mem original (ShrinkBundlePlan.absoluteCD st d o) ∧ + same pub state mem original (ShrinkBundlePlan.blockSize st d) := by + simp only [same,ShrinkBundlePlan.absoluteCD,ShrinkBundlePlan.prefixStart,ShrinkBundlePlan.abStart, + ShrinkBundlePlan.totalStart,ShrinkBundlePlan.sorted,ShrinkBundlePlan.ranks,ShrinkBundlePlan.gathered, + ShrinkBundlePlan.ids,ShrinkBundlePlan.counts,ShrinkBundlePlan.owner,ShrinkBundlePlan.preliminary, + ShrinkBundlePlan.rectangle,ShrinkBundlePlan.bucketCount,ShrinkBundlePlan.blockSize,ShrinkBundlePlan.bundles, + GreedyLevelPlan.greedyStop,GreedyLevelPlan.zeroAddress,GreedyLevelPlan.shiftBase,GreedyLevelPlan.offsetBase, + recordsEnd,firstRecord,sites,slots,origin,eval_add,eval_mul,eval_lit,h.arena,h.vertex,h.deg,h.lane,h.residual, + and_self] + +private theorem selected_heads (h : Inputs B i.val pub state mem original) : + let c := chosen B i + let terms := ShrinkBundlePlan.termInputs i.val (a i) (origin B i) + same pub state mem original c.termBase ∧ same pub state mem original (ShrinkTermRecipe.dense (a i) terms) ∧ + same pub state mem original (SelectedPlan.roleBase c) ∧ same pub state mem original (SelectedPlan.layoutCell c) := by + have hab := (bundle_heads B i h).2.2.2.2.2.1 + simp only [same,chosen,ShrinkBlockInputs.selectedInputs,SelectedPlan.roleBase,SelectedPlan.placementBase, + SelectedPlan.layoutCell,SelectedPlan.scoreBase,ShrinkTermRecipe.term,ShrinkTermRecipe.dense,ShrinkTermRecipe.count, + ShrinkTermRecipe.bundles,ShrinkBundlePlan.termInputs,sites,eval_add,eval_mul,eval_lit, + h.vertex,h.deg,h.lane,h.residual,hab,and_self] + +private theorem slot_heads (h : Inputs B i.val pub state mem original) : + let ar := BlockProgram.arena B i.val 3 + let c := SlotLevel.Recipe.counts (ShrinkBlockInputs.slotTemplate i) + (ShrinkBlockInputs.slotInputs B (F B) i (origin B i) ar) + same pub state mem original c.rows ∧ same pub state mem original c.inverse := by + simp only [same,SlotLevel.Recipe.counts,ShrinkBlockInputs.slotInputs,ShrinkBlockInputs.newSites, + eval_add,eval_mul,eval_lit,h.arena,h.vertex,h.residual,and_self] + +/-- The selected score bit lies after the publication window whenever the +term region starts beyond the header and the final score offset fits. -/ +theorem layoutCell_after (base term rows : ℕ) + (ht : (chosen B i).termBase.eval pub state original = (term : Word w)) + (hn : (chosen B i).motifs.eval pub state original = (rows : Word w)) (low : base+54 ≤ term) + (fit : term+rows*(chosen B i).termStride+2 < 2^w) : + base+54 ≤ ((SelectedPlan.layoutCell (chosen B i)).eval pub state original).val := by + have hw : (SelectedPlan.layoutCell (chosen B i)).eval pub state original = + ((term+rows*(chosen B i).termStride+2 : ℕ) : Word w) := by + simp only [SelectedPlan.layoutCell,SelectedPlan.scoreBase,eval_add,eval_mul,eval_lit,ht,hn,Nat.cast_add,Nat.cast_mul] + rw [hw,Fin.val_natCast,Nat.mod_eq_of_lt fit] + omega + +/-- RHS expressions at offsets 36 through 39 on a shrinking substep. -/ +def shrinkTerms : Fin 4 → Expr := + ![(chosen B i).termBase,.lit (chosen B i).termStride,SelectedPlan.layout (chosen B i), + ShrinkBundlePlan.absoluteCD i.val (a i) (origin B i)] + +/-- RHS expressions at offsets 36 through 39 on the degree refresh. -/ +def refreshTerms : Fin 4 → Expr := + let s := RefreshBlockPlan.shape B + let p := RefreshBlockPlan.input (F B) S.steps (0 : Fin 6) + ![PortRefresh.LevelRecipe.termStart s p,.lit s.stride,.lit 0,.lit 0] + +variable {offset N : ℕ} + +/-- The address of the selected score bit survives all head publications. -/ +theorem shrink_layoutCell_stable (entry : Entry L first pub state original) + (room : levelStart L (first+i.val)+66 ≤ 2^w) (pitch : (pub 1-1).val < levelStart L (first+i.val)+36) + (lo : 36 ≤ offset) (hi : offset+N ≤ 54) + (frame : Agree (PublishedHeads.Outside (levelStart L (first+i.val)+offset) N) mem original) : + (SelectedPlan.layoutCell (chosen B i)).eval pub state mem = (SelectedPlan.layoutCell (chosen B i)).eval pub state original := + (selected_heads B i (readInputs B entry room pitch lo hi frame)).2.2.2 + +set_option maxHeartbeats 1200000 in +theorem shrink_term_stable (entry : Entry L first pub state original) + (room : levelStart L (first+i.val)+66 ≤ 2^w) (pitch : (pub 1-1).val < levelStart L (first+i.val)+36) + (lo : 36 ≤ offset) (hi : offset+N ≤ 54) + (score : levelStart L (first+i.val)+54 ≤ ((SelectedPlan.layoutCell (chosen B i)).eval pub state original).val) + (frame : Agree (PublishedHeads.Outside (levelStart L (first+i.val)+offset) N) mem original) + (j : Fin 4) : (shrinkTerms B i j).eval pub state mem = (shrinkTerms B i j).eval pub state original := by + have h := readInputs B entry room pitch lo hi frame + obtain ⟨ht,_,_,hc⟩ := selected_heads B i h + have hs : same pub state mem original (SelectedPlan.layout (chosen B i)) := by + change mem ((SelectedPlan.layoutCell _).eval _ _ mem).val = _ + rw [hc] + exact frame _ (.inr (by omega)) + have hab := (bundle_heads B i h).2.2.2.2.2.2.1 + fin_cases j + · exact ht + · rfl + · exact hs + · exact hab + +set_option maxHeartbeats 1200000 in +theorem shrink_data_stable (entry : Entry L first pub state original) + (room : levelStart L (first+i.val)+66 ≤ 2^w) (pitch : (pub 1-1).val < levelStart L (first+i.val)+36) + (lo : 36 ≤ offset) (hi : offset+N ≤ 54) + (frame : Agree (PublishedHeads.Outside (levelStart L (first+i.val)+offset) N) mem original) (j : Fin 14) : + let rhs := BlockDataHeads.values B (F B) i (origin B i) (BlockProgram.arena B i.val 1) + (BlockProgram.arena B i.val 2) (BlockProgram.arena B i.val 3) j + rhs.eval pub state mem = rhs.eval pub state original := by + have h := readInputs B entry room pitch lo hi frame + obtain ⟨owner,ranks,ids,sorted,pref,ab,_,size⟩ := bundle_heads B i h + obtain ⟨_,dense,role,_⟩ := selected_heads B i h + obtain ⟨rows,inverse⟩ := slot_heads B i h + have inter : same pub state mem original (BlockSlices.intervals i (BlockProgram.arena B i.val 2)) := by + simp only [same,BlockSlices.intervals,slots,sites,eval_add,eval_mul,eval_lit,h.arena,h.vertex,h.deg,h.lane] + have abHead : same pub state mem original ((ShrinkBundlePlan.abParams i.val (a i) (origin B i)) 4) := by + change same pub state mem original ((ShrinkBundlePlan.abStart i.val (a i) (origin B i)).add + (ShrinkBundlePlan.blockSize i.val (a i))) + simp only [same,eval_add,ab,size] + fin_cases j + · exact h.next + · exact inverse + · exact inter + · exact h.arena 1 + · exact owner + · exact ranks + · exact ids + · exact dense + · exact sorted + · exact pref + · exact ab + · exact abHead + · exact role + · exact rows + +theorem refresh_term_stable (entry : Entry L first pub state original) + (room : levelStart L (first+S.steps)+66 ≤ 2^w) (pitch : (pub 1-1).val < levelStart L (first+S.steps)+36) + (lo : 36 ≤ offset) (hi : offset+N ≤ 54) + (frame : Agree (PublishedHeads.Outside (levelStart L (first+S.steps)+offset) N) mem original) (j : Fin 4) : + (refreshTerms B j).eval pub state mem = (refreshTerms B j).eval pub state original := by + have h := readInputs B entry room pitch lo hi frame + have head : same pub state mem original (PortRefresh.LevelRecipe.termStart (RefreshBlockPlan.shape B) + (RefreshBlockPlan.input (F B) S.steps (0 : Fin 6))) := by + have ar : same pub state mem original (table (F B) S.steps (0 : Fin 6)) := h.arena 0 + simp only [same,PortRefresh.LevelRecipe.termStart,PortRefresh.LevelRecipe.demandStart,PortRefresh.LevelRecipe.blocks, + PortRefresh.LevelRecipe.segments,PortRefresh.LevelRecipe.sites,RefreshBlockPlan.input,eval_add,eval_mul,eval_lit, + h.vertex,h.residual,ar] + fin_cases j <;> first | exact head | rfl + +theorem next_level_stable {step : ℕ} (entry : Entry L first pub state original) + (pitch : (pub 1-1).val < levelStart L (first+step)+36) (lo : 36 ≤ offset) + (frame : Agree (PublishedHeads.Outside (levelStart L (first+step)+offset) N) mem original) : + (atLevel (step+1)).eval pub state mem = (atLevel (step+1)).eval pub state original := by + have afterEntry : Entry L first pub state mem := + ⟨entry.pointer,(frame _ (.inl (pitch.trans_le (Nat.add_le_add_left lo _)))).trans entry.pitch⟩ + exact (eval_atLevel afterEntry (step+1)).trans (eval_atLevel entry (step+1)).symm + +end CompressorRecords.BlockHeadStability + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockHeadWindows.lean b/lean/OAI/Computability/VPVNP/CompressorBlockHeadWindows.lean new file mode 100644 index 0000000000..3df95fca28 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockHeadWindows.lean @@ -0,0 +1,118 @@ +import OAI.Computability.VPVNP.CompressorPublishedHeadWindows +import OAI.Computability.VPVNP.CompressorBlockHeadReads +import OAI.Computability.VPVNP.CompressorSourceGroups + +/-! # The four DFS publication windows of a compression block + +A shrinking block publishes four term operands and fourteen addresses. +The refresh publishes four term operands and the next level address. +Every group runs at its occurrence in the global online script. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.PublishedHeads + +open BurstRAM DescriptorSpace PhaseRecipe BlockPlanner Schedule SourceTransport Compression +open scoped Fin.CommRing + +variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable (base : Word w) (positions blocks t cap : ℕ) (m : Memory w) +local notation "prog" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog prog)) base +local notation "pub" => Schedule.Ports.data pt +local notation "first" => Script.levelsPerBlock prog * t +local notation "st" => (levelStart L (first) : Word w) + +/-- The controller words on entry to a publication group. -/ +structure Ready : Prop where + block : t < blocks + room : endAddress L < 2^w + rows : m (pt).rows.val = (directoryRows L : Word w) + pitch : m (pub 1-1).val = (levelWords L : Word w) + clock : SourceOnline.scanCap prog 7 ≤ cap + +variable {B base positions blocks t cap m} + +private theorem Ready.pitch_before (h : Ready B base positions blocks t cap m) (step : ℕ) : + (pub 1-1).val < levelStart L (first+step)+36 := by + have fit := (levelStart_mono L (Nat.zero_le _)).trans_lt h.room + have controls := Window.lowCells (A:=prog) L base rfl rfl fit + exact controls.2.trans_le ((levelStart_mono L (Nat.zero_le _)).trans (Nat.le_add_right ..)) + +private theorem Ready.entry (h : Ready B base positions blocks t cap m) : + LevelFields.Entry L (first) pub st m := ⟨rfl,h.pitch⟩ + +private theorem Ready.framedEntry (h : Ready B base positions blocks t cap m) {mem : Memory w} + {step offset n : ℕ} (lo : 36 ≤ offset) + (frame : Agree (Outside (levelStart L (first+step)+offset) n) mem m) : + LevelFields.Entry L (first) pub st mem := + ⟨rfl,(frame _ (.inl ((h.pitch_before step).trans_le (Nat.add_le_add_left lo _)))).trans h.pitch⟩ + +variable (B) (i : Fin S.steps) + +/-- The fourteen address expressions published for the selected shrinking reader, computed from +the four designated scratch tables. -/ +def dataValues : Fin 14 → Expr := BlockDataHeads.values B (BlockProgram.geometry B) i + (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 1) (BlockProgram.arena B i.val 2) (BlockProgram.arena B i.val 3) + +private abbrev chosen := ShrinkBlockInputs.selectedInputs B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0) + +/-- The term group uses the bit in the selected layout's score table. -/ +theorem shrink_terms_window (h : Ready B base positions blocks t cap m) + (score : levelStart L (first+i.val)+54 ≤ ((SelectedPlan.layoutCell (chosen B i)).eval pub st m).val) : + Installed B base positions blocks t i.val 36 (BlockHeadStability.shrinkTerms B i) (BlockGroups.shrink B i 10) cap m := by + have room := level_room B base positions blocks t i.val h.block i.isLt.le h.room + have pitch := h.pitch_before i.val + apply install _ _ _ _ _ _ _ _ _ _ _ h.block h.room i.isLt.le (by decide) h.rows h.pitch h.clock + · exact fun _ frame j ↦ BlockHeadStability.shrink_term_stable B i h.entry room pitch le_rfl (by decide) score frame j + · intro mem frame j + apply BlockHeadReads.shrink_terms B i (h.framedEntry le_rfl frame) room _ j + rw [BlockHeadStability.shrink_layoutCell_stable B i h.entry room pitch le_rfl (by decide) frame] + exact ((levelStart_mono L (Nat.zero_le _)).trans (Nat.le_add_right ..)).trans score + +theorem shrink_data_window (h : Ready B base positions blocks t cap m) : + Installed B base positions blocks t i.val 40 (dataValues B i) (BlockGroups.shrink B i 11) cap m := by + have room := level_room B base positions blocks t i.val h.block i.isLt.le h.room + apply install _ _ _ _ _ _ _ _ _ _ _ h.block h.room i.isLt.le (by decide) h.rows h.pitch h.clock + · exact fun _ frame j ↦ BlockHeadStability.shrink_data_stable B i h.entry room (h.pitch_before i.val) (by decide) (by decide) frame j + · exact fun _ frame j ↦ BlockHeadReads.shrink_data B i (h.framedEntry (by decide) frame) room j + +theorem refresh_terms_window (h : Ready B base positions blocks t cap m) : + Installed B base positions blocks t S.steps 36 (BlockHeadStability.refreshTerms B) (BlockGroups.refresh B 5) cap m := by + have room := level_room B base positions blocks t S.steps h.block le_rfl h.room + apply install _ _ _ _ _ _ _ _ _ _ _ h.block h.room le_rfl (by decide) h.rows h.pitch h.clock + · exact fun _ frame j ↦ BlockHeadStability.refresh_term_stable B h.entry room (h.pitch_before S.steps) le_rfl (by decide) frame j + · exact fun _ frame j ↦ BlockHeadReads.refresh_terms B (h.framedEntry le_rfl frame) room j + +theorem refresh_next_window (h : Ready B base positions blocks t cap m) : + Installed B base positions blocks t S.steps 40 (fun _ : Fin 1 ↦ LevelFields.atLevel (S.steps+1)) + (BlockGroups.refresh B 6) cap m := by + apply install _ _ _ _ _ _ _ _ _ _ _ h.block h.room le_rfl (by decide) h.rows h.pitch h.clock + · exact fun _ frame _ ↦ BlockHeadStability.next_level_stable h.entry (h.pitch_before S.steps) (by decide) frame + · exact fun _ _ _ ↦ BlockHeadReads.level (S.steps+1) + +variable {B} + +theorem Ready.after_publication {N step offset : ℕ} {rhs : Fin N → Expr} {W : Window prog (fieldVisits step offset rhs)} + (h : Ready B base positions blocks t cap m) (group : Installed B base positions blocks t step offset rhs W cap m) : + Ready B base positions blocks t cap (image pub st m (levelStart L (first+step)+offset) rhs) := by + have fit := (levelStart_mono L (Nat.zero_le _)).trans_lt h.room + have controls := Window.lowCells (A:=prog) L base rfl rfl fit + have bound : levelStart L 0 ≤ levelStart L (first+step)+offset := + (levelStart_mono L (Nat.zero_le _)).trans (Nat.le_add_right ..) + exact ⟨h.block,h.room,(group.source.outside _ (.inl (controls.1.trans_le bound))).trans h.rows, + (group.source.outside _ (.inl (controls.2.trans_le bound))).trans h.pitch,h.clock⟩ + +end CompressorRecords.PublishedHeads + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockHeaderFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderFootprint.lean new file mode 100644 index 0000000000..20b9483e78 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderFootprint.lean @@ -0,0 +1,167 @@ +import OAI.Computability.VPVNP.CompressorBlockHeaderRun +import OAI.Computability.VPVNP.CompressorFormulaFootprint + +/-! +# Read and write addresses of the compressor's header visits + +All reads of the initial scalar publisher come from the immutable cursor +bank in level zero. The relabel and successor workers read the old header. +The head publisher reads the new level's dimensions and level zero's +capacity. Their report logs can therefore be replayed on memories agreeing +from the first level header onwards. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockHeaderFootprint + +open BurstRAM Compression PhaseRecipe DescriptorSpace BlockHeaderRun SourceTransport +open scoped Fin.CommRing +open private fields nextVertices from OAI.Computability.VPVNP.CompressorDescriptorScalars +open private loadAt rowCount capacity firstColumn from OAI.Computability.VPVNP.CompressorDescriptorHeads + +variable {w a b c : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + +/-- External addresses at or above the first level header, where descriptor data are read and +written. -/ +abbrev Data (L : Layout) (address : ℕ) := levelStart L 0 ≤ address + +private theorem room (L : Layout) (i : Fin L.levels) (fit : endAddress L < 2^w) : + levelStart L i+levelHeaderWords L < 2^w := by + have h := level_room L fit i + have eqn : levelStart L (i.val+1) = levelStart L i + levelWords L := by + simp [levelStart,Nat.succ_mul,Nat.add_assoc] + rw [eqn] at h + unfold levelWords at h + omega + +private theorem data_cell (L : Layout) (i : Fin L.levels) (fit : endAddress L < 2^w) + {j : ℕ} (hj : j < levelHeaderWords L) : Data L (header w L i + (j : Word w)).val := by + have h := room L i fit + change levelStart L 0 ≤ (((levelStart L i : ℕ) : Word w)+(j : Word w)).val + rw [← Nat.cast_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega)] + exact (levelStart_mono L (Nat.zero_le i.val)).trans (Nat.le_add_right ..) + +private theorem header_from (L : Layout) (base : Word w) (pub : Fin 5 → Word w) (m : Memory w) + (j : ℕ) (h : Data L (base+(j : Word w)).val) : (Expr.header j).ReadsFrom (Data L) pub base m := + ⟨⟨trivial,trivial⟩,h⟩ + +private theorem fields_from (p : Scalars.Pass a b) (x y z : Expr) (data : ℕ → Prop) + (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (hx : x.ReadsFrom data pub s m) (hy : y.ReadsFrom data pub s m) (hz : z.ReadsFrom data pub s m) + (j : Fin 6) : (fields p x y z j).ReadsFrom data pub s m := by + fin_cases j <;> simp [fields,Expr.div,Expr.ReadsFrom,hx,hy,hz] + +private theorem scalar_writes (L : Layout) (i : Fin L.levels) (fit : endAddress L < 2^w) + (six : 6 ≤ L.shape.scalarFields) (src : Word w) (m : Memory w) (row : FormulaRow 3) + (dest : row.dest = .publicWord 0) : + Writes (Data L) (scalarReport row src (header w L i) m).events := by + apply row.report_writes + intro j + rw [dest] + change Data L (header w L i+(j.val : Word w)).val + exact data_cell L i fit (by have := j.isLt; unfold levelHeaderWords; omega) + +theorem initial_scalar (L : Layout) (nonempty : 0 < L.levels) (fourteen : 14 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (p : Scalars.Pass a b) (m : Memory w) : + let base := header w L 0 + let es := (scalarReport (Scalars.initialRow p) (base+6) base m).events + Reads (Data L) es ∧ Writes (Data L) es := by + let z : Fin L.levels := ⟨0,nonempty⟩ + let base := header w L 0 + let pub := scalarPorts base + have load (j : ℕ) (hj : j < 8) : (Expr.header j).ReadsFrom (Data L) pub (base+6) m := by + apply header_from + rw [show base+6+(j : Word w) = header w L 0+((6+j : ℕ) : Word w) by simp [base,add_assoc]] + exact data_cell L z fit (by unfold levelHeaderWords; omega) + constructor + · apply (Scalars.initialRow p).report_reads + · trivial + · intro j + exact fields_from p ((Expr.header 3).mul (.header 4)) (.header 2) (.header 5) (Data L) pub (base+6) m + ⟨load 3 (by decide),load 4 (by decide)⟩ + (load 2 (by decide)) (load 5 (by decide)) j + · exact scalar_writes L z fit (by omega) (base+6) m _ rfl + +theorem advance_scalar (L : Layout) (i j : Fin L.levels) (six : 6 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (p : Scalars.Pass a b) (q : Scalars.Pass b c) (m : Memory w) : + let es := (scalarReport (Scalars.advanceRow p q) (header w L i) (header w L j) m).events + Reads (Data L) es ∧ Writes (Data L) es := by + let pub := scalarPorts (header w L j) + let src := header w L i + have load (x : ℕ) (hx : x < 6) : (Expr.header x).ReadsFrom (Data L) pub src m := + header_from L src pub m x (data_cell L i fit (by unfold levelHeaderWords; omega)) + have count : (nextVertices p).ReadsFrom (Data L) pub src m := by + cases p with + | shrink => exact ⟨load 0 (by decide),trivial⟩ + | refresh => exact ⟨load 0 (by decide),load 1 (by decide)⟩ + | terminal => exact load 0 (by decide) + constructor + · apply (Scalars.advanceRow p q).report_reads + · trivial + · exact fields_from q _ _ _ _ pub src m count (load 4 (by decide)) (load 3 (by decide)) + · exact scalar_writes L j fit six src m _ rfl + +theorem heads (L : Layout) (i : Fin L.levels) (six : 6 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (m : Memory w) : Reads (Data L) (headReport L i m).events ∧ Writes (Data L) (headReport L i m).events := by + let z : Fin L.levels := ⟨0, by have := i.isLt; omega⟩ + let pub := headPorts (header w L i) (header w L 0) + have old (j : ℕ) (hj : j < 3) : (loadAt 0 j).ReadsFrom (Data L) pub 0 m := + ⟨⟨trivial,trivial⟩,data_cell L i fit (by unfold levelHeaderWords; omega)⟩ + have first (j : ℕ) (hj : j < 3) : (loadAt 1 j).ReadsFrom (Data L) pub 0 m := + ⟨⟨trivial,trivial⟩,data_cell L z fit (by unfold levelHeaderWords; omega)⟩ + have nr : rowCount.ReadsFrom (Data L) pub 0 m := ⟨⟨old 0 (by decide),old 2 (by decide)⟩,old 1 (by decide)⟩ + have nc : (capacity L.shape).ReadsFrom (Data L) pub 0 m := ⟨⟨first 0 (by decide),first 2 (by decide)⟩,trivial⟩ + have col : (firstColumn L.shape).ReadsFrom (Data L) pub 0 m := ⟨trivial,trivial⟩ + constructor + · apply (DescriptorHeads.publisher L.shape).report_reads + · exact ⟨trivial,trivial⟩ + · intro j + change (if j.val < 6 then _ else _ : Expr).ReadsFrom (Data L) pub 0 m + by_cases hj : j.val < 6 + · rw [ite_eq_left hj]; exact ⟨col,⟨trivial,nr⟩⟩ + · rw [ite_eq_right hj]; exact ⟨⟨col,⟨trivial,nc⟩⟩,⟨trivial,⟨nc,trivial⟩⟩⟩ + · apply (DescriptorHeads.publisher L.shape).report_writes + intro j + change Data L (header w L i+(L.shape.scalarFields : Word w)+(j.val : Word w)).val + rw [show header w L i+(L.shape.scalarFields : Word w)+(j.val : Word w) = + header w L i+((L.shape.scalarFields+j.val : ℕ) : Word w) by simp [add_assoc]] + exact data_cell L i fit (by unfold levelHeaderWords; have := j.isLt; omega) + +private theorem join_reads {data : ℕ → Prop} {xs ys : List (Event w)} (hx : Reads data xs) (hy : Reads data ys) : + Reads data (xs++ys) := fun a v h ↦ (List.mem_append.mp h).elim (hx a v) (hy a v) + +private theorem join_writes {data : ℕ → Prop} {xs ys : List (Event w)} (hx : Writes data xs) (hy : Writes data ys) : + Writes data (xs++ys) := fun a v h ↦ (List.mem_append.mp h).elim (hx a v) (hy a v) + +/-- The complete three-report header log is confined to the descriptor data +suffix, including reads used to compute array capacities from level zero. -/ +theorem substep (v : SelectedLevel B f hf) (L : Layout) (i j : Fin L.levels) + (six : 6 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) (m : Memory w) : + Reads (Data L) (eventLog (reports v L i j m)) ∧ Writes (Data L) (eventLog (reports v L i j m)) := by + have h₁ := advance_scalar L i i six fit (.terminal v.inputExponent) (Scalars.ofOrigin v.origin) m + have h₂ := advance_scalar L i j six fit (Scalars.ofOrigin v.origin) (.terminal v.outputExponent) + (inputMemory v L i m) + have h₃ := heads L j six fit (outputMemory v L i j m) + simp only [reports,eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] + exact ⟨join_reads h₁.1 (join_reads h₂.1 h₃.1), join_writes h₁.2 (join_writes h₂.2 h₃.2)⟩ + +theorem initial (L : Layout) (nonempty : 0 < L.levels) (fourteen : 14 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (a : ℕ) (m : Memory w) : + let start := header w L 0 + let es := eventLog [scalarReport (Scalars.initialRow (.terminal a)) (start+6) start m, + headReport L 0 (initialMemory a L m)] + Reads (Data L) es ∧ Writes (Data L) es := by + have h₁ := initial_scalar L nonempty fourteen fit (.terminal a) m + have h₂ := heads L ⟨0,nonempty⟩ (by omega) fit (initialMemory a L m) + simp only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] + exact ⟨join_reads h₁.1 h₂.1,join_writes h₁.2 h₂.2⟩ + +end CompressorRecords.BlockHeaderFootprint + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockHeaderPacket.lean b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderPacket.lean new file mode 100644 index 0000000000..c3fccf4fe9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderPacket.lean @@ -0,0 +1,173 @@ +import OAI.Computability.VPVNP.CompressorBlockHeaderFootprint +import OAI.Computability.VPVNP.CompressorSourceSequence + +/-! # Native header packets at their actual script occurrences -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.HeaderPacket + +open BurstRAM PhaseRecipe BlockPlanner BlockHeaderRun DescriptorSpace SourceTransport SourceOnline +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- A worker executes the evaluated public operands and stops at the planner's +exclusive cursor bound. Its actual reads and writes stay in descriptor data. -/ +structure Run (L : Layout) (pub : Fin 5 → Word w) (s : Word w) (v : BlockPlanner.Visit) + (m : Memory w) (rs : List (Report w)) (fuel : ℕ) (bits : List (List Bool)) : Prop where + positive : 0 < fuel + execute : let M := (v.worker.table.instantiate w (fun i ↦ (v.params i).eval pub s m)).program + runSegment M fuel (some (v.initial.eval pub s m)) m bits = some rs + progress : Progress (v.stop.eval pub s m) (v.initial.eval pub s m) rs + read : Reads (levelStart L 0 ≤ ·) (eventLog rs) + write : Writes (levelStart L 0 ≤ ·) (eventLog rs) + +/-- The phase index is an actual occurrence in the catalog, including when +several occurrences share the same native code. -/ +def attach (A : Script) (j : Fin A.size) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (fuel : ℕ) (bits : List (List Bool)) : SourceOnline.Visit A w := + ⟨j,fuel,(A.visit j).initial.eval pub s m,(A.visit j).stop.eval pub s m, + fun i ↦ ((A.visit j).params i).eval pub s m,bits⟩ + +theorem attach_runs {L : Layout} (A : Script) (j : Fin A.size) {v pub s m rs fuel bits} + (occurrence : A.visit j = v) (h : Run (w := w) L pub s v m rs fuel bits) : + (attach A j pub s m fuel bits).Runs m rs := by + subst v + exact h.execute + +theorem attach_checked {L : Layout} (A : Script) (j : Fin A.size) {v pub s m rs fuel bits} + (occurrence : A.visit j = v) (h : Run (w := w) L pub s v m rs fuel bits) (cap : ℕ) + (recipe : (A.plan.recipes j).2.code.length+1+2*Schedule.Online.N A.size A.size+5 ≤ cap) + (clock : fuel+3+4*((A.catalog j).params+1)+2*Schedule.Online.N A.size A.size+5 ≤ cap) : + Checked A L cap ⟨attach A j pub s m fuel bits,m,rs⟩ := by + subst v + exact ⟨h.positive,recipe,clock,h.progress,h.read,h.write⟩ + +theorem singleton {L : Layout} {v : BlockPlanner.Visit} {pub : Fin 5 → Word w} {s : Word w} + {m : Memory w} {r : Report w} {fuel : ℕ} (positive : 0 < fuel) + (run : rawCall v pub s m fuel = some r) + (step : v.initial.eval pub s m < v.stop.eval pub s m) + (ret : r.result = some (v.stop.eval pub s m)) + (rd : Reads (levelStart L 0 ≤ ·) r.events) (wr : Writes (levelStart L 0 ≤ ·) r.events) : + Run L pub s v m [r] fuel [[]] := by + refine ⟨positive,?_,.next step ret (.done le_rfl),?_,?_⟩ + · dsimp only + rw [runSegment] + change (match rawCall v pub s m fuel with + | none => none + | some rep => (some ([] : List (Report w))).map (rep :: ·)) = _ + rw [run]; rfl + · simpa only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] using rd + · simpa only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] using wr + +private theorem succ_active (src : Word w) (fit : src.val+1 < 2^w) : src < src+1 := by + have hi : 1 < 2^w := by omega + apply Fin.lt_def.mpr + change src.val < (src.val + (1 % 2^w)) % 2^w + rw [Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt fit] + omega + +theorem formula (L : Layout) (row : FormulaRow 3) (source dest : PhaseRecipe.Expr) + (pub : Fin 5 → Word w) (s src dst : Word w) (m : Memory w) + (he : source.eval pub s m = src) (fit : src.val+1 < 2^w) + (run : rawCall (BlockHeaderPlan.formula row source dest) pub s m (row.recipe.code.length+1) = + some (scalarReport row src dst m)) + (read : Reads (levelStart L 0 ≤ ·) (scalarReport row src dst m).events) + (write : Writes (levelStart L 0 ≤ ·) (scalarReport row src dst m).events) : + Run L pub s (BlockHeaderPlan.formula row source dest) m [scalarReport row src dst m] + (row.recipe.code.length+1) [[]] := by + apply singleton (Nat.succ_pos _) run _ _ read write + · change source.eval pub s m < source.eval pub s m + ((1 : ℕ) : Word w) + rw [he,Nat.cast_one]; exact succ_active src fit + · change some (src+1) = some (source.eval pub s m + ((1 : ℕ) : Word w)) + rw [he,Nat.cast_one] + +theorem heads {L : Layout} {i : Fin L.levels} (six : 6 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (dest : PhaseRecipe.Expr) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (run : rawCall (BlockHeaderPlan.heads L.shape dest) pub s m ((DescriptorHeads.publisher L.shape).recipe.code.length+1) + = some (headReport L i m)) : + Run L pub s (BlockHeaderPlan.heads L.shape dest) m [headReport L i m] + ((DescriptorHeads.publisher L.shape).recipe.code.length+1) [[]] := by + obtain ⟨rd,wr⟩ := BlockHeaderFootprint.heads L i six fit m + have headRoom := DescriptorSpace.level_room L fit i + have two : 1 < 2^w := by + unfold levelStart levelsBase directoryBase plannerTag frameBase at headRoom + omega + apply singleton (Nat.succ_pos _) run _ _ rd wr + · change 0 % 2^w < 1 % 2^w + rw [Nat.zero_mod,Nat.mod_eq_of_lt two]; decide + · change some ((0 : Word w)+1) = some ((1 : ℕ) : Word w) + simp + +open private fit_fields header_val address_val from OAI.Computability.VPVNP.CompressorBlockHeaderRun + +theorem initial {L : Layout} {a low l : ℕ} {m : Memory w} {nonempty : 0 < L.levels} + {six : 6 ≤ L.shape.scalarFields} (h : Initial a low l L nonempty six m) + (fourteen : 14 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (pub : Fin 5 → Word w) (s : Word w) + (first : BlockHeaderPlan.firstHeader.eval pub s m = header w L 0) + (count : (pub 3).val < levelStart L 0) : + let base := header w L 0 + let row := Scalars.initialRow (.terminal a) + let mid := initialMemory a L m + Run L pub s (BlockHeaderPlan.initialScalars a) m [scalarReport row (base+6) base m] + (row.recipe.code.length+1) [[]] ∧ + Run L pub s (BlockHeaderPlan.heads L.shape BlockHeaderPlan.firstHeader) mid [headReport L 0 mid] + ((DescriptorHeads.publisher L.shape).recipe.code.length+1) [[]] := by + obtain ⟨rs,rh⟩ := h.visits pub s first count + let z : Fin L.levels := ⟨0,nonempty⟩ + have room := fit_fields L z fit + have src : BlockHeaderPlan.persistentFrame.eval pub s m = header w L 0+6 := by + change BlockHeaderPlan.firstHeader.eval pub s m + (6 : Word w) = _ + rw [first] + have next : (header w L 0+6).val+1 < 2^w := by + rw [show (header w L 0+6).val = levelStart L 0+6 from address_val L 0 6 (by change levelStart L 0+_ < _ at room; omega)] + change levelStart L 0+_ < _ at room + omega + obtain ⟨read,write⟩ := BlockHeaderFootprint.initial_scalar L nonempty fourteen fit (.terminal a) m + exact ⟨formula L _ _ _ pub s _ _ m src next rs read write,heads (i := z) six fit _ pub s _ rh⟩ + +open Compression LevelFields + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {R : Type*} + [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + +theorem substep (v : SelectedLevel B f hf) {L : Layout} {i j : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} + {m : Memory w} (run : Substep v L i j six m) (fit : endAddress L < 2^w) + (first step : ℕ) (old : first+step = i.val) (new : first+(step+1) = j.val) + (pub : Fin 5 → Word w) (s : Word w) (entry : Entry L first pub s m) + (head : BlockHeaderPlan.firstHeader.eval pub s m = header w L 0) + (pitch : (pub 1-1).val < levelStart L i) (count : (pub 3).val < levelStart L i) : + let ls := BlockHeaderPlan.substep L.shape step (Scalars.ofOrigin v.origin) + let src := header w L i + let dst := header w L j + let mid := inputMemory v L i m + let next := outputMemory v L i j m + Run L pub s (ls[0]'(by simp [ls])) m [scalarReport (inputRow v) src src m] ((inputRow v).recipe.code.length+1) [[]] ∧ + Run L pub s (ls[1]'(by simp [ls])) mid [scalarReport (outputRow v) src dst mid] ((outputRow v).recipe.code.length+1) [[]] ∧ + Run L pub s (ls[2]'(by simp [ls])) next [headReport L j next] ((DescriptorHeads.publisher L.shape).recipe.code.length+1) [[]] := by + obtain ⟨r₁,r₂,r₃⟩ := run.visits v first step old new pub s entry head pitch count + let mid := inputMemory v L i m + have e₁ : Entry L first pub s mid := + ⟨entry.pointer,(run.relabel.2.2.2.2.1 _ (.inl pitch)).trans entry.pitch⟩ + have src : ∀ {mem : Memory w}, Entry L first pub s mem → (atLevel step).eval pub s mem = header w L i := + fun e ↦ old ▸ eval_atLevel e step + have room : (header w L i).val+1 < 2^w := by + rw [header_val L i fit] + have := fit_fields L i fit + omega + obtain ⟨rd₁,wr₁⟩ := BlockHeaderFootprint.advance_scalar L i i six fit (.terminal v.inputExponent) + (Scalars.ofOrigin v.origin) m + obtain ⟨rd₂,wr₂⟩ := BlockHeaderFootprint.advance_scalar L i j six fit (Scalars.ofOrigin v.origin) + (.terminal v.outputExponent) mid + exact ⟨formula L _ _ _ pub s _ _ m (src entry) room r₁ rd₁ wr₁, + formula L _ _ _ pub s _ _ mid (src e₁) room r₂ rd₂ wr₂,heads (i := j) six fit _ pub s _ r₃⟩ + +end CompressorRecords.HeaderPacket + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockHeaderPlan.lean b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderPlan.lean new file mode 100644 index 0000000000..3d5c2d2498 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderPlan.lean @@ -0,0 +1,100 @@ +import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner +import OAI.Computability.VPVNP.CompressorDescriptorScalars +import OAI.Computability.VPVNP.CompressorDescriptorHeads + +/-! +# Initial and per-substep header visits + +The initial cursor frame occupies scalar offsets six through thirteen. +Every level starts with a scalar visit and an array-head visit. At block +boundaries the next level is published with terminal metadata. Starting +another block relabels the same header in place, so a last block can end +with no residual lanes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockHeaderPlan + +open BurstRAM BurstRAM.PrivateRAM PhaseRecipe BlockPlanner LevelFields DescriptorSpace +open scoped Fin.CommRing + +/-- The address gap from the active frame to the directory is two plus the +catalog arity. Reading the runtime row count therefore locates level zero +without a literal for the arity of the program currently being constructed. -/ +def firstHeader : Expr := + (Expr.publicWord 1).add ((((Expr.publicWord 1).sub (.publicWord 0)).add (.lit 1)).mul (.load + (.publicWord 3))) + +theorem firstHeader_eval {w : ℕ} (L : Layout) (base : Word w) (m : Memory w) (s : Word w) + (hb : base = (L.base : Word w)) + (hr : m (base + 8).val = (directoryRows L : Word w)) : + firstHeader.eval (Workspace.ports L.shape.arity base).data s m = (levelStart L 0 : Word w) := by + change (base+((11+L.shape.arity : ℕ) : Word w)) + + ((base+((11+L.shape.arity : ℕ) : Word w)-(base+9))+1) * m (base+8).val = _ + rw [hr,hb] + simp only [levelStart, levelsBase, directoryBase, plannerTag, frameBase, Nat.zero_mul, + Nat.add_zero, Nat.cast_add, + Nat.cast_mul,Nat.cast_ofNat,Nat.cast_one] + ring + +/-- Address expression for the persistent cursor frame, beginning six words into the first +level header. -/ +def persistentFrame := firstHeader.add (.lit 6) + +/-- A single visit evaluating the supplied formula row at its source cursor and writing to the +destination operand. -/ +def formula {g : ℕ} (row : FormulaRow g) (source dest : Expr) : Visit := + ⟨⟨_,_,_,row.recipe.table⟩,source,source.add (.lit 1),![dest,.lit 0,.lit 0,.lit 0,.lit 0]⟩ + +/-- A single deterministic visit sets the six input scalars of the first level. -/ +def initialScalars (a : ℕ) : Visit := + formula (Scalars.initialRow (.terminal a)) persistentFrame firstHeader + +/-- A single visit publishing the current level's array pointers from the current and initial +level headers. -/ +def heads (F : Shape) (current : Expr) : Visit := + ⟨DescriptorHeads.worker F,.lit 0,.lit 1,![current,firstHeader,.lit 0,.lit 0,.lit 0]⟩ + +/-- The startup sequence that publishes initial scalar dimensions, publishes array heads and +scans the persistent cursor frame. -/ +def initial (F : Shape) (a : ℕ) : List Visit := + [initialScalars a, heads F firstHeader, BlockPlanner.cursor persistentFrame] + +/-- The source and destination may agree on the first visit of a block. The +formula row reads all six scalars before it begins the contiguous writes. -/ +def update {a b c : ℕ} (p : Scalars.Pass a b) (q : Scalars.Pass b c) (source dest : Expr) : Visit := + formula (Scalars.advanceRow p q) source dest + +/-- Start a fixed substep by installing its input metadata, then publish +terminal metadata and the incidence/record heads of the next level. -/ +def substep {a b : ℕ} (F : Shape) (step : ℕ) (p : Scalars.Pass a b) : List Visit := + let old := atLevel step + let next := atLevel (step+1) + [update (.terminal a) p old old, update p (.terminal b) old next, heads F next] + +theorem initial_length (F : Shape) (a : ℕ) : (initial F a).length = 3 := rfl +@[simp] theorem substep_length {a b : ℕ} (F : Shape) (step : ℕ) (p : Scalars.Pass a b) : + (substep F step p).length = 3 := rfl + +theorem substep_operands {a b w : ℕ} (F : Shape) (p : Scalars.Pass a b) (step : ℕ) + {L : Layout} {first : ℕ} {pub : Fin 5 → Word w} {state : Word w} {m : Memory w} + (e : Entry L first pub state m) : + ((substep F step p)[0]).initial.eval pub state m = (levelStart L (first+step) : Word w) ∧ + (((substep F step p)[0]).params (0 : Fin 5)).eval pub state m = (levelStart L (first+step) + : Word w) ∧ + ((substep F step p)[1]).initial.eval pub state m = (levelStart L (first+step) : Word w) ∧ + (((substep F step p)[1]).params (0 : Fin 5)).eval pub state m = (levelStart L (first+(step+1)) + : Word w) ∧ + (((substep F step p)[2]).params (0 : Fin 5)).eval pub state m = (levelStart L (first+(step+1)) + : Word w) := + ⟨eval_atLevel e step,eval_atLevel e step,eval_atLevel e step,eval_atLevel e + (step+1),eval_atLevel e (step+1)⟩ + +end CompressorRecords.BlockHeaderPlan + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockHeaderRun.lean b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderRun.lean new file mode 100644 index 0000000000..0e9e07fb78 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderRun.lean @@ -0,0 +1,560 @@ +import OAI.Computability.VPVNP.CompressorBlockHeaderPlan +import OAI.Computability.VPVNP.CompressorSourceWalk + +/-! +# Chronological publication of selected compressor level headers + +The input header of each substep begins in terminal format. The first visit +relabels it in place using the selected pass. The second visit computes the +output state's terminal scalars. The third visits the new header and writes +its incidence and table pointers using the initial level's capacities. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockHeaderRun + +open BurstRAM BurstRAM.PrivateRAM Compression PhaseRecipe DescriptorSpace LevelFields +open scoped Fin.CommRing + +variable {w a b : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + +/-- The machine-word address of the start of level `i`. -/ +def header (w : ℕ) (L : Layout) (i : ℕ) : Word w := (levelStart L i : Word w) +/-- Public operand bank for a scalar publisher, with the destination header in operand zero. -/ +def scalarPorts (dest : Word w) : Fin 5 → Word w := ![dest,0,0,0,0] +/-- Public operand bank for the pointer publisher, carrying the destination header and the +first level header. -/ +def headPorts (dest first : Word w) : Fin 5 → Word w := ![dest,first,0,0,0] + +private theorem span (L : Layout) (i : ℕ) : + levelStart L i + L.shape.scalarFields ≤ levelStart L (i+1) := by + change levelsBase L + i*levelWords L + L.shape.scalarFields ≤ levelsBase L + (i+1)*levelWords L + have h : L.shape.scalarFields ≤ levelWords L := by unfold levelWords levelHeaderWords; omega + rw [Nat.succ_mul]; omega + +private theorem fit_fields (L : Layout) (i : Fin L.levels) (fit : endAddress L < 2^w) : + levelStart L i + L.shape.scalarFields < 2^w := (span L i).trans_lt (level_room L fit i) + +private theorem address_val (L : Layout) (i n : ℕ) (h : levelStart L i+n < 2^w) : + (header w L i+(n : Word w)).val = levelStart L i+n := by + change (((levelStart L i : ℕ) : Word w)+(n : Word w)).val = _ + rw [← Nat.cast_add, Fin.val_natCast,Nat.mod_eq_of_lt h] + +private theorem header_val (L : Layout) (i : Fin L.levels) (fit : endAddress L < 2^w) : + (header w L i).val = levelStart L i := Nat.mod_eq_of_lt (by have := fit_fields L i fit; omega) + +private theorem as_word {z : Word w} {n : ℕ} (h : z.val = n) : z = (n : Word w) := by + subst n + exact Fin.ext (Nat.mod_eq_of_lt z.isLt).symm + +theorem present_counts {p : Scalars.Pass a b} {V l : ℕ} {base : Word w} {m : Memory w} + (h : Scalars.Present p V l base m) : DescriptorHeads.CountsAt base m V (2^a) (2^l) := by + have hw (i : Fin 6) := as_word (h i) + constructor + · simpa [headerCell,Scalars.values] using hw 0 + · simpa [headerCell,Scalars.values] using hw 1 + · simpa [headerCell,Scalars.values] using hw 2 + +private theorem keep_counts {base : Word w} {m out : Memory w} {V D lanes : ℕ} + (h : DescriptorHeads.CountsAt base m V D lanes) + (keep : ∀ i : Fin 3, out (base+(i.val : Word w)).val = m (base+(i.val : Word w)).val) : + DescriptorHeads.CountsAt base out V D lanes := by + have h₀ : out base.val = m base.val := by simpa using keep 0 + have h₁ : out (base+1).val = m (base+1).val := by simpa using keep 1 + have h₂ : out (base+2).val = m (base+2).val := by simpa using keep 2 + exact ⟨h₀.trans h.vertices,h₁.trans h.degree,h₂.trans h.replicas⟩ + +/-- The pass origin identifies the lane count remaining in the actual output +state. This converts six natural scalar loads to the consumer's typed header. -/ +theorem published_of_present (L : Layout) (i : Fin L.levels) (six : 6 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (v : SelectedLevel B f hf) (m : Memory w) + (h : Scalars.Present (Scalars.ofOrigin v.origin) (Fintype.card v.input.Base) v.inputLanes (header w L i) m) : + Published L i v (Scalars.ofOrigin v.origin).expanderDegree m := by + let p := Scalars.ofOrigin v.origin + have room := fit_fields L i fit + have read (j : Fin 6) : + m (levelStart L i+j.val) = (Scalars.values p (Fintype.card v.input.Base) v.inputLanes j : Word w) := by + have eqn := as_word (h j) + change m (header w L i+(j.val : Word w)).val = _ at eqn + rwa [address_val L i j.val (by have := j.isLt; omega)] at eqn + have lane := (Scalars.origin_counts v.origin v.term).1 + have rem : v.inputLanes-p.spent = v.outputLanes := by change v.inputLanes = p.spent+v.outputLanes at lane; omega + refine ⟨by omega,read 0,read 1,read 2,?_,read 4,read 5⟩ + simpa [Scalars.values,rem] using read 3 + +/-- Report of the native six-scalar publisher. Its result is the next cursor +relative to the supplied source, even when source and destination coincide. -/ +def scalarReport (row : FormulaRow 3) (src dest : Word w) (m : Memory w) := + row.recipe.report (scalarPorts dest) src m + +/-- The pointer publisher's report for level `i`, evaluated at cursor zero in the supplied +memory. -/ +def headReport (L : Layout) (i : ℕ) (m : Memory w) := + (DescriptorHeads.publisher L.shape).recipe.report (headPorts (header w L i) (header w L 0)) 0 m + +/-- Physical effects of the incidence/table pointer visit. -/ +structure HeadsRun (L : Layout) (i : Fin L.levels) (rows : ℕ) (m : Memory w) : Prop where + execute : let row := DescriptorHeads.publisher L.shape + let M := (row.recipe.table.instantiate w (headPorts (header w L i) (header w L 0))).program + BurstRAM.execute M (row.recipe.code.length+1) (M.start 0) m [] = some (headReport L i m) + result : (headReport L i m).result = some 1 + incidence : ∀ j : Fin 6, after m (headReport L i m).events (incidenceHead L i j) = + (incidenceBase L i rows j : Word w) + tables : ∀ j : Fin L.shape.tables, after m (headReport L i m).events (tableHead L i j) = + (tableBase L i j : Word w) + outside : ∀ x, x < levelStart L i + L.shape.scalarFields ∨ incidenceStart L i ≤ x → + after m (headReport L i m).events x = m x + cost : let row := DescriptorHeads.publisher L.shape + (headReport L i m).events.length = row.recipe.code.length ∧ + (headReport L i m).probes = row.recipe.reads+(L.shape.tables+3+3) ∧ choiceBits (headReport L i m).events = [] + +theorem heads_run (L : Layout) (i : Fin L.levels) (m : Memory w) (fit : endAddress L < 2^w) + {V D lanes V₀ D₀ lanes₀ : ℕ} (h : DescriptorHeads.CountsAt (header w L i) m V D lanes) + (h₀ : DescriptorHeads.CountsAt (header w L 0) m V₀ D₀ lanes₀) (hP : V₀*lanes₀ = L.positions) : + HeadsRun L i (V*lanes*D) m := by + obtain ⟨he,hr,hi,ht,hf,hc⟩ := DescriptorHeads.publish L i (headPorts (header w L i) (header w L 0)) m 0 fit + rfl rfl h h₀ hP + exact ⟨he,by simpa only [headReport,zero_add] using hr,hi,ht,hf,hc⟩ + +private theorem keep_present {p : Scalars.Pass a b} {V l : ℕ} {base : Word w} {m out : Memory w} + (input : Scalars.Present p V l base m) + (keep : ∀ j : Fin 6, out (base+(j.val : Word w)).val = m (base+(j.val : Word w)).val) : + Scalars.Present p V l base out := by + intro j + change (out (base+(j.val : Word w)).val).val = _ + rw [keep] + exact input j + +private theorem counts_agree {base : Word w} {m out : Memory w} {V D lanes : ℕ} + (h : DescriptorHeads.CountsAt base m V D lanes) (h' : DescriptorHeads.CountsAt base out V D lanes) + (i : Fin 3) : out (base+(i.val : Word w)).val = m (base+(i.val : Word w)).val := by + fin_cases i + · simpa using h'.vertices.trans h.vertices.symm + · exact h'.degree.trans h.degree.symm + · exact h'.replicas.trans h.replicas.symm + +variable (v : SelectedLevel B f hf) + +/-- Scalar formula converting the input's terminal header to the selected pass's header format. -/ +def inputRow := Scalars.advanceRow (.terminal v.inputExponent) (Scalars.ofOrigin v.origin) +/-- Scalar formula advancing from the selected pass's header format to the successor's terminal +format. -/ +def outputRow := Scalars.advanceRow (Scalars.ofOrigin v.origin) (.terminal v.outputExponent) + +/-- Memory after relabeling the input level's scalar header in place. -/ +def inputMemory (L : Layout) (i : ℕ) (m : Memory w) := + after m (scalarReport (inputRow v) (header w L i) (header w L i) m).events + +/-- Memory after the input relabel and the publication of the successor's terminal scalars. -/ +def outputMemory (L : Layout) (i j : ℕ) (m : Memory w) := + let m₁ := inputMemory v L i m + after m₁ (scalarReport (outputRow v) (header w L i) (header w L j) m₁).events + +/-- Memory after both scalar visits and the successor's incidence and table pointer +publication. -/ +def finalMemory (L : Layout) (i j : ℕ) (m : Memory w) := + let m₂ := outputMemory v L i j m + after m₂ (headReport L j m₂).events + +/-- All three reports execute with the actual post-memory of their predecessor. +The published input fields express the selected pass, and the output's terminal +fields can serve as the input of the next substep. -/ +structure Substep (L : Layout) (i j : Fin L.levels) (six : 6 ≤ L.shape.scalarFields) + (m : Memory w) : Prop where + relabel : Scalars.Publishes L i six (inputRow v) (Scalars.ofOrigin v.origin) + (Fintype.card v.input.Base) v.inputLanes (scalarPorts (header w L i)) (header w L i) m + advance : Scalars.Publishes L j six (outputRow v) (.terminal v.outputExponent) + (Fintype.card (v.pass.next v.term).Base) v.outputLanes + (scalarPorts (header w L j)) (header w L i) (inputMemory v L i m) + heads : HeadsRun L j v.outputSlots (outputMemory v L i j m) + input : Published L i v (Scalars.ofOrigin v.origin).expanderDegree (finalMemory v L i j m) + output : Scalars.Present (.terminal v.outputExponent) (Fintype.card (v.pass.next v.term).Base) v.outputLanes + (header w L j) (finalMemory v L i j m) + firstCounts : ∀ t : Fin 3, finalMemory v L i j m (header w L 0+(t.val : Word w)).val = + m (header w L 0+(t.val : Word w)).val + outside : ∀ x, (x < levelStart L i ∨ levelStart L i+6 ≤ x) → + (x < levelStart L j ∨ levelStart L j+6 ≤ x) → + (x < levelStart L j+L.shape.scalarFields ∨ incidenceStart L j ≤ x) → + finalMemory v L i j m x = m x + +theorem substep_run (L : Layout) (i j : Fin L.levels) (next : i.val+1 = j.val) + (six : 6 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) (m : Memory w) + (input : Scalars.Present (.terminal v.inputExponent) (Fintype.card v.input.Base) v.inputLanes (header w L i) m) + {V₀ D₀ lanes₀ : ℕ} (h₀ : DescriptorHeads.CountsAt (header w L 0) m V₀ D₀ lanes₀) + (hP : V₀*lanes₀ = L.positions) (sites : v.input.positions < 2^w) (slots : slotDegree S < 2^w) : + Substep v L i j six m := by + let p := Scalars.ofOrigin v.origin + let m₁ := inputMemory v L i m + let m₂ := outputMemory v L i j m + let m₃ := finalMemory v L i j m + have spent := (Scalars.origin_counts v.origin v.term).1 + change v.inputLanes = p.spent+v.outputLanes at spent + have fs := Scalars.fits_selected v sites slots + have h1 : Scalars.Publishes L i six (inputRow v) p (Fintype.card v.input.Base) v.inputLanes + (scalarPorts (header w L i)) (header w L i) m := by + simpa only [inputRow,p,Scalars.Pass.baseFactor, Nat.mul_one, Scalars.Pass.spent, Nat.sub_zero] using + Scalars.advance L i six fit (.terminal v.inputExponent) p (scalarPorts (header w L i)) (header w L i) m + (header_val L i fit) input (by change p.spent ≤ v.inputLanes-0; omega) + (by simpa only [Scalars.Pass.baseFactor,Nat.mul_one,Scalars.Pass.spent,Nat.sub_zero] using fs) + have live : Scalars.Present p (Fintype.card v.input.Base) v.inputLanes (header w L i) m₁ := + h1.2.2.2.1 + have targetFit : Scalars.Fits (.terminal v.outputExponent) (Fintype.card (v.pass.next v.term).Base) + v.outputLanes w := Scalars.fits_state _ _ (v.outputSites_le.trans_lt sites) + (v.outputDegree_le.trans_lt slots) (v.outputDegree_le.trans_lt slots) (Nat.two_pow_pos _) + have h2 := Scalars.advance_selected v.origin v.term (.terminal v.outputExponent) L j six fit + (scalarPorts (header w L j)) (header w L i) m₁ (header_val L j fit) live (Nat.zero_le _) targetFit + have successor : Scalars.Present (.terminal v.outputExponent) (Fintype.card (v.pass.next v.term).Base) + v.outputLanes (header w L j) m₂ := h2.2.2.2.1 + have before := span L i + rw [next] at before + have zeroLe := levelStart_mono L (Nat.zero_le i.val) + let z : Fin L.levels := ⟨0, by have := i.isLt; omega⟩ + have zeroRoom : levelStart L 0+L.shape.scalarFields < 2^w := fit_fields L z fit + have oldRoom := fit_fields L i fit + have newRoom := fit_fields L j fit + have c₁ : DescriptorHeads.CountsAt (header w L 0) m₁ V₀ D₀ lanes₀ := by + apply keep_counts h₀ + intro t + by_cases eqn : i.val = 0 + · have hsame := counts_agree (present_counts input) (present_counts live) t + simpa only [eqn] using hsame + · have le := levelStart_mono L (show 1 ≤ i.val by omega) + have sep : levelStart L 0+L.shape.scalarFields ≤ levelStart L 1 := span L 0 + rw [address_val L 0 t.val (by have := t.isLt; omega)] + exact h1.2.2.2.2.1 _ (.inl (by have := t.isLt; omega)) + have c₂ : DescriptorHeads.CountsAt (header w L 0) m₂ V₀ D₀ lanes₀ := by + apply keep_counts c₁ + intro t + rw [address_val L 0 t.val (by have := t.isLt; omega)] + exact h2.2.2.2.2.1 _ (.inl (by have := t.isLt; omega)) + have head := heads_run L j m₂ fit (present_counts successor) c₂ hP + have outSlots : Fintype.card (v.pass.next v.term).Base * 2^v.outputLanes * 2^v.outputExponent = v.outputSlots := by + rw [SelectedLevel.outputSlots,SelectedLevel.outputSites,State.positions,Fintype.card_prod, + Fintype.card_congr (bitWordFinEquiv _),Fintype.card_fin] + refine ⟨h1,h2,outSlots ▸ head,?_,?_,?_,?_⟩ + · apply published_of_present L i six fit v m₃ + apply keep_present live + intro t + rw [address_val L i t.val (by have := t.isLt; omega)] + exact (head.outside _ (.inl (by have := t.isLt; omega))).trans + (h2.2.2.2.2.1 _ (.inl (by have := t.isLt; omega))) + · apply keep_present successor + intro t + rw [address_val L j t.val (by have := t.isLt; omega)] + exact head.outside _ (.inl (by have := t.isLt; omega)) + · intro t + rw [← counts_agree h₀ c₂ t] + exact head.outside _ (.inl (by + rw [address_val L 0 t.val (by have := t.isLt; omega)] + have := t.isLt; omega)) + · intro x hx hy hz + exact (head.outside _ hz).trans ((h2.2.2.2.2.1 _ hy).trans (h1.2.2.2.2.1 _ hx)) + +/-- All completed earlier levels and the schedule directory keep their exact +word values throughout this three-visit substep. -/ +theorem Substep.before {L : Layout} {i j : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} + {m : Memory w} (run : Substep v L i j six m) (next : i.val+1 = j.val) (x : ℕ) + (hx : x < levelStart L i) : finalMemory v L i j m x = m x := by + have le := levelStart_mono L (show i.val ≤ j.val by omega) + exact run.outside x (.inl hx) (.inl (by omega)) (.inl (by omega)) + +/-- Immutable scalar cells beyond the six mutable fields survive all three +visits. These include the saved parameter bank and the arena-base word. -/ +theorem Substep.firstScalarTail {L : Layout} {i j : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} + {m : Memory w} (run : Substep v L i j six m) (next : i.val+1 = j.val) (x : ℕ) + (lo : 6 ≤ x) (hi : x < L.shape.scalarFields) : + finalMemory v L i j m (levelStart L 0+x) = m (levelStart L 0+x) := by + have sep : levelStart L 0+L.shape.scalarFields ≤ levelStart L 1 := span L 0 + have nj := levelStart_mono L (show 1 ≤ j.val by omega) + apply run.outside + · by_cases eqn : i.val = 0 + · exact .inr (by rw [eqn]; omega) + · have oi := levelStart_mono L (show 1 ≤ i.val by omega) + exact .inl (by omega) + · exact .inl (by omega) + · exact .inl (by omega) + +theorem Substep.olderPublished {L : Layout} {i j : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} + {m : Memory w} (run : Substep v L i j six m) (next : i.val+1 = j.val) {n dH : ℕ} + {previous : SelectedLevel B f hf} (old : n < i.val) (prev : Published L n previous dH m) : + Published L n previous dH (finalMemory v L i j m) := by + have le := levelStart_mono L (show n+1 ≤ i.val by omega) + have span' := span L n + have keep (x : ℕ) (hx : x < 6) := run.before v next (levelStart L n+x) (by omega) + exact ⟨prev.room,(keep 0 (by decide)).trans prev.vertices,(keep 1 (by decide)).trans prev.degree, + (keep 2 (by decide)).trans prev.lanes,(keep 3 (by decide)).trans prev.residual, + (keep 4 (by decide)).trans prev.nextDegree,(keep 5 (by decide)).trans prev.expander⟩ + +/-- The original eight cursor parameters stay available at the first header +even when the current substep relabels level zero itself. -/ +theorem Substep.cursorFrame {L : Layout} {i j : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} + {m : Memory w} (run : Substep v L i j six m) (next : i.val+1 = j.val) + (fourteen : 14 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) : + (Frame.data (header w L 0+6) (finalMemory v L i j m) : Fin 8 → Word w) = + Frame.data (header w L 0+6) m := by + funext t + let z : Fin L.levels := ⟨0,by have := i.isLt; omega⟩ + have hroom : levelStart L 0+L.shape.scalarFields < 2^w := fit_fields L z fit + have addr : (header w L 0+6+(t.val : Word w)).val = levelStart L 0+(6+t.val) := by + rw [show header w L 0+6+(t.val : Word w) = header w L 0+((6+t.val : ℕ) : Word w) by + simp [add_assoc]] + exact address_val L 0 _ (by have := t.isLt; omega) + change finalMemory v L i j m (header w L 0+6+(t.val : Word w)).val = _ + change _ = m (header w L 0+6+(t.val : Word w)).val + rw [addr] + exact run.firstScalarTail v next (6+t.val) (by omega) (by have := t.isLt; omega) + +/-- The three chronological reports for a selected substep, each computed from the preceding +visit's output memory. -/ +def reports (L : Layout) (i j : ℕ) (m : Memory w) : List (Report w) := + [scalarReport (inputRow v) (header w L i) (header w L i) m, + scalarReport (outputRow v) (header w L i) (header w L j) (inputMemory v L i m), + headReport L j (outputMemory v L i j m)] + +theorem reports_after (L : Layout) (i j : ℕ) (m : Memory w) : + after m (eventLog (reports v L i j m)) = finalMemory v L i j m := by + simp [reports,eventLog,after,List.foldl_append,finalMemory,outputMemory,inputMemory] + +/-- Memory after the level-zero scalar publisher reads the cursor frame and initializes the +first header. -/ +def initialMemory (a : ℕ) (L : Layout) (m : Memory w) := + let start := header w L 0 + after m (scalarReport (Scalars.initialRow (.terminal a)) (start+6) start m).events + +/-- Memory after the initial scalars and level-zero incidence and table pointers have been +published. -/ +def initialFinal (a : ℕ) (L : Layout) (m : Memory w) := + let mid := initialMemory a L m + after mid (headReport L 0 mid).events + +/-- The first two raw workers in the initial calendar sequence. They install +level zero's terminal scalars and heads and retain its eight cursor parameters. -/ +structure Initial (a low l : ℕ) (L : Layout) (nonempty : 0 < L.levels) + (six : 6 ≤ L.shape.scalarFields) (m : Memory w) : Prop where + scalarRun : Scalars.Publishes L ⟨0,nonempty⟩ six (Scalars.initialRow (.terminal a)) (.terminal a) + ((low+l)*2^low) l (scalarPorts (header w L 0)) (header w L 0+6) m + heads : HeadsRun L ⟨0,nonempty⟩ (((low+l)*2^low)*2^l*2^a) (initialMemory a L m) + terminal : Scalars.Present (.terminal a) ((low+l)*2^low) l (header w L 0) (initialFinal a L m) + cursorFrame : (Frame.data (header w L 0+6) (initialFinal a L m) : Fin 8 → Word w) = + Frame.data (header w L 0+6) m + outside : ∀ x, (x < levelStart L 0 ∨ levelStart L 0+6 ≤ x) → + (x < levelStart L 0+L.shape.scalarFields ∨ incidenceStart L 0 ≤ x) → initialFinal a L m x = m x + +theorem initial_run (L : Layout) (nonempty : 0 < L.levels) (fourteen : 14 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (m : Memory w) (a low l : ℕ) {row tag : Word w} {width start : ℕ} + (frame : Frame.data (header w L 0+6) m = CursorRAM.ScheduleInit.inputs row tag low l a width start) + (positions : ((low+l)*2^low)*2^l = L.positions) + (scalars : Scalars.Fits (.terminal a) ((low+l)*2^low) l w) : + Initial a low l L nonempty (by omega) m := by + let z : Fin L.levels := ⟨0,nonempty⟩ + let src := header w L 0 + let mid := initialMemory a L m + have six : 6 ≤ L.shape.scalarFields := by omega + have hs := Scalars.initialize_level L nonempty six fit (.terminal a) (scalarPorts src) (src+6) m + (header_val L z fit) frame (Nat.zero_le l) scalars + have live : Scalars.Present (.terminal a) ((low+l)*2^low) l src mid := hs.2.2.2.1 + have cnt := present_counts live + have head := heads_run L z mid fit cnt cnt positions + have room : levelStart L 0+L.shape.scalarFields < 2^w := fit_fields L z fit + refine ⟨hs,head,?_,?_,?_⟩ + · apply keep_present live + intro j + rw [show (src+(j.val : Word w)).val = levelStart L 0+j.val from address_val L 0 _ (by have := j.isLt; omega)] + exact head.outside (levelStart L 0+j.val) (.inl (by change _ < levelStart L 0+L.shape.scalarFields; have := j.isLt; omega)) + · funext t + have haddr : (src+6+(t.val : Word w)).val = levelStart L 0+(6+t.val) := by + rw [show src+6+(t.val : Word w) = header w L 0+((6+t.val : ℕ) : Word w) by simp [src,add_assoc]] + exact address_val L 0 _ (by have := t.isLt; omega) + change initialFinal a L m (src+6+(t.val : Word w)).val = m (src+6+(t.val : Word w)).val + rw [haddr] + exact (head.outside (levelStart L 0+(6+t.val)) (.inl (by + change _ < levelStart L 0+L.shape.scalarFields; have := t.isLt; omega))).trans + (hs.2.2.2.2.1 (levelStart L 0+(6+t.val)) (.inr (by change levelStart L 0+6 ≤ _; omega))) + · intro x hx hy + exact (head.outside _ hy).trans (hs.2.2.2.2.1 _ hx) + +theorem Initial.scalarTail {a low l : ℕ} {L : Layout} {nonempty : 0 < L.levels} {six : 6 ≤ L.shape.scalarFields} + {m : Memory w} (run : Initial a low l L nonempty six m) (x : ℕ) (lo : 6 ≤ x) + (hi : x < L.shape.scalarFields) : initialFinal a L m (levelStart L 0+x) = m (levelStart L 0+x) := + run.outside _ (.inr (by omega)) (.inl (by omega)) + +/-- Evaluate the actual visit's operand bank and starting cursor, then enter +its native worker. All operand expressions use this visit's entry memory. -/ +def rawCall (visit : BlockPlanner.Visit) (pub : Fin 5 → Word w) (state : Word w) + (m : Memory w) (fuel : ℕ) := + let data := fun j ↦ (visit.params j).eval pub state m + let M := (visit.worker.table.instantiate w data).program + execute M fuel (M.start (visit.initial.eval pub state m)) m [] + +private theorem raw_formula (row : FormulaRow 3) (src dest : Expr) (pub : Fin 5 → Word w) + (state : Word w) (m : Memory w) (fuel : ℕ) : + let M := (row.recipe.table.instantiate w (scalarPorts (dest.eval pub state m))).program + rawCall (BlockHeaderPlan.formula row src dest) pub state m fuel = + execute M fuel (M.start (src.eval pub state m)) m [] := by + have bank : (fun j : Fin 5 ↦ ((BlockHeaderPlan.formula row src dest).params j).eval pub state m) = + scalarPorts (dest.eval pub state m) := by + funext j; fin_cases j <;> rfl + exact congrArg (fun data : Fin 5 → Word w ↦ + let M := (row.recipe.table.instantiate w data).program + execute M fuel (M.start (src.eval pub state m)) m []) bank + +private theorem raw_heads (F : Shape) (dst : Expr) (pub : Fin 5 → Word w) + (state : Word w) (m : Memory w) (fuel : ℕ) : + let bank := headPorts (dst.eval pub state m) (BlockHeaderPlan.firstHeader.eval pub state m) + let M := ((DescriptorHeads.publisher F).recipe.table.instantiate w bank).program + rawCall (BlockHeaderPlan.heads F dst) pub state m fuel = execute M fuel (M.start 0) m [] := by + have bank : (fun j : Fin 5 ↦ ((BlockHeaderPlan.heads F dst).params j).eval pub state m) = + headPorts (dst.eval pub state m) (BlockHeaderPlan.firstHeader.eval pub state m) := by + funext j; fin_cases j <;> rfl + exact congrArg (fun data : Fin 5 → Word w ↦ + let M := ((DescriptorHeads.publisher F).recipe.table.instantiate w data).program + execute M fuel (M.start 0) m []) bank + +private theorem firstHeader_keep (pub : Fin 5 → Word w) (state : Word w) (m out : Memory w) + (h : out (pub 3).val = m (pub 3).val) : + BlockHeaderPlan.firstHeader.eval pub state out = BlockHeaderPlan.firstHeader.eval pub state m := by + simp only [BlockHeaderPlan.firstHeader,Expr.add,Expr.sub,Expr.mul,Expr.eval,h] + +/-- The three native executions use exactly the public operands and cursors of +the compiled block plan. The two directory control cells lie before the level +headers and survive the preceding raw visits. -/ +theorem Substep.visits {L : Layout} {i j : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} {m : Memory w} + (run : Substep v L i j six m) (first step : ℕ) (old : first+step = i.val) (new : first+(step+1) = j.val) + (pub : Fin 5 → Word w) (state : Word w) (entry : Entry L first pub state m) + (hFirst : BlockHeaderPlan.firstHeader.eval pub state m = header w L 0) + (pitch : (pub 1-1).val < levelStart L i) (count : (pub 3).val < levelStart L i) : + let ls := BlockHeaderPlan.substep L.shape step (Scalars.ofOrigin v.origin) + let src := header w L i + let dst := header w L j + let m₁ := inputMemory v L i m + let m₂ := outputMemory v L i j m + rawCall (ls[0]'(by simp [ls])) pub state m ((inputRow v).recipe.code.length+1) = + some (scalarReport (inputRow v) src src m) ∧ + rawCall (ls[1]'(by simp [ls])) pub state m₁ ((outputRow v).recipe.code.length+1) = + some (scalarReport (outputRow v) src dst m₁) ∧ + rawCall (ls[2]'(by simp [ls])) pub state m₂ ((DescriptorHeads.publisher L.shape).recipe.code.length+1) = + some (headReport L j m₂) := by + let m₁ := inputMemory v L i m + let m₂ := outputMemory v L i j m + have before := levelStart_mono L (show i.val ≤ j.val by omega) + have eq₁ (x : ℕ) (hx : x < levelStart L i) : m₁ x = m x := run.relabel.2.2.2.2.1 x (.inl hx) + have eq₂ (x : ℕ) (hx : x < levelStart L i) : m₂ x = m x := + (run.advance.2.2.2.2.1 x (.inl (by omega))).trans (eq₁ _ hx) + have e₁ : Entry L first pub state m₁ := ⟨entry.pointer,(eq₁ _ pitch).trans entry.pitch⟩ + have e₂ : Entry L first pub state m₂ := ⟨entry.pointer,(eq₂ _ pitch).trans entry.pitch⟩ + have oldAt {mem : Memory w} (e : Entry L first pub state mem) : + (atLevel step).eval pub state mem = header w L i := old ▸ eval_atLevel e step + have newAt {mem : Memory w} (e : Entry L first pub state mem) : + (atLevel (step+1)).eval pub state mem = header w L j := new ▸ eval_atLevel e (step+1) + refine ⟨?_,?_,?_⟩ + · change rawCall (BlockHeaderPlan.formula (inputRow v) (atLevel step) (atLevel step)) _ _ _ _ = _ + rw [raw_formula,oldAt entry]; exact run.relabel.1 + · change rawCall (BlockHeaderPlan.formula (outputRow v) (atLevel step) (atLevel (step+1))) pub state m₁ _ = _ + rw [raw_formula,newAt e₁,oldAt e₁]; exact run.advance.1 + · change rawCall (BlockHeaderPlan.heads L.shape (atLevel (step+1))) pub state m₂ _ = _ + rw [raw_heads,newAt e₂,firstHeader_keep pub state m m₂ (eq₂ _ count),hFirst] + exact run.heads.execute + +theorem Initial.visits {a low l : ℕ} {L : Layout} {nonempty : 0 < L.levels} {six : 6 ≤ L.shape.scalarFields} + {m : Memory w} (run : Initial a low l L nonempty six m) (pub : Fin 5 → Word w) (state : Word w) + (hFirst : BlockHeaderPlan.firstHeader.eval pub state m = header w L 0) + (count : (pub 3).val < levelStart L 0) : + let ls := BlockHeaderPlan.initial L.shape a + let src := header w L 0 + let row := Scalars.initialRow (.terminal a) + rawCall (ls[0]'(by simp [ls,BlockHeaderPlan.initial])) pub state m (row.recipe.code.length+1) = + some (scalarReport row (src+6) src m) ∧ + rawCall (ls[1]'(by simp [ls,BlockHeaderPlan.initial])) pub state (initialMemory a L m) + ((DescriptorHeads.publisher L.shape).recipe.code.length+1) = some (headReport L 0 (initialMemory a L m)) := by + let mid := initialMemory a L m + have hMid := firstHeader_keep pub state m mid (run.scalarRun.2.2.2.2.1 _ (.inl count)) + constructor + · change rawCall (BlockHeaderPlan.formula _ BlockHeaderPlan.persistentFrame BlockHeaderPlan.firstHeader) _ _ _ _ = _ + have hs : BlockHeaderPlan.persistentFrame.eval pub state m = header w L 0+6 := by + change BlockHeaderPlan.firstHeader.eval pub state m + ((6 : ℕ) : Word w) = _ + rw [hFirst]; rfl + rw [raw_formula,hFirst,hs] + exact run.scalarRun.1 + · change rawCall (BlockHeaderPlan.heads L.shape BlockHeaderPlan.firstHeader) pub state mid _ = _ + rw [raw_heads,hMid,hFirst]; exact run.heads.execute + +/-- After the two initialization reports, the third visit reads the eight +immutable parameter words from the first header. Its bound and its eleven +public operands are exactly those of the native cursor-incidence scan. -/ +theorem Initial.cursor {a low l : ℕ} {L : Layout} {nonempty : 0 < L.levels} {six : 6 ≤ L.shape.scalarFields} + {m : Memory w} (run : Initial a low l L nonempty six m) (pub : Fin 5 → Word w) (state : Word w) + (hFirst : BlockHeaderPlan.firstHeader.eval pub state m = header w L 0) + (count : (pub 3).val < levelStart L 0) {row tag : Word w} {width start : ℕ} + (frame : Frame.data (header w L 0+6) m = CursorRAM.ScheduleInit.inputs row tag low l a width start) : + let visit := (BlockHeaderPlan.initial L.shape a)[2]'(by simp [BlockHeaderPlan.initial]) + let out := initialFinal a L m + visit.stop.eval pub state out = ((CursorRAM.rowCount low l a : ℕ) : Word w) ∧ + (fun j ↦ (visit.params j).eval pub state out) = CursorRAM.publicWords w low l a width start := by + let out := initialFinal a L m + have hkeep := run.outside _ (.inl count) (.inl (by omega)) + have h := (firstHeader_keep pub state m out hkeep).trans hFirst + have hf : BlockHeaderPlan.persistentFrame.eval pub state out = header w L 0+6 := by + change BlockHeaderPlan.firstHeader.eval pub state out+((6 : ℕ) : Word w) = _ + rw [h]; rfl + apply BlockPlanner.cursor_parameters _ pub state out _ hf + intro j + let i : Fin 8 := ⟨j.val+2,by have := j.isLt; omega⟩ + have hi := congrFun (run.cursorFrame.trans frame) i + change out (header w L 0+6+((j.val+2 : ℕ) : Word w)).val = + CursorRAM.ScheduleInit.inputs row tag low l a width start i at hi + rw [hi] + fin_cases j <;> simp [CursorRAM.ScheduleInit.inputs,CursorRAM.encode,i] + +/-- A one-call deterministic source scan in the compiled visit's own operand +bank. The report and the memory for its successor are retained by SourceWalk. -/ +def OneCall (pub : Fin 5 → Word w) (state : Word w) (visit : BlockPlanner.Visit) + (m : Memory w) (rs : List (Report w)) : Prop := + let data := fun j ↦ (visit.params j).eval pub state m + let M := (visit.worker.table.instantiate w data).program + ∃ fuel, runSegment M fuel (some (visit.initial.eval pub state m)) m [[]] = some rs + +private theorem walk_cons (pub : Fin 5 → Word w) (state : Word w) {visit : BlockPlanner.Visit} + {rest : List BlockPlanner.Visit} {m : Memory w} {rep : Report w} {rs : List (Report w)} {fuel : ℕ} + (h : rawCall visit pub state m fuel = some rep) + (tail : SourceWalk (OneCall pub state) rest (after m rep.events) rs) : + SourceWalk (OneCall pub state) (visit::rest) m (rep::rs) := by + apply SourceWalk.next (rs := [rep]) + · refine ⟨fuel,?_⟩ + rw [runSegment] + change (match rawCall visit pub state m fuel with + | none => none + | some r => (some ([] : List (Report w))).map (r :: ·)) = _ + rw [h] + rfl + · simpa [eventLog] using tail + +theorem Substep.walk {L : Layout} {i j : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} {m : Memory w} + (run : Substep v L i j six m) (first step : ℕ) (old : first+step = i.val) (new : first+(step+1) = j.val) + (pub : Fin 5 → Word w) (state : Word w) (entry : Entry L first pub state m) + (hFirst : BlockHeaderPlan.firstHeader.eval pub state m = header w L 0) + (pitch : (pub 1-1).val < levelStart L i) (count : (pub 3).val < levelStart L i) : + SourceWalk (OneCall pub state) (BlockHeaderPlan.substep L.shape step (Scalars.ofOrigin v.origin)) m + (reports v L i j m) := by + obtain ⟨h₁,h₂,h₃⟩ := run.visits v first step old new pub state entry hFirst pitch count + exact walk_cons pub state h₁ (walk_cons pub state h₂ (walk_cons pub state h₃ (SourceWalk.done _))) + +theorem Initial.walk {a low l : ℕ} {L : Layout} {nonempty : 0 < L.levels} {six : 6 ≤ L.shape.scalarFields} + {m : Memory w} (run : Initial a low l L nonempty six m) (pub : Fin 5 → Word w) (state : Word w) + (hFirst : BlockHeaderPlan.firstHeader.eval pub state m = header w L 0) + (count : (pub 3).val < levelStart L 0) : + SourceWalk (OneCall pub state) + [BlockHeaderPlan.initialScalars a,BlockHeaderPlan.heads L.shape BlockHeaderPlan.firstHeader] m + [scalarReport (Scalars.initialRow (.terminal a)) (header w L 0+6) (header w L 0) m, + headReport L 0 (initialMemory a L m)] := by + obtain ⟨h₁,h₂⟩ := run.visits pub state hFirst count + exact walk_cons pub state h₁ (walk_cons pub state h₂ (SourceWalk.done _)) + +end CompressorRecords.BlockHeaderRun + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockHeaderStartup.lean b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderStartup.lean new file mode 100644 index 0000000000..335eef7733 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockHeaderStartup.lean @@ -0,0 +1,128 @@ +import OAI.Computability.VPVNP.CompressorTransferredStartup +import OAI.Computability.VPVNP.CompressorBlockHeaderRun + +/-! +# First descriptor header after the pair startup + +The eight closed startup calls, including their outer tag transfers, leave the +actual inputs of the two level-zero publishers in the first level. The +publisher addresses and the cursor incidence operands follow from that memory. +The arena bounds and input length survive both publishers. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockHeaderStartup + +open BurstRAM BlockHeaderRun CursorBounds DescriptorSpace +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Memory at the end of the eight transferred startup calls, where the first header publishers +read their operands. -/ +noncomputable def post (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes steps : ℕ) + (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) := + (TransferredStartup.trace D d L B n a lanes steps pub tag m).entry tag m (Fin.last 8) + +private theorem scalar_fits {B n a l dir tag start frame : ℕ} + (capacity : CursorRAM.ParametersInit.Capacity B n a l dir tag start frame) : + Scalars.Fits (.terminal a) ((virtualBits B n-l+l)*2^(virtualBits B n-l)) l (wordBits B n) := by + let V := (virtualBits B n-l+l)*2^(virtualBits B n-l) + have small : V < 2^wordBits B n := by + have h₁ : V ≤ V*2^l := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _) + have h₂ : V*2^l ≤ CursorRAM.rowCount (virtualBits B n-l) l a := + Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _) + have bounds := capacity.arrays_end + omega + obtain ⟨degree,_,lanes⟩ := capacity.shiftResults_lt + intro i + fin_cases i <;> simp [Scalars.values,Scalars.Pass.spent,Scalars.Pass.expanderDegree,small,V] at * <;> + assumption + +/-- The level-zero publishers run on the startup post-memory. The planner's +first-header expression evaluates to the same address for every entry cursor. -/ +structure Ready (L : Layout) (a low l width n : ℕ) (base : Word w) (m : Memory w) : Prop where + nonempty : 0 < L.levels + six : 6 ≤ L.shape.scalarFields + initial : Initial a low l L nonempty six m + first : ∀ state, BlockHeaderPlan.firstHeader.eval (Workspace.ports L.shape.arity base).data state m = + header w L 0 + count : m (Workspace.ports L.shape.arity base).rows.val = (directoryRows L : Word w) + pitch : m ((Workspace.ports L.shape.arity base).directory-1).val = (levelWords L : Word w) + count_before : ((Workspace.ports L.shape.arity base).data 3).val < levelStart L 0 + frame : Frame.data (header w L 0+6) m = + CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L)) (CursorRAM.encode w 1) low l a width + (incidenceStart L 0) + arena : ((initialFinal a L m) (levelStart L 0+14)).val = endAddress L + levels : ((initialFinal a L m) (levelStart L 0+28)).val = L.levels + length : ((initialFinal a L m) (levelStart L 0+29)).val = n + positions : ((low+l)*2^low)*2^l = L.positions + +set_option maxHeartbeats 800000 in +theorem from_startup (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes steps : ℕ) + (pub : Fin 11 → Word (wordBits B n)) (tag : Word (wordBits B n)) (m : Memory (wordBits B n)) + (run : TransferredStartup.Runs D d L B n a lanes steps pub tag m) + (input : OnlineCursorStartup.Input D L B n pub) (nonempty : 0 < L.levels) + (fields : 30 ≤ L.shape.scalarFields) (fit : endAddress L < 2^wordBits B n) + (positions : initialPositions B n = L.positions) + (capacity : CursorRAM.ParametersInit.Capacity B n a (roundedDown D.p D.q n*lanes) + (directoryBase L) 1 (incidenceStart L 0) (levelStart L 0+6)) : + let l := roundedDown D.p D.q n*lanes + Ready L a (virtualBits B n-l) l (initialWidth B n) n (pub 2) (post D d L B n a lanes steps pub tag m) := by + let w := wordBits B n + let l := roundedDown D.p D.q n*lanes + let low := virtualBits B n-l + let out := post D d L B n a lanes steps pub tag m + have hn := input.length ▸ (pub 6).isLt + obtain ⟨installed,saved,arena,levels,length,_⟩ := run.output hn nonempty fields fit + have addr : DescriptorParameters.saved L w = header w L 0+6 := by + change ((levelStart L 0+6 : ℕ) : Word w) = ((levelStart L 0 : ℕ) : Word w)+6 + rw [Nat.cast_add,Nat.cast_ofNat] + have frame : Frame.data (header w L 0+6) out = DescriptorParameters.outputs L B n a l w := addr ▸ saved + have hpos : ((low+l)*2^low)*2^l = L.positions := by + have h := CursorRAM.rowCount_eq_positions capacity.split 0 + simpa only [CursorRAM.rowCount,pow_zero,Nat.mul_one,positions] using h + have initial := initial_run L nonempty (by omega) fit out a low l frame hpos (scalar_fits capacity) + have base : pub 2 = (L.base : Word w) := Fin.ext (by rw [Fin.val_natCast,← input.base,Nat.mod_eq_of_lt (pub 2).isLt]) + have rows : out (pub 2+8).val = (directoryRows L : Word w) := by rw [input.directory]; exact installed.count + refine ⟨nonempty,by omega,initial,fun s ↦ BlockHeaderPlan.firstHeader_eval L (pub 2) out s base rows,rows,installed.pitch,?_, + frame,?_,?_,?_,hpos⟩ + · change (Workspace.ports L.shape.arity (pub 2)).rows.val < levelStart L 0 + rw [base] + change (ports L w).rows.val < _ + rw [(ports_values L fit).2.2.2.1] + simp only [levelStart,levelsBase,directoryBase,plannerTag,frameBase,Nat.zero_mul,Nat.add_zero] + omega + · exact (congrArg Fin.val (initial.scalarTail 14 (by decide) (by omega))).trans arena + · exact (congrArg Fin.val (initial.scalarTail 28 (by decide) (by omega))).trans levels + · exact (congrArg Fin.val (initial.scalarTail 29 (by decide) (by omega))).trans length + +/-- The same length threshold constructs level zero for every memory and +every tag address below the allocated pair workspace. -/ +theorem eventually_ready (D : CalendarRows.Spec) (d : ℕ) (F : Shape) (B a lanes steps : ℕ) + (hB : 1 ≤ B) (hq : 0 < D.q) (hph : 0 < D.phaseRows) + (hθ : (D.p : ℝ)/D.q ≤ 1) (hlanes : lanes ≤ B) + (arity : 7 ≤ F.arity) (fields : 30 ≤ F.scalarFields) {base : ℕ → ℕ} (hb : PolynomiallyBounded base) : + ∀ᶠ n : ℕ in Filter.atTop, ∀ (pub : Fin 11 → Word (wordBits B n)) (tag : Word (wordBits B n)), + (pub 2).val = base n → (pub 6).val = n → (pub 7).val = addressBits B n → tag.val < base n → + ∀ m, let L := LevelFields.tightDirectory (cursorLayout F B steps ((D.p : ℝ)/D.q) (base n) n) (CalendarRows.rows D n) + let l := roundedDown D.p D.q n*lanes + Ready L a (virtualBits B n-l) l (initialWidth B n) n (pub 2) (post D d L B n a lanes steps pub tag m) := by + filter_upwards [TransferredStartup.eventually_run D d F B a lanes steps hB hq hph hθ hlanes arity fields hb, + OnlineCursorStartup.eventually_input D B hB hq hph, + DescriptorParameters.eventually_tight_capacity D F B a lanes hB hθ hlanes hb, + DescriptorParameters.eventually_tight_end D F B steps hB hb] with n run input capacity fit + intro pub tag baseEq len addr lower m + let P := cursorLayout F B steps ((D.p : ℝ)/D.q) (base n) n + exact from_startup D d _ B n a lanes steps pub tag m (run pub tag baseEq len addr lower m) + (input P pub baseEq len addr) (by change 0 < 1 + (steps+1)*Compression.blockCount ((D.p : ℝ)/D.q) n; omega) fields fit rfl + (capacity P.positions P.levels).2 + +end CompressorRecords.BlockHeaderStartup + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockIndex.lean b/lean/OAI/Computability/VPVNP/CompressorBlockIndex.lean new file mode 100644 index 0000000000..87758c16ad --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockIndex.lean @@ -0,0 +1,180 @@ +import OAI.Computability.VPVNP.CompressorBlockProgram + +/-! +# Selector visits in the fixed chronological block + +A shrinking selector follows its header, greedy, bundle and dense demand +passes. A refresh selector follows its header, three segment scans and all +tie demands. The ordinal formulas below locate the same native worker in +every repeated block and identify its compiled calendar phase. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockIndex + +open PhaseRecipe BlockPlanner Compression + +/-- A particular occurrence in a list, recorded with the prefix and suffix that locate it. -/ +structure Focus {α : Type*} (items : List α) where + /-- Entries preceding the distinguished occurrence. -/ + before : List α + /-- The entry at the distinguished occurrence. -/ + item : α + /-- Entries following the distinguished occurrence. -/ + after : List α + split : items = before ++ item :: after + +namespace Focus + +variable {α : Type*} {items : List α} + +/-- Retain the distinguished occurrence when a suffix is appended to the list. -/ +def append (F : Focus items) (tail : List α) : Focus (items++tail) := + ⟨F.before,F.item,F.after++tail,(congrArg (·++tail) F.split).trans (by simp)⟩ + +/-- Retain the distinguished occurrence when a prefix is prepended to the list. -/ +def prepend (head : List α) (F : Focus items) : Focus (head++items) := + ⟨head++F.before,F.item,F.after,(congrArg (head++·) F.split).trans (List.append_assoc ..).symm⟩ + +/-- Transport a distinguished occurrence along an equality of lists. -/ +def cast {other : List α} (h : items = other) (F : Focus items) : Focus other := + ⟨F.before,F.item,F.after,h.symm.trans F.split⟩ + +theorem bound (F : Focus items) : F.before.length < items.length := by + have h := congrArg List.length F.split + simp only [List.length_append,List.length_cons] at h + omega + +/-- The zero-based list index of the distinguished occurrence. -/ +def index (F : Focus items) : Fin items.length := ⟨F.before.length,F.bound⟩ + +theorem lookup (F : Focus items) : items[F.index.val] = F.item := by + have aux (xs ys : List α) (x : α) : (xs++x::ys)[xs.length]'(by simp) = x := by + rw [List.getElem_append_right le_rfl]; simp + exact (List.getElem_of_eq F.split _).trans (aux F.before F.after F.item) + +end Focus + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- The shrinking motif-selection visit, with its demand count, term-record heads and supply +order. -/ +def shrinkSelector (i : Fin S.steps) : Visit := + let step := i.val + let a := ShrinkBlockInputs.a i + let input := ShrinkBundlePlan.termInputs step a (BlockProgram.arena B step 0) + ⟨TermWorker.motifPass B.shrink finTwoEquiv 8,.lit 0,ShrinkTermRecipe.count a input, + TermWorker.motifExprs B.shrink finTwoEquiv SelectedScore.supplyOrder.entries + (ShrinkTermRecipe.termHeads a 10 input)⟩ + +private def shrinkPair (i : Fin S.steps) : Focus (ShrinkBlockInputs.termVisits B i + (BlockProgram.arena B i.val 0)) := + ⟨[_],shrinkSelector B i,[],rfl⟩ + +private def shrinkInput (i : Fin S.steps) : + Focus (ShrinkBlockInputs.beforeSlices B (BlockProgram.geometry B) i + (BlockProgram.arena B i.val 0)) := + (Focus.prepend _ (shrinkPair B i)).append _ + +/-- The occurrence of the motif selector in shrinking step `i`. -/ +def shrink (i : Fin S.steps) : Focus (BlockProgram.shrink B i) := + ((((((shrinkInput B i).append _).append _).append _).append _).append _).append _ + +theorem shrink_selector (i : Fin S.steps) : (shrink B i).item = shrinkSelector B i := rfl + +theorem shrink_offset (i : Fin S.steps) : (shrink B i).before.length = 21 := by + change ((_ ++ _ ++ _) ++ [_]).length = _ + simp only [List.length_append,BlockHeaderPlan.substep_length,GreedyLevelPlan.visits_length, + ShrinkBundlePlan.visits_length,List.length_cons,List.length_nil] + +/-- The term-selection stage of the degree refresh, evaluated from its published level inputs. -/ +def refreshSelector : Visit := + RefreshBlockPlan.stage B (RefreshBlockPlan.input (BlockProgram.geometry B) S.steps (0 : Fin 6)) + .term + +private def refreshStages : Focus (PortRefresh.LevelRecipe.order (RefreshBlockPlan.shape B)) := by + let s := RefreshBlockPlan.shape B + refine ⟨[.gather,.bundles,.offsets] ++ (List.finRange s.ties).map .demand, .term, + .supply :: (List.finRange (s.ports*s.dH)).map .rom ++ (List.finRange s.degree).map .slot + ++ [.base],?_⟩ + simp only [PortRefresh.LevelRecipe.order,List.append_assoc,List.cons_append,List.nil_append,s] + +private def mapFocus {α β : Type*} {xs : List α} (f : α → β) (F : Focus xs) : Focus (xs.map f) := + ⟨F.before.map f,f F.item,F.after.map f,(congrArg (List.map f) F.split).trans (by simp)⟩ + +/-- The occurrence of the term selector in the complete degree-refresh visit list. -/ +def refresh : Focus (BlockProgram.refresh B) := + let native := mapFocus (RefreshBlockPlan.stage B (RefreshBlockPlan.input + (BlockProgram.geometry B) S.steps (0 : Fin 6))) + (refreshStages B) + ((((Focus.prepend _ (native.append _)).append _).append _).append _).append _ + +theorem refresh_selector : (refresh B).item = refreshSelector B := rfl + +theorem refresh_offset : (refresh B).before.length = 6+(RefreshBlockPlan.shape B).ties := by + simp only [refresh,Focus.append,Focus.prepend,mapFocus,refreshStages,List.length_append, + BlockHeaderPlan.substep_length, List.length_map, List.length_cons, List.length_nil, + List.length_finRange] + omega + +/-- All shrinking visits in the block strictly before step `i`. -/ +def earlier (i : Fin S.steps) : List Visit := + ((List.finRange S.steps).take i.val).flatMap (BlockProgram.shrink B) + +/-- The shrinking visits strictly after step `i`, followed by the block's refresh. -/ +def later (i : Fin S.steps) : List Visit := + ((List.finRange S.steps).drop (i.val+1)).flatMap (BlockProgram.shrink B) ++ BlockProgram.refresh B + +theorem split_block (i : Fin S.steps) : + BlockProgram.block B = earlier B i ++ BlockProgram.shrink B i ++ later B i := by + let ls := List.finRange S.steps + have hi : i.val < ls.length := by simp [ls] + have elem : ls[i.val] = i := by simp [ls] + have split : ls = ls.take i.val ++ i :: ls.drop (i.val+1) := by + conv_lhs => rw [← List.take_append_drop i.val ls, List.drop_eq_getElem_cons hi, elem] + change ls.flatMap (BlockProgram.shrink B) ++ _ = _ + conv_lhs => rw [split] + simp only [earlier,later,ls,List.flatMap_append,List.flatMap_cons,List.append_assoc] + +/-- The occurrence of step `i`'s shrinking selector in the complete block. -/ +def blockShrink (i : Fin S.steps) : Focus (BlockProgram.block B) := + ((Focus.prepend (earlier B i) (shrink B i)).append (later B i)).cast (split_block B i).symm + +/-- The occurrence of the refresh selector in the complete block after all shrinking visits. -/ +def blockRefresh : Focus (BlockProgram.block B) := + Focus.prepend ((List.finRange S.steps).flatMap (BlockProgram.shrink B)) (refresh B) + +theorem block_shrink_offset (i : Fin S.steps) : (blockShrink B i).index.val = + (earlier B i).length+21 := by + change ((earlier B i) ++ (shrink B i).before).length = _ + rw [List.length_append,shrink_offset] + +theorem block_refresh_offset : (blockRefresh B).index.val = + ((List.finRange S.steps).flatMap (BlockProgram.shrink B)).length + + (6+(RefreshBlockPlan.shape B).ties) := by + change (_ ++ (refresh B).before).length = _ + rw [List.length_append,refresh_offset] + +theorem selector_at {t : ℕ} (F : Focus (BlockProgram.block B)) : + let A := BlockProgram.script B + let j := F.index + let physical := j.natAdd A.initial.length + let ordinal := A.initial.length+t*A.block.length+j.val + A.visit physical = F.item ∧ + (Schedule.Online.calendar A.plan).phase ordinal = physical.val ∧ + (Schedule.Online.calendar A.plan).level ordinal = t := by + intro A j physical ordinal + exact ⟨(A.block_visit j).trans F.lookup,A.block_phase t j⟩ + +end CompressorRecords.BlockIndex + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockInitialPackets.lean b/lean/OAI/Computability/VPVNP/CompressorBlockInitialPackets.lean new file mode 100644 index 0000000000..16cc1dbfcd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockInitialPackets.lean @@ -0,0 +1,179 @@ +import OAI.Computability.VPVNP.CompressorBlockCursorPacket +import OAI.Computability.VPVNP.CompressorBlockRoleZero + +/-! +# The four chronological source visits at level zero + +The scalar publisher, array-head publisher, cursor scan and role store run +in order. The source trace certifies each visit's stop test and memory +footprint, and leaves the initial cursor incidence and persistent metadata +available even when the block count is zero. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockInitialPackets + +open BurstRAM BlockPlanner DescriptorSpace CursorNetwork BlockHeaderRun BlockHeaderStartup +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- The four level-zero visits in execution order, ending with the store of the cursor role. -/ +def order (L : Layout) (a : ℕ) : List BlockPlanner.Visit := + BlockHeaderPlan.initial L.shape a ++ [BlockRoleZero.visit] + +/-- The initial scalar report and the following pointer report evaluated in its post-memory. -/ +def headLogs (L : Layout) (a : ℕ) (m : Memory w) : List (Report w) := + let first := header w L 0 + [scalarReport (Scalars.initialRow (.terminal a)) (first+6) first m, + headReport L 0 (initialMemory a L m)] + +/-- The cursor scan reports that populate the six incidence columns beginning at level zero's +incidence base. -/ +def cursorLogs (L : Layout) (w a b l width : ℕ) : List (Report w) := + let p := CursorRAM.publicWords w b l a width (incidenceStart L 0) + CursorRAM.scanReports p 0 (CursorRAM.rowCount b l a) + +/-- The full level-zero report sequence for header publication, the cursor scan and the final +role store. -/ +def logs (L : Layout) (a b l width : ℕ) (m : Memory w) : List (Report w) := + headLogs L a m ++ cursorLogs L w a b l width ++ [BlockRoleZero.report w L] + +/-- External memory after all four level-zero source visits. -/ +def post (L : Layout) (a b l width : ℕ) (m : Memory w) := + after m (eventLog (logs L a b l width m)) + +/-- A fixed native clock bound for every source call in this prefix. -/ +def clock (L : Layout) (a : ℕ) := + (Scalars.initialRow (.terminal a)).recipe.code.length + (DescriptorHeads.publisher L.shape).recipe.code.length + + CursorRAM.visit.length + 8 + +/-- A source visit runs on the supplied operands and branch tapes within the initial packet +clock, producing the given reports. -/ +def Source (L : Layout) (a : ℕ) (pub : Fin 5 → Word w) (s : Word w) (v : BlockPlanner.Visit) + (m : Memory w) (rs : List (Report w)) : Prop := + ∃ fuel bits, fuel ≤ clock L a ∧ HeaderPacket.Run L pub s v m rs fuel bits + +private theorem head_after (L : Layout) (a : ℕ) (m : Memory w) : + after m (eventLog (headLogs L a m)) = initialFinal a L m := by + simp only [headLogs,eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil,after,List.foldl_append] + rfl + +private theorem role_run (L : Layout) (pub : Fin 5 → Word w) (m : Memory w) (fit : levelStart L 0+27 < 2^w) : + HeaderPacket.Run L pub (header w L 0) BlockRoleZero.visit m [BlockRoleZero.report w L] 7 [[]] := by + obtain ⟨start,stop,native,_,_,_,reads⟩ := BlockRoleZero.run L pub m + change BlockRoleZero.visit.initial.eval pub (header w L 0) m = 0 at start + change BlockRoleZero.visit.stop.eval pub (header w L 0) m = 1 at stop + apply HeaderPacket.singleton (by decide) (by + unfold rawCall + dsimp only + rw [start]; exact native) + · rw [start,stop] + change 0 % 2^w < 1 % 2^w + rw [Nat.zero_mod,Nat.mod_eq_of_lt (by omega : 1 < 2^w)]; decide + · rw [stop]; rfl + · intro x v h + exact (reads x v h).elim + · intro x v h + have hrole : x = BlockRoleZero.role w L ∧ v = 0 := by simpa [BlockRoleZero.report] using h + rw [hrole.1] + change levelStart L 0 ≤ (levelStart L 0+27)%2^w + rw [Nat.mod_eq_of_lt fit] + omega + +open private fit_fields from OAI.Computability.VPVNP.CompressorBlockHeaderRun + +open Compression in +theorem initial {a b l pad : ℕ} {T : Type} [Fintype T] (L : Layout) (n : ℕ) (base : Word w) + (m : Memory w) (hD : 1 < b+l) (hd : 2+pad = 2^a) (bits : T → ℕ) + (ready : BlockHeaderStartup.Ready L a b l (∑ t, bits t) n base m) + (fields : 30 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (room : incidenceStart L 0+6*CursorRAM.rowCount b l a ≤ 2^w) (width : (∑ t, bits t) < 2^w) : + let W := ∑ t, bits t + let pub := (Workspace.ports L.shape.arity base).data + let s := header w L 0 + let X := cursorState (cursorCoordinateLabels b l) hD hd bits + let out := post L a b l W m + SourceWalk (Source L a pub s) (order L a) m (logs L a b l W m) ∧ + (packedIncidence L w 0 (CursorRAM.rowCount b l a)).Represents X out ∧ + out (levelStart L 0+27) = 0 ∧ + (∀ x, x < incidenceStart L 0 → x ≠ levelStart L 0+27 → out x = initialFinal a L m x) ∧ + (out (levelStart L 0+14)).val = endAddress L ∧ + (out (levelStart L 0+28)).val = L.levels ∧ (out (levelStart L 0+29)).val = n := by + intro W pub s X out + let mid := initialMemory a L m + let afterHeads := initialFinal a L m + let cs := cursorLogs L w a b l W + let afterCursor := after afterHeads (eventLog cs) + let role := BlockRoleZero.report w L + let z : Fin L.levels := ⟨0,ready.nonempty⟩ + have fieldsFit := fit_fields L z fit + change levelStart L 0+L.shape.scalarFields < 2^w at fieldsFit + have roleFit : levelStart L 0+27 < 2^w := by omega + have before : levelStart L 0+27 < incidenceStart L 0 := by unfold incidenceStart levelHeaderWords; omega + obtain ⟨first,second⟩ := HeaderPacket.initial ready.initial (by omega) fit pub s (ready.first s) ready.count_before + obtain ⟨cursor,rep,kept,_,_⟩ := BlockCursorPacket.run L n base m s hD hd bits ready room width + have roleRun := role_run L pub afterCursor roleFit + let firstLog := scalarReport (Scalars.initialRow (.terminal a)) (s+6) s m + let headLog := headReport L 0 mid + have headWalk : SourceWalk (Source L a pub s) [BlockHeaderPlan.initialScalars a, + BlockHeaderPlan.heads L.shape BlockHeaderPlan.firstHeader] m (headLogs L a m) := by + apply SourceWalk.next (rs := [firstLog]) (ts := [headLog]) ⟨_,_,by unfold clock; omega,first⟩ + simp only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] + exact SourceWalk.singleton ⟨_,_,by unfold clock; omega,second⟩ + have tailWalk : SourceWalk (Source L a pub s) [BlockPlanner.cursor BlockHeaderPlan.persistentFrame,BlockRoleZero.visit] + afterHeads (cs++[role]) := by + apply SourceWalk.next (rs := cs) (ts := [role]) ⟨_,_,by unfold clock; omega,cursor⟩ + exact SourceWalk.singleton ⟨_,_,by unfold clock; omega,roleRun⟩ + have eqn : out = writeMemory afterCursor (BlockRoleZero.role w L) 0 := by + change after m (eventLog ((headLogs L a m++cs)++[role])) = _ + rw [SourceWalk.after_append,SourceWalk.after_append,head_after] + simp only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] + rfl + have val : (BlockRoleZero.role w L).val = levelStart L 0+27 := Nat.mod_eq_of_lt roleFit + have keep (x : ℕ) (below : x < incidenceStart L 0) (other : x ≠ levelStart L 0+27) : out x = afterHeads x := by + rw [eqn,writeMemory,val,ite_eq_right other] + exact kept x (.inl below) + have slots : IncidenceDirectory.slotCount X = CursorRAM.rowCount b l a := by + change Fintype.card (Fin (b+l) × Compression.BitWord b)*2^l*2^a = ((b+l)*2^b*2^l)*2^a + rw [Fintype.card_prod,Fintype.card_fin,Fintype.card_congr (Compression.bitWordFinEquiv b),Fintype.card_fin] + have rep' : (packedIncidence L w 0 (CursorRAM.rowCount b l a)).Represents X afterCursor := rep + refine ⟨?_,?_,?_,keep,?_,?_,?_⟩ + · change SourceWalk _ ([_,_]++[_,_]) m (headLogs L a m++cs++[role]) + rw [List.append_assoc] + apply headWalk.append + rwa [head_after] + · rw [eqn] + exact BlockRoleZero.preserve L X _ afterCursor rep' slots.le room before + · rw [eqn,writeMemory,val,ite_eq_left rfl] + · rw [keep _ (by omega) (by omega)]; exact ready.arena + · rw [keep _ (by unfold incidenceStart levelHeaderWords; omega) (by omega)]; exact ready.levels + · rw [keep _ (by unfold incidenceStart levelHeaderWords; omega) (by omega)]; exact ready.length + +/-- Every data call in the initial segment consumes the empty choice string. -/ +theorem quiet (L : Layout) (a b l width : ℕ) (m : Memory w) : + ∀ r ∈ logs L a b l width m, choiceBits r.events = [] := by + intro r hr + rcases List.mem_append.mp hr with h|h + · rcases List.mem_append.mp h with h|h + · rcases List.mem_cons.mp h with rfl|h + · exact (RowRecipe.report_cost ..).2.2 + · obtain rfl := List.mem_singleton.mp h + exact (RowRecipe.report_cost ..).2.2 + · let p := CursorRAM.publicWords w b l a width (incidenceStart L 0) + let N := CursorRAM.rowCount b l a + have paths := ((runSegment_iff ..).mp (CursorRAM.scan_native p 0 N m)).2.2 + have each : choiceBits r.events ∈ branchPaths (CursorRAM.scanReports p 0 N) := List.mem_map.mpr ⟨r,h,rfl⟩ + rw [paths] at each + exact (List.mem_replicate.mp each).2 + · obtain rfl := List.mem_singleton.mp h + rfl + +end CompressorRecords.BlockInitialPackets + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockLevelFit.lean b/lean/OAI/Computability/VPVNP/CompressorBlockLevelFit.lean new file mode 100644 index 0000000000..be2410ed70 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockLevelFit.lean @@ -0,0 +1,112 @@ +import OAI.Computability.VPVNP.CompressorBlockCapacity + +/-! +# Physical endpoints of selected shrink and refresh substeps + +The static table dimensions of the block program fit the actual graph +at any level having at most the initially reserved number of positions. +Each exclusive endpoint stays within its named table, before the next +level and strictly below the machine word modulus. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockLevelFit + +open BurstRAM Compression DescriptorSpace ShrinkSlots SlotLevel + +variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable (base positions blocks : ℕ) + +/-- Natural address of the first word of table `j` in the given level's fixed-stride array +bank. -/ +def tableStart (L : Layout) (level j : ℕ) := arrayBase L level + j*tableWords L + +/-- Bounds placing an exclusive suballocation end inside its table, before the next level and +below the word modulus. -/ +structure Endpoint (w : ℕ) (L : Layout) (level : ℕ) (j endAddr : ℕ) : Prop where + within : endAddr ≤ tableStart L level j + tableWords L + next : endAddr ≤ levelStart L (level+1) + word : endAddr < 2^w + +private theorem endpoint {L : Layout} (level : Fin L.levels) {j e : ℕ} (hj : j < L.shape.tables) + (h : e ≤ tableStart L level j + tableWords L) (fit : endAddress L < 2^w) : + Endpoint w L level.val j e := by + have next := h.trans (tableEnd_le_nextLevel L level ⟨j,hj⟩) + exact ⟨h,next,next.trans_lt (level_room L fit level)⟩ + +variable {L : Layout} (level : Fin L.levels) +local notation "head" => tableStart L level.val + +/-- All seven packed arenas and both resident placements use the native +indices of the actual shrink calendar. Table zero also admits the contiguous +output and resident variants. -/ +theorem shrink (physical : L = BlockProgram.layout B base positions blocks) (i : Fin S.steps) {g : ℕ} + (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) + (size : X.positions ≤ positions) (fit : endAddress L < 2^w) : + let a := S.degreeExponent i.castSucc + let b := S.degreeExponent i.succ + let sh := levelShape (b := b) X + let term := ShrinkInput.termHead (w := w) X (head 0) + let stride := Fin.ofNat (2^w) 10 + let role := SelectedArena.roleBase X term stride + let selected := SelectedFinish.stop X term stride + Endpoint w L level.val 0 (ShrinkInput.stop X (head 0)) ∧ + Endpoint w L level.val 0 (ShrinkInput.termEnd X (head 0) 10) ∧ + Endpoint w L level.val 0 selected ∧ + Endpoint w L level.val 0 (ShrinkOutput.stop (b := b) X term.val stride.val role selected) ∧ + Endpoint w L level.val 1 (head 1+ShrinkTermSelection.bundles X* + IndexedStarts.capacity (2^(Shrink.colors a)*2^a/4) (ShrinkRankSpace.cap a)) ∧ + Endpoint w L level.val 2 (ShrinkOutput.slotsBase X (head 2) sh) ∧ + Endpoint w L level.val 3 (finish sh (ShrinkOutput.heads sh role (head 3))) ∧ + Endpoint w L level.val 0 (ShrinkResidentLayout.layout X selected).endAddr ∧ + Endpoint w L level.val 5 (ShrinkResidentLayout.layout X (head 5)).endAddr := by + intro a b sh term stride role selected + have capacity : X.positions * ShrinkLevelSpace.tableFactor S ≤ tableWords L := by + rw [physical] + unfold tableWords slotCapacity + rw [Nat.mul_assoc] + exact Nat.mul_le_mul size (BlockProgram.field_rates B base positions blocks).1 + have tables : L.shape.tables = 6 := physical ▸ rfl + have bound (j : Fin 6) {n : ℕ} + (h : n ≤ head j + X.positions*ShrinkLevelSpace.tableFactor S) : Endpoint w L level.val j n := + endpoint level (tables.symm ▸ j.isLt) (h.trans (Nat.add_le_add_left capacity _)) fit + obtain ⟨h₁,h₂,h₃,h₄,h₅,h₆,h₇⟩ := ShrinkLevelSpace.packed_ends S i X (head 0) (head 1) (head 2) (head 3) w + obtain ⟨r₀,r₅⟩ := ShrinkLevelSpace.resident_table S i X (head 0) (head 5) w + exact ⟨bound 0 h₁,bound 0 h₂,bound 0 h₃,bound 0 h₄,bound 1 h₅,bound 2 h₆,bound 3 h₇,bound 0 r₀,bound 5 r₅⟩ + +/-- Table zero holds the complete refresh scratch, term, supply and output +incidence plan. Table four holds the three physical placement columns. -/ +theorem refresh (physical : L = BlockProgram.layout B base positions blocks) {g : ℕ} (X : State S.portExponent (S.portExponent+g)) + (size : X.positions ≤ positions) (fit : endAddress L < 2^w) : + let s := RefreshBlockPlan.shape B + let plan := PortRefresh.Allocation.plan X (S.degreeExponent 0) s.dH s.ties s.stride (head 0) + Endpoint w L level.val 0 plan.stop ∧ Endpoint w L level.val 4 (head 4+3*X.positions) := by + intro s plan + have posEq : plan.sites = X.positions := by + change Fintype.card X.Base*2^S.portExponent*2^g = Fintype.card (X.Base × BitWord (S.portExponent+g)) + rw [Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv _),Fintype.card_fin,pow_add,Nat.mul_assoc] + obtain ⟨_,refreshRate,_,placement⟩ := BlockProgram.field_rates B base positions blocks + have count : L.positions = positions := physical ▸ rfl + have sites : plan.sites ≤ L.positions := (posEq.le.trans size).trans_eq count.symm + have tables : L.shape.tables = 6 := physical ▸ rfl + let zero : Fin L.shape.tables := ⟨0,by omega⟩ + have rates : 7*2^S.portExponent+s.ties+s.stride+3*s.dH+6*2^(S.degreeExponent 0) ≤ L.shape.slots*L.shape.fields := by + rw [physical]; exact refreshRate + have allocated := refresh_table_room (w := w) L X (S.degreeExponent 0) s.dH s.ties s.stride level zero + sites rates fit + have places : 3*X.positions ≤ tableWords L := by + rw [physical] + unfold tableWords slotCapacity + rw [Nat.mul_comm 3,Nat.mul_assoc] + exact Nat.mul_le_mul size placement + exact ⟨endpoint level (by omega) allocated.1 fit, + endpoint level (by omega) (Nat.add_le_add_left places _) fit⟩ + +end CompressorRecords.BlockLevelFit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockMetadata.lean b/lean/OAI/Computability/VPVNP/CompressorBlockMetadata.lean new file mode 100644 index 0000000000..417b77d342 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockMetadata.lean @@ -0,0 +1,438 @@ +import OAI.Computability.VPVNP.CompressorBlockHeaderRun +import OAI.Computability.VPVNP.PairSimulationNodeFieldSpace +import OAI.Computability.VPVNP.CompressorShrinkSelectedPlan +import OAI.Computability.VPVNP.CompressorFormulaFootprint +import OAI.Computability.VPVNP.PairTraversalRoles +import OAI.Computability.VPVNP.CompressorRefreshStageFrame + +/-! +# Publishing the DFS descriptor and prefix of a compressor substep + +The planner emits three one-call rows. The first worker copies twelve +computed operands into the input graph header. The other two workers set +the next graph's DFS layer base and producing role. The native writer +reads its public operand bank before its first external store. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockMetadata + +open BurstRAM BurstRAM.PrivateRAM PhaseRecipe RowRecipe DescriptorSpace BlockPlanner LevelFields +open scoped Fin.CommRing + +/-- Substep-specific child placement columns and the exclusive child capacity. -/ +structure Fields where + /-- Expression for the number of sites produced by the selected pass. -/ + newSites : Expr + /-- Expression for the base of the column mapping old site identifiers to their owners. -/ + owner : Expr + /-- Expression for the base of the child-count column, indexed by new site identifier. -/ + count : Expr + /-- Expression for the base of the rows listing each new site's old children. -/ + row : Expr + /-- Expression for the number of child identifiers reserved per placement row. -/ + cap : Expr + +/-- The selected shrink's collector and the DFS reader use the same count +and row intervals and the same maximum preimage cardinality. -/ +def Fields.shrink (a : ℕ) (I : SelectedPlan.Inputs) : Fields := + ⟨I.newSites, SelectedPlan.placementColumn I 0, SelectedPlan.roleEnd I, SelectedPlan.childRows I, + .lit (ShrinkPreimages.capacity a)⟩ + +/-- Refresh placement is a bijection. Its owner, count, and unique-child +columns are three consecutive site-sized intervals. -/ +def Fields.refresh (step : ℕ) (table4 : Expr) : Fields := + let count := table4.add (sites step) + ⟨sites step,table4,count,count.add (sites step),.lit 1⟩ + +/-- The kind of compressor pass that produced a traversal layer. -/ +inductive Role | shrink | refresh deriving DecidableEq + +/-- Numerical role tag stored in the successor header, one for shrinking and two for refresh. -/ +def Role.code : Role → ℕ | .shrink => 1 | .refresh => 2 + +/-- Expression reading the input length from word 29 of the first level header. -/ +def lengthWord : Expr := .load (BlockHeaderPlan.firstHeader.add (.lit 29)) + +/-- Header offsets 15 through 26 in the order consumed by the DFS handler. -/ +def fieldExprs (F : Shape) (step recordLimit slotDegree : ℕ) (v : Fields) : Fin 12 → Expr := + ![.lit (recordLimit+2),degree step,lengthWord, + ((Expr.lit (2*slotDegree)).mul lengthWord).add (.lit 1), + incidence F step 4,incidence F step 5,sites step, + v.newSites,v.owner,v.count,v.row,v.cap] + +/-- Advance the DFS row base by the current site count times the reserved row stride. -/ +def nextBase (step recordLimit : ℕ) : Expr := + (scalar step 14).add ((Expr.lit (recordLimit+2)).mul (sites step)) + +/-- Destination followed by the twelve evaluated operands. -/ +def writer : Recipe 13 13 9 where + lines := (List.finRange 13).map fun j ↦ ⟨j,.publicWord j⟩ + dest := 0 + tag := 1 + start := 2 + stop := 3 + params := fun j ↦ j.succ.succ.succ.succ + +/-- The visit that writes the twelve traversal metadata operands starting at offset 15 of the +input header. -/ +def current (F : Shape) (step recordLimit slotDegree : ℕ) (v : Fields) : Visit := + ⟨⟨_,_,_,writer.table⟩,.lit 0,.lit 1,Fin.cons (address step 15) (fieldExprs F step recordLimit slotDegree v)⟩ + +/-- The visit that stores the computed DFS row base at offset 14 of the successor header. -/ +def outputBase (step recordLimit : ℕ) : Visit := + BlockPlanner.publish (address (step+1) 14) (nextBase step recordLimit) + +/-- The visit that stores the producing pass's role tag at offset 27 of the successor header. -/ +def outputRole (step : ℕ) (role : Role) : Visit := + BlockPlanner.publish (address (step+1) 27) (.lit role.code) + +/-- Publish the input level's traversal metadata, then the successor's row base and role tag. -/ +def visits (F : Shape) (step recordLimit slotDegree : ℕ) (role : Role) (v : Fields) : List Visit := + [current F step recordLimit slotDegree v, outputBase step recordLimit, outputRole step role] + +@[simp] theorem visits_length (F : Shape) (step recordLimit slotDegree : ℕ) (role : Role) (v : Fields) : + (visits F step recordLimit slotDegree role v).length = 3 := rfl + +variable {w : ℕ} + +private theorem load_bank (pub : Fin 13 → Word w) (s : Word w) (m : Memory w) + (js : List (Fin 13)) (regs : PrimedStackRAM.Regs w 13) (j : Fin 13) : + (evaluate pub s m (js.map fun i ↦ (⟨i,.publicWord i⟩ : Assign 13 13)) regs).2 j = + if j ∈ js then pub j else regs j := by + induction js generalizing regs with + | nil => simp [evaluate] + | cons i js ih => + simp only [List.map_cons, evaluate, RHS.value, ih, List.mem_cons] + by_cases e : j=i <;> by_cases h : j ∈ js <;> simp [e,h] + +theorem writer_values (pub : Fin 13 → Word w) (s : Word w) (m : Memory w) : + writer.values pub s m = pub := by + funext i + change (evaluate pub s m ((List.finRange 13).map _) _).2 i = _ + rw [load_bank,ite_eq_left (List.mem_finRange i)] + +theorem writer_address (pub : Fin 13 → Word w) (s : Word w) (m : Memory w) : + writer.address pub s m = pub 0 := by rw [Recipe.address, writer_values]; rfl + +theorem writer_words (pub : Fin 13 → Word w) (s : Word w) (m : Memory w) : + writer.words pub s m = List.ofFn (fun j : Fin 12 ↦ pub j.succ) := by + rw [Recipe.words, writer_values] + rfl + +open private stores_at from OAI.Computability.VPVNP.CompressorRecordsCursorInit + +/-- The worker uses 12 external probes, all writes. The returned cursor +advances once even when the first input field has numerical value zero. -/ +theorem write_native (pub : Fin 13 → Word w) (s : Word w) (m : Memory w) + (fit : (pub 0).val+12 ≤ 2^w) : + let M := writer.table.instantiate w pub + let rep := writer.report pub s m + execute M.program 42 (M.program.start s) m [] = some rep ∧ rep.result = some (s+1) ∧ + (∀ j : Fin 12, after m rep.events ((pub 0).val+j.val) = pub j.succ) ∧ + (∀ addr, addr < (pub 0).val ∨ (pub 0).val+12 ≤ addr → after m rep.events addr = m addr) ∧ + rep.events.length = 41 ∧ rep.probes = 12 ∧ choiceBits rep.events = [] := by + intro M rep + have room : (writer.address pub s m).val + (9+3) ≤ 2^w := by rwa [writer_address] + have stored := row_stores writer pub s m room + rw [writer_address,writer_words] at stored + obtain ⟨ht,hp,hc⟩ := report_cost writer pub s m + refine ⟨execute_row writer pub s m [] 42 (by decide),rfl,?_,?_,ht,hp,hc⟩ + · intro j + have hj : j.val < (List.ofFn (fun i : Fin 12 ↦ pub i.succ)).length := + by simpa only [List.length_ofFn] using j.isLt + exact (stores_at _ _ stored (by simpa using fit) hj).trans (List.getElem_ofFn hj) + · intro addr h + exact row_outside writer pub s m room addr (by rwa [writer_address]) + +open SourceTransport +open private storeLog eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe +open private store_writes store_no_reads from OAI.Computability.VPVNP.CompressorFormulaFootprint + +/-- Native worker footprints. Planner evaluation of the operand expressions +takes place in a separate burst. -/ +theorem writer_footprint (pub : Fin 13 → Word w) (s : Word w) (m : Memory w) + (fit : (pub 0).val+12 ≤ 2^w) (data : ℕ → Prop) (cells : ∀ i : Fin 12, data ((pub 0).val+i.val)) : + let es := (writer.report pub s m).events + Reads (fun _ ↦ False) es ∧ Writes data es := by + intro es + have count : countProbes (evaluate pub s m writer.lines (fun _ ↦ 0)).1 = 0 := + (eval_cost pub s m writer.lines _).2 + have init := FlowFootprint.bounds_of_noProbes (fun _ ↦ False) data count + have stores : Writes data (storeLog (writer.address pub s m) (writer.words pub s m)) := by + rw [writer_address,writer_words] + apply store_writes + intro i + have hi : i.val < 12 := by simpa only [List.length_ofFn] using i.isLt + rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : i.val < 2^w), + Nat.mod_eq_of_lt (by omega : (pub 0).val+i.val < 2^w)] + exact cells ⟨i.val,hi⟩ + constructor <;> intro a v h + all_goals simp only [es,Recipe.report,List.mem_append,List.mem_cons,List.not_mem_nil,reduceCtorEq,or_false] at h + · exact h.elim (init.1 a v) (store_no_reads (fun _ ↦ False) _ _ a v) + · exact h.elim (init.2 a v) (stores a v) + +/-- Evaluate a phase's public parameters before executing its worker. -/ +def bank (visit : Visit) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : Fin visit.worker.params → Word w := + fun j ↦ (visit.params j).eval pub s m + +/-- The address and all data supplied by the actual online planner. -/ +theorem current_bank (F : Shape) (step recordLimit slotDegree : ℕ) (v : Fields) + (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + let data : Fin 13 → Word w := bank (current F step recordLimit slotDegree v) pub s m + data 0 = (address step 15).eval pub s m ∧ ∀ j : Fin 12, + data j.succ = (fieldExprs F step recordLimit slotDegree v j).eval pub s m := ⟨rfl,fun _ ↦ rfl⟩ + +/-- Data values supplied by the physical child-directory implementation at this substep. -/ +structure Placement where + /-- Number of output sites indexing the completed placement directory. -/ + newSites : ℕ + /-- Natural base address of the column recording the owner of each old site. -/ + owner : ℕ + /-- Natural base address of the column recording the number of children of each output site. -/ + count : ℕ + /-- Natural base address of the fixed-stride child-identifier rows. -/ + row : ℕ + /-- Number of child identifiers reserved in each output site's row. -/ + cap : ℕ + +/-- The planner's five placement expressions evaluate to the recorded site count, column bases +and row capacity. -/ +def Placement.reads (data : Placement) (v : Fields) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : Prop := + v.newSites.eval pub s m = (data.newSites : Word w) ∧ v.owner.eval pub s m = (data.owner : Word w) ∧ + v.count.eval pub s m = (data.count : Word w) ∧ v.row.eval pub s m = (data.row : Word w) ∧ + v.cap.eval pub s m = (data.cap : Word w) + +/-- The twelve metadata words at offsets 15 through 26, including the DFS stride, argument +frame, incidence pointers and child directory. -/ +def payload (recordLimit slotDegree degree n actualIn width oldSites : ℕ) (x : Placement) : Fin 12 → ℕ := + ![recordLimit+2,degree,n,PairSimulation.NodeArguments.frameStride slotDegree n,actualIn,width, + oldSites,x.newSites,x.owner,x.count,x.row,x.cap] + +/-- Agreement with the DFS row stride, private arena, actual incidence pointers, +and the five placement operands. This statement allows arbitrarily different +old and new site counts. -/ +theorem field_values {L : Layout} {step : ℕ} {pub : Fin 5 → Word w} {s : Word w} {m : Memory w} + (recordLimit slotDegree : ℕ) (v : Fields) (x : Placement) + {n dg oldSites actualIn width : ℕ} (firstHead : BlockHeaderPlan.firstHeader.eval pub s m = (levelStart L 0 : Word w)) + (firstRoom : levelStart L 0+29 < 2^w) (nCell : m (levelStart L 0+29) = (n : Word w)) + (deg : (degree step).eval pub s m = (dg : Word w)) (sitesEq : (sites step).eval pub s m = (oldSites : Word w)) + (inPtr : (incidence L.shape step 4).eval pub s m = (actualIn : Word w)) + (widthPtr : (incidence L.shape step 5).eval pub s m = (width : Word w)) + (placement : x.reads v pub s m) (j : Fin 12) : + (fieldExprs L.shape step recordLimit slotDegree v j).eval pub s m = + (payload recordLimit slotDegree dg n actualIn width oldSites x j : Word w) := by + have len : lengthWord.eval pub s m = (n : Word w) := by + change m (BlockHeaderPlan.firstHeader.eval pub s m + (29 : Word w)).val = _ + rw [firstHead, ← show ((levelStart L 0+29 : ℕ) : Word w) = (levelStart L 0 : Word w)+29 by simp, + Fin.val_natCast, Nat.mod_eq_of_lt firstRoom, nCell] + obtain ⟨newSites,owner,count,row,cap⟩ := placement + fin_cases j + · rfl + · exact deg + · exact len + · change ((2*slotDegree : ℕ) : Word w)*lengthWord.eval pub s m+1 = ((2*slotDegree*n+1 : ℕ) : Word w) + simp only [len,Nat.cast_add,Nat.cast_mul,Nat.cast_one] + · exact inPtr + · exact widthPtr + · exact sitesEq + · exact newSites + · exact owner + · exact count + · exact row + · exact cap + +/-- The one-store worker's report, writing the given value at its destination and returning +cursor one. -/ +def storeReport (dest val : Word w) : Report w := + ⟨[.tick,.tick,.tick,.write dest val,.tick,.tick],some (0+1)⟩ + +private theorem raw_store (dest val : Expr) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + BlockHeaderRun.rawCall (BlockPlanner.publish dest val) pub s m 7 = + some (storeReport (dest.eval pub s m) (val.eval pub s m)) := by + let data : Fin 2 → Word w := bank (BlockPlanner.publish dest val) pub s m + exact (BlockPlanner.publish_native dest val data 0 m).1 + +private theorem store_after (m : Memory w) (dest val : Word w) : + after m (storeReport dest val).events = writeMemory m dest val := rfl + +/-- The source relation retains the actual public bank, input cursor and +individual native budget of each visit. -/ +def Source (pub : Fin 5 → Word w) (s : Word w) (visit : Visit) (m : Memory w) (rs : List (Report w)) := + ∃ (fuel : ℕ) (rep : Report w), rs = [rep] ∧ 0 < fuel ∧ fuel ≤ 42 ∧ rep.result = some 1 ∧ + BlockHeaderRun.rawCall visit pub s m fuel = some rep + +/-- Each metadata row contributes one completed source scan and one real +worker run at its planner-supplied operands. -/ +theorem Source.packet {pub : Fin 5 → Word w} {s : Word w} {visit : Visit} {m : Memory w} + {rs : List (Report w)} (h : Source pub s visit m rs) : + StageFrame.Scanned 0 1 rs ∧ ∃ fuel, 0 < fuel ∧ fuel ≤ 42 ∧ + let M := (visit.worker.table.instantiate w (bank visit pub s m)).program + runSegment M fuel (some (visit.initial.eval pub s m)) m [[]] = some rs := by + obtain ⟨fuel,r,rfl,positive,bounded,ret,call⟩ := h + refine ⟨.next (by decide) (by simpa using ret) (.done 1),fuel,positive,bounded,?_⟩ + dsimp only + rw [runSegment] + change execute (visit.worker.table.instantiate w (bank visit pub s m)).program fuel + ((visit.worker.table.instantiate w (bank visit pub s m)).program.start (visit.initial.eval pub s m)) m [] = some r at call + rw [call] + rfl + +/-- The three visits run on consecutive memory images. All other addresses, +including the original layer base, cursor frame, and both pointer banks, +retain their original values. -/ +theorem publish_metadata {L : Layout} {first step : ℕ} {pub : Fin 5 → Word w} + {s : Word w} (m : Memory w) (entry : Entry L first pub s m) + (recordLimit slotDegree : ℕ) (role : Role) (v : Fields) (oldSites : ℕ) + (sitesEq : (sites step).eval pub s m = (oldSites : Word w)) + (wide : 30 ≤ L.shape.scalarFields) (nextLevel : first+(step+1) < L.levels) + (room : endAddress L < 2^w) (pitchBefore : (pub 1-1).val < levelStart L (first+step)) : + let head := levelStart L (first+step) + let next := levelStart L (first+(step+1)) + ∃ rs, SourceWalk (Source pub s) (visits L.shape step recordLimit slotDegree role v) m rs ∧ + let out := after m (eventLog rs) + (∀ j : Fin 12, out (head+15+j.val) = (fieldExprs L.shape step recordLimit slotDegree v j).eval pub s m) ∧ + out (next+14) = m (head+14) + ((recordLimit+2 : ℕ) : Word w) * (oldSites : Word w) ∧ + out (next+27) = (role.code : Word w) ∧ + (∀ x, (x < head+15 ∨ head+27 ≤ x) → x ≠ next+14 → x ≠ next+27 → out x = m x) ∧ + Reads (fun _ ↦ False) (eventLog rs) ∧ + Writes (fun x ↦ (head+15 ≤ x ∧ x .shrink + | .refresh _ => .refresh + +theorem producingRole_code {k : Type*} [_root_.Field k] {S : Compression.BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + (v : SelectedLevel B f hf) : (producingRole v.origin).code = (tagLevel B f hf v).code := by + obtain ⟨a,l,b,g,X,p,o,z,bits⟩ := v + cases o <;> rfl + +end CompressorRecords.BlockMetadata + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockMetadataGraphFrame.lean b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataGraphFrame.lean new file mode 100644 index 0000000000..362cfd8a5d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataGraphFrame.lean @@ -0,0 +1,70 @@ +import OAI.Computability.VPVNP.CompressorBlockMetadataPackets +import OAI.Computability.VPVNP.CompressorCurrentGraphFrame + +/-! # Current-graph and startup cells preserved by the DFS metadata -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockMetadata + +open BurstRAM Compression DescriptorSpace CurrentGraph + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {w : ℕ} {base : Word w} {positions blocks t step : ℕ} {role : Role} {fields : Fields} +variable {m : Memory w} {oldSites : ℕ} {rs : List (Report w)} +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "i" => BlockPlanner.Script.levelsPerBlock (BlockProgram.script B)*t+step +local notation "old" => levelStart L i +local notation "new" => levelStart L (i+1) + +theorem Published.graphFrame (P : Published B base positions blocks t step role fields m oldSites rs) + (x : ℕ) (hx : graphCell L i x ∨ graphCell L (i+1) x ∨ startupCell L x) : + after m (eventLog rs) x = m x := by + have adv (j : ℕ) : levelStart L (j+1) = levelStart L j+levelWords L := by + simp only [levelStart,Nat.succ_mul,Nat.add_assoc] + have width : 66 ≤ levelWords L := by + have sz : levelHeaderWords L=66 := rfl + simp only [levelWords,sz] + omega + have next := adv i + have tail : levelStart L (BlockPlanner.Script.levelsPerBlock (BlockProgram.script B)*t+(step+1))=new := by + rw [← Nat.add_assoc] + have ptr (l : ℕ) : incidenceStart L l = levelStart L l+66 := rfl + have fields : (L).shape.scalarFields=54 := rfl + rcases hx with h|h|⟨j,hj,rfl⟩ + · rcases h with h|h + · apply P.outside <;> omega + · rw [fields,ptr] at h + apply P.outside <;> omega + · rcases h with h|h + · apply P.outside <;> omega + · rw [fields,ptr] at h + apply P.outside <;> omega + · have floor := levelStart_mono L (Nat.zero_le i) + by_cases zero : i=0 + · have here : old=levelStart L 0 := congrArg _ zero + simp only [List.mem_cons,List.not_mem_nil,or_false] at hj + apply P.outside <;> omega + · have one : 1 ≤ i := Nat.one_le_iff_ne_zero.mpr zero + have top := levelStart_mono L one + have first := adv 0 + change levelStart L 1 = levelStart L 0 + levelWords L at first + simp only [List.mem_cons,List.not_mem_nil,or_false] at hj + apply P.outside <;> omega + +/-- The eight original cursor words survive every metadata publication, +including the first substep, whose input header is the first level. -/ +theorem Published.cursorFrame (P : Published B base positions blocks t step role fields m oldSites rs) + (x : ℕ) (hx : frameCell L x) : after m (eventLog rs) x = m x := by + have floor := levelStart_mono L (Nat.zero_le i) + have successor := levelStart_mono L (show i ≤ BlockPlanner.Script.levelsPerBlock (BlockProgram.script B)*t+(step+1) by omega) + unfold frameCell at hx + apply P.outside <;> omega + +end CompressorRecords.BlockMetadata + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockMetadataOperandReads.lean b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataOperandReads.lean new file mode 100644 index 0000000000..3893a0a7c9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataOperandReads.lean @@ -0,0 +1,131 @@ +import OAI.Computability.VPVNP.CompressorPublishedHeadWindows +import OAI.Computability.VPVNP.CompressorShrinkABSliceOperands +import OAI.Computability.VPVNP.CompressorGreedyPlannerFootprint + +/-! # Planner reads for the three DFS metadata rows + +The two successor-header writes use the runtime pitch. The current-header +publisher reads the input length at offset 29 of level zero and derives the +substep-specific placement and child-directory heads from the active header. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockMetadata + +open BurstRAM Compression BlockPlanner DescriptorSpace PhaseRecipe LevelFields Schedule +open scoped Fin.CommRing +open private first atLevel from OAI.Computability.VPVNP.CompressorHeaderOperands + +variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable (base : Word w) (positions blocks t : ℕ) +local notation "A" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog A)) base +local notation "pub" => Schedule.Ports.data pt +local notation "firstLevel" => Script.levelsPerBlock A * t +local notation "st" => (levelStart L firstLevel : Word w) +local notation "D" => Window.operandRegion A L base +local notation "F" => BlockProgram.geometry B + +private theorem scalar_reads (step : ℕ) (m : Memory w) (ht : t < blocks) (hs : step ≤ S.steps) + (fit : endAddress L < 2^w) (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (n : ℕ) (hn : n < 66) : (scalar step n).ReadsFrom D pub st m := by + have room := PublishedHeads.level_room B base positions blocks t step ht hs fit + have entry : Entry L firstLevel pub st m := ⟨rfl,pitch⟩ + have inside : levelStart L 0 ≤ levelStart L (firstLevel+step)+n := + (levelStart_mono L (Nat.zero_le _)).trans (Nat.le_add_right ..) + exact GreedyVisit.scalar_support D L firstLevel step n entry (.inr (.inl rfl)) + (.inr (.inr inside)) ((Nat.add_lt_add_left hn _).trans_le room) + +private theorem length_reads (m : Memory w) (ht : t < blocks) (fit : endAddress L < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) : lengthWord.ReadsFrom D pub st m := by + have hf : BlockHeaderPlan.firstHeader.eval pub st m = (levelStart L 0 : Word w) := + BlockHeaderPlan.firstHeader_eval L base m st (Fin.ofNat_val_eq_self base).symm rows + have room := PublishedHeads.level_room B base positions blocks 0 0 (by omega) (Nat.zero_le _) fit + simp only [Nat.mul_zero,Nat.add_zero] at room + refine ⟨⟨first D pub st m (.inl rfl),trivial⟩,?_⟩ + change D (BlockHeaderPlan.firstHeader.eval pub st m + (29 : Word w)).val + rw [hf,← show ((levelStart L 0 + 29 : ℕ) : Word w) = (levelStart L 0 : Word w)+29 by simp, + Fin.val_natCast,Nat.mod_eq_of_lt (by omega : levelStart L 0+29 < 2^w)] + exact .inr (.inr (Nat.le_add_right ..)) + +private theorem visits_supported (step : ℕ) (m : Memory w) (v : Fields) (role : Role) + (field : ∀ n < 66, (scalar step n).ReadsFrom D pub st m) + (length : lengthWord.ReadsFrom D pub st m) + (newSites : v.newSites.ReadsFrom D pub st m) (owner : v.owner.ReadsFrom D pub st m) + (count : v.count.ReadsFrom D pub st m) (row : v.row.ReadsFrom D pub st m) + (cap : v.cap.ReadsFrom D pub st m) (j : Visit) + (hj : j ∈ visits F step B.recordLimit (slotDegree S) role v) : + HeaderOperands.Supported D pub st m j := by + have addr (k n : ℕ) : (address k n).ReadsFrom D pub st m := + ⟨atLevel D pub st m (.inr (.inl rfl)) k,trivial⟩ + have sites : (LevelFields.sites step).ReadsFrom D pub st m := ⟨field 0 (by decide),field 2 (by decide)⟩ + rcases List.mem_cons.mp hj with rfl | h + · refine ⟨trivial,trivial,?_⟩ + intro p + change Fin 13 at p + cases p using Fin.cases with + | zero => exact addr step 15 + | succ p => + change (fieldExprs F step B.recordLimit (slotDegree S) v p).ReadsFrom D pub st m + fin_cases p + exacts [trivial,field 1 (by decide),length,⟨⟨trivial,length⟩,trivial⟩,field 58 (by decide), + field 59 (by decide),sites,newSites,owner,count,row,cap] + rcases List.mem_cons.mp h with rfl | h + · refine ⟨trivial,trivial,?_⟩ + intro p; change Fin 2 at p; fin_cases p + · exact addr _ _ + · exact ⟨field 14 (by decide),trivial,sites⟩ + obtain rfl := List.mem_singleton.mp h + refine ⟨trivial,trivial,?_⟩ + intro p; change Fin 2 at p; fin_cases p + · exact addr _ _ + · trivial + +/-- The shrink metadata visits in their installed substep window. -/ +theorem shrink_operand_reads (i : Fin S.steps) (m : Memory w) (ht : t < blocks) (fit : endAddress L < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (v : Visit) (hv : v ∈ (BlockGroups.parts B i)[9]'(by rw [BlockGroups.parts_length]; decide)) : HeaderOperands.Supported D pub st m v := by + let origin := BlockProgram.arena B i.val 0 + let I := ShrinkBlockInputs.selectedInputs B F i origin + let fields := Fields.shrink (ShrinkBlockInputs.a i) I + let reads := Expr.ReadsFrom D pub st m + have field := scalar_reads B base positions blocks t i.val m ht i.isLt.le fit pitch + have src : reads origin := field 60 (by decide) + have ab := BlockSlices.ab_supported i D pub st m origin origin + (fun j => field j.val (by have := j.isLt; omega)) src src + have num : reads I.motifs := ⟨ab.rows,trivial⟩ + have term : reads I.termBase := ⟨⟨ab.newWidths,trivial,num⟩,trivial,num⟩ + have sites : reads I.oldSites := ⟨field 0 (by decide),field 2 (by decide)⟩ + have slots : reads I.oldSlots := ⟨sites,field 1 (by decide)⟩ + have newSites : reads I.newSites := ⟨field 0 (by decide),trivial,field 3 (by decide)⟩ + have place : reads (SelectedPlan.placementBase I) := ⟨⟨term,num,trivial⟩,trivial⟩ + have count : reads (SelectedPlan.roleEnd I) := ⟨⟨place,trivial,sites⟩,trivial,slots⟩ + exact visits_supported B base positions blocks t i.val m fields .shrink field + (length_reads B base positions blocks t m ht fit rows) + newSites ⟨place,trivial,sites⟩ count ⟨count,newSites⟩ trivial v hv + +/-- The refresh metadata visits in their installed substep window. -/ +theorem refresh_operand_reads (m : Memory w) (ht : t < blocks) (fit : endAddress L < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (v : Visit) (hv : v ∈ (BlockGroups.refreshParts B)[4]'(by rw [BlockGroups.refreshParts_length]; decide)) : HeaderOperands.Supported D pub st m v := by + have field := scalar_reads B base positions blocks t S.steps m ht le_rfl fit pitch + let head := BlockProgram.arena B S.steps 4 + have owner : head.ReadsFrom D pub st m := field 64 (by decide) + have sites : (LevelFields.sites S.steps).ReadsFrom D pub st m := ⟨field 0 (by decide),field 2 (by decide)⟩ + exact visits_supported B base positions blocks t S.steps m (.refresh S.steps head) .refresh field + (length_reads B base positions blocks t m ht fit rows) + sites owner ⟨owner,sites⟩ ⟨⟨owner,sites⟩,sites⟩ trivial v hv + +end CompressorRecords.BlockMetadata + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockMetadataPackets.lean b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataPackets.lean new file mode 100644 index 0000000000..dc971a565b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataPackets.lean @@ -0,0 +1,159 @@ +import OAI.Computability.VPVNP.CompressorBlockMetadata +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorWindowPackets +import OAI.Computability.VPVNP.CompressorSourceScanned + +/-! # Native online packets for the three DFS metadata publications -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockMetadata + +open BurstRAM DescriptorSpace PhaseRecipe BlockPlanner Schedule SourceTransport SourceOnline +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Each source segment inherits the event footprint of its chronological +walk. The same footprint preserves the lower control words at every join. -/ +private theorem data_walk {J : Type*} {src dest : J → Memory w → List (Report w) → Prop} + {js : List J} {m : Memory w} {rs : List (Report w)} + (h : SourceWalk src js m rs) (head : ℕ) (original : Memory w) + (agree : ∀ x < head, m x = original x) + (rd : Reads (head ≤ ·) (eventLog rs)) (wr : Writes (head ≤ ·) (eventLog rs)) + (lift : ∀ j ∈ js, ∀ mem logs, src j mem logs → (∀ x < head, mem x = original x) → + Reads (head ≤ ·) (eventLog logs) → Writes (head ≤ ·) (eventLog logs) → dest j mem logs) : + SourceWalk dest js m rs := by + induction h with + | done => exact .done _ + | @next j js m xs ys srcHead _ ih => + rw [eventLog,List.flatMap_append] at rd wr + have rd₁ : Reads (head ≤ ·) (eventLog xs) := fun a v hv => rd a v (List.mem_append_left _ hv) + have wr₁ : Writes (head ≤ ·) (eventLog xs) := fun a v hv => wr a v (List.mem_append_left _ hv) + have middle (x) (hx : x rd a v (List.mem_append_right _ hv)) + (fun a v hv => wr a v (List.mem_append_right _ hv)) + (fun k hk => lift k (List.mem_cons_of_mem _ hk))) + +private theorem limits (F : Shape) (step limit deg : ℕ) (role : Role) (v : Fields) + (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) : + ∀ j ∈ visits F step limit deg role v, j.initial.eval pub st m = 0 ∧ j.stop.eval pub st m = 1 := by + intro j hj + simp only [visits,List.mem_cons,List.not_mem_nil,or_false] at hj + rcases hj with rfl | rfl | rfl <;> exact ⟨Nat.cast_zero,Nat.cast_one⟩ + +variable {k : Type*} [_root_.Field k] {S : Compression.BlockSchedule k} (B : S.Templates) +variable (base : Word w) (positions blocks t step : ℕ) (role : Role) (fields : Fields) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Schedule.Ports.data pt +local notation "first" => Script.levelsPerBlock scr*t +local notation "st" => (levelStart L (first) : Word w) +local notation "head" => levelStart L (first+step) +local notation "nextHead" => levelStart L (first+(step+1)) +local notation "vis" => visits (Layout.shape L) step B.recordLimit (slotDegree S) role fields +local notation "D" => Window.operandRegion scr L base +local notation "Pkt" => SourceOnline.Packet scr w + +/-- All twelve descriptor fields, the next DFS row pointer and the role +are read from the actual post-memory. Writes outside these fourteen cells +are excluded on the complete chronological report stream. -/ +structure Published (m : Memory w) (oldSites : ℕ) (rs : List (Report w)) : Prop where + payload : ∀ j : Fin 12, after m (eventLog rs) (head+15+j.val) = + (fieldExprs (L).shape step B.recordLimit (slotDegree S) fields j).eval pub st m + successor : after m (eventLog rs) (nextHead+14) = + m (head+14)+((B.recordLimit+2 : ℕ) : Word w)*(oldSites : Word w) + tag : after m (eventLog rs) (nextHead+27) = (role.code : Word w) + outside : ∀ x, (x < head+15 ∨ head+27 ≤ x) → x ≠ nextHead+14 → x ≠ nextHead+27 → + after m (eventLog rs) x = m x + reads : Reads (fun _ => False) (eventLog rs) + writes : Writes (fun x => (head+15 ≤ x ∧ x p.stage.phase) = W.indices ∧ + Published B base positions blocks t step role fields m oldSites (ps.flatMap SourceWalk.Packet.reports) := by + have Hfit : levelStart L 0 < 2^w := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + have low := Window.lowCells (A := scr) L base rfl rfl Hfit + have hOld := levelStart_mono L (show 0 ≤ first+step from Nat.zero_le _) + have hNext := levelStart_mono L (show 0 ≤ first+(step+1) from Nat.zero_le _) + have hLevel : first+(step+1) < (L).levels := by + have h := Nat.mul_le_mul_left (S.steps+1) ltBlock + change (S.steps+1)*t+(step+1)<1+(S.steps+1)*blocks + rw [Nat.mul_succ] at h + omega + let entry : LevelFields.Entry L (first) pub st m := ⟨rfl,pitch⟩ + obtain ⟨rs,walk,cells,successor,tag,other,reads,writes,len,cost⟩ := + publish_metadata m entry B.recordLimit (slotDegree S) role fields oldSites old (by change 30 ≤ 54; decide) + hLevel fit (low.2.trans_le hOld) + have wr : Writes (levelStart L 0 ≤ ·) (eventLog rs) := by + intro a v hv + rcases writes a v hv with h | h | h <;> omega + have raw : SourceWalk (Window.Raw (A := scr) L base t 42) vis m rs := by + apply data_walk walk (levelStart L 0) m (fun _ _ => rfl) (fun a v hv => (reads a v hv).elim) wr + intro j hj mem logs source ag rd wt + obtain ⟨fuel,r,rfl,positive,bounded,ret,call⟩ := source + obtain ⟨start,stop⟩ := limits (L).shape step B.recordLimit (slotDegree S) role fields pub st mem j hj + have one : 1 < 2^w := by + change (L).base+_+_+_+_+_ < 2^w at Hfit + omega + refine ⟨fuel,[[]],bounded,HeaderPacket.singleton positive call ?_ ?_ ?_ ?_,?_⟩ + · rw [start,stop]; apply Fin.lt_def.mpr; change 0 < 1 % (2^w); rw [Nat.mod_eq_of_lt one]; decide + · exact ret.trans (congrArg some stop.symm) + · simpa only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] using rd + · simpa only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] using wt + · exact supported mem ((ag _ low.1).trans rows) ((ag _ low.2).trans pitch) j hj + have bounds (j : Fin (scr).size) := SourceOnline.scanCap_clocks + (p := ⟨HeaderPacket.attach scr j pub st m 42 [[]],m,[]⟩) 42 (by rfl) clock + have live (j : Fin (vis).length) : Window.ordinal (A := scr) t (W.index j) < directoryRows L := by + rw [W.ordinal_index,BlockProgram.directory_rows,(scr).calendar_total] + have pos := (W.position j).isLt + have mul := Nat.mul_le_mul_right (scr).block.length ltBlock + rw [Nat.succ_mul] at mul + omega + obtain ⟨ps,group,ph,hr⟩ := W.group L base t rfl rfl Hfit cap 42 m rs raw rows pitch + live (fun j _ => (bounds j).1) + (fun j _ => (bounds j).2) + refine ⟨ps,group,ph,?_⟩ + rw [hr] + exact ⟨cells,successor,tag,other,reads,writes,len,cost,walk⟩ + +/-- The controller may compose arbitrarily many substeps: metadata writes +touch only two consecutive headers. Earlier levels, later levels and the +live group's control words agree with the source. -/ +theorem Published.levelsFrame {m : Memory w} {oldSites : ℕ} {rs : List (Report w)} + (P : Published B base positions blocks t step role fields m oldSites rs) (x : ℕ) + (out : x < head ∨ levelStart L (first+step+2) ≤ x) : after m (eventLog rs) x = m x := by + have advance (j : ℕ) : levelStart L (j+1) = levelStart L j + levelWords L := by + simp only [levelStart,Nat.succ_mul,Nat.add_assoc] + have next : nextHead = head+levelWords L := by rw [← Nat.add_assoc,advance] + have later : levelStart L (first+step+2) = nextHead+levelWords L := by + rw [show first+step+2=(first+(step+1))+1 by omega,advance] + have width : 30 ≤ levelWords L := by + have hh : levelHeaderWords L=66 := rfl + simp only [levelWords,hh] + omega + rw [later,next] at out + apply P.outside <;> omega + +end CompressorRecords.BlockMetadata + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockMetadataRefreshReadback.lean b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataRefreshReadback.lean new file mode 100644 index 0000000000..cf313bb35d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataRefreshReadback.lean @@ -0,0 +1,87 @@ +import OAI.Computability.VPVNP.CompressorBlockMetadataWindows +import OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders +import OAI.Computability.VPVNP.LiveHeaderProtectedCore + +/-! # Refresh DFS geometry on the installed metadata packet's actual memory -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockMetadata + +open BurstRAM BlockPlanner DescriptorSpace Schedule Compression PortRefresh.TraversalHeaders +open scoped Fin.CommRing + +variable {w : ℕ} + +private theorem unique_source {pub : Fin 5 → Word w} {s : Word w} {v : BlockPlanner.Visit} {m : Memory w} + {rs ss : List (Report w)} (a : Source pub s v m rs) (b : Source pub s v m ss) : rs=ss := by + obtain ⟨f,r,rfl,_,_,_,run⟩ := a + obtain ⟨g,q,rfl,_,_,_,run'⟩ := b + unfold BlockHeaderRun.rawCall at run run' + have rf := BurstRAM.execute_extend run g + have rg := BurstRAM.execute_extend run' f + rw [Nat.add_comm g f] at rg + rw [rf] at rg + rw [Option.some.inj rg] + +private theorem unique_walk {pub : Fin 5 → Word w} {s : Word w} {vs : List BlockPlanner.Visit} {m : Memory w} + {rs ss : List (Report w)} (walk : SourceWalk (Source pub s) vs m rs) + (other : SourceWalk (Source pub s) vs m ss) : rs = ss := by + induction walk generalizing ss with + | done => cases other; rfl + | next h _ ih => + cases other with + | next h' tail => + obtain rfl := unique_source h h' + exact congrArg (_ ++ ·) (ih tail) + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable {f : B.Entry → R} {hf : B.IsSolution f} (v : SelectedLevel B f hf) +variable (base : Word w) (positions blocks t : ℕ) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Ports.data pt +local notation "first" => Script.levelsPerBlock scr*t +local notation "st" => (levelStart L first : Word w) +local notation "prev" => first+S.steps +local notation "lastHead" => first+(S.steps+1) + +/-- The private refresh evaluator recovers its input/output incidence and +argument-stack pointers after these very three native reports. -/ +theorem Published.refresh_geometry {oldSites n oldRows newRows dH : ℕ} {m : Memory w} {rs : List (Report w)} + (P : Published B base positions blocks t S.steps .refresh (refreshFields B) m oldSites rs) + (ht : t ShrinkInput.termHead (w := w) X start + +/-- Physical child-directory bases used by the selected placement and its +append worker. -/ +def shrinkPlacement : Placement := ⟨ShrinkPreimages.newCount X, + SelectedArena.placementBase X term 10,SelectedFinish.countStart X term 10, + SelectedFinish.rowStart X term 10,ShrinkPreimages.capacity (a i)⟩ + +variable (base : Word w) (positions blocks t : ℕ) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Ports.data pt +local notation "first" => Script.levelsPerBlock scr*t +local notation "st" => (levelStart L first : Word w) +local notation "I" => ShrinkBlockInputs.selectedInputs B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0) +local notation "pre" => ShrinkInput.placementBank X T start + +/-- The physical owner, count and rows of the new node family are the +same native arrays filled by the selected shrinking passes. -/ +theorem Published.shrink_payload {m : Memory w} {rs : List (Report w)} + (P : Published B base positions blocks t i.val .shrink (shrinkFields B i) m (ShrinkPreimages.oldCount X) rs) + (header : ShrinkHeaderReads.Header i X T start L first m) + (entry : LevelFields.Entry L first pub st m) (termFits : ShrinkInput.termEnd X start 10 < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (n : ℕ) (nCell : m (levelStart L 0+29) = (n : Word w)) (j : Fin 12) : + after m (eventLog rs) (levelStart L (first+i.val)+15+j.val) = + (BlockMetadata.payload B.recordLimit (slotDegree S) (2^(a i)) n T.actualIn.val T.width.val + (ShrinkPreimages.oldCount X) (shrinkPlacement (w := w) i X start) j : Word w) := by + have lo := levelStart_mono L (Nat.zero_le (first+i.val)) + have ten : 10 < 2^w := by have := header.room; omega + have read := (SelectedTailPackets.header_values B i X T start pub st m header entry termFits ten + (fun _ => True) trivial (fun _ _ => trivial)).1 + have basic := header.reads B entry + have initial : BlockHeaderPlan.firstHeader.eval pub st m = (levelStart L 0 : Word w) := + BlockHeaderPlan.firstHeader_eval L base m st (Fin.cast_val_eq_self _).symm rows + have stride : ((I).termStride : Word w) = 10 := by + change ((10 : ℕ) : Word w) = 10 + simp only [Nat.cast_ofNat] + have owner : (SelectedPlan.placementColumn I 0).eval pub st m = + (SelectedArena.placementBase X term 10 : Word w) := by + have h := SelectedPlan.placement_column I X pre T term pub st m read 0 + simpa only [SelectedArena.placementWord,Fin.val_zero,Nat.zero_mul,Nat.add_zero,stride,Fin.ofNat_eq_cast] using h + have count := roleEnd_value I X term pre T pub st m read + have row := rows_value I X term pre T pub st m read + rw [stride] at count row + have placement : (shrinkPlacement (w := w) i X start).reads (shrinkFields B i) pub st m := + ⟨read.nextSites,owner,count.trans (Fin.ofNat_eq_cast _ _),row.trans (Fin.ofNat_eq_cast _ _),rfl⟩ + have hin : (LevelFields.incidence (L).shape i.val 4).eval pub st m = (T.actualIn.val : Word w) := + (basic.incidence 4).trans (Fin.cast_val_eq_self _).symm + have hwid : (LevelFields.incidence (L).shape i.val 5).eval pub st m = (T.width.val : Word w) := + (basic.incidence 5).trans (Fin.cast_val_eq_self _).symm + exact (P.payload j).trans (field_values B.recordLimit (slotDegree S) (shrinkFields B i) + (shrinkPlacement (w := w) i X start) initial (by have := header.room; omega) nCell basic.degree read.sites + hin hwid placement j) + +end CompressorRecords.BlockMetadata + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockMetadataWindows.lean b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataWindows.lean new file mode 100644 index 0000000000..fefb2a9846 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockMetadataWindows.lean @@ -0,0 +1,77 @@ +import OAI.Computability.VPVNP.CompressorBlockMetadataPackets +import OAI.Computability.VPVNP.CompressorBlockMetadataOperandReads +import OAI.Computability.VPVNP.CompressorShrinkForward + +/-! # Installing the DFS metadata in shrinking and refresh substeps -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockMetadata + +open BurstRAM Compression DescriptorSpace BlockPlanner Schedule SourceOnline +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {w : ℕ} (base : Word w) (positions blocks t cap : ℕ) (m : Memory w) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Ports.data pt +local notation "st" => (levelStart L (Script.levelsPerBlock scr*t) : Word w) + +/-- Header fields published by the shrinking pass at this scheduled degree. -/ +def shrinkFields (i : Fin S.steps) : Fields := .shrink (ShrinkBlockInputs.a i) + (ShrinkBlockInputs.selectedInputs B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0)) + +/-- The metadata batch occupies group nine of the actual shrink. Its +report image fills the selected old and successor headers. -/ +theorem shrink_group (i : Fin S.steps) (ht : t < blocks) (fit : endAddress L < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) (clock : scanCap scr 42 ≤ cap) + (oldSites : ℕ) (old : (LevelFields.sites i.val).eval pub st m = (oldSites : Word w)) : + ∃ ps : List (Packet scr w), Group scr L base cap + (ShrinkForward.first B i t + ShrinkForward.visitsBefore B i 9) (directoryRows L) m ps ∧ + ps.map (fun p => p.stage.phase) = (BlockGroups.shrink B i 9).indices ∧ + Published B base positions blocks t i.val .shrink (shrinkFields B i) m oldSites + (ps.flatMap SourceWalk.Packet.reports) := by + let W := BlockGroups.shrink B i 9 + have offset : (scr).initial.length+t*(scr).block.length+W.before.length = + ShrinkForward.first B i t+ShrinkForward.visitsBefore B i 9 := by + rw [show W.before.length = _ from BlockGroups.shrink_offset B i 9] + unfold ShrinkForward.first ShrinkForward.visitsBefore + rw [show (9 : Fin 12).val = 9 by decide] + omega + rw [← offset] + exact install B base positions blocks t i.val .shrink (shrinkFields B i) W cap m ht i.isLt.le fit + rows pitch clock oldSites old (fun mem hr hs v hv => shrink_operand_reads B base positions blocks t i mem ht fit hr hs v hv) + +/-- Header fields published when the port refresh reaches its metadata stage. -/ +def refreshFields : Fields := .refresh S.steps (BlockProgram.arena B S.steps 4) + +/-- Group four of the refresh carries the DFS row cursor across the +singleton-child placement and records the refresh role in the new header. -/ +theorem refresh_group (ht : t < blocks) (fit : endAddress L < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) (clock : scanCap scr 42 ≤ cap) + (oldSites : ℕ) (old : (LevelFields.sites S.steps).eval pub st m = (oldSites : Word w)) : + let W := BlockGroups.refresh B 4 + ∃ ps : List (Packet scr w), Group scr L base cap + ((scr).initial.length+t*(scr).block.length+W.before.length) (directoryRows L) m ps ∧ + ps.map (fun p => p.stage.phase) = W.indices ∧ + Published B base positions blocks t S.steps .refresh (refreshFields B) m oldSites + (ps.flatMap SourceWalk.Packet.reports) := by + intro W + exact install B base positions blocks t S.steps .refresh (refreshFields B) W cap m ht le_rfl fit + rows pitch clock oldSites old (fun mem hr hs v hv => refresh_operand_reads B base positions blocks t mem ht fit hr hs v hv) + +end CompressorRecords.BlockMetadata + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockProgram.lean b/lean/OAI/Computability/VPVNP/CompressorBlockProgram.lean new file mode 100644 index 0000000000..548a4c2718 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockProgram.lean @@ -0,0 +1,188 @@ +import OAI.Computability.VPVNP.CompressorBlockDataHeads +import OAI.Computability.VPVNP.CompressorRefreshBlockPlan +import OAI.Computability.VPVNP.CompressorRefreshPlacementRows +import OAI.Computability.VPVNP.CompressorShrinkResidentsPlan +import OAI.Computability.VPVNP.CompressorBlockMetadata +import OAI.Computability.VPVNP.CompressorShrinkLevelSpace +import OAI.Computability.VPVNP.CompressorDescriptorTableFits + +/-! +# The online descriptor program for a fixed compression template + +The initial four visits publish the cursor counts, construct its incidence +table and mark its role. One block contains the prescribed shrinking +substeps in increasing order and one degree refresh. Every phase computes +its operands from the live RAM. The script depends on the fixed compressor +template. The input size, iteration count and choices enter through RAM +and the branch tapes. + +Table zero holds the greedy, rank, term and selected placement data of a +shrink, or the packed allocation of a refresh. Tables one through five +hold the AB intersections, surviving width and interval rows, sorted-slot +workspace, refresh preimages, and shrink resident tables, respectively. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockProgram + +open BurstRAM PhaseRecipe BlockPlanner Compression DescriptorSpace +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Per-site scratch allowance for refresh segment columns, demands, term records, supply, +expander tables and output incidence. -/ +def refreshRate := + let s := RefreshBlockPlan.shape B + 7*s.ports+s.ties+s.stride+3*s.dH+6*s.degree + +/-- The resident arrays contain twice the combined number of hidden and +map occurrences, plus one count for each new site in each directory. -/ +def residentRate (S : BlockSchedule k) := 20*slotDegree S+2 + +/-- Reserved field count per table slot, covering the largest shrinking, refresh or resident +workspace with three extra fields. -/ +def fieldCount := max (ShrinkLevelSpace.tableFactor S) (max (refreshRate B) (residentRate S))+3 + +/-- Only the scalar, table, slot and field dimensions are compiled into the +phase programs. The physical directory below uses the resulting catalog +arity and chronological row counts. -/ +def geometry : Shape := + ⟨0,0,0,0,54,6,slotDegree S,fieldCount B⟩ + +/-- Expression reading the base address of one of the six tables at the given level. -/ +def arena (step : ℕ) (index : Fin 6) : Expr := LevelFields.table (geometry B) step index + +/-- Four visits publishing the term base, term stride, layout and absolute operand at header +offsets 36 through 39. -/ +def termPointers (step : ℕ) (termHead termStride layout absolute : Expr) : List Visit := + let operands : Fin 4 → Expr := ![termHead,termStride,layout,absolute] + List.ofFn fun j : Fin 4 ↦ BlockPlanner.publish (LevelFields.address step (36+j.val)) (operands j) + +theorem termPointers_length (step : ℕ) (h s l a : Expr) : (termPointers step h s l a).length = + 4 := by + simp [termPointers] + +/-- Every selected graph level uses the old graph's published columns and +writes the next graph's canonical incidence columns. -/ +def shrink (i : Fin S.steps) : List Visit := + let F := geometry B + let step := i.val + let a := ShrinkBlockInputs.a i + let origin := arena B step 0 + let chosen := ShrinkBlockInputs.selectedInputs B F i origin + let absolute := ShrinkBundlePlan.absoluteCD step a origin + ShrinkBlockInputs.beforeSlices B F i origin ++ + ShrinkResidentsPlan.visits chosen (arena B step 5) (LevelFields.atLevel step) absolute a ++ + BlockSlices.visits B F i origin (arena B step 1) (arena B step 2) ++ + ShrinkBlockInputs.slots B F i origin (arena B step 3) (arena B step 2) ++ + BlockMetadata.visits F step B.recordLimit (slotDegree S) .shrink (.shrink a chosen) ++ + termPointers step chosen.termBase (.lit chosen.termStride) (SelectedPlan.layout chosen) + absolute ++ + BlockDataHeads.visits B F i origin (arena B step 1) (arena B step 2) (arena B step 3) + +/-- The singleton-child placement scan, using consecutive owner, count and child columns of one +word per site. -/ +def refreshPlacement (step : ℕ) (table4 : Expr) : Visit := + let n := LevelFields.sites step + ⟨RefreshPlacement.worker,.lit 0,n,![table4,table4.add n,table4.add ((Expr.lit 2).mul n)]⟩ + +/-- The complete refresh visit sequence, including successor incidence copies, singleton +placement and the traversal metadata. -/ +def refresh : List Visit := + let F := geometry B + let step := S.steps + let s := RefreshBlockPlan.shape B + let p := RefreshBlockPlan.input F step (0 : Fin 6) + let fields := BlockMetadata.Fields.refresh step (arena B step 4) + BlockHeaderPlan.substep F step (.refresh S.portExponent (S.degreeExponent 0) S.expanderExponent) + ++ + RefreshBlockPlan.visits B F step (0 : Fin 6) ++ [refreshPlacement step (arena B step 4)] ++ + BlockMetadata.visits F step B.recordLimit (slotDegree S) .refresh fields ++ + termPointers step (PortRefresh.LevelRecipe.termStart s p) (.lit s.stride) (.lit 0) (.lit 0) ++ + [BlockPlanner.publish (LevelFields.address step 40) (LevelFields.atLevel (step+1))] + +/-- The initial header and cursor visits followed by publication of the cursor role at level +zero. -/ +def initial : List Visit := + BlockHeaderPlan.initial (geometry B) (S.degreeExponent 0) ++ + [BlockPlanner.publish (LevelFields.address 0 27) (.lit 0)] + +/-- One compression block, consisting of the shrinking steps in schedule order followed by the +refresh. -/ +def block : List Visit := (List.finRange S.steps).flatMap (shrink B) ++ refresh B + +/-- The fixed script with its initial visits and its repeatable block of shrinking and refresh +visits. -/ +def script : BlockPlanner.Script := ⟨S.steps+1,initial B,block B⟩ + +/-- Finite instruction table for all inputs and all branch selections. -/ +def template := Schedule.Online.template (script B).plan + +/-- Instantiate the block script as a RAM program at the supplied scheduler ports. -/ +def native {w : ℕ} (ports : Schedule.Ports w) := (script B).program ports + +theorem initial_length : (script B).initial.length = 4 := rfl + +theorem shrink_length (i : Fin S.steps) : + let a := ShrinkBlockInputs.a i + let m := ShrinkBundlePlan.thickCount a + let n := ShrinkBundlePlan.cap a + (shrink B i).length = 95+m+n+2*(m*n) := by + simp only [shrink, List.length_append, ShrinkBlockInputs.beforeSlices_length, + ShrinkResidentsPlan.visits_length, + BlockSlices.visits_length, ShrinkBlockInputs.slots_length, termPointers_length, + BlockDataHeads.visits_length] + change 36+12+(_+_+_+4)+22+3+4+14 = _ + omega + +/-- The directory uses the program's actual arity. The capacity calculation +can reserve one complete block per state, and the physical run then takes +exactly the shorter chronological directory. -/ +def allocationShape : Shape := + { (geometry B) with + arity := Schedule.arity (script B).catalog + initialRows := (initial B).length + levelPasses := (block B).length } + +/-- The physical descriptor layout for the given base, position capacity and block count, with +the directory sized to the actual visit count. -/ +def layout (base positions blocks : ℕ) : Layout := + let L : Layout := ⟨allocationShape B,base,positions,1+(S.steps+1)*blocks⟩ + LevelFields.tightDirectory L ((initial B).length+blocks*(block B).length) + +theorem directory_rows (base positions blocks : ℕ) : + directoryRows (layout B base positions blocks) = (Schedule.Online.calendar + (script B).plan).total blocks := + (LevelFields.tight_rows ..).trans ((script B).calendar_total blocks).symm + +theorem allocation_end (base positions blocks : ℕ) : + endAddress (layout B base positions blocks) ≤ + endAddress ⟨allocationShape B,base,positions,1+(S.steps+1)*blocks⟩ := by + apply LevelFields.tight_end + apply LevelFields.calendar_capacity + · exact le_rfl + · change blocks ≤ 1+(S.steps+1)*blocks + exact (Nat.le_mul_of_pos_left blocks (show 0 < S.steps+1 by omega)).trans (Nat.le_add_left ..) + · simp [passesPerLevel,allocationShape,geometry] + +theorem layout_arity (base positions blocks : ℕ) : + (layout B base positions blocks).shape.arity = Schedule.arity (script B).catalog := rfl + +theorem actual_level_count (base positions blocks : ℕ) : + (layout B base positions blocks).levels = 1+(S.steps+1)*blocks := rfl + +theorem table_fields : 54 ≤ (geometry B).scalarFields ∧ 6 = (geometry B).tables := ⟨le_rfl,rfl⟩ + +end CompressorRecords.BlockProgram + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockRoleZero.lean b/lean/OAI/Computability/VPVNP/CompressorBlockRoleZero.lean new file mode 100644 index 0000000000..61b2589333 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockRoleZero.lean @@ -0,0 +1,101 @@ +import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner +import OAI.Computability.VPVNP.CompressorRecordsShrinkFrame + +/-! +# Publishing the initial cursor role + +The fourth initial visit writes the cursor role at scalar offset 27. Its +worker receives the two operands computed by the planner. The six packed +incidence columns begin after the level header, so their typed readback +survives the role write. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockRoleZero + +open BurstRAM BurstRAM.PrivateRAM Compression DescriptorSpace BlockPlanner PhaseRecipe IncidenceDirectory +open scoped Fin.CommRing + +variable {w a l : ℕ} + +/-- The level-zero visit that stores the cursor role tag at header offset 27. -/ +def visit := BlockPlanner.publish (LevelFields.address 0 27) (.lit 0) + +/-- Machine-word address of the initial level's role tag. -/ +def role (w : ℕ) (L : DescriptorSpace.Layout) : Word w := ((levelStart L 0+27 : ℕ) : Word w) + +/-- The initial role writer's report, storing zero at the role address and returning cursor +one. -/ +def report (w : ℕ) (L : DescriptorSpace.Layout) : Report w := + ⟨[.tick,.tick,.tick,.write (role w L) 0,.tick,.tick],some 1⟩ + +/-- The operands are evaluated at the first level header; the worker enters +at its own initial cursor zero and returns cursor one. -/ +theorem run (L : DescriptorSpace.Layout) (pub : Fin 5 → Word w) (m : Memory w) : + let header := ((levelStart L 0 : ℕ) : Word w) + let ports : Fin 2 → Word w := fun j ↦ (visit.params j).eval pub header m + let P := (visit.worker.table.instantiate w ports).program + visit.initial.eval pub header m = 0 ∧ visit.stop.eval pub header m = 1 ∧ + execute P 7 (P.start 0) m [] = some (report w L) ∧ + after m (report w L).events = writeMemory m (role w L) 0 ∧ (report w L).probes = 1 ∧ + choiceBits (report w L).events = [] ∧ ∀ x v, Event.read x v ∉ (report w L).events := by + intro header ports P + have dest : ports 0 = role w L := by + change header + (0 : Word w) * LevelFields.stride.eval pub header m + (27 : Word w) = _ + simp [header,role] + have zero : ports 1 = 0 := rfl + obtain ⟨exec,_,_,_⟩ := BlockPlanner.publish_native (LevelFields.address 0 27) (.lit 0) ports 0 m + refine ⟨rfl,rfl,?_,rfl,rfl,rfl,?_⟩ + · change execute ((BlockPlanner.publish (LevelFields.address 0 27) (.lit 0)).worker.table.instantiate w ports).program 7 + (((BlockPlanner.publish (LevelFields.address 0 27) (.lit 0)).worker.table.instantiate w ports).program.start 0) m [] = _ + rw [exec, dest, zero, zero_add]; rfl + · intro x v + simp [report] + +/-- The header write preserves all six base and actual incidence columns. +The column stride may exceed the exact slot count of the represented state. -/ +theorem preserve (L : DescriptorSpace.Layout) (X : State a l) (rows : ℕ) (m : Memory w) + (rep : (packedIncidence L w 0 rows).Represents X m) + (fits : IncidenceDirectory.slotCount X ≤ rows) + (room : incidenceStart L 0 + 6*rows ≤ 2^w) + (before : levelStart L 0+27 < incidenceStart L 0) : + (packedIncidence L w 0 rows).Represents X (after m (report w L).events) := by + let T := packedIncidence L w 0 rows + have roleVal : (role w L).val = levelStart L 0+27 := Nat.mod_eq_of_lt (by omega) + have keep (c : Fin 6) (v : Word w) (hv : v.val < IncidenceDirectory.slotCount X) : + after m (report w L).events (T.column c+v).val = m (T.column c+v).val := by + have hc := Nat.mul_le_mul_right rows c.isLt + rw [Nat.succ_mul] at hc + have top : incidenceBase L 0 rows c+v.val < 2^w := by unfold incidenceBase; omega + have val : (T.column c+v).val = incidenceBase L 0 rows c+v.val := by + rw [show T.column c = CursorRAM.encode w (incidenceBase L 0 rows c) from packed_column .., + Fin.val_add, show (CursorRAM.encode w (incidenceBase L 0 rows c)).val = incidenceBase L 0 rows c + from Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt top] + change writeMemory m (role w L) 0 _ = _ + rw [val, writeMemory, ite_eq_right] + unfold incidenceBase + omega + have base (c : Fin 6) (e : X.Base × Fin (2^a)) := keep c (basePort X e) (basePort_lt X e) + have actual (c : Fin 6) (e : (X.Base × BitWord l) × Fin (2^a)) := keep c (actualPort X e) (actualPort_lt X e) + exact ⟨fun e ↦ (base 0 e).trans (rep.baseOut e),fun e ↦ (base 1 e).trans (rep.baseIn e), + fun e ↦ (base 2 e).trans (rep.shift e),fun e ↦ (actual 3 e).trans (rep.actualOut e), + fun e ↦ (actual 4 e).trans (rep.actualIn e),fun e ↦ (actual 5 e).trans (rep.width e)⟩ + +/-- In a physical level-zero allocation the slot-capacity and exclusive +end-address bounds imply the column room required by the frame proof. -/ +theorem preserve_allocated (L : DescriptorSpace.Layout) (X : State a l) (m : Memory w) + (hl : 0 < L.levels) (scalars : 28 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (slots : IncidenceDirectory.slotCount X ≤ slotCapacity L) + (rep : (packedIncidence L w 0 (IncidenceDirectory.slotCount X)).Represents X m) : + (packedIncidence L w 0 (IncidenceDirectory.slotCount X)).Represents X (after m (report w L).events) := + preserve L X _ m rep le_rfl (packed_incidence_room L fit ⟨0,hl⟩ slots).le + (by unfold incidenceStart levelHeaderWords; omega) + +end CompressorRecords.BlockRoleZero + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockShrinkPrefixFits.lean b/lean/OAI/Computability/VPVNP/CompressorBlockShrinkPrefixFits.lean new file mode 100644 index 0000000000..aead99752b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockShrinkPrefixFits.lean @@ -0,0 +1,175 @@ +import OAI.Computability.VPVNP.CompressorBlockCapacity +import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch +import OAI.Computability.VPVNP.CompressorDescriptorTableFits +import OAI.Computability.VPVNP.CursorDescriptorWords + +/-! +# Word and instruction bounds for the shrinking prefix + +The six current incidence columns end before the first scratch table. The +fixed block's table geometry holds the ten-word term array at every selected +degree. A single eventual threshold handles the capacity of the sorted +bundle totals and the arithmetic performed by the nondeterministic term +worker. Its clock is quartic in the binary input length. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkBranch + +open Compression BurstRAM CursorBounds DescriptorSpace Filter +open scoped Classical + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- A common clock for the deterministic gather and every admitted shrinking +term worker, including its private opcode dispatch. -/ +def prefixClock (b n : ℕ) := + ((SelectedTerms.shrinkGrid B).stepConstant*((b+10)^4+2)+7+ShrinkDemandGather.cost+1)*(n.log2+1)^4 + +theorem prefix_clock {b n M : ℕ} (hM : M ≤ n) : + ShrinkDemandGather.cost < prefixClock B b n ∧ + TermWorker.budget B.shrink 2 8 (wordBits b n) M ≤ prefixClock B b n := by + let L := (n.log2+1)^4 + let G := SelectedTerms.shrinkGrid B + have hL : 1 ≤ L := pow_pos (Nat.succ_pos _) _ + have hs := (G.steps_le (wordBits b n) M).trans (Nat.mul_le_mul_left G.stepConstant (word_plus_clog_le b n M hM)) + have eqn : TermWorker.budget B.shrink 2 8 (wordBits b n) M = + TermRecordScan.eventsPerRow G.block G.d G.e (wordBits b n) M+7 := by + change TermWorker.budget B.shrink 2 8 _ _ = TermRecordScan.eventsPerRow B.shrink 2 8 _ _+7 + unfold TermWorker.budget TermRecordScan.eventsPerRow TermRecordScan.prepFuel; omega + rw [eqn] + change ShrinkDemandGather.cost < (G.stepConstant*((b+10)^4+2)+7+ShrinkDemandGather.cost+1)*L ∧ + _ ≤ (G.stepConstant*((b+10)^4+2)+7+ShrinkDemandGather.cost+1)*L + change _ ≤ G.stepConstant*(((b+10)^4+2)*L) at hs + rw [← Nat.mul_assoc] at hs + have grow (x : ℕ) := Nat.le_mul_of_pos_right x hL + simp only [Nat.add_mul,Nat.one_mul] + have := grow 7 + have := grow ShrinkDemandGather.cost + omega + +/-- Every current incidence column, indexed with the actual row count, ends +before every scratch table, including the zeroth table. -/ +theorem incidence_before (L : Layout) (w level rows : ℕ) (table : Fin L.shape.tables) + (fits : rows ≤ slotCapacity L) (c : Fin 6) : + ((packedIncidence L w level rows).column c).val+rows ≤ tableBase L level table := by + rw [packed_column] + have h := Nat.mul_le_mul_right rows c.isLt + rw [Nat.succ_mul] at h + have hc := h.trans (Nat.mul_le_mul_left 6 fits) + exact (Nat.add_le_add_right (Nat.mod_le ..) _).trans (by + change incidenceStart L level+c.val*rows+rows ≤ incidenceStart L level+6*slotCapacity L+table.val*tableWords L + omega) + +/-- In the compiled block allocation the exclusive ends of the six +incidence columns precede the term workspace. The sole ambient address +bound is that the allocated levels fit in the machine word. -/ +theorem prefix_layout {a g w : ℕ} (i : Fin S.steps) (h : a = S.degreeExponent i.castSucc) + (X : State a (packingLaneBits a g)) (base pos blocks : ℕ) + (level : Fin (BlockProgram.layout B base pos blocks).levels) + (positions : X.positions ≤ pos) + (room : endAddress (BlockProgram.layout B base pos blocks) < 2^w) : + let L := BlockProgram.layout B base pos blocks + let T := packedIncidence L w level.val (DemandRAM.oldCount X) + let start := tableBase L level.val (0 : Fin 6) + (∀ c : Fin 6, (T.column c).val+DemandRAM.oldCount X ≤ start) ∧ + ShrinkInput.termEnd X start 10 < 2^w := by + subst a + intro L T start + have sites : Fintype.card X.Base*2^(packingLaneBits (S.degreeExponent i.castSucc) g) = X.positions := by + simp only [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv _),Fintype.card_fin] + have deg : 2^S.degreeExponent i.castSucc ≤ slotDegree S := + (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ _)).trans + (le_max_right ..) + have rs : DemandRAM.oldCount X ≤ slotCapacity L := by + change Fintype.card X.Base*2^_*2^_ ≤ pos*slotDegree S + rw [sites] + exact Nat.mul_le_mul positions deg + refine ⟨incidence_before L w level.val (DemandRAM.oldCount X) (0 : Fin 6) rs,?_⟩ + have fit := (BlockProgram.field_rates B base pos blocks).1 + have size : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords L := by + change _ ≤ pos*slotDegree S*BlockProgram.fieldCount B + rw [Nat.mul_assoc]; exact Nat.mul_le_mul positions fit + exact (ShrinkLevelSpace.packed_ends S i X start 0 0 0 w).2.1.trans_lt (tableStop_lt L level (0 : Fin 6) size room) + +private theorem prefix_numeric {a g w : ℕ} (X : State a (packingLaneBits a g)) + (T : IncidenceDirectory w) (start cap : ℕ) + (cols : ∀ c : Fin 6, (T.column c).val+DemandRAM.oldCount X ≤ start) + (room : ShrinkInput.termEnd X start 10 < 2^w) (ten : 10 < 2^w) + (width : ShrinkRankSpace.cap a*X.maxWireWidth < 2^w) + (bits : ShrinkTermSelection.fitConstant B.shrink+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (gather : ShrinkDemandGather.cost < cap) (clock : TermWorker.budget B.shrink 2 8 w X.maxWireWidth ≤ cap) : + PrefixFits B X T start (Fin.ofNat _ 10) cap := by + have stride : (Fin.ofNat (2^w) 10).val = 10 := Nat.mod_eq_of_lt ten + exact ⟨cols,stride.ge,by rw [stride]; exact room,width,bits,gather,clock⟩ + +set_option maxHeartbeats 1200000 in +/-- One input threshold works for every level, every split of the lane bits +and every allowed shrinking choice. The current position and width bounds +are exactly the bounds supplied by the selected cursor execution. -/ +theorem eventually_prefixFits (b : ℕ) (hb : 1 ≤ b) : ∀ᶠ n : ℕ in atTop, + ∀ (i : Fin S.steps) {g : ℕ} + (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)), + X.positions ≤ initialPositions b n → X.maxWireWidth ≤ n → + ∀ (base blocks : ℕ) (level : Fin (BlockProgram.layout B base (initialPositions b n) blocks).levels), + let w := wordBits b n + let L := BlockProgram.layout B base (initialPositions b n) blocks + let T := packedIncidence L w level.val (DemandRAM.oldCount X) + let start := tableBase L level.val (0 : Fin 6) + endAddress L < 2^w → ∀ cap, prefixClock B b n ≤ cap → PrefixFits B X T start (Fin.ofNat _ 10) cap := by + let Q := Finset.univ.sup fun i : Fin S.steps => ShrinkRankSpace.cap (S.degreeExponent i.castSucc) + filter_upwards [CursorRAM.eventual_word_room b hb ((PolynomiallyBounded.const Q).mul PolynomiallyBounded.id), + CursorRAM.eventual_word_room b hb (PolynomiallyBounded.const 10), + DemandPreparation.eventually_live_word_fits b hb (ShrinkTermSelection.fitConstant B.shrink) 4 1 1] + with n product ten words + intro i g X positions width base blocks level w L T start room cap enough + have layout := prefix_layout B i rfl X base (initialPositions b n) blocks level positions room + have clocks := prefix_clock B (b := b) width + have wordFit := words X.maxWireWidth (by simpa using width) + have q : ShrinkRankSpace.cap (S.degreeExponent i.castSucc) ≤ Q := Finset.le_sup (f := fun j : Fin S.steps => ShrinkRankSpace.cap (S.degreeExponent j.castSucc)) (Finset.mem_univ i) + exact prefix_numeric B X T start cap layout.1 layout.2 ten ((Nat.mul_le_mul q width).trans_lt product) + wordFit (clocks.1.trans_le enough) (clocks.2.trans enough) + +/-- The chosen selector-bit constant and all four integerized relative masses +fit at one common threshold independent of the current shrinking state. -/ +theorem eventually_selectionWords (b : ℕ) (hb : 1 ≤ b) : ∀ᶠ n : ℕ in atTop, + (Fin.ofNat (2^(wordBits b n)) B.shrink.selectorBits).val = B.shrink.selectorBits ∧ + ∀ t, MotifAdmission.weight ShrinkMotif.relativeMass t < 2^(wordBits b n) := by + let K := B.shrink.selectorBits+Finset.univ.sup (MotifAdmission.weight ShrinkMotif.relativeMass) + filter_upwards [CursorRAM.eventual_word_room b hb (PolynomiallyBounded.const K)] with n room + change K < 2^(wordBits b n) at room + refine ⟨Nat.mod_eq_of_lt ((Nat.le_add_right ..).trans_lt room),fun t => ?_⟩ + exact (Finset.le_sup (f := MotifAdmission.weight ShrinkMotif.relativeMass) (Finset.mem_univ t)).trans_lt + ((Nat.le_add_left ..).trans_lt room) + +/-- The selected geometry fits the same zeroth scratch table as its term +array. Together with the two eventual word lemmas this supplies every +numerical premise of the actual shrinking-branch construction. -/ +theorem selected_geometry_fit {g w : ℕ} (i : Fin S.steps) + (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) + (base pos blocks : ℕ) (level : Fin (BlockProgram.layout B base pos blocks).levels) + (sites : X.positions ≤ pos) (room : endAddress (BlockProgram.layout B base pos blocks) < 2^w) : + let L := BlockProgram.layout B base pos blocks + let start := tableBase L level.val (0 : Fin 6) + SelectedFinish.stop X (ShrinkInput.termHead (w := w) X start) (Fin.ofNat _ 10) ≤ 2^w := by + intro L start + have fit := (BlockProgram.field_rates B base pos blocks).1 + have size : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords L := by + change _ ≤ pos*slotDegree S*BlockProgram.fieldCount B + rw [Nat.mul_assoc] + exact Nat.mul_le_mul sites fit + exact ((ShrinkLevelSpace.packed_ends S i X start 0 0 0 w).2.2.1.trans_lt + (tableStop_lt L level (0 : Fin 6) size room)).le + +end CompressorRecords.ShrinkBranch + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockSlices.lean b/lean/OAI/Computability/VPVNP/CompressorBlockSlices.lean new file mode 100644 index 0000000000..3d1c1b0d9b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockSlices.lean @@ -0,0 +1,92 @@ +import OAI.Computability.VPVNP.CompressorShrinkBlockInputs +import OAI.Computability.VPVNP.CompressorShrinkABSliceRecipe +import OAI.Computability.VPVNP.CompressorSurvivingNative + +/-! +# Physical AB intersections and selected-role subdivisions of a block + +The AB stage pairs the thick sorted fields with the new AB widths in the +same bundle. The four selected-role stages recover the absolute motif ID, +read its chosen supply coordinate and write both the split width and the +singleton intersection record. The subsequent slot pass reads those +physical split widths. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockSlices + +open BurstRAM PhaseRecipe BlockPlanner Compression ShrinkSliceSweep +open ShrinkBlockInputs + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + (F : DescriptorSpace.Shape) (i : Fin S.steps) + +/-- Address operands for intersecting the sorted old thick-wire intervals with the new AB +intervals in each bundle. -/ +def abInputs (origin abArena : Expr) : ShrinkABSliceRecipe.Inputs := + let thick := ShrinkBundlePlan.prefixParams i.val (a i) origin false + let fresh := ShrinkBundlePlan.abParams i.val (a i) origin + ⟨ShrinkBundlePlan.bundles i.val (a i),thick 3,thick 2,thick 1,fresh 4,fresh 3,fresh 1,abArena⟩ + +/-- The AB interval-intersection scans for the given shrinking step and its fixed thick-wire +and bundle capacities. -/ +def intersections (origin abArena : Expr) : List Visit := + ShrinkABSliceRecipe.visits (abInputs i origin abArena) (ShrinkBundlePlan.thickCount (a i)) + (ShrinkBundlePlan.cap (a i)) + +/-- Total subdivision count across the shrinking slot template. -/ +def subdivisionSum := ∑ t, (slotTemplate i).subdivisions t + +/-- Address of the surviving-interval array following the four width columns for each slot +subdivision. -/ +def intervals (widthArena : Expr) : Expr := + widthArena.add (((Expr.lit 4).mul (LevelFields.slots i.val)).mul (.lit (subdivisionSum i))) + +/-- The physical motif, term, layout, width and interval operands used to compute the surviving +subdivisions. -/ +def survivingHeads (origin widthArena : Expr) : SurvivingNative.Heads := + let chosen := selectedInputs B F i origin + ⟨chosen.motifs,chosen.termBase,.lit chosen.termStride,ShrinkBundlePlan.absoluteCD i.val + (a i) origin, + SelectedPlan.layoutCell chosen,.lit chosen.selectorBits,widthArena,intervals i widthArena⟩ + +/-- The native phases that read the selected terms and write the surviving subdivision widths +and intervals. -/ +def surviving (origin widthArena : Expr) : List Visit := + SurvivingNative.phases (slotTemplate i).subdivisions (survivingHeads B F i origin widthArena) + +/-- The shrinking slice visits in order, first AB intersections and then surviving-role +subdivisions. -/ +def visits (origin abArena widthArena : Expr) : List Visit := + intersections i origin abArena ++ surviving B F i origin widthArena + +theorem visits_length (origin abArena widthArena : Expr) : + let m := ShrinkBundlePlan.thickCount (a i) + let n := ShrinkBundlePlan.cap (a i) + (visits B F i origin abArena widthArena).length = m+n+2*(m*n)+4 := by + simp only [visits,intersections,surviving,List.length_append,ShrinkABSliceRecipe.visits_length, + SurvivingNative.phases,List.length_ofFn] + +theorem split_source (origin widthArena : Expr) : + (survivingHeads B F i origin widthArena).widthBase = widthArena := rfl + +theorem ab_operands (origin abArena : Expr) : + (abInputs i origin abArena).oldStarts = ShrinkBundlePlan.prefixStart i.val (a i) origin ∧ + (abInputs i origin abArena).oldWidths = ShrinkBundlePlan.sorted i.val (a i) origin ∧ + (abInputs i origin abArena).newWidths = ShrinkBundlePlan.abStart i.val (a i) origin ∧ + (abInputs i origin abArena).newStarts = + (ShrinkBundlePlan.abStart i.val (a i) origin).add (ShrinkBundlePlan.blockSize i.val (a i)) := + ⟨rfl,rfl,rfl,rfl⟩ + +end CompressorRecords.BlockSlices + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBlockStartupPrefix.lean b/lean/OAI/Computability/VPVNP/CompressorBlockStartupPrefix.lean new file mode 100644 index 0000000000..4a0bc535bd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBlockStartupPrefix.lean @@ -0,0 +1,183 @@ +import OAI.Computability.VPVNP.CompressorBlockInitialPackets + +/-! +# The level-zero source prefix from physical startup data + +At each sufficiently large length the saved cursor operands come from the +eight linked startup stages. The four initial descriptor workers produce +the typed cursor graph, preserve all eight operands, and publish the +terminal six scalars used by the first selected substep. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockStartupPrefix + +open BurstRAM BlockPlanner CursorBounds DescriptorSpace CursorNetwork BlockHeaderRun +open scoped Fin.CommRing +open private address_val fit_fields from OAI.Computability.VPVNP.CompressorBlockHeaderRun + +variable {w : ℕ} + +open Compression in +/-- The level-zero startup reports execute and leave the packed cursor graph and its persistent +metadata in memory. -/ +structure Resident (L : Layout) (a b l width n : ℕ) (base : Word w) (m : Memory w) (X : State a l) : Prop where + walk : SourceWalk (BlockInitialPackets.Source L a (Workspace.ports L.shape.arity base).data (header w L 0)) + (BlockInitialPackets.order L a) m (BlockInitialPackets.logs L a b l width m) + rows : IncidenceDirectory.slotCount X = CursorRAM.rowCount b l a + room : incidenceStart L 0 + 6*CursorRAM.rowCount b l a ≤ 2^w + incidenceHeads : ∀ c : Fin 6, BlockInitialPackets.post L a b l width m (incidenceHead L 0 c) = + (incidenceBase L 0 (CursorRAM.rowCount b l a) c : Word w) + tableHeads : ∀ j : Fin L.shape.tables, BlockInitialPackets.post L a b l width m (tableHead L 0 j) = + (tableBase L 0 j : Word w) + incidence : (packedIncidence L w 0 (CursorRAM.rowCount b l a)).Represents X (BlockInitialPackets.post L a b l width m) + scalars : Scalars.Present (.terminal a) ((b+l)*2^b) l (header w L 0) (BlockInitialPackets.post L a b l width m) + frame : Frame.data (header w L 0+6) (BlockInitialPackets.post L a b l width m) = + CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L)) (CursorRAM.encode w 1) b l a width + (incidenceStart L 0) + role : BlockInitialPackets.post L a b l width m (levelStart L 0+27) = 0 + arena : (BlockInitialPackets.post L a b l width m (levelStart L 0+14)).val = endAddress L + levels : (BlockInitialPackets.post L a b l width m (levelStart L 0+28)).val = L.levels + length : (BlockInitialPackets.post L a b l width m (levelStart L 0+29)).val = n + positions : ((b+l)*2^b)*2^l = L.positions + +/-- All fields consumed by the following pass are recovered on a live +memory agreeing with the raw output above the first level header. This +includes the incoming and outgoing columns at their computed indices. -/ +theorem Resident.live {L : Layout} {a b l width n : ℕ} {base : Word w} {m : Memory w} + {X : Compression.State a l} (resident : Resident L a b l width n base m X) (live : Memory w) + (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) (BlockInitialPackets.post L a b l width m) live) + (nonempty : 0 < L.levels) (fields : 14 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) : + let N := CursorRAM.rowCount b l a + (packedIncidence L w 0 N).Represents X live ∧ + Scalars.Present (.terminal a) ((b+l)*2^b) l (header w L 0) live ∧ + Frame.data (header w L 0+6) live = + CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L)) (CursorRAM.encode w 1) b l a width + (incidenceStart L 0) ∧ + (∀ c : Fin 6, live (incidenceHead L 0 c) = (incidenceBase L 0 N c : Word w)) ∧ + (∀ j : Fin L.shape.tables, live (tableHead L 0 j) = (tableBase L 0 j : Word w)) ∧ + live (levelStart L 0+27) = 0 ∧ (live (levelStart L 0+14)).val = endAddress L ∧ + (live (levelStart L 0+28)).val = L.levels ∧ (live (levelStart L 0+29)).val = n := by + intro N + let raw := BlockInitialPackets.post L a b l width m + let T := packedIncidence L w 0 N + have col (c : Fin 6) (j : Word w) (hj : j.val < N) : live (T.column c+j).val = raw (T.column c+j).val := by + apply (agree _ _).symm + have right := Nat.mul_le_mul_right N c.isLt + rw [Nat.succ_mul] at right + have room := resident.room + change incidenceStart L 0 + 6*N ≤ 2^w at room + have top : incidenceBase L 0 N c+j.val < 2^w := by unfold incidenceBase; omega + rw [show T.column c = CursorRAM.encode w (incidenceBase L 0 N c) from packed_column .., + Fin.val_add,show (CursorRAM.encode w (incidenceBase L 0 N c)).val = incidenceBase L 0 N c + from Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt top] + unfold incidenceBase incidenceStart + omega + have baseRead (c : Fin 6) (e : X.Base × Fin (2^a)) := col c (IncidenceDirectory.basePort X e) + ((IncidenceDirectory.basePort_lt X e).trans_le resident.rows.le) + have actualRead (c : Fin 6) (e : (X.Base × Compression.BitWord l) × Fin (2^a)) := col c + (IncidenceDirectory.actualPort X e) ((IncidenceDirectory.actualPort_lt X e).trans_le resident.rows.le) + have inc := resident.incidence + have rep : T.Represents X live := + ⟨fun e ↦ (baseRead 0 e).trans (inc.baseOut e),fun e ↦ (baseRead 1 e).trans (inc.baseIn e), + fun e ↦ (baseRead 2 e).trans (inc.shift e),fun e ↦ (actualRead 3 e).trans (inc.actualOut e), + fun e ↦ (actualRead 4 e).trans (inc.actualIn e),fun e ↦ (actualRead 5 e).trans (inc.width e)⟩ + have room := fit_fields L ⟨0,nonempty⟩ fit + change levelStart L 0+L.shape.scalarFields < 2^w at room + have field (j : ℕ) (hj : j < 14) : + live (header w L 0+(j : Word w)).val = raw (header w L 0+(j : Word w)).val := by + rw [address_val L 0 j (by omega)] + exact (agree _ (Nat.le_add_right ..)).symm + refine ⟨rep,?_,?_,?_,?_,?_,?_,?_,?_⟩ + · intro j + exact (congrArg Fin.val (field j.val (j.isLt.trans (by decide)))).trans (resident.scalars j) + · refine Eq.trans ?_ resident.frame + funext j + change live (header w L 0+6+(j.val : Word w)).val = raw (header w L 0+6+(j.val : Word w)).val + rw [show header w L 0+6+(j.val : Word w) = header w L 0+((6+j.val : ℕ) : Word w) by simp [add_assoc]] + exact field _ (by have := j.isLt; omega) + · intro c + exact (agree _ (by unfold incidenceHead; omega)).symm.trans (resident.incidenceHeads c) + · intro j + exact (agree _ (by unfold tableHead; omega)).symm.trans (resident.tableHeads j) + · exact (agree _ (Nat.le_add_right ..)).symm.trans resident.role + · exact (congrArg Fin.val (agree _ (Nat.le_add_right ..)).symm).trans resident.arena + · exact (congrArg Fin.val (agree _ (Nat.le_add_right ..)).symm).trans resident.levels + · exact (congrArg Fin.val (agree _ (Nat.le_add_right ..)).symm).trans resident.length + +theorem resident {a b l pad : ℕ} {T : Type} [Fintype T] (L : Layout) (n : ℕ) (base : Word w) + (m : Memory w) (hD : 1 < b+l) (hd : 2+pad = 2^a) (bits : T → ℕ) + (ready : BlockHeaderStartup.Ready L a b l (∑ t, bits t) n base m) (fields : 30 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (room : incidenceStart L 0+6*CursorRAM.rowCount b l a ≤ 2^w) + (width : (∑ t, bits t) < 2^w) : + Resident L a b l (∑ t, bits t) n base m (cursorState (cursorCoordinateLabels b l) hD hd bits) := by + obtain ⟨walk,inc,role,keep,arena,levels,len⟩ := BlockInitialPackets.initial L n base m hD hd bits + ready fields fit room width + have hfield := fit_fields L ⟨0,ready.nonempty⟩ fit + change levelStart L 0 + L.shape.scalarFields < 2^w at hfield + have low (i : ℕ) (hi : i < 14) : + BlockInitialPackets.post L a b l (∑ t, bits t) m (header w L 0+(i : Word w)).val = + initialFinal a L m (header w L 0+(i : Word w)).val := by + rw [address_val L 0 i (by omega)] + exact keep _ (by unfold incidenceStart levelHeaderWords; omega) (by omega) + have cards : IncidenceDirectory.slotCount (cursorState (cursorCoordinateLabels b l) hD hd bits) = CursorRAM.rowCount b l a := by + change Fintype.card (Fin (b+l) × Compression.BitWord b)*2^l*2^a = ((b+l)*2^b*2^l)*2^a + rw [Fintype.card_prod,Fintype.card_fin,Fintype.card_congr (Compression.bitWordFinEquiv b),Fintype.card_fin] + refine ⟨walk,cards,room,?_,?_,inc,?_,?_,role,arena,levels,len,ready.positions⟩ + · intro c + rw [keep _ (by unfold incidenceHead incidenceStart levelHeaderWords; have := c.isLt; omega) + (by unfold incidenceHead; omega)] + exact ready.initial.heads.incidence c + · intro j + rw [keep _ (by unfold tableHead incidenceStart levelHeaderWords; have := j.isLt; omega) + (by unfold tableHead; omega)] + exact ready.initial.heads.tables j + · intro j + exact (congrArg Fin.val (low j.val (j.isLt.trans (by decide)))).trans (ready.initial.terminal j) + · refine Eq.trans ?_ (ready.initial.cursorFrame.trans ready.frame) + funext i + change BlockInitialPackets.post L a b l (∑ t, bits t) m (header w L 0+6+(i.val : Word w)).val = _ + have addr : header w L 0+6+(i.val : Word w) = header w L 0+((6+i.val : ℕ) : Word w) := by simp [add_assoc] + change BlockInitialPackets.post L a b l (∑ t, bits t) m (header w L 0+6+(i.val : Word w)).val = + initialFinal a L m (header w L 0+6+(i.val : Word w)).val + rw [addr] + exact low _ (by have := i.isLt; omega) + +open CursorRouting Compression in +/-- One length threshold covers both the true pair startup and all four +initial descriptor visits, uniformly in the incoming contents of RAM. -/ +theorem eventually_resident (D : CalendarRows.Spec) (d : ℕ) (F : Shape) (B a pad lanes steps : ℕ) + (hd : 2+pad = 2^a) (hB : 1 ≤ B) (hq : 0 < D.q) (hph : 0 < D.phaseRows) + (hθ : (D.p : ℝ)/D.q ≤ 1) (hlanes : lanes ≤ B) + (arity : 7 ≤ F.arity) (fields : 30 ≤ F.scalarFields) {base : ℕ → ℕ} (hb : PolynomiallyBounded base) : + ∀ᶠ n : ℕ in Filter.atTop, ∀ (pub : Fin 11 → Word (wordBits B n)) (tag : Word (wordBits B n)), + (pub 2).val = base n → (pub 6).val = n → (pub 7).val = addressBits B n → tag.val < base n → + ∀ m, let L := LevelFields.tightDirectory (cursorLayout F B steps ((D.p : ℝ)/D.q) (base n) n) (CalendarRows.rows D n) + let l := roundedDown D.p D.q n*lanes + let b := virtualBits B n-l + let widths : RAMSystem (virtualBits B n) → ℕ := ramFieldBits (virtualBucket n) (wordBits B n) + ∃ hD : 1 < b+l, Resident L a b l (initialWidth B n) n (pub 2) + (BlockHeaderStartup.post D d L B n a lanes steps pub tag m) + (cursorState (cursorCoordinateLabels b l) hD hd widths) := by + filter_upwards [BlockHeaderStartup.eventually_ready D d F B a lanes steps hB hq hph hθ hlanes arity fields hb, + DescriptorParameters.eventually_tight_capacity D F B a lanes hB hθ hlanes hb, + DescriptorParameters.eventually_tight_end D F B steps hB hb] with n ready cap fit + intro pub tag workspace length address lower m + let P := cursorLayout F B steps ((D.p : ℝ)/D.q) (base n) n + let L := LevelFields.tightDirectory P (CalendarRows.rows D n) + let l := roundedDown D.p D.q n*lanes + let b := virtualBits B n-l + let bits : RAMSystem (virtualBits B n) → ℕ := ramFieldBits (virtualBucket n) (wordBits B n) + have hc := (cap P.positions P.levels).2 + have large : 1 < b+l := hc.split ▸ hc.cursors + refine ⟨large,resident L n (pub 2) _ large hd bits (ready pub tag workspace length address lower m) + fields fit hc.arrays_end.le hc.width_lt⟩ + +end CompressorRecords.BlockStartupPrefix + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBranchSegments.lean b/lean/OAI/Computability/VPVNP/CompressorBranchSegments.lean new file mode 100644 index 0000000000..2f93843099 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBranchSegments.lean @@ -0,0 +1,177 @@ +import OAI.Computability.VPVNP.CompressorOnlineRowInverse +import OAI.Computability.VPVNP.CompressorSourceWalk +import OAI.Computability.VPVNP.LiveDeterministicPaths + +/-! # Factoring a native compression pass at its term-selection row + +Every surrounding descriptor scan has a verified run on empty choice tapes. +An accepting stream must follow those scans exactly. The selector row is +inverted on the actual intervening memory, and its source-worker inverse +recovers the selected term. Concatenation preserves the remaining native +calls, their reports and the memory used by the next compression level. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BranchSegments +open BurstRAM + +variable {w : ℕ} {Q : Type*} {P : BurstRAM.Program w Q} {cap : ℕ} +variable {st : Option (Word w)} {m : Memory w} + +/-- A finite initial portion of a run of the fixed table. -/ +structure Segment (P : BurstRAM.Program w Q) (cap : ℕ) (st : Option (Word w)) (m : Memory w) where + /-- One choice tape for each successive native call in the segment. -/ + bits : List (List Bool) + /-- Reports returned by those calls, in execution order. -/ + logs : List (Report w) + run : runSegment P cap st m bits = some logs + +namespace Segment + +variable (s : Segment P cap st m) + +/-- The cursor returned by the segment, computed from its initial state and reports. -/ +def state := endState st s.logs +/-- External memory obtained by applying all events in the segment to its initial memory. -/ +def memory := after m (eventLog s.logs) + +/-- Concatenate consecutive runs, feeding the first segment's ending cursor and memory to the +second. -/ +def append (t : Segment P cap s.state s.memory) : Segment P cap st m where + bits := s.bits ++ t.bits + logs := s.logs ++ t.logs + run := by + rw [PrimedSchedule.runSegment_append,s.run] + change (runSegment P cap s.state s.memory t.bits).map _ = _ + rw [t.run]; rfl + +@[simp] theorem append_state (t : Segment P cap s.state s.memory) : (s.append t).state = t.state := + endState_append _ _ _ + +@[simp] theorem append_memory (t : Segment P cap s.state s.memory) : (s.append t).memory = t.memory := + SourceWalk.after_append _ _ _ + +/-- The zero-call segment with empty tape and report lists. -/ +def empty (P : BurstRAM.Program w Q) (cap : ℕ) (st : Option (Word w)) (m : Memory w) : Segment P cap st m := + ⟨[],[],rfl⟩ + +/-- Once the choice prefix is known, the reports and continuation memory +are uniquely determined by native execution. -/ +theorem remainder {tail : List (List Bool)} {logs : List (Report w)} + (run : runSegment P cap st m (s.bits ++ tail) = some logs) (halt : endState st logs = none) : + ∃ more, logs = s.logs ++ more ∧ runSegment P cap s.state s.memory tail = some more ∧ + endState s.state more = none := by + rw [PrimedSchedule.runSegment_append,s.run] at run + change (runSegment P cap s.state s.memory tail).map _ = some logs at run + obtain ⟨more,hr,rfl⟩ := Option.map_eq_some_iff.mp run + exact ⟨more,rfl,hr,(endState_append st s.logs more).symm.trans halt⟩ + +end Segment + +/-- Distinct mathematical choices have incompatible prefixes on the physical +tape, and every accepting run starts with one of these prefixes. -/ +structure Cut (P : BurstRAM.Program w Q) (cap : ℕ) (st : Option (Word w)) (m : Memory w) (I : Type*) where + /-- The initial native segment associated with each possible branch index. -/ + part : I → Segment P cap st m + separate : ∀ i j a b, (part i).bits ++ a = (part j).bits ++ b → i = j + cover : ∀ bs rs, runSegment P cap st m bs = some rs → endState st rs = none → + ∃ i tail, bs = (part i).bits ++ tail + +namespace Cut + +variable {I : Type*} (c : Cut P cap st m I) + +/-- Restore the precise logs and native execution of the suffix. -/ +theorem split {bs rs} (run : runSegment P cap st m bs = some rs) (halt : endState st rs = none) : + ∃ i tail more, bs = (c.part i).bits ++ tail ∧ rs = (c.part i).logs ++ more ∧ + runSegment P cap (c.part i).state (c.part i).memory tail = some more ∧ + endState (c.part i).state more = none := by + obtain ⟨i,tail,rfl⟩ := c.cover bs rs run halt + obtain ⟨more,hl,hr,hh⟩ := (c.part i).remainder run halt + exact ⟨i,tail,more,rfl,hl,hr,hh⟩ + +/-- The next branch tree is chosen in the actual memory left by this one. -/ +def bind {J : I → Type*} (k : ∀ i, Cut P cap (c.part i).state (c.part i).memory (J i)) : + Cut P cap st m (Sigma J) where + part z := (c.part z.1).append ((k z.1).part z.2) + separate := by + rintro ⟨i,x⟩ ⟨j,y⟩ a b h + change ((c.part i).bits ++ ((k i).part x).bits) ++ a = ((c.part j).bits ++ ((k j).part y).bits) ++ b at h + simp only [List.append_assoc] at h + cases c.separate i j _ _ h + cases (k i).separate x y _ _ (List.append_cancel_left h) + rfl + cover := by + intro bs rs run halt + obtain ⟨i,tail,more,hb,_,hr,hh⟩ := c.split run halt + obtain ⟨j,rest,hj⟩ := (k i).cover tail more hr hh + exact ⟨⟨i,j⟩,rest,by simp only [hb,hj,Segment.append,List.append_assoc]⟩ + +/-- A run on empty choices is forced call by call, even if a later term +selection has no valid branches. -/ +def deterministic (s : Segment P cap st m) (n : ℕ) (hb : s.bits = List.replicate n []) : + Cut P cap st m Unit where + part _ := s + separate _ _ _ _ _ := Subsingleton.elim _ _ + cover bs rs run halt := by + obtain ⟨rest,_,e,_,_⟩ := LiveProgram.split_empty_segment (hb ▸ s.run) run halt + exact ⟨(),rest,hb.symm ▸ e⟩ + +/-- Prepend a forced part without adding an index to the selected terms. -/ +def before (s : Segment P cap st m) (n : ℕ) (emptyBits : s.bits = List.replicate n []) + (k : Cut P cap s.state s.memory I) : Cut P cap st m I where + part i := s.append (k.part i) + separate i j a b h := by + change (s.bits ++ (k.part i).bits) ++ a = (s.bits ++ (k.part j).bits) ++ b at h + simp only [List.append_assoc] at h + exact k.separate i j _ _ (List.append_cancel_left h) + cover bs rs run halt := by + obtain ⟨_,tail,more,hb,_,hr,hh⟩ := (deterministic s n emptyBits).split run halt + obtain ⟨i,rest,e⟩ := k.cover tail more hr hh + exact ⟨i,rest,by simpa only [Segment.append,deterministic,List.append_assoc,e] using hb⟩ + +/-- Attach the forced output-directory scans for each selected term. -/ +def afterChoice (k : ∀ i, Segment P cap (c.part i).state (c.part i).memory) + (n : I → ℕ) (emptyBits : ∀ i, (k i).bits = List.replicate (n i) []) : Cut P cap st m I where + part i := (c.part i).append (k i) + separate i j a b h := by + change ((c.part i).bits ++ (k i).bits) ++ a = ((c.part j).bits ++ (k j).bits) ++ b at h + simp only [List.append_assoc] at h + exact c.separate i j _ _ h + cover bs rs run halt := by + obtain ⟨i,tail,more,hb,_,hr,hh⟩ := c.split run halt + obtain ⟨_,rest,e⟩ := (deterministic (k i) (n i) (emptyBits i)).cover tail more hr hh + exact ⟨i,rest,by simpa only [Segment.append,deterministic,List.append_assoc,e] using hb⟩ + +/-- Physical path bijection, retaining a cap or observation on the entire +concatenated report sequence. -/ +noncomputable def pathsEquiv (allow : List (Report w) → Prop) : + (Σ i, LiveProgram.PathsFrom P cap (c.part i).state (c.part i).memory + (fun rs => allow ((c.part i).logs ++ rs))) ≃ LiveProgram.PathsFrom P cap st m allow := by + let join : (Σ i, LiveProgram.PathsFrom P cap (c.part i).state (c.part i).memory + (fun rs => allow ((c.part i).logs ++ rs))) → LiveProgram.PathsFrom P cap st m allow := fun z => + ⟨(c.part z.1).bits ++ z.2.val,by + obtain ⟨rs,hr,hh,allowed⟩ := z.2.property + let t : Segment P cap (c.part z.1).state (c.part z.1).memory := ⟨z.2.val,rs,hr⟩ + exact ⟨_,((c.part z.1).append t).run,((c.part z.1).append_state t).trans hh,allowed⟩⟩ + apply Equiv.ofBijective join + constructor + · rintro ⟨i,x⟩ ⟨j,y⟩ h + have e := congrArg Subtype.val h + change (c.part i).bits ++ x.val = (c.part j).bits ++ y.val at e + cases c.separate i j _ _ e + cases Subtype.ext (List.append_cancel_left e) + rfl + · rintro ⟨bs,rs,hr,hh,allowed⟩ + obtain ⟨i,rest,more,hb,rfl,run,halt⟩ := c.split hr hh + exact ⟨⟨i,rest,more,run,halt,allowed⟩,Subtype.ext hb.symm⟩ + +end Cut +end CompressorRecords.BranchSegments + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleFixedGather.lean b/lean/OAI/Computability/VPVNP/CompressorBundleFixedGather.lean new file mode 100644 index 0000000000..44fdf3809f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleFixedGather.lean @@ -0,0 +1,74 @@ +import OAI.Computability.VPVNP.CompressorBundleKeyTable +import OAI.Computability.VPVNP.CompressorRecordsShrinkRAM + +/-! +# A fixed-bank worker for gathering the complete pair of bundle key tables + +The cursor visits a packed port's thick-wire entries followed by its motif +entries. The physical rectangular arrays keep all thick rows first and all +motif rows second. Integer division and a single bit computed from the +within-port position give the correct physical row without changing the +public parameter bank between calls. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleGather.Fixed + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open ShrinkRAM (div mod) + +variable {w : ℕ} + +/-- Encode a natural table size, index or address as a machine word of the chosen width. -/ +abbrev word (j : ℕ) : Word w := Fin.ofNat (2^w) j + +/-- Public words are the total per port, thick entries per port, port count, +row stride, ID base, classifier key base, and gathered key base. -/ +def visit : List (Op 8 7) := + [.stateWord 0, .publicWord 1 0, .binary .div 2 0 1, .binary .mod 3 0 1, + .publicWord 4 1, .constant 5 1, .binary .add 6 3 5, .binary .div 6 4 6, + .binary .div 6 6 6, .binary .sub 6 5 6, .publicWord 7 2, .binary .mul 7 6 7, + .binary .add 2 2 7, .publicWord 7 3, .binary .mul 2 2 7, .binary .mul 7 6 4, + .binary .sub 3 3 7, .binary .add 2 2 3, .publicWord 7 4, .binary .add 7 7 2, + .read 1 7, .publicWord 7 5, .binary .add 7 7 1, .read 1 7, + .publicWord 7 6, .binary .add 7 7 2, .write 7 1, .binary .add 0 0 5] + +/-- The quotient test is positive exactly in the thick part of a port. -/ +def offset (p : Fin 7 → Word w) (i : Word w) : Word w := + let z := mod i (p 0) + let ratio := div (p 1) (z+1) + let cd := 1 - div ratio ratio + (div i (p 0) + cd * p 2) * p 3 + (z - cd * p 1) + +/-- The visit reads the stored arc identifier, looks up its key, and writes that key into the +corresponding output slot. -/ +def events (p : Fin 7 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + let off := offset p i + let src := p 4+off + let id := m src.val + let keyAddr := p 5+id + let key := m keyAddr.val + List.replicate 20 .tick ++ [.read src id,.tick,.tick,.read keyAddr key,.tick,.tick,.write (p 6+off) key,.tick] + +theorem native (p : Fin 7 → Word w) (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program 29 (M.program.start i) m [] = some ⟨events p m i,some (i+1)⟩ := by + change execute ((template visit 0).instantiate w p).program (1+visit.length) ⟨_,i,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + rw [execute_template,run_eq_trace] + rfl + +theorem after_events (p : Fin 7 → Word w) (m : Memory w) (i : Word w) : + after m (events p m i) = + writeMemory m (p 6+offset p i) (m (p 5 + m (p 4+offset p i).val).val) := rfl + +theorem work (p : Fin 7 → Word w) (m : Memory w) (i : Word w) : + (events p m i).length = 28 ∧ countProbes (events p m i) = 3 := ⟨rfl,rfl⟩ + +end CompressorRecords.BundleGather.Fixed + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleFixedGatherScan.lean b/lean/OAI/Computability/VPVNP/CompressorBundleFixedGatherScan.lean new file mode 100644 index 0000000000..5c26186b88 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleFixedGatherScan.lean @@ -0,0 +1,149 @@ +import OAI.Computability.VPVNP.CompressorBundleFixedGather + +/-! +# A complete fixed-program scan of the two bundle key tables + +A cursor visits the live positions of the uniform-stride rectangle. At each +position the program reads the stored arc ID, follows it to the original key, +and writes the key at the same physical slot in the output. The slot embedding +determines every live address and lets the frame include all padding. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleGather.Fixed + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w N S A : ℕ} + +/-- Fit and pairwise separation from the output rectangle. -/ +structure ScanLayout (p : Fin 7 → Word w) (S A : ℕ) : Prop where + idsFit : (p 4).val + S ≤ 2 ^ w + keysFit : (p 5).val + A ≤ 2 ^ w + outputFits : (p 6).val + S ≤ 2 ^ w + idsApart : (p 4).val + S ≤ (p 6).val ∨ (p 6).val + S ≤ (p 4).val + keysApart : (p 5).val + A ≤ (p 6).val ∨ (p 6).val + S ≤ (p 5).val + +/-- Readback and memory frame after the first `k` calls. -/ +structure Filled (p : Fin 7 → Word w) (initial m : Memory w) (slot : Fin N ↪ Fin S) (k : ℕ) : Prop where + readback : ∀ j : Fin N, j.val < k → m ((p 6).val + (slot j).val) = + initial ((p 5).val + (initial ((p 4).val + (slot j).val)).val) + frame : ∀ a, (∀ j : Fin N, j.val < k → a ≠ (p 6).val + (slot j).val) → m a = initial a + +private theorem filled_step {p : Fin 7 → Word w} {initial m : Memory w} {slot : Fin N ↪ Fin S} + (reg : ScanLayout p S A) (decode : ∀ j : Fin N, (offset p (word j.val)).val = (slot j).val) + (legal : ∀ j : Fin N, (initial ((p 4).val + (slot j).val)).val < A) + {k : ℕ} (hk : k < N) (prior : Filled p initial m slot k) : + Filled p initial (after m (events p m (word k))) slot (k+1) := by + let j : Fin N := ⟨k,hk⟩ + let off := offset p (word k) + have hOff : off.val = (slot j).val := decode j + have hs := (slot j).isLt + have src : (p 4 + off).val = (p 4).val + (slot j).val := by + have fit := reg.idsFit + rw [Fin.val_add, hOff, Nat.mod_eq_of_lt (by omega)] + have dst : (p 6 + off).val = (p 6).val + (slot j).val := by + have fit := reg.outputFits + rw [Fin.val_add, hOff, Nat.mod_eq_of_lt (by omega)] + have sameId : m (p 4 + off).val = initial ((p 4).val + (slot j).val) := by + rw [src] + apply prior.frame + intro l _ + have := (slot l).isLt + have := reg.idsApart + omega + let id := initial ((p 4).val + (slot j).val) + have hi : id.val < A := legal j + have key : (p 5 + id).val = (p 5).val + id.val := by + have fit := reg.keysFit + rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)] + have sameKey : m (p 5 + id).val = initial ((p 5).val + id.val) := by + rw [key] + apply prior.frame + intro l _ + have := (slot l).isLt + have := reg.keysApart + omega + rw [after_events] + change Filled p initial (writeMemory m (p 6 + off) (m (p 5 + m (p 4 + off).val).val)) slot (k+1) + rw [sameId, sameKey] + constructor + · intro l hl + by_cases eq : l = j + · subst l + simp only [writeMemory, dst, ite_true, id] + · have hne : (slot l).val ≠ (slot j).val := fun h => eq (slot.injective (Fin.ext h)) + have hn : l.val ≠ k := fun h => eq (Fin.ext h) + rw [writeMemory, dst, ite_eq_right (fun h => hne (Nat.add_left_cancel h))] + exact prior.readback l (by omega) + · intro a h + rw [writeMemory, dst, ite_eq_right (h j (Nat.lt_succ_self k))] + exact prior.frame a fun l hl => h l (Nat.lt_succ_of_lt hl) + +private theorem run_aux {p : Fin 7 → Word w} {initial m : Memory w} {slot : Fin N ↪ Fin S} + (reg : ScanLayout p S A) (decode : ∀ j : Fin N, (offset p (word j.val)).val = (slot j).val) + (legal : ∀ j : Fin N, (initial ((p 4).val + (slot j).val)).val < A) + {k : ℕ} (prior : Filled p initial m slot k) (count : ℕ) (fit : k + count ≤ N) : + let P := ((template visit 0).instantiate w p).program + ∃ rs, runSegment P 29 (some (word k)) m (List.replicate count []) = some rs ∧ + endState (some (word k)) rs = some (word (k+count)) ∧ + Filled p initial (after m (eventLog rs)) slot (k+count) ∧ + rs.length = count ∧ (∀ r ∈ rs, r.events.length = 28 ∧ r.probes = 3) ∧ + RAMBuckets.cost Report.probes rs = 4*count := by + induction count generalizing k m with + | zero => exact ⟨[],rfl,rfl,prior,rfl,by simp,rfl⟩ + | succ n ih => + let r : Report w := ⟨events p m (word k), some (word k+1)⟩ + have inc : word (w := w) k + 1 = word (k+1) := by + apply Fin.ext + simp [word, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + have shift : (k+1)+n = k+(n+1) := by omega + obtain ⟨rs,hr,hs,hf,hl,hw,hc⟩ := ih (filled_step reg decode legal (by omega) prior) (by omega) + refine ⟨r::rs, ?_, ?_, ?_, by simp [hl], ?_, ?_⟩ + · rw [List.replicate_succ, runSegment, native, inc] + simpa only [r, inc, Option.map_some] using congrArg (Option.map (r :: ·)) hr + · change endState (some (word k+1)) rs = _ + rw [inc, hs, shift] + · change Filled p initial ((events p m (word k) ++ eventLog rs).foldl BurstRAM.update m) slot _ + rw [List.foldl_append, ← shift] + exact hf + · intro s h + rcases List.mem_cons.mp h with rfl | h + · exact work p m (word k) + · exact hw s h + · rw [RAMBuckets.cost, show r.probes = 3 from (work ..).2, hc, Nat.mul_succ] + omega + +/-- The same public bank and program execute every visit. All live slots +contain the corresponding original classifier key. Every other cell, +including a padding slot in the output rectangle, retains its value. -/ +structure FullRun (p : Fin 7 → Word w) (initial : Memory w) (slot : Fin N ↪ Fin S) + (rs : List (Report w)) : Prop where + executed : runSegment ((template visit 0).instantiate w p).program 29 (some 0) + initial (List.replicate N []) = some rs + cursor : endState (some 0) rs = some (word N) + readback : ∀ j : Fin N, after initial (eventLog rs) ((p 6).val + (slot j).val) = + initial ((p 5).val + (initial ((p 4).val + (slot j).val)).val) + frame : ∀ a, (∀ j : Fin N, a ≠ (p 6).val + (slot j).val) → after initial (eventLog rs) a = initial a + length : rs.length = N + work : ∀ r ∈ rs, r.events.length = 28 ∧ r.probes = 3 + cost : RAMBuckets.cost Report.probes rs = 4*N + +/-- Run the whole native gather through its actual cursor in increasing order. -/ +theorem full_run (p : Fin 7 → Word w) (initial : Memory w) (slot : Fin N ↪ Fin S) + (reg : ScanLayout p S A) (decode : ∀ j : Fin N, (offset p (word j.val)).val = (slot j).val) + (legal : ∀ j : Fin N, (initial ((p 4).val + (slot j).val)).val < A) : + ∃ rs, FullRun p initial slot rs := by + have empty : Filled p initial initial slot 0 := ⟨by simp, fun _ _ => rfl⟩ + obtain ⟨rs,hr,hs,hf,hl,hw,hc⟩ := run_aux reg decode legal empty N (by simp) + rw [Nat.zero_add] at hs hf + exact ⟨rs, hr, hs, fun j => hf.readback j j.isLt, fun a h => hf.frame a (fun j _ => h j), hl, hw, hc⟩ + +end CompressorRecords.BundleGather.Fixed + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleFixedGatherTable.lean b/lean/OAI/Computability/VPVNP/CompressorBundleFixedGatherTable.lean new file mode 100644 index 0000000000..28ada781e2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleFixedGatherTable.lean @@ -0,0 +1,73 @@ +import OAI.Computability.VPVNP.CompressorBundleGatherCoordinates +import OAI.Computability.VPVNP.CompressorBundleFixedGatherScan + +/-! +# The complete key rectangle built by a single fixed native scan + +The dense traversal visits the live prefixes of both row classes exactly +once and preserves all padding. The resulting key table has the same +readback and external frame as the bounded row-wise construction. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleGather.Fixed + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM BundleKeys + +variable {w : ℕ} (t : KeyTable w) (reg : t.Layout) + +private theorem slot_at (b : Fin t.bundles) (i : Fin t.thickCount ⊕ Fin t.motifCount) : + (slot t reg (entryIndex t (b,i))).val = i.elim + (fun z ↦ b.val*t.stride+z.val) (fun z ↦ (t.bundles+b.val)*t.stride+z.val) := by + cases i <;> simp [slot,physical,finProdFinEquiv, Nat.mul_comm,Nat.add_comm] + +private theorem live (j : Fin (entryCount t)) : + ∃ b i, b < 2*t.bundles ∧ i < t.rowSize b ∧ (slot t reg j).val = b*t.stride+i := by + obtain ⟨⟨b,i | i⟩,rfl⟩ := (entryIndex t).surjective j + · exact ⟨b.val,i.val,by have := b.isLt; omega,by simp [KeyTable.rowSize,b.isLt],slot_at t reg b (.inl i)⟩ + · exact ⟨t.bundles+b.val,i.val,by have := b.isLt; omega,by simp [KeyTable.rowSize],slot_at t reg b (.inr i)⟩ + +private theorem cover (b : ℕ) (hb : b < 2*t.bundles) (i : ℕ) (hi : i < t.rowSize b) : + ∃ j, (slot t reg j).val = b*t.stride+i := by + by_cases h : b < t.bundles + · let z : Fin t.thickCount := ⟨i, by simpa [KeyTable.rowSize,h] using hi⟩ + exact ⟨entryIndex t (⟨b,h⟩,.inl z),slot_at t reg _ _⟩ + · let z : Fin t.motifCount := ⟨i, by simpa [KeyTable.rowSize,h] using hi⟩ + let r : Fin t.bundles := ⟨b-t.bundles,by omega⟩ + refine ⟨entryIndex t (r,.inr z), ?_⟩ + rw [slot_at] + change (t.bundles + (b-t.bundles))*t.stride+i = _ + rw [Nat.add_sub_of_le (by omega)] + +/-- Single native table and one public parameter bank for all old IDs. +The total call count is the sum of the exact two fiber sizes over all ports. -/ +theorem table_run (hsize : entryCount t < 2^w) (m : Memory w) + (legal : ∀ b < 2*t.bundles, ∀ i < t.rowSize b, (m (t.idStart b+i)).val < t.arcCount) : + ∃ rs, FullRun (parameters t) m (slot t reg) rs ∧ + t.Completed m (after m (eventLog rs)) (2*t.bundles) := by + have eqn : slots t = 2*t.bundles*t.stride := by rw [slots,two_mul] + have regions : ScanLayout (parameters t) (slots t) t.arcCount := by + rw [eqn]; exact ⟨reg.idsFit,reg.keysFit,reg.outputFits,reg.idsApart,reg.keysApart⟩ + obtain ⟨rs,run⟩ := full_run (parameters t) m (slot t reg) regions (offset_eq t reg hsize) (fun j ↦ by + obtain ⟨b,i,hb,hi,he⟩ := live t reg j + change (m (t.idsBase.val+(slot t reg j).val)).val < _ + rw [he,← Nat.add_assoc]; exact legal b hb i hi) + refine ⟨rs,run,⟨fun b hb i hi ↦ ?_,fun addr outside ↦ ?_⟩⟩ + · obtain ⟨j,he⟩ := cover t reg b hb i hi + simpa only [KeyTable.lookup,KeyTable.idStart,KeyTable.outStart,he,Nat.add_assoc,show parameters t 4 = t.idsBase from rfl,show parameters t 5 = t.keyBase from rfl,show parameters t 6 = t.outputBase from rfl] using run.readback j + · apply run.frame + intro j + obtain ⟨b,i,hb,hi,he⟩ := live t reg j + change addr ≠ t.outputBase.val+(slot t reg j).val + have bound := outside b hb + dsimp [KeyTable.outStart] at bound + rw [he]; omega + +end CompressorRecords.BundleGather.Fixed + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleGatherCoordinates.lean b/lean/OAI/Computability/VPVNP/CompressorBundleGatherCoordinates.lean new file mode 100644 index 0000000000..d780ffee50 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleGatherCoordinates.lean @@ -0,0 +1,148 @@ +import OAI.Computability.VPVNP.CompressorBundleFixedGather + +/-! +# Dense cursor order and physical addresses for the fixed-bank key gather + +Each cursor decodes to a packed port and an element of the disjoint sum of +its thick and motif entries. The physical address embeds this sum into two +separate sets of equal-stride rows. Both maps work with empty classes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleGather.Fixed + +open BurstRAM BundleKeys +open ShrinkRAM (div mod) +open scoped Fin.CommRing + +variable {w : ℕ} (t : KeyTable w) + +/-- A live entry identified by a bundle and either a thick-wire index or a motif index. -/ +abbrev Entry (t : KeyTable w) := Fin t.bundles × (Fin t.thickCount ⊕ Fin t.motifCount) +/-- Total number of live thick-wire and motif entries across all bundles. -/ +abbrev entryCount (t : KeyTable w) := t.bundles*(t.thickCount+t.motifCount) +/-- Number of physical slots reserved for the two strided row banks, including padding. -/ +abbrev slots (t : KeyTable w) := (t.bundles+t.bundles)*t.stride + +/-- Number the live entries consecutively, using the thick-wire indices before the motif +indices within each bundle. -/ +def entryIndex : Entry t ≃ Fin (entryCount t) := + ((Equiv.refl (Fin t.bundles)).prodCongr finSumFinEquiv).trans finProdFinEquiv + +/-- Place thick-wire entries in the first bank of rows and motif entries in the second, +retaining their index within each row. -/ +def physical (reg : t.Layout) : Entry t ↪ Fin (t.bundles+t.bundles) × Fin t.stride where + toFun z := match z.2 with + | .inl i => (finSumFinEquiv (.inl z.1),i.castLE reg.thickFits) + | .inr i => (finSumFinEquiv (.inr z.1),i.castLE reg.motifFits) + inj' := by + rintro ⟨a,i | i⟩ ⟨b,j | j⟩ h <;> + have hr := finSumFinEquiv.injective (congrArg Prod.fst h) + · exact Prod.ext (Sum.inl.inj hr) (congrArg Sum.inl (Fin.ext (congrArg (Fin.val ∘ Prod.snd) h))) + · contradiction + · contradiction + · exact Prod.ext (Sum.inr.inj hr) (congrArg Sum.inr (Fin.ext (congrArg (Fin.val ∘ Prod.snd) h))) + +/-- Map the dense cursor range bijectively onto the live rectangular slots. -/ +def slot (reg : t.Layout) : Fin (entryCount t) ↪ Fin (slots t) := + (entryIndex t).symm.toEmbedding.trans ((physical t reg).trans finProdFinEquiv.toEmbedding) + +/-- The gather worker's seven operands, encoding the row dimensions and the identifier, +lookup-key and output bases. -/ +def parameters : Fin 7 → Word w := + ![word (t.thickCount+t.motifCount),word t.thickCount,word t.bundles,word t.stride, + t.idsBase,t.keyBase,t.outputBase] + +private theorem word_add (a b : ℕ) : word (w := w) a + word b = word (a+b) := + Fin.ext (Nat.add_mod ..).symm + +private theorem word_mul (a b : ℕ) : word (w := w) a * word b = word (a*b) := + Fin.ext (Nat.mul_mod ..).symm + +private theorem div_val (a b : Word w) : (div a b).val = a.val/b.val := + Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt a.isLt) + +private theorem mod_val (a b : Word w) : (mod a b).val = a.val%b.val := + Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt a.isLt) + +private theorem word_ext {i : Word w} {k : ℕ} (h : i.val = k) : i = word k := by + subst k; exact Fin.ext (Nat.mod_eq_of_lt i.isLt).symm + +private theorem mark (z k : Word w) (hz : z.val+1 < 2^w) : + let q := div k (z+1) + 1-div q q = if z.val < k.val then 0 else 1 := by + intro q + have hs : (z+1).val = z.val+1 := by + rw [Fin.val_add,Fin.val_one',Nat.mod_eq_of_lt (show 1 < 2^w by omega),Nat.mod_eq_of_lt hz] + have hq : q.val = k.val/(z.val+1) := (div_val _ _).trans (by rw [hs]) + by_cases h : z.val < k.val + · have hp := Nat.div_pos (Nat.succ_le_of_lt h) (Nat.zero_lt_succ z.val) + have he : div q q = 1 := by + apply Fin.ext + rw [div_val,Nat.div_self (hq ▸ hp),Fin.val_one',Nat.mod_eq_of_lt (by omega)] + simp [he,h] + · have he : q.val = 0 := hq.trans (Nat.div_eq_of_lt (by omega)) + have eqn : div q q = 0 := Fin.ext (by rw [div_val,he,Nat.div_zero,Fin.val_zero]) + simp [eqn,h] + +/-- The native decoder gives the exact embedded slot. The stop word of the +absolute-port scan represents its full entry count. -/ +theorem offset_eq (reg : t.Layout) (hsize : entryCount t < 2^w) (j : Fin (entryCount t)) : + (offset (parameters t) (word j.val)).val = (slot t reg j).val := by + obtain ⟨z,rfl⟩ := (entryIndex t).surjective j + let b := z.1 + let u := finSumFinEquiv z.2 + let m := t.thickCount+t.motifCount + let i := word (w := w) (entryIndex t z).val + have hb : 0 < t.bundles := b.isLt.pos + have hm : 0 < m := u.isLt.pos + have hmf : m < 2^w := (Nat.le_mul_of_pos_left m hb).trans_lt hsize + have hcf : t.thickCount < 2^w := (Nat.le_add_right ..).trans_lt hmf + have hi : i.val = (entryIndex t z).val := Nat.mod_eq_of_lt ((entryIndex t z).isLt.trans hsize) + have he : (entryIndex t z).val = m*b.val + u.val := by change u.val + m*b.val = _; omega + have hmword : ((parameters t) 0).val = m := Nat.mod_eq_of_lt hmf + have hd : (div i ((parameters t) 0)).val = b.val := by + rw [div_val,hi,he,hmword,Nat.mul_add_div hm,Nat.div_eq_of_lt u.isLt,Nat.add_zero] + have hu : (mod i ((parameters t) 0)).val = u.val := by + rw [mod_val,hi,he,hmword,Nat.mul_comm m b.val,Nat.mul_add_mod_of_lt u.isLt] + have hmkr := mark (mod i ((parameters t) 0)) ((parameters t) 1) + (show (mod i ((parameters t) 0)).val+1 < 2^w by rw [hu]; exact (Nat.succ_le_of_lt u.isLt).trans_lt hmf) + rw [hu, show ((parameters t) 1).val = t.thickCount from Nat.mod_eq_of_lt hcf] at hmkr + change (offset (parameters t) i).val = _ + rw [offset,hmkr,word_ext hd,word_ext hu] + have hslot : slot t reg (entryIndex t z) = finProdFinEquiv (physical t reg z) := by + simp [slot] + rw [hslot] + obtain ⟨b', v | v⟩ := z + · have hlt : u.val < t.thickCount := v.isLt + rw [ite_eq_left hlt,zero_mul,add_zero,zero_mul,sub_zero] + change (word b'.val * word t.stride + word v.val).val = _ + rw [word_mul,word_add,Fin.val_ofNat] + change (b'.val*t.stride+v.val) % (2^w) = v.val + t.stride * b'.val + have bound := Nat.mul_le_mul_right t.stride (b'.isLt.trans_le (Nat.le_mul_of_pos_left t.bundles (by decide : 0<2))) + rw [Nat.succ_mul] at bound + have fit := reg.outputFits + change t.outputBase.val+(2*t.bundles)*t.stride ≤ 2^w at fit + rw [Nat.mod_eq_of_lt (by have := v.isLt.trans_le reg.thickFits; omega)] + ac_rfl + · have uval : u.val = t.thickCount+v.val := rfl + rw [ite_eq_right (by rw [uval]; omega : ¬ u.val < t.thickCount),one_mul,one_mul,uval] + change ((word b'.val + word t.bundles) * word t.stride + + (word (t.thickCount+v.val)-word t.thickCount)).val = _ + rw [← word_add,add_sub_cancel_left,word_add,word_mul,word_add,Fin.val_ofNat] + change ((b'.val+t.bundles)*t.stride+v.val) % (2^w) = v.val + t.stride * (t.bundles+b'.val) + have bound := Nat.mul_le_mul_right t.stride (show b'.val+t.bundles+1 ≤ 2*t.bundles by have := b'.isLt; omega) + rw [Nat.succ_mul] at bound + have fit := reg.outputFits + change t.outputBase.val+(2*t.bundles)*t.stride ≤ 2^w at fit + rw [Nat.mod_eq_of_lt (by have := v.isLt.trans_le reg.motifFits; omega)] + ac_rfl + +end CompressorRecords.BundleGather.Fixed + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleGatherFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorBundleGatherFootprint.lean new file mode 100644 index 0000000000..b25e3cdbaa --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleGatherFootprint.lean @@ -0,0 +1,82 @@ +import OAI.Computability.VPVNP.CompressorBundleFixedGatherTable +import OAI.Computability.VPVNP.CompressorSlotScanFootprint +import OAI.Computability.VPVNP.CompressorLogAccess + +/-! # Physical addresses of the fixed shrinking key gather + +Each cursor reads one initialized ID slot, follows that actual ID to a +classifier key and writes exactly the corresponding gathered-key slot. +Unused padding in the ID rectangle has no effect on the footprint. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleGather.Fixed + +open BurstRAM PrimedStackRAM SourceTransport BundleKeys +open private live from OAI.Computability.VPVNP.CompressorBundleFixedGatherTable + +variable {w : ℕ} + +theorem table_access (t : KeyTable w) (reg : t.Layout) (fit : entryCount t < 2^w) (init : Memory w) + (legal : ∀ b < 2*t.bundles, ∀ i < t.rowSize b, (init (t.idStart b+i)).val < t.arcCount) + (rs : List (Report w)) (hr : runSegment ((template visit 0).instantiate w (parameters t)).program 29 + (some 0) init (List.replicate (entryCount t) []) = some rs) : + LogAccess (fun x ↦ t.idsBase.val ≤ x ∧ x < t.idsBase.val+slots t ∨ + t.keyBase.val ≤ x ∧ x < t.keyBase.val+t.arcCount) + (fun x ↦ t.outputBase.val ≤ x ∧ x < t.outputBase.val+slots t) rs := by + let p := parameters t + let I (mem : Memory w) := ∀ j : Fin (entryCount t), mem (t.idsBase.val+(slot t reg j).val) = + init (t.idsBase.val+(slot t reg j).val) + apply SlotEventBounds.scan _ 29 (entryCount t) (events p) I _ _ (native p) _ init rs (fun _ ↦ rfl) hr + intro j hj mem keep + let x : Fin (entryCount t) := ⟨j,hj⟩ + let i := word (w := w) j + let off := offset p i + have hoff : off.val = (slot t reg x).val := offset_eq t reg fit x + have hext : slots t = 2*t.bundles*t.stride := by rw [slots,two_mul] + have ho : off.val < slots t := hoff ▸ (slot t reg x).isLt + have idsFit : t.idsBase.val+(2*t.bundles)*t.stride ≤ 2^w := reg.idsFit + have outFit : t.outputBase.val+(2*t.bundles)*t.stride ≤ 2^w := reg.outputFits + have src : (p 4+off).val = t.idsBase.val+(slot t reg x).val := by + change (t.idsBase+off).val = _ + rw [Fin.val_add,hoff,Nat.mod_eq_of_lt (by have := (slot t reg x).isLt; omega)] + have dst : (p 6+off).val = t.outputBase.val+off.val := by + change (t.outputBase+off).val = _ + rw [Fin.val_add,Nat.mod_eq_of_lt (by omega)] + let id := mem (p 4+off).val + have hid : id.val < t.arcCount := by + change (mem (p 4+off).val).val < _ + rw [src,keep x] + obtain ⟨b,z,hb,hz,eq⟩ := live t reg x + rw [eq,← Nat.add_assoc]; exact legal b hb z hz + have key : (p 5+id).val = t.keyBase.val+id.val := by + change (t.keyBase+id).val = _ + rw [Fin.val_add,Nat.mod_eq_of_lt (by have := reg.keysFit; omega)] + have read : Reads (fun z ↦ t.idsBase.val ≤ z ∧ z < t.idsBase.val+slots t ∨ + t.keyBase.val ≤ z ∧ z < t.keyBase.val+t.arcCount) (events p mem i) := by + intro addr value h + simp only [events,List.mem_append,List.mem_replicate,List.mem_cons,List.not_mem_nil, + reduceCtorEq,Event.read.injEq,and_false,or_false,false_or] at h + rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ + · left; rw [src]; exact ⟨Nat.le_add_right ..,Nat.add_lt_add_left (slot t reg x).isLt _⟩ + · right; rw [key]; exact ⟨Nat.le_add_right ..,Nat.add_lt_add_left hid _⟩ + have write : Writes (fun z ↦ t.outputBase.val ≤ z ∧ z < t.outputBase.val+slots t) (events p mem i) := by + intro addr value h + simp only [events,List.mem_append,List.mem_replicate,List.mem_cons,List.not_mem_nil, + reduceCtorEq,Event.write.injEq,and_false,or_false,false_or] at h + obtain ⟨rfl,_⟩ := h + rw [dst]; exact ⟨Nat.le_add_right ..,Nat.add_lt_add_left ho _⟩ + refine ⟨read,write,fun k ↦ (SourceTransport.after_outside mem write ?_).trans (keep k)⟩ + have apart : t.idsBase.val+(2*t.bundles)*t.stride ≤ t.outputBase.val ∨ + t.outputBase.val+(2*t.bundles)*t.stride ≤ t.idsBase.val := reg.idsApart + have := (slot t reg k).isLt + omega + +end CompressorRecords.BundleGather.Fixed + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleKeyMaterialization.lean b/lean/OAI/Computability/VPVNP/CompressorBundleKeyMaterialization.lean new file mode 100644 index 0000000000..440746676d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleKeyMaterialization.lean @@ -0,0 +1,124 @@ +import OAI.Computability.VPVNP.CompressorSlotOwnerRuns + +/-! +# Gathering classifier keys for the arcs of one bundle + +The classifier stores a key for every old arc at its absolute identifier. +The preimage scan stores a consecutive row of the identifiers assigned to +one bundle. The worker looks up each identifier's key and writes it at the +same offset in a separate row. The rank scan can then traverse these keys +without changing the original identifiers or the old widths. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleKeys + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- Public words are the starting addresses of the ID row, global key column, +and destination row. The persistent cursor is an offset in the two rows. -/ +def materializeKey : List (Op 3 3) := + [.stateWord 0, .publicWord 1 0, .binary .add 1 1 0, .read 2 1, + .publicWord 1 1, .binary .add 1 1 2, .read 2 1, + .publicWord 1 2, .binary .add 1 1 0, .write 1 2, + .constant 1 1, .binary .add 0 0 1] + +/-- Each row entry requires an ID read, an indirect key read, and one write. -/ +def materializeEvents (p : Fin 3 → Word w) (mem : Memory w) (i : Word w) : List (Event w) := + let idAddr := p 0 + i + let id := mem idAddr.val + let keyAddr := p 1 + id + let key := mem keyAddr.val + [.tick, .tick, .tick, .read idAddr id, .tick, .tick, .read keyAddr key, + .tick, .tick, .write (p 2 + i) key, .tick, .tick] + +theorem materialize_native (p : Fin 3 → Word w) (mem : Memory w) (i : Word w) : + let M := (template materializeKey 0).instantiate w p + execute M.program 13 (M.program.start i) mem [] = + some ⟨materializeEvents p mem i, some (i + 1)⟩ := by + let M := (template materializeKey 0).instantiate w p + change execute M.program (1 + materializeKey.length) ⟨M.entry, i, fun _ => 0, fun _ => 0⟩ mem [] = _ + rw [execute_template, run_eq_trace] + rfl + +theorem materialize_after (p : Fin 3 → Word w) (mem : Memory w) (i : Word w) : + after mem (materializeEvents p mem i) = + writeMemory mem (p 2 + i) (mem (p 1 + mem (p 0 + i).val).val) := rfl + +theorem materialize_work (p : Fin 3 → Word w) (mem : Memory w) (i : Word w) : + countProbes (materializeEvents p mem i) = 3 ∧ (materializeEvents p mem i).length = 12 := ⟨rfl, rfl⟩ + +/-- The output interval is disjoint from the ID row and both absolute-arc +columns. Each disjoint interval can lie on either side of the output. -/ +structure KeyRowRegions (p : Fin 3 → Word w) (count arcCount widthBase : ℕ) : Prop where + idsFit : (p 0).val + count ≤ 2 ^ w + keysFit : (p 1).val + arcCount ≤ 2 ^ w + destinationFits : (p 2).val + count ≤ 2 ^ w + idsApart : (p 0).val + count ≤ (p 2).val ∨ (p 2).val + count ≤ (p 0).val + keysApart : (p 1).val + arcCount ≤ (p 2).val ∨ (p 2).val + count ≤ (p 1).val + widthsApart : widthBase + arcCount ≤ (p 2).val ∨ (p 2).val + count ≤ widthBase + +/-- Gather the complete row in ID order. One call and three probes per entry +fill the destination. Every cell outside it keeps its value, including the +whole old-width column. -/ +theorem materialize_run (p : Fin 3 → Word w) (initial : Memory w) (count arcCount widthBase : ℕ) + (reg : KeyRowRegions p count arcCount widthBase) + (legal : ∀ i < count, (initial ((p 0).val + i)).val < arcCount) : + let P := ((template materializeKey 0).instantiate w p).program + ∃ rs, SlotOwners.FilledRun P 13 3 12 count (p 2) + (fun i => initial ((p 1).val + (initial ((p 0).val + i)).val)) initial rs ∧ + ∀ e < arcCount, after initial (eventLog rs) (widthBase + e) = initial (widthBase + e) := by + intro P + let value := fun i => initial ((p 1).val + (initial ((p 0).val + i)).val) + have visit : SlotOwnerPass.Visit P 13 3 12 (p 2).val 0 count value initial := by + intro j _ hj mem frame + let i := Fin.ofNat (2 ^ w) j + have hj' : j < count := by simpa only [Nat.zero_add] using hj + have hidFit := reg.idsFit + have hi : i.val = j := Nat.mod_eq_of_lt (by omega) + have ha : (p 0 + i).val = (p 0).val + j := by + rw [Fin.val_add, hi, Nat.mod_eq_of_lt (by omega)] + have sameID : mem (p 0 + i).val = initial ((p 0).val + j) := by + rw [ha] + apply frame + have := reg.idsApart + omega + let id := initial ((p 0).val + j) + have hid : id.val < arcCount := legal j hj' + have keyFit := reg.keysFit + have hk : (p 1 + id).val = (p 1).val + id.val := by + rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)] + have sameKey : mem (p 1 + id).val = value j := by + rw [hk] + apply frame + have := reg.keysApart + omega + have hd : p 2 + i = Fin.ofNat (2 ^ w) ((p 2).val + j) := by + apply Fin.ext + rw [Fin.val_add, hi, Fin.val_ofNat] + have hs : i + 1 = Fin.ofNat (2 ^ w) (j + 1) := by + apply Fin.ext + simp [i, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + refine ⟨materializeEvents p mem i, ?_, ?_, (materialize_work p mem i).1, (materialize_work p mem i).2⟩ + · rw [materialize_native p mem i, hs] + · rw [materialize_after, hd, sameID] + exact congrArg (writeMemory mem (Fin.ofNat (2 ^ w) ((p 2).val + j))) sameKey + obtain ⟨rs, executed, cursor, filled, frame, len, calls, cost⟩ := + SlotOwnerPass.run P 13 3 12 (p 2).val 0 count value initial (by simpa using reg.destinationFits) visit + refine ⟨rs, ⟨executed, by simpa using cursor, fun j hj => filled j (Nat.zero_le j) (by simpa using hj), + fun a ha => frame a (by simpa using ha), len, calls, cost⟩, ?_⟩ + intro e he + apply frame + have := reg.widthsApart + omega + +end CompressorRecords.BundleKeys + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleKeyTable.lean b/lean/OAI/Computability/VPVNP/CompressorBundleKeyTable.lean new file mode 100644 index 0000000000..ab15a5705d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleKeyTable.lean @@ -0,0 +1,335 @@ +import OAI.Computability.VPVNP.CompressorBundleKeyMaterialization +import OAI.Computability.VPVNP.CompressorRecordsBundleKeys + +/-! +# Materializing keys for every thick-wire and motif bundle + +The preimage table has two consecutive sets of bundle rows. Each set has +a fixed number of live entries per row. The key table uses the same stride +as the ID table, so the rank scan reads its row and offset directly. +Successive runs of the three-probe worker share their external memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleKeys + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression + +variable {w : ℕ} + +/-- The four external arrays and the shape of the two sets of bundle rows. -/ +structure KeyTable (w : ℕ) where + /-- Base of the strided bundle rows containing the arc identifiers to look up. -/ + idsBase : Word w + /-- Base of the key array addressed by arc identifier. -/ + keyBase : Word w + /-- Base of the strided output rows receiving the gathered keys. -/ + outputBase : Word w + /-- Base of the width array associated with the bundle key table. -/ + widthBase : Word w + /-- Number of bundles represented in each of the thick-wire and motif row banks. -/ + bundles : ℕ + /-- Number of words reserved per physical bundle row. -/ + stride : ℕ + /-- Number of occupied thick-wire entries in each bundle. -/ + thickCount : ℕ + /-- Number of occupied motif entries in each bundle. -/ + motifCount : ℕ + /-- Size of the arc-identifier domain used to look up keys. -/ + arcCount : ℕ + +/-- In each bundle, the thick-wire row and the motif row account for every +color-mask and slot-label combination exactly once. -/ +theorem bundle_row_lengths_add {d c : ℕ} (hc : 2 ≤ c) : + 2 ^ c * d / 4 + PackingData.pieceCount d c = 2 ^ c * d := by + obtain ⟨k, rfl⟩ := Nat.exists_eq_add_of_le hc + have h : 2 ^ (2 + k) * d = 4 * (2 ^ k * d) := by rw [pow_add]; ring + simp only [PackingData.pieceCount, h] + omega + +/-- Both gather scans together read exactly the old physical arc count. -/ +theorem bundle_rows_total (n a g : ℕ) : + numBundles n a g * (2 ^ Shrink.colors a * 2 ^ a / 4) + + numBundles n a g * PackingData.pieceCount (2 ^ a) (Shrink.colors a) = + (n * 2 ^ (packingLaneBits a g)) * 2 ^ a := by + have hc : 2 ≤ Shrink.colors a := by + have hp := Nat.two_pow_pos a + unfold Shrink.colors + omega + rw [← Nat.mul_add, bundle_row_lengths_add hc] + simp only [numBundles, packingLaneBits, Shrink.J, Shrink.colors, pow_add] + ring + +namespace KeyTable + +variable (t : KeyTable w) + +/-- Thick-wire rows precede the motif rows. -/ +def rowSize (b : ℕ) : ℕ := if b < t.bundles then t.thickCount else t.motifCount + +/-- Natural address of the first identifier in physical row `b`. -/ +def idStart (b : ℕ) : ℕ := t.idsBase.val + b * t.stride +/-- Natural address at which gathered keys for physical row `b` begin. -/ +def outStart (b : ℕ) : ℕ := t.outputBase.val + b * t.stride + +/-- Read the identifier at row `b`, offset `i`, then read its key from the lookup array. -/ +def lookup (m : Memory w) (b i : ℕ) : Word w := + m (t.keyBase.val + (m (t.idStart b + i)).val) + +/-- The row gather receives the base addresses of the identifier row, the key lookup, and the +output row. -/ +def rowPublic (b : ℕ) : Fin 3 → Word w := + ![Fin.ofNat _ (t.idStart b), t.keyBase, Fin.ofNat _ (t.outStart b)] + +/-- Both row tables occupy whole rectangles. The destination rectangle is +disjoint from the ID table and from both absolute-arc columns. -/ +structure Layout : Prop where + thickFits : t.thickCount ≤ t.stride + motifFits : t.motifCount ≤ t.stride + idsFit : t.idStart (2 * t.bundles) ≤ 2 ^ w + outputFits : t.outStart (2 * t.bundles) ≤ 2 ^ w + keysFit : t.keyBase.val + t.arcCount ≤ 2 ^ w + idsApart : t.idStart (2 * t.bundles) ≤ t.outputBase.val ∨ + t.outStart (2 * t.bundles) ≤ t.idsBase.val + keysApart : t.keyBase.val + t.arcCount ≤ t.outputBase.val ∨ + t.outStart (2 * t.bundles) ≤ t.keyBase.val + widthsApart : t.widthBase.val + t.arcCount ≤ t.outputBase.val ∨ + t.outStart (2 * t.bundles) ≤ t.widthBase.val + +theorem size_le_stride (reg : t.Layout) (b : ℕ) : t.rowSize b ≤ t.stride := by + unfold rowSize + split <;> first | exact reg.thickFits | exact reg.motifFits + +private theorem rowBounds (reg : t.Layout) (b : ℕ) (hb : b < 2 * t.bundles) : + t.idStart b + t.rowSize b ≤ t.idStart (2 * t.bundles) ∧ + t.outStart b + t.rowSize b ≤ t.outStart (2 * t.bundles) := by + have h := Nat.mul_le_mul_right t.stride (Nat.succ_le_of_lt hb) + rw [Nat.succ_mul] at h + have hs := t.size_le_stride reg b + dsimp [idStart, outStart] + omega + +/-- The word address used by the rank worker agrees with the rectangular +natural address for every slot, including the padding. -/ +theorem outAddress_eq (reg : t.Layout) (b stride offset : Word w) + (hb : b.val < 2 * t.bundles) (hs : stride.val = t.stride) (hi : offset.val < t.stride) : + (t.outputBase + b * stride + offset).val = t.outStart b.val + offset.val := by + have fit := reg.outputFits + have bound := Nat.mul_le_mul_right t.stride (Nat.succ_le_of_lt hb) + rw [Nat.succ_mul] at bound + dsimp [outStart] at fit ⊢ + rw [Fin.val_add, Fin.val_add, Fin.val_mul, hs, Nat.add_mod_mod, Nat.mod_add_mod, Nat.mod_eq_of_lt (by omega)] + +private theorem public_eq (reg : t.Layout) (b : ℕ) (hb : b < 2 * t.bundles) : + ((t.rowPublic b) 0).val = t.idStart b ∧ ((t.rowPublic b) 2).val = t.outStart b := by + have idFit := reg.idsFit + have outFit := reg.outputFits + have h := Nat.mul_le_mul_right t.stride (Nat.succ_le_of_lt hb) + rw [Nat.succ_mul] at h + change (t.idStart b) % (2 ^ w) = _ ∧ (t.outStart b) % (2 ^ w) = _ + by_cases hzero : t.stride = 0 + · simp [idStart, outStart, hzero, Nat.mod_eq_of_lt t.idsBase.isLt, Nat.mod_eq_of_lt t.outputBase.isLt] + · dsimp [idStart, outStart] at idFit outFit ⊢ + exact ⟨Nat.mod_eq_of_lt (by omega), Nat.mod_eq_of_lt (by omega)⟩ + +theorem rowRegions (reg : t.Layout) (b : ℕ) (hb : b < 2 * t.bundles) : + KeyRowRegions (t.rowPublic b) (t.rowSize b) t.arcCount t.widthBase.val := by + obtain ⟨hid, hout⟩ := t.public_eq reg b hb + obtain ⟨ib, ob⟩ := t.rowBounds reg b hb + have is : t.idsBase.val ≤ t.idStart b := Nat.le_add_right .. + have os : t.outputBase.val ≤ t.outStart b := Nat.le_add_right .. + have key : (t.rowPublic b) 1 = t.keyBase := rfl + refine ⟨?_, ?_, ?_, ?_, ?_, ?_⟩ + · rw [hid] + exact ib.trans reg.idsFit + · simpa only [key] using reg.keysFit + · rw [hout] + exact ob.trans reg.outputFits + · rw [hid, hout] + have := reg.idsApart + omega + · rw [key, hout] + have := reg.keysApart + omega + · rw [hout] + have := reg.widthsApart + omega + +/-- Each row scan uses the memory left by all preceding rows. Its exact +cost, persistent cursor, readback, and external frame are recorded. -/ +inductive Runs (initial : Memory w) : ℕ → List (Report w) → Prop where + | nil : Runs initial 0 [] + | snoc {b earlier reports} (previous : Runs initial b earlier) + (row : let mem := after initial (eventLog earlier) + let p := t.rowPublic b + SlotOwners.FilledRun ((template materializeKey 0).instantiate w p).program + 13 3 12 (t.rowSize b) (p 2) (t.lookup mem b) mem reports) : + Runs initial (b + 1) (earlier ++ reports) + +/-- Exactly the live prefixes of the completed rows have been written. The +frame also covers every unused padding cell inside a completed row. -/ +structure Completed (initial final : Memory w) (k : ℕ) : Prop where + filled : ∀ b < k, ∀ i < t.rowSize b, final (t.outStart b + i) = t.lookup initial b i + frame : ∀ addr, (∀ b < k, addr < t.outStart b ∨ t.outStart b + t.rowSize b ≤ addr) → + final addr = initial addr + +theorem Completed.outside {initial final : Memory w} {k : ℕ} + (done : t.Completed initial final k) (reg : t.Layout) (hk : k ≤ 2 * t.bundles) + (addr : ℕ) (h : addr < t.outputBase.val ∨ t.outStart (2 * t.bundles) ≤ addr) : + final addr = initial addr := by + apply done.frame + intro b hb + have ob := (t.rowBounds reg b (hb.trans_le hk)).2 + have os : t.outputBase.val ≤ t.outStart b := Nat.le_add_right .. + omega + +/-- Throughout a prefix of the scan all cells of the ID, classifier-key, +and old-width inputs retain their original values. -/ +theorem Completed.inputs {initial final : Memory w} {k : ℕ} + (done : t.Completed initial final k) (reg : t.Layout) (hk : k ≤ 2 * t.bundles) : + (∀ j < 2 * t.bundles * t.stride, final (t.idsBase.val + j) = initial (t.idsBase.val + j)) ∧ + (∀ e < t.arcCount, final (t.keyBase.val + e) = initial (t.keyBase.val + e)) ∧ + (∀ e < t.arcCount, final (t.widthBase.val + e) = initial (t.widthBase.val + e)) := by + refine ⟨?_, ?_, ?_⟩ + · intro j hj + apply done.outside t reg hk + have := reg.idsApart + dsimp [idStart] at this + omega + · intro e he + apply done.outside t reg hk + have := reg.keysApart + omega + · intro e he + apply done.outside t reg hk + have := reg.widthsApart + omega + +/-- Number of actual ID entries in the first `k` rows. -/ +def entries (k : ℕ) := min k t.bundles * t.thickCount + (k - t.bundles) * t.motifCount + +private theorem entries_succ (k : ℕ) : t.entries (k + 1) = t.entries k + t.rowSize k := by + by_cases h : k < t.bundles + · simp [entries, rowSize, h, Nat.min_eq_left h.le, + Nat.sub_eq_zero_of_le h.le, Nat.sub_eq_zero_of_le (Nat.succ_le_of_lt h), Nat.succ_mul] + · have he : k + 1 - t.bundles = (k - t.bundles) + 1 := by omega + simp [entries, rowSize, h, Nat.min_eq_right (by omega : t.bundles ≤ k), + Nat.min_eq_right (by omega : t.bundles ≤ k + 1), he, Nat.succ_mul, Nat.add_assoc] + +/-- Materialize any prefix of the two rectangular tables in ordinal bucket +order, accounting for the shorter real prefixes of thick-wire rows. -/ +theorem runPrefix (reg : t.Layout) (initial : Memory w) + (legal : ∀ b < 2 * t.bundles, ∀ i < t.rowSize b, (initial (t.idStart b + i)).val < t.arcCount) + (k : ℕ) (hk : k ≤ 2 * t.bundles) : + ∃ reports, t.Runs initial k reports ∧ t.Completed initial (after initial (eventLog reports)) k ∧ + RAMBuckets.cost Report.probes reports = 4 * t.entries k := by + induction k with + | zero => exact ⟨[], .nil, ⟨by simp, fun _ _ => rfl⟩, by simp [RAMBuckets.cost, entries]⟩ + | succ b ih => + obtain ⟨earlier, runs, done, cost⟩ := ih (by omega) + let mem := after initial (eventLog earlier) + let p := t.rowPublic b + have hb : b < 2 * t.bundles := hk + obtain ⟨hid, hout⟩ := t.public_eq reg b hb + have hkey : p 1 = t.keyBase := rfl + obtain ⟨ids, keys, _⟩ := done.inputs t reg (by omega) + have sameId (i : ℕ) (hi : i < t.rowSize b) : mem (t.idStart b + i) = initial (t.idStart b + i) := by + have ib := (t.rowBounds reg b hb).1 + dsimp [idStart] at ib ⊢ + rw [Nat.add_assoc] + exact ids _ (by omega) + have sameValue (i : ℕ) (hi : i < t.rowSize b) : t.lookup mem b i = t.lookup initial b i := by + rw [lookup, lookup, sameId i hi] + exact keys _ (legal b hb i hi) + obtain ⟨reports, row, _⟩ := materialize_run p mem (t.rowSize b) t.arcCount t.widthBase.val + (t.rowRegions reg b hb) (fun i hi => by + change (mem (((t.rowPublic b) 0).val + i)).val < _ + rw [hid, sameId i hi] + exact legal b hb i hi) + have recorded : SlotOwners.FilledRun ((template materializeKey 0).instantiate w p).program + 13 3 12 (t.rowSize b) (p 2) (t.lookup mem b) mem reports := by + convert row using 1 + dsimp [lookup, p] + rw [hid] + rfl + have afterBoth : after initial (eventLog (earlier ++ reports)) = after mem (eventLog reports) := by + simp only [eventLog, List.flatMap_append, after, List.foldl_append, mem] + refine ⟨earlier ++ reports, .snoc runs recorded, ?_, ?_⟩ + · rw [afterBoth] + constructor + · intro a ha i hi + by_cases eq : a = b + · subst a + have h := recorded.filled i hi + change after mem (eventLog reports) (((t.rowPublic b) 2).val + i) = t.lookup mem b i at h + rw [hout] at h + exact h.trans (sameValue i hi) + · have hab : a < b := by omega + have bound := Nat.mul_le_mul_right t.stride (Nat.succ_le_of_lt hab) + rw [Nat.succ_mul] at bound + have hs := t.size_le_stride reg a + have keep := recorded.frame (t.outStart a + i) (Or.inl (by + change _ < ((t.rowPublic b) 2).val + rw [hout] + dsimp [outStart] + omega)) + exact keep.trans (done.filled a hab i hi) + · intro addr outside + have right := outside b (Nat.lt_succ_self b) + have localFrame := recorded.frame addr (by + change addr < ((t.rowPublic b) 2).val ∨ ((t.rowPublic b) 2).val + t.rowSize b ≤ addr + rwa [hout]) + exact localFrame.trans (done.frame addr fun a ha => outside a (Nat.lt_succ_of_lt ha)) + · rw [RAMBuckets.cost_append, cost, recorded.cost, entries_succ, Nat.mul_add] + +/-- The whole pair of tables in ordinal order, with exactly four charged +operations per real entry across both kinds of bundles. -/ +theorem run (reg : t.Layout) (initial : Memory w) + (legal : ∀ b < 2 * t.bundles, ∀ i < t.rowSize b, (initial (t.idStart b + i)).val < t.arcCount) : + ∃ reports, t.Runs initial (2 * t.bundles) reports ∧ + t.Completed initial (after initial (eventLog reports)) (2 * t.bundles) ∧ + RAMBuckets.cost Report.probes reports = 4 * (t.bundles * (t.thickCount + t.motifCount)) := by + have h : t.entries (2 * t.bundles) = t.bundles * (t.thickCount + t.motifCount) := by + rw [entries, Nat.min_eq_right (by omega), show 2 * t.bundles - t.bundles = t.bundles by omega, + Nat.mul_add] + simpa only [h] using t.runPrefix reg initial legal (2 * t.bundles) (le_refl _) + +/-- Instantiate the row counts for the dyadic packing with `n` base sites, +degree `2^a`, and `g` residual lane bits. -/ +def dyadic (ids keys output widths : Word w) (stride n a g : ℕ) : KeyTable w where + idsBase := ids + keyBase := keys + outputBase := output + widthBase := widths + bundles := numBundles n a g + stride := stride + thickCount := 2 ^ Shrink.colors a * 2 ^ a / 4 + motifCount := PackingData.pieceCount (2 ^ a) (Shrink.colors a) + arcCount := (n * 2 ^ packingLaneBits a g) * 2 ^ a + +/-- For the packing's actual two row counts the full materialization costs +exactly four charged operations per original arc. -/ +theorem dyadic_run (ids keys output widths : Word w) (stride n a g : ℕ) (initial : Memory w) + (reg : (dyadic ids keys output widths stride n a g).Layout) + (legal : let t := dyadic ids keys output widths stride n a g + ∀ b < 2 * t.bundles, ∀ i < t.rowSize b, (initial (t.idStart b + i)).val < t.arcCount) : + let t := dyadic ids keys output widths stride n a g + ∃ reports, t.Runs initial (2 * t.bundles) reports ∧ + t.Completed initial (after initial (eventLog reports)) (2 * t.bundles) ∧ + RAMBuckets.cost Report.probes reports = 4 * t.arcCount := by + let t := dyadic ids keys output widths stride n a g + have counted : t.bundles * (t.thickCount + t.motifCount) = t.arcCount := by + rw [Nat.mul_add] + exact bundle_rows_total n a g + simpa only [counted] using t.run reg initial legal + +end KeyTable + +end CompressorRecords.BundleKeys + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleRankFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorBundleRankFootprint.lean new file mode 100644 index 0000000000..70383ef9f4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleRankFootprint.lean @@ -0,0 +1,108 @@ +import OAI.Computability.VPVNP.CompressorRecordsPortRankScan +import OAI.Computability.VPVNP.CompressorSlotScanFootprint + +/-! # Probe addresses of the absolute-port rank scan + +A ranking call reads the owner and pivot, reads the owner's count and then +scans the whole fixed-stride row, including its padding. Its only write is +the rank indexed by the visiting old port. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRankRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport +open private preEvents walkEvents finalEvents setup_trace walk_trace finish_trace word_succ + from OAI.Computability.VPVNP.CompressorRecordsPortRankRAM + +variable {w : ℕ} + +private def exactEvents (p : Fin 6 → Word w) (cap : ℕ) (m : Memory w) (i : Word w) := + preEvents p m i ++ (walkEvents m (start p m i) cap ++ finalEvents p i (result p m i cap)) + +private theorem native_events (p : Fin 6 → Word w) (cap : ℕ) (m : Memory w) (i : Word w) : + let P := ((template (visit cap) 0).instantiate w p).program + execute P (1+(visit cap).length) (P.start i) m [] = some ⟨exactEvents p cap m i,some (i+1)⟩ := by + obtain ⟨r,hs,h0,hptr,hpiv,hrem,hacc,hu⟩ := setup_trace p m i + obtain ⟨s,hw,hs0,hsu,hs4⟩ := walk_trace p m i cap r hu + obtain ⟨t,hf,hret⟩ := finish_trace p m i s (hs0.trans h0) hsu + have val : s 4 = result p m i cap := by simpa only [result,row,hptr,hpiv,hrem,hacc,zero_add] using hs4 + rw [val] at hf + change execute ((template (visit cap) 0).instantiate w p).program (1+(visit cap).length) + ⟨_,i,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + rw [execute_template,run_eq_trace,visit,trace_append,trace_append,hs] + simp [hw,hf,hret,hptr,exactEvents,List.append_assoc] + +private theorem walk_access (m : Memory w) (ptr : Word w) (cap : ℕ) (rd : ℕ → Prop) + (live : ∀ j < cap, rd (ptr+Fin.ofNat (2^w) j).val) : + Reads rd (walkEvents m ptr cap) ∧ Writes (fun _ ↦ False) (walkEvents m ptr cap) := by + induction cap generalizing ptr with + | zero => simp [walkEvents,Reads,Writes] + | succ n ih => + have later (j : ℕ) (hj : j < n) : rd (ptr+1+Fin.ofNat (2^w) j).val := by + have eq : ptr+1+Fin.ofNat (2^w) j = ptr+Fin.ofNat (2^w) (j+1) := by + rw [word_succ,add_right_comm,add_assoc] + rw [eq]; exact live _ (by omega) + obtain ⟨rs,ws⟩ := ih (ptr+1) later + constructor <;> intro a v h + · rw [walkEvents] at h + rcases List.mem_append.mp h with h | h + · simp only [List.mem_cons,List.not_mem_nil,or_false,reduceCtorEq,Event.read.injEq] at h + obtain ⟨rfl,_⟩ := h + simpa using live 0 (Nat.zero_lt_succ n) + · exact rs a v h + · rw [walkEvents] at h + rcases List.mem_append.mp h with h | h + · simp at h + · exact ws a v h + +private theorem row_access (p : Fin 6 → Word w) (cap : ℕ) (m : Memory w) (i : Word w) (rd wr : ℕ → Prop) + (bounds : ∀ x ∈ inputs p m i cap, rd x.val) (dest : wr (p 5+i).val) : + Reads rd (exactEvents p cap m i) ∧ Writes wr (exactEvents p cap m i) := by + obtain ⟨walkRd,walkWr⟩ := walk_access m (start p m i) cap rd fun j hj ↦ + bounds _ (List.mem_append_right _ (List.mem_map.mpr ⟨j,List.mem_range.mpr hj,rfl⟩)) + constructor <;> intro a v h + · rcases List.mem_append.mp h with h | h + · simp only [preEvents,List.mem_cons,List.not_mem_nil,or_false,false_or,reduceCtorEq,Event.read.injEq] at h + rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> exact bounds _ (by simp [inputs]) + · rcases List.mem_append.mp h with h | h + · exact walkRd a v h + · simp [finalEvents] at h + · rcases List.mem_append.mp h with h | h + · simp [preEvents] at h + · rcases List.mem_append.mp h with h | h + · exact (walkWr a v h).elim + · simp only [finalEvents,List.mem_cons,List.not_mem_nil,or_false,false_or,reduceCtorEq,Event.write.injEq] at h + exact h.1 ▸ dest + +/-- Accesses in every report of an actual completed native ranking scan. -/ +theorem scan_access (p : Fin 6 → Word w) (init : Memory w) (cap A : ℕ) + (reg : Regions p init cap A) (rd wr : ℕ → Prop) + (read : ∀ j < A, ∀ x ∈ inputs p init (Fin.ofNat _ j) cap, rd x.val) + (write : ∀ j < A, wr ((p 5).val+j)) (rs : List (Report w)) + (run : runSegment ((template (visit cap) 0).instantiate w p).program (1+(visit cap).length) + (some 0) init (List.replicate A []) = some rs) : Reads rd (eventLog rs) ∧ Writes wr (eventLog rs) := by + let I (mem : Memory w) := ∀ j < A, owner p mem (Fin.ofNat _ j) = owner p init (Fin.ofNat _ j) + apply SlotEventBounds.scan _ _ A (exactEvents p cap) I rd wr (native_events p cap) _ init rs (fun _ _ ↦ rfl) run + intro j hj mem same + let i := Fin.ofNat (2^w) j + have hd : (p 5+i).val = (p 5).val+j := by + rw [Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt (by have := reg.outputFits; omega)] + have equal : inputs p mem i cap = inputs p init i cap := by simp only [inputs,start,same j hj,i] + obtain ⟨hr,hw⟩ := row_access p cap mem i rd wr (fun x hx ↦ read j hj x (equal ▸ hx)) (hd ▸ write j hj) + refine ⟨hr,hw,fun k hk ↦ ?_⟩ + obtain ⟨es,he,afterEq,_,_⟩ := run_one p mem i cap + obtain ⟨rfl,_⟩ := Report.mk.inj (Option.some.inj (he.symm.trans (native_events p cap mem i))) + have src := reg.reads k hk (p 0+Fin.ofNat _ k) (by simp [inputs]) + unfold owner at * + rw [afterEq,writeMemory,ite_eq_right (by omega)] + exact same k hk + +end CompressorRecords.PortRankRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleRankLayout.lean b/lean/OAI/Computability/VPVNP/CompressorBundleRankLayout.lean new file mode 100644 index 0000000000..b416e03e11 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleRankLayout.lean @@ -0,0 +1,119 @@ +import OAI.Computability.VPVNP.CompressorBundleTableReadback +import OAI.Computability.VPVNP.CompressorRecordsPortRankScan + +/-! +# Array layout for gathering keys and ranking every original arc + +The rank pass shares the append pass's owner, stride, and count parameters. +It reads the classifier's key column and the new rectangular key rows. Static +interval bounds verify its memory frame even for probes in the padding at the +end of a short thick row. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleGather + +open BurstRAM Compression.PackingData PortRankRAM + +variable {w A n d c : ℕ} + +/-- Construct the six operands of the bundle ranking pass from the inherited parameters and the +supplied key, output and destination words. -/ +def rankPublic (p : Fin 6 → Word w) (keys out dest : Word w) : Fin 6 → Word w := + ![p 1,keys,out,p 4,p 3,dest] + +/-- Two disjoint half-open intervals, in either physical order. -/ +def separated (base₁ size₁ base₂ size₂ : ℕ) : Prop := + base₁+size₁ ≤ base₂ ∨ base₂+size₂ ≤ base₁ + +variable (p : Fin 6 → Word w) (keys out widths dest : Word w) +local notation "T" => table A n d c p keys out widths +local notation "R" => rankPublic p keys out dest + +/-- The materialized key rectangle must preserve the owner/count columns. +The rank destination column is separate from all four arrays read by ranking. -/ +structure RankLayout (p : Fin 6 → Word w) (keys out dest : Word w) (A buckets : ℕ) : Prop where + keepOwners : separated (p 1).val A out.val (buckets*(p 4).val) + keepCounts : separated (p 3).val buckets out.val (buckets*(p 4).val) + destFits : dest.val + A ≤ 2^w + owners : separated (p 1).val A dest.val A + counts : separated (p 3).val buckets dest.val A + keys : separated keys.val A dest.val A + rows : separated out.val (buckets*(p 4).val) dest.val A + +theorem separated.outside {a m b n i : ℕ} (h : separated a m b n) (hi : i < m) : + a+i < b ∨ b+n ≤ a+i := by unfold separated at h; omega + +theorem rank_start (reg : (T).Layout) (mem : Memory w) (i : Word w) + (hu : (ownerAt p mem i).val < 2*(n*d)) : + (start R mem i).val = (T).outStart (ownerAt p mem i).val := by + let u := ownerAt p mem i + have fit := reg.outputFits + change out.val + (2*(n*d))*(p 4).val ≤ 2^w at fit + change (out + u*p 4).val = out.val+u.val*(p 4).val + rw [Fin.val_add, Fin.val_mul, Nat.add_mod_mod] + by_cases h : (p 4).val = 0 + · simp [h,Nat.mod_eq_of_lt out.isLt] + · have hh := Nat.mul_le_mul_right (p 4).val (Nat.succ_le_of_lt hu) + rw [Nat.succ_mul] at hh + exact Nat.mod_eq_of_lt (by change u.val*_+_ ≤ _ at hh; omega) + +theorem rank_row_fits (reg : (T).Layout) (u : ℕ) (hu : u < 2*(n*d)) : + (T).outStart u + pieceCount d c ≤ 2^w := by + have fit := reg.outputFits + have cap := reg.motifFits + have hh := Nat.mul_le_mul_right (p 4).val (Nat.succ_le_of_lt hu) + rw [Nat.succ_mul] at hh + change out.val + (2*(n*d))*(p 4).val ≤ 2^w at fit + change pieceCount d c ≤ (p 4).val at cap + change out.val+u*(p 4).val+pieceCount d c ≤ 2^w + omega + +theorem rank_regions (reg : (T).Layout) (sep : RankLayout p keys out dest A (2*(n*d))) + (pre : RowRegions p) (hA : (p 0).val = A) (hB : (p 2).val = n*d+n*d) + (mem : Memory w) (legal : ∀ i : Word w, i.val < A → (ownerAt p mem i).val < 2*(n*d)) : + Regions R mem (pieceCount d c) A := by + constructor + · exact sep.destFits + · intro j hj v hv + let i := Fin.ofNat (2^w) j + let u := ownerAt p mem i + have hf := sep.destFits + have hi : i.val = j := Nat.mod_eq_of_lt (by omega) + have hu : u.val < 2*(n*d) := legal i (hi ▸ hj) + change v ∈ [p 1+i,keys+i,p 3+u] ++ (List.range (pieceCount d c)).map (fun z ↦ start R mem i + Fin.ofNat _ z) at hv + change v.val < dest.val ∨ dest.val+A ≤ v.val + rcases List.mem_append.mp hv with h | h + · simp only [List.mem_cons,List.not_mem_nil,or_false] at h + rcases h with rfl | rfl | rfl + · have hb := pre.ownersBeforeCounts + rw [Fin.val_add,hi,Nat.mod_eq_of_lt (by have := (p 3).isLt; omega)] + exact sep.owners.outside hj + · have hb := reg.keysFit + change keys.val+A ≤ 2^w at hb + rw [Fin.val_add,hi,Nat.mod_eq_of_lt (by omega)] + exact sep.keys.outside hj + · have hb := pre.countsBeforeRows + rw [Fin.val_add,Nat.mod_eq_of_lt (by have := (p 5).isLt; omega)] + exact sep.counts.outside hu + · obtain ⟨z,hz,rfl⟩ := List.mem_map.mp h + have hz' := List.mem_range.mp hz + have fits := rank_row_fits p keys out widths reg u.val hu + have cap := reg.motifFits + change pieceCount d c ≤ (p 4).val at cap + rw [Fin.val_add,rank_start p keys out widths dest reg mem i hu,Fin.val_ofNat,Nat.add_mod_mod, + Nat.mod_eq_of_lt (by change (T).outStart u.val + z < _; omega)] + change out.val+u.val*(p 4).val+z < dest.val ∨ dest.val+A ≤ out.val+u.val*(p 4).val+z + simp only [Nat.add_assoc] + have hh := Nat.mul_le_mul_right (p 4).val (Nat.succ_le_of_lt hu) + rw [Nat.succ_mul] at hh + exact sep.rows.outside (by omega) + +end CompressorRecords.BundleGather + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleRankedInput.lean b/lean/OAI/Computability/VPVNP/CompressorBundleRankedInput.lean new file mode 100644 index 0000000000..10c7393fcb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleRankedInput.lean @@ -0,0 +1,69 @@ +import OAI.Computability.VPVNP.CompressorRecordsRankedDirectory +import OAI.Computability.VPVNP.CompressorBundleSortedWidths + +/-! +# Reading the ranked shrinking directory in the width scatter + +The three arrays left by `ranked_directory` are the owner, rank and +width inputs of the native scatter. Every actual port address is shared +with the classification pass. Representability of the old widths gives +their exact natural values. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleWidthScatter + +open BurstRAM Compression BundleKeys BundleLists + +variable {w a g : ℕ} (X : State a (packingLaneBits a g)) +local notation "N" => Fintype.card X.Base +local notation "A" => N * 2^(packingLaneBits a g) * 2^a +local notation "P" => X.packingData +local notation "arcs" => oldArcOrder (a := a) (g := g) X.baseIndex +local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex + +/-- Assemble the typed scatter input from the final four-pass directory +readbacks. Each array uses the original absolute outgoing arc ID. -/ +theorem ranked_input (T : IncidenceDirectory w) (q : Fin 6 → Word w) (dest sorted : Word w) + (mem : Memory w) + (space : Layout (scatterPublic q dest T.width sorted) A (N*(2^(Shrink.J a)*2^g)) (2^a) (Shrink.colors a)) + (fit : ∀ e : OldArc X.Base a g, X.packingWidth e < 2^w) + (motifs : ∀ b (x : (P).MotifFiber b), mem (dest.val+(arcs x.val.val).val) = Fin.ofNat _ (X.shrinkNumber b x).val) + (thick : ∀ b (x : (P).ThickFiber b), mem (dest.val+(arcs x.val.val).val) = Fin.ofNat _ (X.shrinkOrder b x).val) + (widths : ∀ e : OldArc X.Base a g, mem (T.width.val+(arcs e).val) = Fin.ofNat _ (X.packingWidth e)) + (owners : ∀ e : OldArc X.Base a g, mem ((q 1).val+(arcs e).val) = Fin.ofNat _ (bucketIndex sites (bucketOf P e)).val) : + RankedInput P X.shrinkNumber X.shrinkOrder arcs sites (scatterPublic q dest T.width sorted) mem X.packingWidth := by + let s := scatterPublic q dest T.width sorted + have addr (e : OldArc X.Base a g) (t : Fin 3) : + (source s t (arcWord arcs e)).val = (s (t.castAdd 2)).val+(arcs e).val := by + have h := space.sourceFits t + change (s (t.castAdd 2)).val+A ≤ 2^w at h + rw [source,Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt (by have := (arcs e).isLt; omega)] + constructor + · intro e + rw [addr e 0]; exact owners e + · intro e + rw [addr e 1] + by_cases h : (P).thick (sourcePosition e) ∧ (P).thick (sourcePosition ((P).actual e)) + · let x : (P).ThickFiber e.1 := ⟨⟨e,h⟩,rfl⟩ + rw [show rankOf P X.shrinkNumber X.shrinkOrder e = (X.shrinkOrder e.1 x).val from + rank_thick P X.shrinkNumber X.shrinkOrder x] + exact thick _ x + · let m : (P).Motif := ⟨e,h⟩ + let x : (P).MotifFiber ((P).bundle m) := ⟨m,rfl⟩ + rw [show rankOf P X.shrinkNumber X.shrinkOrder e = (X.shrinkNumber _ x).val from + rank_motif P X.shrinkNumber X.shrinkOrder x] + exact motifs _ x + · intro e + rw [addr e 2] + change (mem (T.width.val+(arcs e).val)).val = _ + rw [widths,Fin.val_ofNat,Nat.mod_eq_of_lt (fit e)] + +end CompressorRecords.BundleWidthScatter + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleRankedTable.lean b/lean/OAI/Computability/VPVNP/CompressorBundleRankedTable.lean new file mode 100644 index 0000000000..da8ecd6908 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleRankedTable.lean @@ -0,0 +1,203 @@ +import OAI.Computability.VPVNP.CompressorBundleRankLayout + +/-! +# Ranking all old ports from the completed bundle lists + +The native gather schedule runs on the append pass's memory. The rank +scan starts in the resulting memory, uses the same owner and count cells, +and writes the sorted bundle number for every original arc. No input about +the contents of the unused tail of a thick-wire row is required. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleGather + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.PackingData +open BundleLists BundleRank BundleKeys PortRankRAM + +variable {V H Tag L : Type} {n d c A w N J : ℕ} +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) +variable (arcs : Arc V H Tag L d c ≃ Fin A) (site : Site V Tag L ≃ Fin n) +variable (p : Fin 6 → Word w) (keys out widths dest : Word w) +local notation "T" => table A n d c p keys out widths +local notation "R" => rankPublic p keys out dest + +private theorem owner_preserved (reg : (T).Layout) (sep : RankLayout p keys out dest A (2*(n*d))) + (pre : RowRegions p) (hA : (p 0).val = A) {m f : Memory w} + (done : (T).Completed m f (2*(n*d))) (i : Word w) (hi : i.val < A) : + ownerAt p f i = ownerAt p m i := by + have fit := pre.ownersBeforeCounts + unfold ownerAt + rw [Fin.val_add,Nat.mod_eq_of_lt (by have := (p 3).isLt; omega)] + exact done.outside T reg (le_refl _) _ (sep.keepOwners.outside hi) + +private theorem count_preserved (reg : (T).Layout) (sep : RankLayout p keys out dest A (2*(n*d))) + (pre : RowRegions p) (hB : (p 2).val = n*d+n*d) {m f : Memory w} + (done : (T).Completed m f (2*(n*d))) (u : Word w) (hu : u.val < 2*(n*d)) : + f (countAt p u).val = m (countAt p u).val := by + have fit := pre.countsBeforeRows + rw [countAt,Fin.val_add,Nat.mod_eq_of_lt (by have := (p 5).isLt; omega)] + exact done.outside T reg (le_refl _) _ (sep.keepCounts.outside hu) + +private theorem ranked_header (reg : (T).Layout) (sep : RankLayout p keys out dest A (2*(n*d))) + (pre : RowRegions p) (hA : (p 0).val = A) (hB : (p 2).val = n*d+n*d) + {m f : Memory w} (done : (T).Completed m f (2*(n*d))) + (filled : PreimagesAt p (wordOwner P arcs site) m A) (a : Arc V H Tag L d c) + (b : Bucket V Tag L d) (hb : bucketOf P a = b) : + let i := Fin.ofNat (2^w) (arcs a).val + (lengthAt R f i).val = (arcList (w := w) P arcs site b).length ∧ + (start R f i).val = (T).outStart (bucketIndex site b).val ∧ + pivot R f i = m (keys.val+(arcs a).val) := by + intro i + let u := Fin.ofNat (2^w) (bucketIndex site b).val + have ha : A ≤ 2^w := hA ▸ (p 0).isLt.le + have hn : n*d+n*d ≤ 2^w := hB ▸ (p 2).isLt.le + have hi : i.val = (arcs a).val := Nat.mod_eq_of_lt ((arcs a).isLt.trans_le ha) + have hui : u.val = (bucketIndex site b).val := Nat.mod_eq_of_lt ((bucketIndex site b).isLt.trans_le hn) + have hu : u < p 2 := by change u.val < _; rw [hui,hB]; exact (bucketIndex site b).isLt + have hu' : u.val < 2*(n*d) := by have h := (bucketIndex site b).isLt; omega + have legal : i < p 0 := by change i.val < _; rw [hi,hA]; exact (arcs a).isLt + have ho : ownerAt p f i = u := by + rw [owner_preserved p keys out widths dest reg sep pre hA done i (hA ▸ legal), filled.owners i legal, + wordOwner_at P arcs site ha hn a,hb] + have hhead : lengthAt R f i = f (countAt p u).val := by + change f (p 3+ownerAt p f i).val = _; rw [ho]; rfl + refine ⟨?_,?_,?_⟩ + · rw [hhead, count_preserved p keys out widths dest reg sep pre hB done u hu'] + exact (filled.rows u hu).1 + · rw [rank_start p keys out widths dest reg f i (ho ▸ hu'),ho,hui] + · have keyfit := reg.keysFit + change keys.val+A ≤ 2^w at keyfit + change f (keys+i).val = _ + rw [Fin.val_add,hi,Nat.mod_eq_of_lt (by have := (arcs a).isLt; omega)] + exact (done.inputs T reg (le_refl _)).2.1 _ (arcs a).isLt + +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] + +/-- Readback of both classes from the one rank column indexed by the original ports. -/ +structure Ranked (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (hc : 2 ≤ c) + (dest : Word w) (m : Memory w) : Prop where + motif : ∀ b (x : P.MotifFiber b), m (dest.val+(arcs x.val.val).val) = + Fin.ofNat _ (P.sortedBundleNumbering vertices tags hc b x).val + thick : ∀ b (x : P.ThickFiber b), m (dest.val+(arcs x.val.val).val) = + Fin.ofNat _ (P.sortedThickNumbering hc b x).val + +private theorem rank_after_scan (hc : 2 ≤ c) (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) + (fitM : N*(J*(d*(2^c*d))) ≤ 2^w) (fitT : 2^c*d ≤ 2^w) + (reg : (T).Layout) (sep : RankLayout p keys out dest A (2*(n*d))) (pre : RowRegions p) + (hA : (p 0).val = A) (hB : (p 2).val = n*d+n*d) + (m : Memory w) (filled : PreimagesAt p (wordOwner P arcs site) m A) + (motifs : ∀ x : P.Motif, m (keys.val+(arcs x.val).val) = (motifKey P vertices tags x).castLE fitM) + (thick : ∀ x : P.ThickWire, m (keys.val+(arcs x.val).val) = (thickKey P x).castLE fitT) (scan : List (Report w) → Prop) + (gather : ∀ (ha : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w), Stored P arcs site p m → + ∃ rs, scan rs ∧ (T).Completed m (after m (eventLog rs)) (2*(n*d)) ∧ + KeyRows P arcs site p keys out widths ha hn m (after m (eventLog rs)) ∧ + RAMBuckets.cost Report.probes rs = 4*A) : + let cap := pieceCount d c + let M := (template (visit cap) 0).instantiate w R + ∃ gs rs, let f := after m (eventLog gs) + scan gs ∧ (T).Completed m f (2*(n*d)) ∧ + SlotOwners.FilledRun M.program (1+(visit cap).length) (cap+4) (visit cap).length A dest + (fun j ↦ result R f (Fin.ofNat _ j) cap) f rs ∧ + Ranked P arcs vertices tags hc dest (after f (eventLog rs)) ∧ + RAMBuckets.cost Report.probes gs + RAMBuckets.cost Report.probes rs = (cap+9)*A := by + intro cap M + have ha : A ≤ 2^w := hA ▸ (p 0).isLt.le + have hn : n*d+n*d ≤ 2^w := hB ▸ (p 2).isLt.le + have stored : Stored P arcs site p m := by + intro b + exact filled.rows _ (show (bucketIndex site b).val % (2^w) < (p 2).val by + rw [Nat.mod_eq_of_lt ((bucketIndex site b).isLt.trans_le hn),hB]; exact (bucketIndex site b).isLt) + obtain ⟨gs,run,done,read,cost⟩ := gather ha hn stored + let f := after m (eventLog gs) + have legal (i : Word w) (hi : i.val < A) : (ownerAt p f i).val < 2*(n*d) := by + let j : Fin A := ⟨i.val,hi⟩ + have he : Fin.ofNat (2^w) j.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt) + rw [owner_preserved p keys out widths dest reg sep pre hA done i hi,filled.owners i (show i.val < (p 0).val from hA ▸ hi), + ← he,wordOwner,encodedPlacement_eq arcs (bucketIndex site) (bucketOf P) ha hn] + have h := (bucketIndex site (bucketOf P (arcs.symm j))).isLt + omega + have rreg := rank_regions p keys out widths dest reg sep pre hA hB f legal + have header := ranked_header P arcs site p keys out widths dest reg sep pre hA hB done filled + obtain ⟨rs,ranks,hm,ht⟩ := graph_scan P arcs R f cap rreg vertices tags hc fitM fitT (fun b x ↦ by + let i := Fin.ofNat (2^w) (arcs x.val.val).val + let g : Fin 3 → Word w := ![0,keys,start R f i] + let r := motifRow P arcs site ha hn b + have hnum := header x.val.val (.inr b) ((bucketOf_motif P x.val).trans (congrArg Sum.inr x.prop)) + obtain ⟨hl,hs,hp⟩ := hnum + have hlen := motifRow_length P hc b r + have hkey := motif_read P arcs site ha hn vertices tags b m f g fitM motifs + (fun j ↦ by change f ((start R f i).val+j.val) = _; rw [hs]; exact read _ j) + refine ⟨r, ⟨?_, hlen.le, hp.trans (motifs x.val), ?_, hkey⟩⟩ + · exact hl.trans ((arcList_length P arcs site hc ha hn (.inr b)).trans hlen.symm) + · rw [hs, hlen] + apply rank_row_fits p keys out widths reg + have h := (bucketIndex site (.inr b)).isLt; omega) + (fun b x ↦ by + let i := Fin.ofNat (2^w) (arcs x.val.val).val + let g : Fin 3 → Word w := ![0,keys,start R f i] + let r := thickRow P arcs site ha hn b + have hnum := header x.val.val (.inl b) ((bucketOf_thick P x.val).trans (congrArg Sum.inl x.prop)) + obtain ⟨hl,hs,hp⟩ := hnum + have hlen := thickRow_length P hc b r + have hcap : r.ids.length ≤ cap := hlen.le.trans (Nat.div_le_div_right (by omega : 2^c*d ≤ 3*(2^c*d))) + have hkey := thick_read P arcs site ha hn b m f g fitT thick + (fun j ↦ by change f ((start R f i).val+j.val) = _; rw [hs]; exact read _ j) + refine ⟨r, ⟨?_, hcap, hp.trans (thick x.val), ?_, hkey⟩⟩ + · exact hl.trans ((arcList_length P arcs site hc ha hn (.inl b)).trans hlen.symm) + · rw [hs] + apply (Nat.add_le_add_left hcap _).trans (rank_row_fits p keys out widths reg _ ?_) + have h := (bucketIndex site (.inl b)).isLt; omega) + exact ⟨gs,rs,run,done,ranks,⟨hm,ht⟩,by rw [cost,ranks.cost,← Nat.add_mul]; congr 1; omega⟩ + +/-- Build the rectangular key table from actual bounded ID rows, then execute +one rank call per original port in the resulting physical memory. -/ +theorem ranked_table (hc : 2 ≤ c) (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) + (fitM : N*(J*(d*(2^c*d))) ≤ 2^w) (fitT : 2^c*d ≤ 2^w) + (reg : (T).Layout) (sep : RankLayout p keys out dest A (2*(n*d))) (pre : RowRegions p) + (hA : (p 0).val = A) (hB : (p 2).val = n*d+n*d) + (m : Memory w) (filled : PreimagesAt p (wordOwner P arcs site) m A) + (motifs : ∀ x : P.Motif, m (keys.val+(arcs x.val).val) = (motifKey P vertices tags x).castLE fitM) + (thick : ∀ x : P.ThickWire, m (keys.val+(arcs x.val).val) = (thickKey P x).castLE fitT) : + let cap := pieceCount d c + let M := (template (visit cap) 0).instantiate w R + ∃ gs rs, let f := after m (eventLog gs) + (T).Runs m (2*(n*d)) gs ∧ (T).Completed m f (2*(n*d)) ∧ + SlotOwners.FilledRun M.program (1+(visit cap).length) (cap+4) (visit cap).length A dest + (fun j ↦ result R f (Fin.ofNat _ j) cap) f rs ∧ + Ranked P arcs vertices tags hc dest (after f (eventLog rs)) ∧ + RAMBuckets.cost Report.probes gs + RAMBuckets.cost Report.probes rs = (cap+9)*A := by + apply rank_after_scan P arcs site p keys out widths dest hc vertices tags fitM fitT reg sep pre hA hB m filled motifs thick + intro ha hn stored + exact gather_table P arcs site p keys out widths hc ha hn reg m stored + +/-- Execute both whole-table scans using one fixed bank each. -/ +theorem fixed_ranked_table (hc : 2 ≤ c) (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) + (fitM : N*(J*(d*(2^c*d))) ≤ 2^w) (fitT : 2^c*d ≤ 2^w) + (reg : (T).Layout) (sep : RankLayout p keys out dest A (2*(n*d))) (pre : RowRegions p) + (hA : (p 0).val = A) (hB : (p 2).val = n*d+n*d) + (m : Memory w) (filled : PreimagesAt p (wordOwner P arcs site) m A) + (motifs : ∀ x : P.Motif, m (keys.val+(arcs x.val).val) = (motifKey P vertices tags x).castLE fitM) + (thick : ∀ x : P.ThickWire, m (keys.val+(arcs x.val).val) = (thickKey P x).castLE fitT) : + let cap := pieceCount d c + let M := (template (visit cap) 0).instantiate w R + ∃ gs rs, let f := after m (eventLog gs) + Fixed.FullRun (Fixed.parameters T) m (Fixed.slot T reg) gs ∧ (T).Completed m f (2*(n*d)) ∧ + SlotOwners.FilledRun M.program (1+(visit cap).length) (cap+4) (visit cap).length A dest + (fun j ↦ result R f (Fin.ofNat _ j) cap) f rs ∧ + Ranked P arcs vertices tags hc dest (after f (eventLog rs)) ∧ + RAMBuckets.cost Report.probes gs + RAMBuckets.cost Report.probes rs = (cap+9)*A := by + apply rank_after_scan P arcs site p keys out widths dest hc vertices tags fitM fitT reg sep pre hA hB m filled motifs thick + intro ha hn stored + exact fixed_gather_table P arcs site p keys out widths hc (hA ▸ (p 0).isLt) hn reg m stored + +end CompressorRecords.BundleGather + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleSortedWidths.lean b/lean/OAI/Computability/VPVNP/CompressorBundleSortedWidths.lean new file mode 100644 index 0000000000..bb0a0c3a97 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleSortedWidths.lean @@ -0,0 +1,121 @@ +import OAI.Computability.VPVNP.CompressorBundleRankedTable +import OAI.Computability.VPVNP.CompressorRecordsBundleWidthScatter + +/-! +# Sorted width rows from the bounded lists of old ports + +Run the global key gather, the increasing-port rank scan, and the width scatter +on their successive post-memories. The resulting thick rows give the +concatenation order used to assemble AB blocks. Motif rows give the old CD +widths in piece-number order. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleWidthScatter + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.PackingData +open BundleGather BundleLists BundleRank + +variable {V H Tag L : Type} {n d c A w N J : ℕ} +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] [DecidableEq V] [DecidableEq Tag] [DecidableEq L] + +/-- Use the original owner/width columns and the completed rank destination. +The sorted width rectangle has the same stride as the bounded lists. -/ +def scatterPublic (p : Fin 6 → Word w) (dest widths sorted : Word w) : Fin 5 → Word w := + ![p 1,dest,widths,p 4,sorted] + +variable (P : PackingData V H Tag L d c) (arcs : Arc V H Tag L d c ≃ Fin A) +variable (site : Site V Tag L ≃ Fin n) (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (hc : 2 ≤ c) +variable (p : Fin 6 → Word w) (keys out widths dest sorted : Word w) + +local notation "T" => table A n d c p keys out widths +local notation "R" => rankPublic p keys out dest +local notation "S" => scatterPublic p dest widths sorted +local notation "CD" => P.sortedBundleNumbering vertices tags hc +local notation "DD" => P.sortedThickNumbering hc + +omit [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] [Fintype V] [Fintype H] [Fintype Tag] + [Fintype L] [DecidableEq V] [DecidableEq Tag] [DecidableEq L] in +private theorem source_val {q : Fin 5 → Word w} (layout : Layout q A n d c) + (t : Fin 3) (a : Arc V H Tag L d c) : + (source q t (arcWord arcs a)).val = (q (t.castAdd 2)).val + (arcs a).val := by + have h := layout.sourceFits t + have hi := (arcs a).isLt + rw [source, Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)] + +/-- Three successive native passes produce the exact sorted width rows directly +from the preimage table, the classified keys, and the old width column. -/ +theorem sorted_widths (fitM : N*(J*(d*(2^c*d))) ≤ 2^w) (fitT : 2^c*d ≤ 2^w) + (reg : (T).Layout) (sep : RankLayout p keys out dest A (2*(n*d))) (pre : RowRegions p) + (space : Layout S A n d c) (widthsApart : separated widths.val A dest.val A) + (hA : (p 0).val = A) (hB : (p 2).val = n*d+n*d) (m : Memory w) + (filled : PreimagesAt p (wordOwner P arcs site) m A) + (motifs : ∀ x : P.Motif, m (keys.val+(arcs x.1).val) = (motifKey P vertices tags x).castLE fitM) + (thick : ∀ x : P.ThickWire, m (keys.val+(arcs x.1).val) = (thickKey P x).castLE fitT) + (old : Arc V H Tag L d c → ℕ) (oldWidths : ∀ a, (m (widths.val+(arcs a).val)).val = old a) : + let cap := pieceCount d c + let M := (template (PortRankRAM.visit cap) 0).instantiate w R + let W := (template visit 0).instantiate w S + ∃ gs rs ws, let f := after m (eventLog gs) + let g := after f (eventLog rs) + let final := after g (eventLog ws) + (T).Runs m (2*(n*d)) gs ∧ (T).Completed m f (2*(n*d)) ∧ + SlotOwners.FilledRun M.program (1+(PortRankRAM.visit cap).length) (cap+4) + (PortRankRAM.visit cap).length A dest (fun j ↦ PortRankRAM.result R f (word j) cap) f rs ∧ + Ranked P arcs vertices tags hc dest g ∧ + runSegment W.program 19 (some 0) g (List.replicate A []) = some ws ∧ + endState (some 0) ws = some (word A) ∧ Filled S g final A ∧ + ws.length = A ∧ (∀ r ∈ ws, r.events.length = 18 ∧ r.probes = 4) ∧ + (∀ b i, (final ((rowBase S site (.inl b)).val + i.val)).val = old ((DD b).symm i).1.1) ∧ + (∀ b i, (final ((rowBase S site (.inr b)).val + i.val)).val = old ((CD b).symm i).1.1) ∧ + RAMBuckets.cost Report.probes gs + RAMBuckets.cost Report.probes rs + + RAMBuckets.cost Report.probes ws = (cap+14)*A := by + intro cap M W + obtain ⟨gs,rs,gr,gd,rr,rd,cost⟩ := ranked_table P arcs site p keys out widths dest hc vertices tags fitM fitT + reg sep pre hA hB m filled motifs thick + let f := after m (eventLog gs) + let g := after f (eventLog rs) + have ha : A ≤ 2^w := hA ▸ (p 0).isLt.le + have hb : n*d+n*d ≤ 2^w := hB ▸ (p 2).isLt.le + have hinput : RankedInput P CD DD arcs site S g old := by + constructor + · intro a + have hi := (arcs a).isLt + have hid : (arcWord (w := w) arcs a).val = (arcs a).val := Nat.mod_eq_of_lt (hi.trans_le ha) + have hslot : (source S 0 (arcWord arcs a)).val = (p 1).val+(arcs a).val := source_val arcs space 0 a + dsimp only [g, f] + rw [hslot, rr.frame _ (sep.owners.outside hi), gd.outside T reg (le_refl _) _ (sep.keepOwners.outside hi)] + have hread := filled.owners (arcWord arcs a) (show (arcWord arcs a).val < (p 0).val by rw [hid,hA]; exact hi) + rw [wordOwner_at P arcs site ha hb a] at hread + change m (source S 0 (arcWord arcs a)).val = _ at hread + rwa [hslot] at hread + · intro a + have hslot : (source S 1 (arcWord arcs a)).val = dest.val+(arcs a).val := source_val arcs space 1 a + rw [hslot] + by_cases ht : P.thick (sourcePosition a) ∧ P.thick (sourcePosition (P.actual a)) + · let x : P.ThickFiber a.1 := ⟨⟨a,ht⟩,rfl⟩ + rw [show rankOf P CD DD a = (DD _ x).val from rank_thick P CD DD x] + exact rd.thick _ x + · let m' : P.Motif := ⟨a,ht⟩ + let x : P.MotifFiber (P.bundle m') := ⟨m',rfl⟩ + rw [show rankOf P CD DD a = (CD _ x).val from rank_motif P CD DD x] + exact rd.motif _ x + · intro a + have hi := (arcs a).isLt + have hslot : (source S 2 (arcWord arcs a)).val = widths.val+(arcs a).val := source_val arcs space 2 a + dsimp only [g, f] + rw [hslot, rr.frame _ (widthsApart.outside hi)] + exact (congrArg Fin.val ((gd.inputs T reg (le_refl _)).2.2 _ hi)).trans (oldWidths a) + obtain ⟨ws,wr,wc,wd,wl,ww,costW,th,cd⟩ := graph_run P CD DD arcs site S g old space hinput + refine ⟨gs,rs,ws,gr,gd,rr,rd,wr,wc,wd,wl,ww,th,cd,?_⟩ + rw [cost,costW,← Nat.add_mul] + +end CompressorRecords.BundleWidthScatter + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorBundleTableReadback.lean b/lean/OAI/Computability/VPVNP/CompressorBundleTableReadback.lean new file mode 100644 index 0000000000..da9fe878f7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorBundleTableReadback.lean @@ -0,0 +1,161 @@ +import OAI.Computability.VPVNP.CompressorBundleFixedGatherTable +import OAI.Computability.VPVNP.CompressorRecordsBundleGather + +/-! +# Typed readback of the complete rectangular bundle key table + +The ID rows in the post-memory of the native append pass supply the addresses +for the complete key-gathering schedule. Every live cell of the resulting +rectangle contains the key of the corresponding thick wire or motif. The +whole schedule costs four calls-plus-probes per original arc. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleGather + +open Compression Compression.PackingData BurstRAM BundleLists BundleRank BundleKeys + +variable {V H Tag L : Type} {n d c A w N J : ℕ} +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) +variable (arcs : Arc V H Tag L d c ≃ Fin A) (site : Site V Tag L ≃ Fin n) + +/-- Specialize the rectangular key table to the row stride and ID base +written by the preimage pass. -/ +def table (A n d c : ℕ) (p : Fin 6 → Word w) (keys out widths : Word w) : KeyTable w where + idsBase := p 5 + keyBase := keys + outputBase := out + widthBase := widths + bundles := n*d + stride := (p 4).val + thickCount := 2^c*d/4 + motifCount := pieceCount d c + arcCount := A + +/-- The mathematical ID rows held in the physical count and row arrays. -/ +def Stored (p : Fin 6 → Word w) (mem : Memory w) : Prop := + ∀ b : Bucket V Tag L d, let u := Fin.ofNat (2^w) (bucketIndex site b).val + rowRepresents mem (countAt p u) (rowAt p u) (arcList P arcs site b) + +omit [AddCommGroup Tag] [AddCommGroup L] in +private theorem size_index (p : Fin 6 → Word w) (keys out widths : Word w) (b : Bucket V Tag L d) : + (table A n d c p keys out widths).rowSize (bucketIndex site b).val = rowLength (c := c) b := by + cases b with + | inl b => + change (if (portIndex site b).val < n*d then _ else _) = _ + rw [ite_eq_left (portIndex site b).isLt]; rfl + | inr b => + change (if n*d+(portIndex site b).val < n*d then _ else _) = _ + rw [ite_eq_right (by omega)]; rfl + +variable (p : Fin 6 → Word w) (keys out widths : Word w) +local notation "T" => table A n d c p keys out widths + +omit [AddCommGroup Tag] [AddCommGroup L] in +private theorem idStart_eq (reg : (T).Layout) (hn : n*d+n*d ≤ 2^w) (b : Bucket V Tag L d) : + (T).idStart (bucketIndex site b).val = (rowAt p (Fin.ofNat _ (bucketIndex site b).val)).val := by + let i := (bucketIndex site b).val + have hi : i < n*d+n*d := (bucketIndex site b).isLt + have fit := reg.idsFit + change (p 5).val + (2*(n*d))*(p 4).val ≤ 2^w at fit + change (p 5).val + i*(p 4).val = (p 5+Fin.ofNat (2^w) i * p 4).val + rw [Fin.val_add, Fin.val_mul, Fin.val_ofNat, Nat.mod_eq_of_lt (hi.trans_le hn), Nat.add_mod_mod] + by_cases hs : (p 4).val = 0 + · simp [hs, Nat.mod_eq_of_lt (p 5).isLt] + · have h := Nat.mul_le_mul_right (p 4).val (show i+1 ≤ 2*(n*d) by omega) + rw [Nat.succ_mul] at h + exact (Nat.mod_eq_of_lt (by omega)).symm + +private theorem id_at (reg : (T).Layout) (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) + (b : Bucket V Tag L d) (mem : Memory w) (stored : Stored P arcs site p mem) + (i : Fin (arcList (w := w) P arcs site b).length) : + (mem ((T).idStart (bucketIndex site b).val+i.val)).val = (arcs (ordinalEquiv P arcs site hA hn b i).val).val := by + rw [idStart_eq site p keys out widths reg hn b, (stored b).2 i] + change ((arcList P arcs site b).get i).val = _ + rw [ordinalEquiv_id P arcs site hA hn, Fin.val_ofNat, Nat.mod_eq_of_lt ((arcs _).isLt.trans_le hA)] + +include P arcs site in +omit [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] in +private theorem total_arcs (hc : 2 ≤ c) : (n*d)*(2^c*d/4 + pieceCount d c) = A := by + let f : Arc V H Tag L d c ≃ Fin ((n*d)*(2^c*d)) := + ((portIndex site).prodCongr (((bitWordFinEquiv c).prodCongr P.slotLabel).trans finProdFinEquiv)).trans finProdFinEquiv + have e : (n*d)*(2^c*d) = A := by simpa using Fintype.card_congr (f.symm.trans arcs) + rw [← e] + congr 1 + obtain ⟨k,rfl⟩ := Nat.exists_eq_add_of_le hc + unfold pieceCount + rw [pow_add, show 2^2 = 4 by decide, Nat.mul_assoc] + omega + +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] + +/-- Physical table readback directly in terms of the original typed arcs. -/ +def KeyRows (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) (initial final : Memory w) : Prop := + ∀ (b : Bucket V Tag L d) (i : Fin (arcList (w := w) P arcs site b).length), + final ((T).outStart (bucketIndex site b).val+i.val) = + initial (keys.val+(arcs (ordinalEquiv P arcs site hA hn b i).val).val) + +private theorem size_arcList (hc : 2 ≤ c) (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) + (b : Bucket V Tag L d) : + (T).rowSize (bucketIndex site b).val = (arcList (w := w) P arcs site b).length := + (size_index site p keys out widths b).trans (arcList_length P arcs site hc hA hn b).symm + +private theorem table_legal (hc : 2 ≤ c) (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) (reg : (T).Layout) + (initial : Memory w) (stored : Stored P arcs site p initial) (j : ℕ) (hj : j < 2*(T).bundles) + (i : ℕ) (hi : i < (T).rowSize j) : + (initial ((T).idStart j+i)).val < (T).arcCount := by + have size := size_arcList P arcs site p keys out widths hc hA hn + change j < 2*(n*d) at hj + obtain ⟨b,hb⟩ := (bucketIndex site (d := d)).surjective ⟨j,by omega⟩ + have he : (bucketIndex site b).val = j := congrArg Fin.val hb + let k : Fin (arcList (w := w) P arcs site b).length := ⟨i, by rwa [← size b, he]⟩ + exact he ▸ (id_at P arcs site p keys out widths reg hA hn b initial stored k).trans_lt (arcs _).isLt + +private theorem keyRows_completed (hc : 2 ≤ c) (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) (reg : (T).Layout) + (initial final : Memory w) (stored : Stored P arcs site p initial) + (done : (T).Completed initial final (2*(T).bundles)) : + KeyRows P arcs site p keys out widths hA hn initial final := by + intro b i + have size := size_arcList P arcs site p keys out widths hc hA hn + have hb := (bucketIndex site b).isLt + have h := done.filled (bucketIndex site b).val (show _ < 2*(n*d) by omega) i.val ((size b).symm ▸ i.isLt) + rw [KeyTable.lookup, id_at P arcs site p keys out widths reg hA hn b initial stored i] at h + exact h + +/-- Run the key table over the actual list memory and recover every typed +entry, with the exact original-arc cost. `Completed.frame` covers every +cell outside the written prefixes, including the original widths. -/ +theorem gather_table (hc : 2 ≤ c) (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) (reg : (T).Layout) + (initial : Memory w) (stored : Stored P arcs site p initial) : + ∃ rs, (T).Runs initial (2*(T).bundles) rs ∧ (T).Completed initial (after initial (eventLog rs)) (2*(T).bundles) ∧ + KeyRows P arcs site p keys out widths hA hn initial (after initial (eventLog rs)) ∧ + RAMBuckets.cost Report.probes rs = 4*A := by + obtain ⟨rs,run,done,cost⟩ := (T).run reg initial (table_legal P arcs site p keys out widths hc hA hn reg initial stored) + exact ⟨rs,run,done,keyRows_completed P arcs site p keys out widths hc hA hn reg initial _ stored done, + cost.trans (congrArg (4*·) (total_arcs P arcs site hc))⟩ + +/-- A single public bank supplies the cursor decoder and all three bases +for the entire gather. Its report sequence has the exact same physical +readback and cost as the row-wise schedule. -/ +theorem fixed_gather_table (hc : 2 ≤ c) (hA : A < 2^w) (hn : n*d+n*d ≤ 2^w) (reg : (T).Layout) + (initial : Memory w) (stored : Stored P arcs site p initial) : + ∃ rs, Fixed.FullRun (Fixed.parameters T) initial (Fixed.slot T reg) rs ∧ + (T).Completed initial (after initial (eventLog rs)) (2*(T).bundles) ∧ + KeyRows P arcs site p keys out widths hA.le hn initial (after initial (eventLog rs)) ∧ + RAMBuckets.cost Report.probes rs = 4*A := by + have count : Fixed.entryCount T = A := total_arcs P arcs site hc + obtain ⟨rs,run,done⟩ := Fixed.table_run T reg (count ▸ hA) initial + (table_legal P arcs site p keys out widths hc hA.le hn reg initial stored) + exact ⟨rs,run,done,keyRows_completed P arcs site p keys out widths hc hA.le hn reg initial _ stored done, + run.cost.trans (congrArg (4*·) count)⟩ + +end CompressorRecords.BundleGather + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCalendarArenaTransfers.lean b/lean/OAI/Computability/VPVNP/CompressorCalendarArenaTransfers.lean new file mode 100644 index 0000000000..660e8e4721 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCalendarArenaTransfers.lean @@ -0,0 +1,183 @@ +import OAI.Computability.VPVNP.CompressorCalendarTransfers +import OAI.Computability.VPVNP.CompressorHistoryArenaBase + +/-! +# Starting the history arena and calendar across pair-linker calls + +After the cursor parameters have been copied to the active frame, four native +calls compute the level stride, publish the history arena and traversal +bounds, install the pointer bank, and arm the calendar. The external tag is +updated after each accepting call. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CalendarArenaTransfers + +open BurstRAM BurstRAM.PrivateRAM CursorBounds DescriptorSpace OnlineCursorStartup +open private closed_call from OAI.Computability.VPVNP.CompressorOnlineCursorStartup +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- The four startup reports that install the descriptor stride, history arena, scheduler bank +and calendar arm. -/ +structure Trace (w : ℕ) where + /-- Report of the worker that publishes the descriptor stride. -/ + stride : Report w + /-- Report of the worker that computes the history arena base from the calendar and level + dimensions. -/ + arena : Report w + /-- Report of the worker that initializes the scheduler operand bank. -/ + bank : Report w + /-- Report of the worker that arms the online calendar. -/ + arm : Report w + +/-- Memory after applying the stride report and transferring control to stage five. -/ +def Trace.postStride (t : Trace w) (tag : Word w) (m : Memory w) := transfer m t.stride tag 5 +/-- Memory after publishing the history arena base and transferring control to stage six. -/ +def Trace.postArena (t : Trace w) (tag : Word w) (m : Memory w) := transfer (t.postStride tag m) t.arena tag 6 +/-- Memory after the scheduler bank is initialized and control advances to stage seven. -/ +def Trace.postBank (t : Trace w) (tag : Word w) (m : Memory w) := transfer (t.postArena tag m) t.bank tag 7 +/-- Memory after the calendar is armed and the stage tag advances to eight. -/ +def Trace.post (t : Trace w) (tag : Word w) (m : Memory w) := transfer (t.postBank tag m) t.arm tag 8 + +/-- Construct the four startup reports chronologically, using each tagged transfer's output +memory for the next worker. -/ +def trace (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (steps : ℕ) + (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) : Trace w := + let stride := closed (DescriptorStride.report L.shape pub 0 m) + let arena := closed (HistoryArenaBase.report L.shape D.initialRows D.phaseRows steps pub 0 (transfer m stride tag 5)) + ⟨stride,arena,Workspace.initReport L.shape.arity (pub 2),Workspace.calendarReport d (pub 2)⟩ + +variable (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes steps : ℕ) +variable (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) + +local notation "tr" => trace D d L steps pub tag m + +/-- Each startup worker executes at the specified clock and stage entry, producing the +corresponding report of the trace. -/ +structure Runs : Prop where + callStride : Call (OnlineWorkspace.strideTable L.shape) pub (1+DescriptorStride.cost L.shape) 0 m (tr).stride + callArena : Call (LiveOneShot.oneShot (HistoryArenaBase.table L.shape D.initialRows D.phaseRows steps)) pub + (1+HistoryArenaBase.cost L.shape D.initialRows D.phaseRows steps) 0 ((tr).postStride tag m) (tr).arena + callBank : Call (Workspace.initTable L.shape.arity) pub 42 0 ((tr).postArena tag m) (tr).bank + callArm : Call (Workspace.calendarStart d) pub 6 0 ((tr).postBank tag m) (tr).arm + ready : OnlineWorkspace.Ready d L.shape.arity (pub 2) (CalendarRows.rows D n) (levelWords L) ((tr).post tag m) + saved : Frame.data (DescriptorParameters.saved L w) ((tr).post tag m) = + DescriptorParameters.outputs L B n a (roundedDown D.p D.q n*lanes) w + levelWords_after : ∀ x, levelStart L 0 ≤ x → (tr).post tag m x = HistoryArenaBase.install L n m x + tagged : (tr).post tag m tag.val = 8 + source_below : ∀ x < L.base, + after m (tr).stride.events x = m x ∧ + after ((tr).postStride tag m) (tr).arena.events x = (tr).postStride tag m x ∧ + after ((tr).postArena tag m) (tr).bank.events x = (tr).postArena tag m x ∧ + after ((tr).postBank tag m) (tr).arm.events x = (tr).postBank tag m x + +private theorem install_away (L : Layout) (n : ℕ) (m : Memory w) (fit : levelStart L 0+29 < 2^w) + (x : ℕ) (a : x ≠ levelStart L 0+14) (b : x ≠ levelStart L 0+28) (c : x ≠ levelStart L 0+29) : + HistoryArenaBase.install L n m x = m x := by + simp only [HistoryArenaBase.install, writeMemory, Fin.val_natCast, Nat.mod_eq_of_lt fit, + Nat.mod_eq_of_lt (show levelStart L 0+14 < 2^w by omega), Nat.mod_eq_of_lt (show levelStart L 0+28 < 2^w by omega), + a,b,c,↓reduceIte] + +/-- At entry, both cursor banks and the natural row count come from the +preceding four linked calls. The layout and word bounds certify every +address used in the history-arena header. -/ +theorem run (input : Input D L B n pub) (lower : tag.val < L.base) + (hL : roundedDown D.p D.q n*lanes ≤ virtualBits B n) (positions : initialPositions B n = L.positions) + (levels : L.levels = 1+roundedDown D.p D.q n*(steps+1)) + (fit : levelStart L 0+29 < 2^w) + (cnt : m (pub 2+8).val = (CalendarRows.rows D n : Word w)) + (active : Frame.data (pub 2+9) m = DescriptorParameters.outputs L B n a (roundedDown D.p D.q n*lanes) w) + (saved : Frame.data (DescriptorParameters.saved L w) m = + DescriptorParameters.outputs L B n a (roundedDown D.p D.q n*lanes) w) : + Runs D d L B n a lanes steps pub tag m := by + let head := levelStart L 0 + let base := pub 2 + let g := L.shape.arity + let pitch := OnlineWorkspace.gap g base + let pitched := (tr).postStride tag m + let staged := (tr).postArena tag m + have hbase : base.val = L.base := input.base + have sep : L.base+10+g < head := by + simp only [head,g,levelStart,levelsBase,directoryBase,plannerTag,frameBase,Nat.zero_mul,Nat.add_zero] + omega + change head+29 < 2^w at fit + have countVal : (base+8).val = L.base+8 := (offset_value base 8 (by omega)).trans (by rw [hbase]) + have pitchVal : pitch.val = L.base+(10+g) := + (offset_value base (10+g) (by omega)).trans (by rw [hbase]) + have pos := (position_count hL).trans positions + have ⟨strideExec,_,strideEffect,_⟩ := DescriptorStride.native L pub 0 m active pos + have pitchedEq : pitched = writeMemory (writeMemory m pitch (levelWords L)) tag 5 := + congrArg (fun z ↦ writeMemory z tag 5) strideEffect + have pitchAt : pitched pitch.val = (levelWords L : Word w) := by + rw [pitchedEq, writeMemory, ite_eq_right (by omega : pitch.val ≠ tag.val)]; simp [writeMemory] + have countAt : pitched (base+8).val = (CalendarRows.rows D n : Word w) := by + rw [pitchedEq, writeMemory, ite_eq_right (by omega : (base+8).val ≠ tag.val), writeMemory, + ite_eq_right (by omega : (base+8).val ≠ pitch.val)] + exact cnt + have keepPitch (x : ℕ) (hx : head ≤ x) : pitched x = m x := by + rw [pitchedEq,writeMemory,ite_eq_right (by omega : x ≠ tag.val),writeMemory,ite_eq_right (by omega : x ≠ pitch.val)] + have entry : DescriptorParameters.Ready L B n D.initialRows D.phaseRows (roundedDown D.p D.q n) pub pitched := by + refine ⟨input.base,input.length,input.address,?_,?_,input.phase_pos,input.phase_fit⟩ + · rw [countAt,Fin.val_natCast,Nat.mod_eq_of_lt input.rows_fit,CalendarRows.rows,Nat.mul_comm] + · rw [input.directory,CalendarRows.rows,Nat.mul_comm] + obtain ⟨arenaExec,arenaEffect,_⟩ := HistoryArenaBase.native entry steps levels pitchAt 0 + have stagedEq : staged = writeMemory (HistoryArenaBase.install L n pitched) tag 6 := + congrArg (fun z ↦ writeMemory z tag 6) arenaEffect + have low (x : ℕ) (lo : tag.val < x) (hi : x < head) : staged x = pitched x := by + rw [stagedEq,writeMemory,ite_eq_right (ne_of_gt lo)] + exact install_away L n pitched fit x (by change x ≠ head+14; omega) (by change x ≠ head+28; omega) + (by change x ≠ head+29; omega) + obtain ⟨initExec,armExec,armed,keep⟩ := transferred_arm d g pub staged tag + (CalendarRows.rows D n) (levelWords L) (by omega) (by omega) + ((low (base+8).val (by omega) (by omega)).trans countAt) ((low pitch.val (by omega) (by omega)).trans pitchAt) + have allLevels (x : ℕ) (hx : head ≤ x) : (tr).post tag m x = HistoryArenaBase.install L n m x := by + rw [show (tr).post tag m x = staged x from keep x (by change base.val+8 ≤ x; omega)] + rw [stagedEq,writeMemory,ite_eq_right (by omega : x ≠ tag.val)] + simp only [HistoryArenaBase.install,writeMemory,keepPitch x hx] + have before (x : ℕ) (hx : x < L.base) : + after m (tr).stride.events x = m x ∧ + after pitched (tr).arena.events x = pitched x ∧ + after staged (tr).bank.events x = staged x ∧ + after ((tr).postBank tag m) (tr).arm.events x = (tr).postBank tag m x := by + refine ⟨?_,?_,?_,?_⟩ + · change after m (DescriptorStride.report L.shape pub 0 m).events x = m x + rw [strideEffect,writeMemory] + apply ite_eq_right + rw [offset_value _ _ (by change base.val + (10+g) < 2^w; omega)] + change x ≠ base.val+(10+g) + omega + · change after pitched (HistoryArenaBase.report L.shape D.initialRows D.phaseRows steps pub 0 pitched).events x = _ + rw [arenaEffect] + exact install_away L n pitched fit x (by change x ≠ head+14; omega) (by change x ≠ head+28; omega) + (by change x ≠ head+29; omega) + · apply Workspace.init_outside + intro i + have hi := i.isLt + rw [offset_value _ _ (by change base.val+i.val < 2^w; omega)] + change x ≠ base.val+i.val + omega + · change after ((tr).postBank tag m) (Workspace.calendarReport d base).events x = _ + rw [(Workspace.calendar_effect d g base _).1,writeMemory,ite_eq_right] + have hv : (Workspace.ports g base).tag.val = base.val+6 := offset_value base 6 (by omega) + omega + refine ⟨closed_call _ _ _ _ _ _ strideExec, closed_call _ _ _ _ _ _ arenaExec, + initExec,armExec,armed,?_,allLevels,transfer_tag ..,before⟩ + apply Eq.trans _ saved + funext j + have val : (DescriptorParameters.saved L w).val = head+6 := Nat.mod_eq_of_lt (by omega) + have room : (DescriptorParameters.saved L w).val+8 ≤ 2^w := by omega + have hj := j.isLt + rw [Frame.data_at _ _ room, Frame.data_at _ _ room, val, allLevels _ (by omega)] + exact install_away L n m fit _ (by change head+6+j.val ≠ head+14; omega) + (by change head+6+j.val ≠ head+28; omega) (by change head+6+j.val ≠ head+29; omega) + +end CompressorRecords.CalendarArenaTransfers + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCalendarRows.lean b/lean/OAI/Computability/VPVNP/CompressorCalendarRows.lean new file mode 100644 index 0000000000..089b964507 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCalendarRows.lean @@ -0,0 +1,305 @@ +import OAI.Computability.VPVNP.CompressorRecordsCursorCapacity +import OAI.Computability.VPVNP.RAMParameters + +/-! +# Computing the online descriptor calendar's row count + +A fixed burst-RAM program raises the input length to the numerator of the +compression rate and repeatedly divides by the radix determined by its +denominator. It writes the resulting affine row count at workspace offset +eight. Only this final instruction accesses external memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CalendarRows + +open BurstRAM BurstRAM.PrivateRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Parameters for the calendar's row count as an initial count plus a fixed number of rows per +complete block. -/ +structure Spec where + /-- Numerator of the ratio controlling the logarithmic number of complete compressor blocks. -/ + p : ℕ + /-- Denominator of the block-count ratio, used as the exponent in the repeated division by a + power of two. -/ + q : ℕ + /-- Number of directory rows occupied before the first repeated compressor block. -/ + initialRows : ℕ + /-- Number of directory rows contributed by one complete compressor block. -/ + phaseRows : ℕ + +/-- Total chronological row count for an input length, including startup and all complete +repeated blocks. -/ +def rows (D : Spec) (n : ℕ) := D.initialRows + D.phaseRows * roundedDown D.p D.q n + +theorem rows_eq (D : Spec) (n : ℕ) : + rows D n = D.initialRows + D.phaseRows * Compression.blockCount ((D.p : ℝ) / D.q) n := by + rw [rows, roundedDown_eq] + +/-- Private instructions through address calculation, including all loop tests. -/ +def ticks (D : Spec) (n : ℕ) := 14 + 3 * D.p + 3 * roundedDown D.p D.q n + +private def bound (D : Spec) := D.p + 2^D.q + D.initialRows + D.phaseRows + 9 +private def lit (D : Spec) (a : ℕ) : Word (Nat.clog 2 (bound D)) := Fin.ofNat _ a + +private theorem lit_val (D : Spec) (a : ℕ) (ha : a < bound D) : (lit D a).val = a := + Nat.mod_eq_of_lt (ha.trans_le (Nat.le_pow_clog (by decide) _)) + +/-- Registers zero and seven retain one and zero. Register two counts down the +multiplications. Register three holds the power and then the running quotient. +Register four counts divisions and subsequently holds the affine row count. -/ +def table (D : Spec) : Template 20 8 11 where + literalWidth := Nat.clog 2 (bound D) + entry := 0 + code + | 0 => .constant 0 (lit D 1) 1 + | 1 => .publicWord 1 6 2 + | 2 => .constant 2 (lit D D.p) 3 + | 3 => .copy 3 0 4 + | 4 => .jumpEq 2 7 7 5 + | 5 => .binary .mul 3 3 1 6 + | 6 => .binary .sub 2 2 0 4 + | 7 => .constant 1 (lit D (2^D.q)) 8 + | 8 => .jumpLt 3 1 11 9 + | 9 => .binary .div 3 3 1 10 + | 10 => .binary .add 4 4 0 8 + | 11 => .constant 1 (lit D D.phaseRows) 12 + | 12 => .binary .mul 4 4 1 13 + | 13 => .constant 1 (lit D D.initialRows) 14 + | 14 => .binary .add 4 4 1 15 + | 15 => .publicWord 2 2 16 + | 16 => .constant 1 (lit D 8) 17 + | 17 => .binary .add 2 2 1 18 + | 18 => .writeExternal 2 4 19 + | _ => .accept + +private abbrev machine (D : Spec) (pub : Fin 11 → Word w) := (table D).instantiate w pub + +private def transcript (t : ℕ) (addr value : Word w) : Report w := + ⟨List.replicate t .tick ++ [.write addr value], none⟩ + +/-- The native report that computes the row count and writes it at offset eight of the +workspace. -/ +def report (D : Spec) (pub : Fin 11 → Word w) (n : ℕ) : Report w := + transcript (ticks D n) (pub 2 + 8) (rows D n) + +private def answer (bs : List Bool) (t : ℕ) (addr value : Word w) := + if bs = [] then some (transcript t addr value) else none + +private theorem more (bs : List Bool) (t : ℕ) (addr value : Word w) : + (answer bs t addr value).map (Report.prepend .tick) = answer bs (t+1) addr value := by + by_cases h : bs = [] <;> simp [answer, h, transcript, List.replicate_succ, Report.prepend] + +set_option maxRecDepth 4096 in +private theorem finish (D : Spec) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (f : ℕ) (rs : Fin 8 → Word w) : + execute (machine D pub).program (f+9) ⟨11,s,rs,fun _ ↦ 0⟩ m bs = + answer bs 7 (pub 2+8) ((D.initialRows : Word w) + (D.phaseRows : Word w) * rs 4) := by + have h₁ := lit_val D D.phaseRows (by unfold bound; have := Nat.zero_le (2^D.q); omega) + have h₂ := lit_val D D.initialRows (by unfold bound; have := Nat.zero_le (2^D.q); omega) + have h₃ := lit_val D 8 (by unfold bound; have := Nat.zero_le (2^D.q); omega) + by_cases h : bs = [] <;> + simp (config := {decide := true}) [execute, Machine.program, machine, Template.instantiate, table, + Instr.resize, Instr.run, Config.put, BinaryOp.eval, h₁, h₂, h₃, h, answer, transcript, + List.replicate_succ, Report.prepend, add_comm, mul_comm] + +private theorem log_run (D : Spec) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (f x : ℕ) (rs : Fin 8 → Word w) + (hx : (rs 3).val = x) (hr : (rs 1).val = 2^D.q) (ho : rs 0 = 1) (hbase : 1 < 2^D.q) : + execute (machine D pub).program (f+10+3*Nat.log (2^D.q) x) ⟨8,s,rs,fun _ ↦ 0⟩ m bs = + answer bs (8+3*Nat.log (2^D.q) x) (pub 2+8) + ((D.initialRows : Word w) + (D.phaseRows : Word w) * (rs 4 + (Nat.log (2^D.q) x : Word w))) := by + induction x using Nat.strong_induction_on generalizing rs with + | h x ih => + by_cases small : x < 2^D.q + · have test : rs 3 < rs 1 := by change (rs 3).val < (rs 1).val; omega + simp only [Nat.log_of_lt small, Nat.mul_zero, Nat.cast_zero, add_zero] + change (execute (machine D pub).program (f+9) + ⟨if rs 3 < rs 1 then 11 else 9,s,rs,fun _ ↦ 0⟩ m bs).map (Report.prepend .tick) = _ + rw [ite_eq_left test, finish D pub s m bs f rs, more] + · let b := 2^D.q + have log_step : Nat.log b x = Nat.log b (x/b) + 1 := + Nat.log_of_one_lt_of_le hbase (by omega) + have test : ¬ rs 3 < rs 1 := by change ¬ (rs 3).val < (rs 1).val; omega + let next := Function.update (Function.update rs (3 : Fin 8) (BinaryOp.div.eval (rs 3) (rs 1))) + (4 : Fin 8) (rs 4+rs 0) + have half : (next 3).val = x/b := by + change _ = x/(2^D.q) + have fit := (Nat.div_le_self (rs 3).val (rs 1).val).trans_lt (rs 3).isLt + simp (config := {decide := true}) [next, BinaryOp.eval, hx, hr, + Nat.mod_eq_of_lt (show x / 2^D.q < 2^w from hx ▸ hr ▸ fit)] + have recur := ih (x/b) (Nat.div_lt_self (by omega) hbase) next half + (by simpa (config := {decide := true}) [next] using hr) + (by simpa (config := {decide := true}) [next] using ho) + rw [show f+10+3*Nat.log (2^D.q) x = (f+10+3*Nat.log b (x/b))+3 by + change f+10+3*Nat.log b x = _; omega] + change (Option.map (Report.prepend .tick) (execute (machine D pub).program _ + ⟨if rs 3 < rs 1 then 11 else 9,s,rs,fun _ ↦ 0⟩ m bs)) = _ + rw [ite_eq_right test] + change (((execute (machine D pub).program _ ⟨8,s,next,fun _ ↦ 0⟩ m bs).map + (Report.prepend .tick)).map (Report.prepend .tick)).map (Report.prepend .tick) = _ + rw [recur, more, more, more] + change answer bs _ _ _ = answer bs (8+3*Nat.log b x) _ _ + rw [log_step, Nat.cast_add, Nat.cast_one] + congr 1 + simp only [next, Function.update_self, ho, b] + ring + +private theorem power_run (D : Spec) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (f x k : ℕ) (rs : Fin 8 → Word w) + (hk : (rs 2).val = k) (hv : rs 3 * rs 1 ^ k = (x : Word w)) + (ho : rs 0 = 1) (hz : rs 7 = 0) (hc : rs 4 = 0) + (hx : x < 2^w) (hr : 2^D.q < 2^w) (hb : 1 < 2^D.q) : + execute (machine D pub).program (f+12+3*Nat.log (2^D.q) x+3*k) ⟨4,s,rs,fun _ ↦ 0⟩ m bs = + answer bs (10+3*Nat.log (2^D.q) x+3*k) (pub 2+8) + ((D.initialRows : Word w) + (D.phaseRows : Word w) * (Nat.log (2^D.q) x : Word w)) := by + induction k generalizing rs with + | zero => + have z : rs 2 = rs 7 := by rw [hz]; exact Fin.ext (by simpa using hk) + have v : (rs 3).val = x := by + simpa only [pow_zero, mul_one, Fin.val_natCast, Nat.mod_eq_of_lt hx] using congrArg Fin.val hv + have literal := lit_val D (2^D.q) (by unfold bound; have := Nat.zero_le (2^D.q); omega) + let next := Function.update rs (1 : Fin 8) ((2^D.q : ℕ) : Word w) + have run := log_run D pub s m bs f x next (by simpa (config := {decide := true}) [next] using v) + (by + change (Function.update rs (1 : Fin 8) ((2^D.q : ℕ) : Word w) 1).val = _ + rw [Function.update_self, Fin.val_natCast, Nat.mod_eq_of_lt hr]) (by simpa (config := {decide := true}) [next] using ho) hb + simp only [Nat.mul_zero, Nat.add_zero] + rw [show f+12+3*Nat.log (2^D.q) x = (f+10+3*Nat.log (2^D.q) x)+2 by omega] + change (execute (machine D pub).program _ ⟨if rs 2 = rs 7 then 7 else 5,s,rs,fun _ ↦ 0⟩ m bs).map + (Report.prepend .tick) = _ + rw [ite_eq_left z] + change ((execute (machine D pub).program _ ⟨8,s,Function.update rs 1 (Fin.ofNat _ (lit D (2^D.q)).val), + fun _ ↦ 0⟩ m bs).map (Report.prepend .tick)).map (Report.prepend .tick) = _ + rw [literal, Fin.ofNat_eq_cast, run, more, more] + rw [show 8+3*Nat.log (2^D.q) x+1+1 = 10+3*Nat.log (2^D.q) x by omega] + simp (config := {decide := true}) [next, hc] + | succ k ih => + have nonzero : rs 2 ≠ rs 7 := by + rw [hz]; intro e; have := congrArg Fin.val e; simp [hk] at this + let next := Function.update (Function.update rs (3 : Fin 8) (rs 3*rs 1)) (2 : Fin 8) (rs 2-rs 0) + have one : (1 : Word w).val = 1 := by rw [Fin.val_one', Nat.mod_eq_of_lt (hb.trans hr)] + have count : (next 2).val = k := by + simp only [next, Function.update_self, ho] + rw [Fin.sub_val_of_le (by change (1 : Word w).val ≤ (rs 2).val; omega), hk, one] + omega + have acc : next 3 * next 1 ^ k = (x : Word w) := by + simp only [next, Function.update_self, Function.update_of_ne (by decide : (3 : Fin 8) ≠ 2), + Function.update_of_ne (by decide : (1 : Fin 8) ≠ 2), Function.update_of_ne (by decide : (1 : Fin 8) ≠ 3)] + rw [mul_assoc, ← pow_succ', hv] + have recur := ih next count acc (by simpa (config := {decide := true}) [next] using ho) + (by simpa (config := {decide := true}) [next] using hz) + (by simpa (config := {decide := true}) [next] using hc) + rw [show f+12+3*Nat.log (2^D.q) x+3*(k+1) = (f+12+3*Nat.log (2^D.q) x+3*k)+3 by omega] + change (execute (machine D pub).program _ ⟨if rs 2 = rs 7 then 7 else 5,s,rs,fun _ ↦ 0⟩ m bs).map + (Report.prepend .tick) = _ + rw [ite_eq_right nonzero] + change (((execute (machine D pub).program _ ⟨4,s,next,fun _ ↦ 0⟩ m bs).map + (Report.prepend .tick)).map (Report.prepend .tick)).map (Report.prepend .tick) = _ + rw [recur, more, more, more] + congr 1 + +/-- For every sufficient instruction cap the native stage accepts on its +unique empty choice stream and writes the encoded row count. -/ +theorem execute_native (D : Spec) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (n : ℕ) (hq : 0 < D.q) (hinput : (pub 6).val = n) + (hp : D.p < 2^w) (hr : 2^D.q < 2^w) (hx : n^D.p < 2^w) + {cap : ℕ} (hcap : ticks D n + 2 ≤ cap) : + let P := ((table D).instantiate w pub).program + execute P cap (P.start s) m bs = if bs = [] then some (report D pub n) else none := by + dsimp only + let x := n^D.p + let b := 2^D.q + let f := cap-(ticks D n+2) + have fuel : cap = (f+12+3*Nat.log b x+3*D.p)+4 := by + change 14 + 3 * D.p + 3 * Nat.log b x + 2 ≤ cap at hcap + dsimp [f,ticks,roundedDown,b,x] at *; omega + let z : Fin 8 → Word w := fun _ ↦ 0 + let start := Function.update (Function.update (Function.update (Function.update z (0 : Fin 8) 1) + 1 (pub 6)) 2 (D.p : Word w)) 3 (1 : Word w) + have litOne := lit_val D 1 (by unfold bound; have := Nat.zero_le (2^D.q); omega) + have litP := lit_val D D.p (by unfold bound; have := Nat.zero_le (2^D.q); omega) + have input : pub 6 = (n : Word w) := Fin.ext (by + rw [Fin.val_natCast, ← hinput, Nat.mod_eq_of_lt (pub 6).isLt]) + have run := power_run D pub s m bs f x D.p start + (by simp (config := {decide := true}) [start, Nat.mod_eq_of_lt hp]) + (by simp (config := {decide := true}) [start, x, input, Nat.cast_pow]) + (by simp (config := {decide := true}) [start]) + (by simp (config := {decide := true}) [start,z]) + (by simp (config := {decide := true}) [start,z]) + hx hr (Nat.one_lt_two_pow (by omega)) + rw [fuel] + change ((((execute (machine D pub).program _ ⟨4,s,Function.update + (Function.update (Function.update (Function.update z 0 (Fin.ofNat _ (lit D 1).val)) + 1 (pub 6)) 2 (Fin.ofNat _ (lit D D.p).val)) 3 (Fin.ofNat _ (lit D 1).val), fun _ ↦ 0⟩ + m bs).map (Report.prepend .tick)).map (Report.prepend .tick)).map + (Report.prepend .tick)).map (Report.prepend .tick) = _ + rw [litOne,litP,Fin.ofNat_eq_cast,Fin.ofNat_eq_cast, Nat.cast_one, run, more, more, more, more] + have length : 10+3*Nat.log b x+3*D.p+1+1+1+1 = ticks D n := by + change 10+3*Nat.log b x+3*D.p+1+1+1+1 = 14+3*D.p+3*Nat.log b x + omega + rw [length] + simp only [answer, report, rows, roundedDown, Nat.cast_add, Nat.cast_mul, x] + +private theorem trace_cost (t : ℕ) (a v : Word w) (m : Memory w) : + after m (transcript t a v).events = writeMemory m a v ∧ + countProbes (transcript t a v).events = 1 ∧ choiceBits (transcript t a v).events = [] := by + induction t with + | zero => exact ⟨rfl,rfl,rfl⟩ + | succ t ih => + simpa only [transcript, List.replicate_succ, List.cons_append, after, List.foldl_cons, + update, countProbes, choiceBits] using ih + +theorem after_report (D : Spec) (pub : Fin 11 → Word w) (n : ℕ) (m : Memory w) : + after m (report D pub n).events = writeMemory m (pub 2 + 8) (rows D n) := + (trace_cost ..).1 + +theorem work (D : Spec) (pub : Fin 11 → Word w) (n : ℕ) : + (report D pub n).events.length = ticks D n + 1 ∧ + (report D pub n).probes = 1 ∧ choiceBits (report D pub n).events = [] := + ⟨by simp [report, transcript], (trace_cost _ _ _ (fun _ ↦ 0)).2⟩ + +theorem stored_rows (D : Spec) (pub : Fin 11 → Word w) (n : ℕ) (m : Memory w) + (fit : rows D n < 2^w) : + (after m (report D pub n).events (pub 2 + 8).val).val = + D.initialRows + D.phaseRows * Compression.blockCount ((D.p : ℝ) / D.q) n := by + rw [after_report, ← rows_eq, writeMemory, ite_eq_left rfl, Fin.val_natCast, Nat.mod_eq_of_lt fit] + +/-- Each successful division consumes at least one binary digit. -/ +theorem ticks_le (D : Spec) (n : ℕ) : + ticks D n ≤ 14 + 3 * D.p + 3 * (Nat.clog 2 n * D.p) := by + unfold ticks roundedDown + rw [Nat.log_pow_left] + apply Nat.add_le_add_left + apply Nat.mul_le_mul_left + apply (Nat.div_le_self ..).trans + have h : n^D.p ≤ 2^(Nat.clog 2 n * D.p) := by + rw [pow_mul]; exact Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) n) _ + simpa only [Nat.log_pow (by decide : 1 < 2)] using Nat.log_mono_right (b := 2) h + +/-- With the paper's live word width, every integer used in a loop guard +and the full natural row count are representable for all sufficiently large lengths. -/ +theorem eventually_fits (D : Spec) (B : ℕ) (hB : 1 ≤ B) : + ∀ᶠ n : ℕ in Filter.atTop, + D.p < 2^CursorBounds.wordBits B n ∧ 2^D.q < 2^CursorBounds.wordBits B n ∧ + n^D.p < 2^CursorBounds.wordBits B n ∧ rows D n < 2^CursorBounds.wordBits B n := by + have powers := PolynomiallyBounded.id.pow D.p + have upper := (PolynomiallyBounded.const D.initialRows).add + ((PolynomiallyBounded.const D.phaseRows).mul powers) + filter_upwards [CursorRAM.eventual_word_room B hB (PolynomiallyBounded.const D.p), + CursorRAM.eventual_word_room B hB (PolynomiallyBounded.const (2^D.q)), + CursorRAM.eventual_word_room B hB powers, CursorRAM.eventual_word_room B hB upper] with n hp hr hx hu + refine ⟨hp, hr, hx, lt_of_le_of_lt ?_ hu⟩ + exact Nat.add_le_add_left (Nat.mul_le_mul_left _ (Nat.log_le_self (2^D.q) (n^D.p))) _ + +end CompressorRecords.CalendarRows + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCalendarTransfers.lean b/lean/OAI/Computability/VPVNP/CompressorCalendarTransfers.lean new file mode 100644 index 0000000000..ee366862b9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCalendarTransfers.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.CompressorOnlineCursorStartup + +/-! +# Calendar control across outer pair tag transfers + +The compressed pair writes its stage tag after each successful component. +When that tag precedes the descriptor workspace, these writes preserve the +controller's pointer bank, controls, stride, and all persistent level cells. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.OnlineCursorStartup + +open BurstRAM BurstRAM.PrivateRAM DescriptorSpace +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- The outer stage transfer appends a tag write to the source memory effect. -/ +def transfer (m : Memory w) (rep : Report w) (tag : Word w) (index : ℕ) : Memory w := + writeMemory (after m rep.events) tag (index : Word w) + +theorem transfer_tag (m : Memory w) (rep : Report w) (tag : Word w) (index : ℕ) : + transfer m rep tag index tag.val = (index : Word w) := by simp [transfer,writeMemory] + +theorem lower_write_frame {k : ℕ} (m : Memory w) (base tag value : Word w) + (lower : tag.val < base.val) (fit : base.val+k ≤ 2^w) : + (Frame.data base (writeMemory m tag value) : Fin k → Word w) = Frame.data base m := by + funext i + rw [Frame.data_at _ _ fit, Frame.data_at _ _ fit, writeMemory, ite_eq_right (by omega)] + +theorem offset_value (base : Word w) (j : ℕ) (fit : base.val+j < 2^w) : + (base+(j : Word w)).val = base.val+j := by + rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (show j < 2^w by omega), Nat.mod_eq_of_lt fit] + +theorem lower_write_ready (d g : ℕ) (base rows stride tag value : Word w) (m : Memory w) + (lower : tag.val < base.val) (fit : base.val+10+g < 2^w) + (ready : OnlineWorkspace.Ready d g base rows stride m) : + OnlineWorkspace.Ready d g base rows stride (writeMemory m tag value) := by + have same (j : ℕ) (hj : j ≤ 10+g) : + writeMemory m tag value (base+(j : Word w)).val = m (base+(j : Word w)).val := by + rw [offset_value _ _ (by omega), writeMemory, ite_eq_right (by omega)] + constructor + · exact (lower_write_frame m base tag value lower (by omega : base.val+6 ≤ 2^w)).trans ready.bank + · exact (same 6 (by omega)).trans ready.tag + · exact (same 7 (by omega)).trans ready.ordinal + · exact (same 8 (by omega)).trans ready.count + · rw [OnlineWorkspace.gap_eq] + apply (same (10+g) le_rfl).trans + simpa only [OnlineWorkspace.gap_eq, OnlineWorkspace.gap] using ready.pitch + +/-- Insert the two real transfer writes between and after the workspace +initializer and calendar selector. The ready workspace and every persistent +word above its controls are available to the next stage. -/ +theorem transferred_arm (d g : ℕ) (pub : Fin 11 → Word w) (m : Memory w) + (tag rows stride : Word w) (lower : tag.val < (pub 2).val) (fit : (pub 2).val+10+g < 2^w) + (hr : m (pub 2+8).val = rows) (hs : m (OnlineWorkspace.gap g (pub 2)).val = stride) : + let init := Workspace.initReport g (pub 2) + let mid := transfer m init tag 7 + let arm := Workspace.calendarReport d (pub 2) + let out := transfer mid arm tag 8 + Call (Workspace.initTable g) pub 42 0 m init ∧ Call (Workspace.calendarStart d) pub 6 0 mid arm ∧ + OnlineWorkspace.Ready d g (pub 2) rows stride out ∧ + (∀ x, (pub 2).val+8 ≤ x → out x = m x) := by + intro init mid arm out + have ⟨initExec,_,ready⟩ := OnlineWorkspace.arm d g pub 0 m rows stride (by omega) hr hs + have armtag : (Workspace.ports g (pub 2)).tag.val = (pub 2).val+6 := + offset_value (pub 2) 6 (by omega) + have desc : out = writeMemory (OnlineWorkspace.armed d g (pub 2) m) tag (8 : Word w) := by + funext x + change writeMemory (after mid (Workspace.calendarReport d (pub 2)).events) tag _ x = + writeMemory (after (after m init.events) (Workspace.calendarReport d (pub 2)).events) tag _ x + rw [(Workspace.calendar_effect d g _ mid).1, (Workspace.calendar_effect d g _ (after m init.events)).1] + by_cases ht : x = tag.val <;> simp [writeMemory, ht, mid, transfer] + refine ⟨initExec, Workspace.execute_calendarStart d pub 0 mid [] 6 le_rfl, + desc ▸ lower_write_ready d g _ rows stride tag 8 _ lower fit ready, ?_⟩ + intro x hx + rw [desc, writeMemory, ite_eq_right (by omega : x ≠ tag.val), OnlineWorkspace.armed, + (Workspace.calendar_effect d g ..).1, writeMemory, + ite_eq_right (by omega : x ≠ (Workspace.ports g (pub 2)).tag.val)] + apply Workspace.init_outside + intro i + rw [offset_value _ _ (by have := i.isLt; omega)] + have := i.isLt + omega + +end CompressorRecords.OnlineCursorStartup + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCanonicalNativeTapes.lean b/lean/OAI/Computability/VPVNP/CompressorCanonicalNativeTapes.lean new file mode 100644 index 0000000000..3ebea984bb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCanonicalNativeTapes.lean @@ -0,0 +1,125 @@ +import OAI.Computability.VPVNP.PairSimulationSelectorReindex +import OAI.Computability.VPVNP.CompressorShrinkTermOnline +import OAI.Computability.VPVNP.CompressorRefreshCorePackets + +/-! +# Canonical tapes and the physical term packets + +Shrinking orders motifs by their dense bundle and CD rank and orders each +layout's supply by role. Refresh uses the base vertex number followed by +the residual lane and the expander's port-major supply order. In these +coordinates the term tapes of both native passes are the canonical worker +tapes of their actual mathematical choices. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.CanonicalWorker + +open BurstRAM Compression Compression.Refresh SelectedTerms PairSimulation.LocalHistory +open PortRefresh +open scoped Classical + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) + +section Shrink + +variable (i : Fin S.steps) {g : ℕ} +variable (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) +variable (s : X.ShrinkSelection B.shrink) (w : ℕ) +local notation "o" => PassOrigin.shrink (B := B) (f := f) (hf := hf) i rfl X + +/-- The two descriptions of the complete shrinking term tape agree at +each physical motif ordinal. -/ +theorem shrink_tapes : ShrinkTermSelection.tapes B.shrink X s w = workerTapes o w s := by + funext j + rfl + +theorem shrink_choices : ShrinkTermPackets.choices (w := w) B i X s .select = + List.ofFn (workerTapes o w s) := congrArg List.ofFn (shrink_tapes B f hf i X s w) + +/-- Read off the row-major choice tapes from the actual accepted native +shrinking term reports. -/ +theorem shrink_branches (origin : PhaseRecipe.Expr) (T : IncidenceDirectory w) (start cap : ℕ) + {m : Memory w} {rs : List (Report w)} (h : ShrinkTermPackets.PacketRun B i origin X T start s cap .select m rs) : + branchPaths rs = List.ofFn (workerTapes o w s) := + h.branches.trans (shrink_choices B f hf i X s w) + +/-- The occurrence of the shrinking selector in the global script carries +the entire canonical term tape as its scheduled choices. -/ +theorem shrink_online_choices (T : IncidenceDirectory w) (start cap : ℕ) : + (ShrinkTermOnline.globalVisit B i X T start s cap .select).choices = List.ofFn (workerTapes o w s) := + shrink_choices B f hf i X s w + +end Shrink + +section Refresh + +variable {g : ℕ} (X : State S.portExponent (S.portExponent+g)) +local notation "hd" => Nat.two_pow_pos S.expanderExponent +private abbrev connected := (S.port_bound.connected_and_pos S.port_order).1 +local notation "hc" => connected (S := S) +local notation "o" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +variable (c : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (w : ℕ) + +/-- The inverse physical block ordinal is the same base/lane order as +the refresh pass's term rows. -/ +theorem refresh_blocks : + (DemandScan.blocks X).symm = + (Order.prod ⟨_,X.baseIndex.symm⟩ ⟨_,(bitWordFinEquiv g).symm⟩).entries := rfl + +/-- The full native refresh tape, including every supply coordinate, is +the canonical worker tape of the same choice. -/ +theorem refresh_tapes : blockTapes S.graph hd hc B.refresh X c w = workerTapes o w c := by + funext j + rfl + +theorem refresh_choices (start : ℕ) : + Scheduled.tapes (w := w) (t := (RefreshBlockPlan.shape B).ties) X S.graph hd hc B.refresh c start + (RefreshBlockPlan.shape B).stride .term = List.ofFn (workerTapes o w c) := + congrArg List.ofFn (refresh_tapes B f hf X c w) + +/-- In an executed refresh term stage the genuine branch bits are exactly +the selected canonical stream, in the same order. -/ +theorem refresh_branches (old : IncidenceDirectory w) (start cap : ℕ) {m : Memory w} {rs : List (Report w)} + (h : Scheduled.Source X S.graph hd hc B.refresh S.degree_bounds.2 c (RefreshBlockPlan.order B) old + start (RefreshBlockPlan.shape B).stride cap .term m rs) : + branchPaths rs = List.ofFn (workerTapes o w c) := + ((runSegment_iff ..).mp h).2.2.trans (refresh_choices B f hf X c w start) + +open private refreshStages from OAI.Computability.VPVNP.CompressorBlockIndex + +/-- The refresh selector follows the gather, bundle and offset scans and +all the tie-demand scans. -/ +def refreshTermIndex : Fin (RefreshCore.stages B).length := (refreshStages B).index + +theorem refreshTermIndex_val : (refreshTermIndex B).val = 3+(RefreshBlockPlan.shape B).ties := by + simp only [refreshTermIndex,BlockIndex.Focus.index,refreshStages,List.length_append,List.length_cons, + List.length_nil,List.length_map,List.length_finRange] + +theorem refreshTermIndex_stage : (RefreshCore.stages B)[(refreshTermIndex B).val] = .term := + (refreshStages B).lookup + +set_option maxHeartbeats 900000 in +/-- The native refresh occurrence is the actual term stage of the live +script; its scheduled choice lists agree with the mathematical worker +tapes at every port-block ordinal. -/ +theorem refresh_online_choices (old : IncidenceDirectory w) (start cap : ℕ) : + (RefreshCore.visit B X c old start cap (refreshTermIndex B)).choices = List.ofFn (workerTapes o w c) := by + simp only [RefreshCore.visit,SourceOnline.Visit.ofWorker,refreshTermIndex_stage] + exact refresh_choices B f hf X c w start + +end Refresh + +end CompressorRecords.CanonicalWorker + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCanonicalWorkerFit.lean b/lean/OAI/Computability/VPVNP/CompressorCanonicalWorkerFit.lean new file mode 100644 index 0000000000..b55ecf0e9f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCanonicalWorkerFit.lean @@ -0,0 +1,64 @@ +import OAI.Computability.VPVNP.CompressorSelectedTermWorker +import OAI.Computability.VPVNP.CursorDescriptorWords + +/-! +# Uniform word bounds for the canonical dense term-worker input + +Demand rows begin at zero and the strided term rows begin at the end of +the demand array. Both shrink and refresh grids have template-fixed row +widths. Their storage, including the two header words and the independent +stride operands, is polynomially bounded in the original cursor length. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.CanonicalWorker + +open BurstRAM CursorBounds Compression Filter SelectedTerms PairSimulation.LocalHistory +open scoped Classical + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Every origin of every selected execution satisfying the current position +and maximum-width bounds has the exact dense addresses, private operand +width and input word range required by the canonical worker. -/ +theorem eventually_fit (b : ℕ) (hb : 1 ≤ b) : ∀ᶠ len : ℕ in atTop, + ∀ {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + {a g b' n' : ℕ} {X : State a g} {p : StatePass R X b' n'} (o : PassOrigin B f hf p), + X.positions ≤ initialPositions b len → X.maxWireWidth ≤ len → + let G := grid o + let w := wordBits b len + o.motifCount*(G.d+(2+G.e))+max G.d (2+G.e)+2 < 2^w ∧ + SelectedTermWorker.fitConstant B+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w ∧ X.maxWireWidth < 2^w := by + let width (G : Grid k) := G.d+(2+G.e) + let K := max (width (shrinkGrid B)) (width (refreshGrid B)) + have bounded := ((((CursorRAM.bounded_positions b).mul (PolynomiallyBounded.const (slotDegree S))).mul + (PolynomiallyBounded.const K)).add (PolynomiallyBounded.const K)).add (PolynomiallyBounded.const 2) + filter_upwards [CursorRAM.eventual_word_room b hb bounded,CursorRAM.eventual_word_room b hb PolynomiallyBounded.id, + DemandPreparation.eventually_live_word_fits b hb (SelectedTermWorker.fitConstant B) 4 1 1] + with len room input bits + intro R _ f hf a g b' n' X p o positions maxWidth G w + have degree : 2^a ≤ slotDegree S := by + cases o with + | shrink i _ _ => exact (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) + (Finset.mem_univ i.castSucc)).trans (le_max_right ..) + | refresh => exact le_max_left .. + have dim : G.d+(2+G.e) ≤ K := by + change width (grid o) ≤ K + cases o <;> first | exact le_max_left .. | exact le_max_right .. + have motifs := o.motifCount_le.trans (Nat.mul_le_mul positions degree) + have stride : max G.d (2+G.e) ≤ K := (max_le (Nat.le_add_right ..) (Nat.le_add_left ..)).trans dim + have scratch := Nat.add_le_add (Nat.mul_le_mul motifs dim) stride + exact ⟨(Nat.add_le_add_right scratch 2).trans_lt room,bits _ (by simpa using maxWidth),maxWidth.trans_lt input⟩ + +end CompressorRecords.CanonicalWorker + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCanonicalWorkerInputs.lean b/lean/OAI/Computability/VPVNP/CompressorCanonicalWorkerInputs.lean new file mode 100644 index 0000000000..8036840c01 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCanonicalWorkerInputs.lean @@ -0,0 +1,100 @@ +import OAI.Computability.VPVNP.CompressorCanonicalWorkerRows +import OAI.Computability.VPVNP.CompressorCanonicalWorkerFit +import OAI.Computability.VPVNP.CompressorPrefixLevelScale + +/-! +# Canonical worker inputs on every reachable selection + +The input threshold applies at once to the entire adaptive execution +tree. Each shrinking and refresh node gets the real demand vectors of +its own graph. Changing to a physical directory holding those vectors +preserves the emitted tapes at that node and on every continuation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.CanonicalWorker + +open Compression CursorBounds CursorNetwork PrefixLevelScale PairSimulation.LocalHistory Filter + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f} +variable {a g b l : ℕ} {X : State a g} + +private theorem tree {P M w : ℕ} + (perPass : ∀ {a' g' b' l' : ℕ} {Y : State a' g'} {p : StatePass A Y b' l'} (o : PassOrigin B f hf p), + Y.positions ≤ P → Y.maxWireWidth ≤ M → Nonempty (WorkerInput o w)) + (E : StateExecution A b l X) (o : PassOrigins B f hf E) (within : Within P M E) : + Nonempty (WorkerInputs E o w) := by + induction E with + | done => exact ⟨()⟩ + | more p next ih => + exact ⟨(perPass o.1 within.1 within.2.1).some,fun c => (ih c (o.2 c) (within.2.2 c)).some⟩ + +theorem eventually_inputs (factor : ℕ) (positive : 1 ≤ factor) : ∀ᶠ len : ℕ in atTop, + ∀ {R : Type*} [CommRing R] {coeff : B.Entry → R} {sol : B.IsSolution coeff} + {a' g' b' l' : ℕ} {Y : State a' g'} (E : StateExecution R b' l' Y) (o : PassOrigins B coeff sol E), + Within (initialPositions factor len) len E → Nonempty (WorkerInputs E o (wordBits factor len)) := by + filter_upwards [eventually_fit B factor positive] with len fits + intro R _ coeff sol a' g' b' l' Y E o within + apply tree B (P := initialPositions factor len) (M := len) _ E o within + intro a'' g'' b'' l'' Z p origin pos mx + obtain ⟨space,width,values⟩ := fits origin pos mx + let G := SelectedTerms.grid origin + have dense : origin.motifCount*G.d + origin.motifCount*(2+G.e) < 2^(wordBits factor len) := by + rw [← Nat.mul_add] + exact (Nat.le_add_right ..).trans_lt ((Nat.le_add_right ..).trans_lt space) + exact ⟨input origin _ dense width values⟩ + +theorem eventually_execute_inputs (u : PairExponents B.growthConstant) (factor : ℕ) (hfactor : max S.laneBits 5 ≤ factor) : + ∀ᶠ len : ℕ in atTop, ∀ {base lanes : ℕ} (labels : Fin (virtualBits factor len) ≃ Fin base ⊕ Fin lanes) + (hD : 1 < virtualBits factor len) (hT : blockCount (u.θ : ℝ) len*S.laneBits ≤ lanes) + (R : Type*) [CommRing R] (coeff : B.Entry → R) (sol : B.IsSolution coeff), + let count := blockCount (u.θ : ℝ) len + let X₀ := pairInput S labels hD + Nonempty (WorkerInputs (B.execute coeff sol count hT X₀) (executeOrigins B coeff sol count hT X₀) + (wordBits factor len)) := by + filter_upwards [PrefixLevelScale.eventually_execute B u factor hfactor,eventually_inputs B factor (by omega)] + with len bounded inputs + intro base lanes labels hD hT R _ coeff sol count X₀ + exact inputs _ _ (bounded labels hD hT R coeff sol) + +theorem ordinalTapes_eq {w : ℕ} (E : StateExecution A b l X) (origin : PassOrigins B f hf E) + (I J : WorkerInputs E origin w) (z : E.Choices) : ordinalTapes E origin I z = ordinalTapes E origin J z := by + induction E with + | done => rfl + | more p next ih => + rcases z with ⟨i,z⟩ + simp only [ordinalTapes,WorkerInput.termEquiv_tapes,ih i (origin.2 i) (I.2 i) (J.2 i) z] + +open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels + +private theorem byLevel {w : ℕ} (E : StateExecution A b l X) (origin : PassOrigins B f hf E) + (W : E.MapWitnesses f) (r : ExecutionReaders E W) (I : WorkerInputs E origin w) (z : E.Choices) : + ordinalTapes E origin I z = (collectLevels B f hf E W r origin z).map fun v => + List.ofFn (workerTapes v.origin w v.term) := by + induction E with + | done => rfl + | more p next ih => + rcases z with ⟨i,z⟩ + simp only [ordinalTapes,collectLevels,List.map_cons,WorkerInput.termEquiv_tapes, + ih i (origin.2 i) (W.2 i) (r.2 i) (I.2 i) z] + +theorem execute_tapes {w lanes : ℕ} (count : ℕ) (h : count*S.laneBits ≤ lanes) + (Y : State (S.degreeExponent 0) lanes) + (I : WorkerInputs (B.execute f hf count h Y) (executeOrigins B f hf count h Y) w) (z : (B.execute f hf count h Y).Choices) : + ordinalTapes (B.execute f hf count h Y) (executeOrigins B f hf count h Y) I z = + (executeLevels B f hf count h Y z).map fun v => List.ofFn (workerTapes v.origin w v.term) := + byLevel B _ _ _ _ I z + +end CompressorRecords.CanonicalWorker + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCanonicalWorkerRows.lean b/lean/OAI/Computability/VPVNP/CompressorCanonicalWorkerRows.lean new file mode 100644 index 0000000000..919af1d213 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCanonicalWorkerRows.lean @@ -0,0 +1,89 @@ +import OAI.Computability.VPVNP.CompressorSelectedTermWorker + +/-! +# A fixed dense representation of the demand rows of a semantic pass + +The representation uses the exact demand vector of every motif of the +shrinking or refresh pass. The native verifier on this memory has the same +successful tapes as on any physical level directory representing those +vectors, including on an empty set of demand coordinates. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.CanonicalWorker + +open BurstRAM Compression SelectedTerms PairSimulation.LocalHistory +open scoped Fin.CommRing + +variable {m d n w : ℕ} {D : Type} (order : Fin d ≃ D) (demand : Fin m → D → ℕ) + +/-- Row-major initial memory for the demand scan, storing motif demands in the specified +coordinate order and zero outside the table. -/ +def memory (w : ℕ) : Memory w := fun x => + if h : x/d < m ∧ x%d < d then Fin.ofNat _ (demand ⟨x/d,h.1⟩ (order ⟨x%d,h.2⟩)) else 0 + +theorem cell (i : Fin m) (j : Fin d) : + memory order demand w (i.val*d+j.val) = Fin.ofNat _ (demand i (order j)) := by + have div : (i.val*d+j.val)/d = i.val := by + rw [Nat.mul_comm i.val d,Nat.mul_add_div (by have := j.isLt; omega),Nat.div_eq_of_lt j.isLt,Nat.add_zero] + have mod : (i.val*d+j.val)%d = j.val := Nat.mul_add_mod_of_lt j.isLt + simp [memory,div,mod,i.isLt,j.isLt] + +/-- Disjoint strided demand and term tables, with the first term record immediately after the +final demand row. -/ +def layout (space : m*d+m*(2+n) < 2^w) : TermRecordScan.Layout m d n w := + TermRecordScan.strided m d n w 0 (m*d) d (2+n) le_rfl le_rfl (Nat.zero_add _).le space + +theorem inputs (space : m*d+m*(2+n) < 2^w) (values : ∀ i e, demand i e < 2^w) : + TermRecordScan.Inputs order (layout space) demand (memory order demand w) := by + intro i + funext e + obtain ⟨j,rfl⟩ := order.surjective e + rw [DemandPreparation.demandAt_address order _ _ ((layout space).sourceFits i) j] + have hmul := Nat.mul_le_mul_right d i.isLt.le + have addr : ((layout space).source i).val = i.val*d := by + change (0+i.val*d) % 2^w = _ + rw [Nat.zero_add,Nat.mod_eq_of_lt (by omega)] + rw [addr,cell] + exact Nat.mod_eq_of_lt (values i (order j)) + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f} +variable {a g b l : ℕ} {X : State a g} {p : StatePass A X b l} (o : PassOrigin B f hf p) +local notation "G" => grid o + +/-- The fixed dense encoding runs the real native term program and uses +its uniform clock. It only depends on the old graph and the pass origin. -/ +def input (w : ℕ) (space : o.motifCount*(G).d+o.motifCount*(2+(G).e) < 2^w) + (width : SelectedTermWorker.fitConstant B+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (values : X.maxWireWidth < 2^w) : WorkerInput o w := + let L := layout space + let order := (G).demandOrder.entries + let demand := (termRows o).demand + SelectedTermWorker.input o width L ![0,((G).d : ℕ),(o.motifCount*(G).d : ℕ),(2+(G).e : ℕ)] + (TermWorker.addresses_strided 0 (o.motifCount*(G).d) (G).d (2+(G).e) le_rfl le_rfl (Nat.zero_add _).le space) + (memory order demand w) (inputs order demand space fun i e => ((termRows o).bounded i e).trans_lt values) + +theorem accepts_iff (I J : WorkerInput o w) (bs : Fin o.motifCount → List Bool) : + (I.run bs).isSome ↔ (J.run bs).isSome := by + have transport (P Q : WorkerInput o w) (h : (P.run bs).isSome) : (Q.run bs).isSome := by + let x : P.Accepted := ⟨bs,h⟩ + let v := P.termEquiv.symm x + have eqn : workerTapes o w v = bs := congrArg Subtype.val (P.termEquiv.apply_symm_apply x) + have yes := (Q.termEquiv v).property + rw [WorkerInput.termEquiv_tapes,eqn] at yes + exact yes + exact ⟨transport I J,transport J I⟩ + +end CompressorRecords.CanonicalWorker + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCatalogRates.lean b/lean/OAI/Computability/VPVNP/CompressorCatalogRates.lean new file mode 100644 index 0000000000..7d8fea63d0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCatalogRates.lean @@ -0,0 +1,603 @@ +import OAI.Computability.VPVNP.CompressorSlotPhaseCosts +import OAI.Computability.VPVNP.CompressorRecordGreedyPass +import OAI.Computability.VPVNP.CompressorRecordRefreshPrepare +import OAI.Computability.VPVNP.CompressorRecordRefreshSupplyScan +import OAI.Computability.VPVNP.CompressorRecordsBundleScan +import OAI.Computability.VPVNP.CompressorRecordsShrinkScan +import OAI.Computability.VPVNP.CompressorBundleFixedGather +import OAI.Computability.VPVNP.CompressorBundleKeyTable +import OAI.Computability.VPVNP.CompressorShrinkMotifAbsolute +import OAI.Computability.VPVNP.CompressorRecordsPortRankRAM +import OAI.Computability.VPVNP.CompressorRecordsBundlePrefixRAM +import OAI.Computability.VPVNP.CompressorRecordsABWidths +import OAI.Computability.VPVNP.CompressorShrinkDemandGatherCall + +/-! +# Native worker traffic at an actual compressor state + +The greedy color and tag readers are charged per original base. Dense bundle +arrays are charged by the actual old-port count, and the refresh tie and supply +arrays by the counts of blocks, ports and expander arcs. The per-call caps +depend on the fixed degrees and tables. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CatalogRates + +open BurstRAM Compression PhaseCosts +variable {w : ℕ} + +/-- Coefficient of the base count for one greedy preparer followed by its reader. -/ +def greedyRate (rows width arity candidates : ℕ) := + 16 + rows + width + 2*arity*candidates*candidates + +/-- Maximum instructions of either worker of a prepared greedy pass. -/ +def greedyCap (rows width arity candidates : ℕ) := + max (33+8*rows+6*width) (13+((4*arity+4)*candidates+4)*candidates) + +open Greedy Greedy.WalkLayout in +theorem preparedPassCounts {A V : Type*} {n d width arity k : ℕ} + {L : WalkLayout w n width} {rows : OperandRows d} {m : Memory w} {enc : A → Word w} + {order : V ≃ Fin n} {f : V → A} (h : L.PreparedPass rows m arity k enc order f) : + ∃ prep reads, + runSegment (prepareMachine w rows).program (1+(prepareCode rows).length) (some 0) m + (List.replicate n []) = some prep ∧ + runSegment (visitMachine w arity k).program (1+(visitCode arity k).length) (some (L.base 0)) + (after m (eventLog prep)) (List.replicate n []) = some reads ∧ + (prep++reads).length = 2*n ∧ + RAMBuckets.cost Report.probes (prep++reads) = n*greedyRate rows.length width arity k ∧ + ∀ r ∈ prep++reads, r.events.length+1 ≤ greedyCap rows.length width arity k := by + obtain ⟨prep,hp,_,np,cp,wp,hread⟩ := h + obtain ⟨rs,hr',cr⟩ := hread.cost + obtain ⟨reads,hr,_,_,nr,wr⟩ := hread + have he : rs = reads := Option.some.inj (hr'.symm.trans hr) + subst rs + refine ⟨prep,reads,hp,hr,by rw [List.length_append,np,nr]; omega,?_,?_⟩ + · rw [RAMBuckets.cost_append] + change RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) prep + + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) reads = _ + rw [cp,cr]; unfold greedyRate; ring + · intro r hr + rcases List.mem_append.mp hr with h | h + · apply le_trans _ (le_max_left ..) + have := (wp r h).1 + omega + · apply le_trans _ (le_max_right ..) + rw [(wr r h).1]; omega + +open Greedy.WalkLayout in +/-- Combined per-base-vertex charge for preparing and reading the greedy colors and +displacement tags at degree `d`. -/ +def greedyShrinkRate (d : ℕ) := + greedyRate (2*d) (2*d) 1 (2*d) + greedyRate (tagCount d) (4*tagCount d) 4 (tagCount d) + +open Greedy.WalkLayout in +/-- Maximum per-call instruction bound over the color and tag passes at degree `d`. -/ +def greedyShrinkCap (d : ℕ) := + max (greedyCap (2*d) (2*d) 1 (2*d)) (greedyCap (tagCount d) (4*tagCount d) 4 (tagCount d)) + +open Greedy Greedy.WalkLayout in +/-- Both greedy scans on the original base graph. The rate uses the exact base count, +which is at most the number of physical positions. -/ +theorem greedyStateCounts {a g j : ℕ} (X : State a g) (hw : j ≤ w) + (colorLayout : WalkLayout w (Fintype.card X.Base) (2 * 2 ^ a)) + (tagLayout : WalkLayout w (Fintype.card X.Base) (4 * tagCount (2 ^ a))) + (colorMem tagMem : Memory w) (tags : X.Base → BitWord j) + (hcolor : colorLayout.PreparedPass (colorOperandRows (2 ^ a)) colorMem 1 (2 * 2 ^ a) + (fun v : Fin (2*2^a+1) ↦ Fin.ofNat _ v.val) X.baseIndex + (X.slots.base.orderedColor X.baseIndex)) + (htag : tagLayout.PreparedPass (tagOperandRows (2^a)) tagMem 4 (tagCount (2^a)) + (tagWord hw) X.baseIndex tags) : + ∃ pc rc pt rt : List (Report w), + runSegment (prepareMachine w (colorOperandRows (2^a))).program + (1+(prepareCode (colorOperandRows (2^a))).length) (some 0) colorMem + (List.replicate (Fintype.card X.Base) []) = some pc ∧ + runSegment (visitMachine w 1 (2*2^a)).program (1+(visitCode 1 (2*2^a)).length) + (some (colorLayout.base 0)) (after colorMem (eventLog pc)) + (List.replicate (Fintype.card X.Base) []) = some rc ∧ + runSegment (prepareMachine w (tagOperandRows (2^a))).program + (1+(prepareCode (tagOperandRows (2^a))).length) (some 0) tagMem + (List.replicate (Fintype.card X.Base) []) = some pt ∧ + runSegment (visitMachine w 4 (tagCount (2^a))).program + (1+(visitCode 4 (tagCount (2^a))).length) + (some (tagLayout.base 0)) (after tagMem (eventLog pt)) + (List.replicate (Fintype.card X.Base) []) = some rt ∧ + let all := (pc++rc)++(pt++rt) + all.length = 4*Fintype.card X.Base ∧ + RAMBuckets.cost Report.probes all = Fintype.card X.Base*greedyShrinkRate (2^a) ∧ + RAMBuckets.cost Report.probes all ≤ X.positions*greedyShrinkRate (2^a) ∧ + ∀ rep ∈ all, rep.events.length+1 ≤ greedyShrinkCap (2^a) := by + obtain ⟨pc,rc,runC,readC,nC,cC,capC⟩ := preparedPassCounts hcolor + obtain ⟨pt,rt,runT,readT,nT,cT,capT⟩ := preparedPassCounts htag + have csz : (colorOperandRows (2^a)).length = 2*2^a := by simp [colorOperandRows] + have tsz : (tagOperandRows (2^a)).length = tagCount (2^a) := by simp [tagOperandRows,tagCount] + rw [csz] at cC capC + rw [tsz] at cT capT + have hc : RAMBuckets.cost Report.probes ((pc++rc)++(pt++rt)) = + Fintype.card X.Base * greedyShrinkRate (2^a) := by + rw [RAMBuckets.cost_append,cC,cT] + unfold greedyShrinkRate + ring + have hn : Fintype.card X.Base ≤ X.positions := by + rw [State.positions,Fintype.card_prod]; exact Nat.le_mul_of_pos_right _ Fintype.card_pos + refine ⟨pc,rc,pt,rt,runC,readC,runT,readT,?_,hc,hc.trans_le (Nat.mul_le_mul_right _ hn),?_⟩ + · rw [List.length_append,nC,nT]; omega + · intro rep hrep + rcases List.mem_append.mp hrep with h|h + · exact (capC rep h).trans (le_max_left ..) + · exact (capT rep h).trans (le_max_right ..) + +open PortRefresh in +private theorem demandScanCounts {n t : ℕ} {p : Fin t → DemandScan.Params w} + {ks : List (Fin t)} {m : Memory w} {rs : List (Report w)} (r : DemandScan.Runs p n ks m rs) : + rs.length = n*ks.length ∧ RAMBuckets.cost Report.probes rs = 3*n*ks.length ∧ + ∀ rep ∈ rs, rep.events.length+1 ≤ 26 := by + induction r with + | nil => simp + | cons k head tail ih => + obtain ⟨nh,ch,_,wh⟩ := fixedScanCounts _ (DemandScan.native (p k)) (DemandScan.work (p k)) head + refine ⟨?_,?_,?_⟩ + · rw [List.length_append,nh,ih.1,List.length_cons]; ring + · rw [RAMBuckets.cost_append,ch,ih.2.1,List.length_cons]; ring + · intro rep hr + rcases List.mem_append.mp hr with h|h + · rw [wh _ h] + · exact ih.2.2 _ h + +/-- Catalog coefficient per refreshed position, using the number of tie coordinates as a +uniform upper bound on the dense demand scans per position. -/ +def refreshRate (degree dH outDegree ties : ℕ) := + 12 + 12*degree + 11*dH + 4*(outDegree-(dH+1)) + 3*ties + +open PortRefresh PortRefresh.NewSlots Compression.DegreeRefresh PrimedStackRAM in +/-- External descriptors, every dense demand tie, every selected expander supply, and +all three output incidence columns. Motif term selection can intervene between the +prepared demand and supply scans. -/ +theorem refreshStateCounts {a g outDegree dH t : ℕ} (X : State a (a + g)) (T : IncidenceDirectory w) + (q : Fin 8 → Word w) (out lanes : Word w) (ties : Fin t ≃ Tie (2 ^ a)) + {fit : Fintype.card X.Base * 2 ^ a * 2 ^ g * 2 ^ a ≤ 2 ^ w} + (m m' : Memory w) (prep : List (Report w)) (ready : PrepareRun X T q out ties lanes fit m + m' prep) + (supply : Fin 7 → Word w) (selected : Memory w) (sr : List (Report w)) + (hs : runSegment ((template SupplyScan.visit 0).instantiate w supply).program 34 (some 0) + selected (List.replicate ((Fintype.card X.Base * 2 ^ a * 2 ^ g) * dH) []) = some sr) + (hd : dH + 1 ≤ outDegree) (pub : Fin outDegree → Public w) (os : List (Report w)) + (ho : AllSlots.Runs (fun k ↦ kindOf ((refreshSlots hd).symm k)) pub + (Fintype.card X.Base * 2 ^ a * 2 ^ g) (List.finRange outDegree) (after selected + (eventLog sr)) os) : + let B := Fintype.card X.Base*2^g + let all := prep++sr++os + all.length = X.positions*(2*2^a+1+dH+outDegree) + B*t ∧ + RAMBuckets.cost Report.probes all = + X.positions*(12+12*2^a+11*dH+4*(outDegree-(dH+1))) + 3*B*t ∧ + RAMBuckets.cost Report.probes all ≤ X.positions*refreshRate (2^a) dH outDegree t ∧ + ∀ rep ∈ all, rep.events.length+1 ≤ 46 := by + intro B all + obtain ⟨rg,rd,re,ds,ext,demand,_,eqPrep⟩ := ready + obtain ⟨hg,hb,he,extCost,_⟩ := ext + obtain ⟨nd,cd,wd⟩ := demandScanCounts demand + rw [List.length_finRange] at nd cd + obtain ⟨ns,cs,_,ws⟩ := fixedScanCounts _ (SupplyScan.visit_native supply) + (SupplyScan.events_work supply) hs + obtain ⟨no,co,_,wo⟩ := refreshWrites _ _ ho + rw [List.length_finRange] at no + rw [← List.ofFn_id,List.map_ofFn,List.sum_ofFn] at co + have co' := co.trans (slot_cost hd _) + have pos : Fintype.card X.Base*2^a*2^g = X.positions := AllSlots.site_count X + have B_le : B ≤ X.positions := by + rw [← pos]; dsimp [B] + exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)) + have ng := (run_length hg).trans (List.length_replicate ..) + have nb := (run_length hb).trans (List.length_replicate ..) + have ne := (run_length he).trans (List.length_replicate ..) + have count : RAMBuckets.cost Report.probes all = + X.positions*(12+12*2^a+11*dH+4*(outDegree-(dH+1))) + 3*B*t := by + rw [show all = (((rg++rd++re)++ds)++sr)++os from by dsimp only [all]; rw [eqPrep], + RAMBuckets.cost_append,RAMBuckets.cost_append,RAMBuckets.cost_append,extCost,cd,cs,co'] + dsimp [B] + rw [← pos]; ring + refine ⟨?_,count,?_,?_⟩ + · rw [show all = (((rg++rd++re)++ds)++sr)++os from by dsimp only [all]; rw [eqPrep]] + simp only [List.length_append,ng,nb,ne,nd,ns,no] + rw [← pos]; dsimp [B]; ring + · rw [count,refreshRate,Nat.mul_add] + linarith only [Nat.mul_le_mul_right t (Nat.mul_le_mul_left 3 B_le)] + · intro rep hr + rw [show all = (((rg++rd++re)++ds)++sr)++os from by dsimp only [all]; rw [eqPrep]] at hr + simp only [List.mem_append] at hr + rcases hr with ((((hh|hh)|hh)|hh)|hh)|hh + · exact (run_cap hg _ hh).trans (by decide) + · exact (run_cap hb _ hh).trans (by decide) + · exact (run_cap he _ hh).trans (by decide) + · exact (wd _ hh).trans (by decide) + · rw [ws _ hh]; decide + · exact wo _ hh + +/-- The dimensions used by the selected shrinking workers, on the input state's actual +base enumeration and residual lanes. -/ +def shrinkShape {a g : ℕ} (X : State a (packingLaneBits a g)) (subdiv : Fin 4 → ℕ) + (newDegree : ℕ) : SlotLevel.Shape := + ⟨Fintype.card X.Base, 2^(Shrink.J a), 2^g, 2^a, Shrink.colors a, subdiv, newDegree⟩ + +theorem shrinkShape_positions {a g : ℕ} (X : State a (packingLaneBits a g)) + (subdiv : Fin 4 → ℕ) (degree : ℕ) : + let s := shrinkShape X subdiv degree + SlotLevel.sites s*(2^s.colors*s.oldDegree) = X.positions := by + simp only [shrinkShape, SlotLevel.sites, State.positions, Fintype.card_prod, + Fintype.card_congr (bitWordFinEquiv (packingLaneBits a g)), Fintype.card_fin, + packingLaneBits, pow_add, + Shrink.colors, Shrink.J] + ring + +/-- Number of workers in a dense rank scan depends only on the motif row capacity. -/ +def denseRankCap (s : SlotLevel.Shape) := + 20 + 9*PackingData.pieceCount s.oldDegree s.colors + +open PrimedStackRAM in +/-- Physical dense key/rank scans. The two prefix rows partition the old arcs and the +motif-absolute writeback visits all old arcs. AB widths and dense demand pairs visit only +the compact motif rectangle. -/ +structure DenseShrinkScans (w : ℕ) (s : SlotLevel.Shape) where + /-- Seven public operands used by the dense bundle key-gather scan. -/ + keyBank : Fin 7 → Word w + /-- Six public operands used to rank bundle entries by their gathered keys. -/ + rankBank : Fin 6 → Word w + /-- Five public operands used to scatter widths into rank order. -/ + widthBank : Fin 5 → Word w + /-- Seven public operands used to compute absolute motif identifiers. -/ + absBank : Fin 7 → Word w + /-- Five public operands used to scan prefix widths of the thick-wire entries. -/ + thickBank : Fin 5 → Word w + /-- Five public operands used to scan prefix widths of the motif entries. -/ + motifBank : Fin 5 → Word w + /-- Five public operands used to compute the new AB widths. -/ + abBank : Fin 5 → Word w + /-- Six public operands used to gather the shrinking motif demands. -/ + demandBank : Fin 6 → Word w + /-- Native key-gather run on every dense bundle entry. -/ + key : NativeScan ((template BundleGather.Fixed.visit 0).instantiate w keyBank).program + 29 (SlotLevel.sites s*s.oldDegree*(2^s.colors*s.oldDegree)) + /-- Native run assigning each dense bundle entry its rank. -/ + rank : NativeScan ((template (PortRankRAM.visit (PackingData.pieceCount s.oldDegree + s.colors)) 0).instantiate w rankBank).program + (1+(PortRankRAM.visit (PackingData.pieceCount s.oldDegree s.colors)).length) + (SlotLevel.sites s*s.oldDegree*(2^s.colors*s.oldDegree)) + /-- Native run scattering each entry's width to its ranked position. -/ + width : NativeScan ((template BundleWidthScatter.visit 0).instantiate w widthBank).program + 19 (SlotLevel.sites s*s.oldDegree*(2^s.colors*s.oldDegree)) + /-- Native run materializing the absolute motif identifiers. -/ + absolute : NativeScan ((template MotifAbsolute.visit 0).instantiate w absBank).program + 25 (SlotLevel.sites s*s.oldDegree*(2^s.colors*s.oldDegree)) + /-- Native prefix scan of the sorted thick-wire widths in each bundle. -/ + thick : NativeScan ((template BundlePrefixRAM.visit 0).instantiate w thickBank).program + 25 (SlotLevel.sites s*s.oldDegree*(2^s.colors*s.oldDegree/4)) + /-- Native prefix scan of the motif widths in each bundle. -/ + motif : NativeScan ((template BundlePrefixRAM.visit 0).instantiate w motifBank).program + 25 (SlotLevel.sites s*s.oldDegree*PackingData.pieceCount s.oldDegree s.colors) + /-- Native scan computing AB widths for the motif entries. -/ + ab : NativeScan ((template ABWidths.visit 0).instantiate w abBank).program + 30 (SlotLevel.sites s*s.oldDegree*PackingData.pieceCount s.oldDegree s.colors) + /-- Native scan gathering demand rows for the shrinking motifs. -/ + demand : NativeScan (ShrinkDemandGather.program demandBank) 25 + (SlotLevel.sites s*s.oldDegree*PackingData.pieceCount s.oldDegree s.colors) + +/-- The eight dense shrinking scans' reports concatenated in execution order. -/ +def DenseShrinkScans.all {s : SlotLevel.Shape} (b : DenseShrinkScans w s) := + b.key.reports ++ b.rank.reports ++ b.width.reports ++ b.absolute.reports ++ b.thick.reports ++ + b.motif.reports ++ b.ab.reports ++ b.demand.reports + +open private checked_scan from OAI.Computability.VPVNP.CompressorSlotPhaseCosts + +/-- Exact physical traffic and call count for the eight dense shrinking passes. -/ +theorem denseShrinkCounts (s : SlotLevel.Shape) (hc : 2 ≤ s.colors) (b : DenseShrinkScans w s) : + let K := 2^s.colors*s.oldDegree + let Q := PackingData.pieceCount s.oldDegree s.colors + let B := SlotLevel.sites s*s.oldDegree + let A := B*K + b.all.length = 5*A+2*(B*Q) ∧ + RAMBuckets.cost Report.probes b.all = (Q+24)*A + 9*(B*Q) ∧ + ∀ r ∈ b.all, r.events.length+1 ≤ max 30 (denseRankCap s) := by + intro K Q B A + have k := fixedScanCounts _ (BundleGather.Fixed.native b.keyBank) + (BundleGather.Fixed.work b.keyBank) b.key.executed + have r := checked_scan (ticks := (PortRankRAM.visit Q).length) (probes := Q+4) + (P := ((PrimedStackRAM.template (PortRankRAM.visit Q) 0).instantiate w b.rankBank).program) + (fuel := 1+(PortRankRAM.visit Q).length) (fun m i r h ↦ by + obtain ⟨es,he,_,hp,ht⟩ := PortRankRAM.run_one b.rankBank m i Q + rw [he] at h; cases h; exact ⟨ht,hp⟩) b.rank.executed + have v := fixedScanCounts (ticks := 18) (probes := 4) _ (BundleWidthScatter.native b.widthBank) + (fun _ _ ↦ ⟨rfl,rfl⟩) b.width.executed + have z := fixedScanCounts (ticks := 24) (probes := 4) _ (MotifAbsolute.native b.absBank) + (fun _ _ ↦ ⟨rfl,rfl⟩) b.absolute.executed + have t := fixedScanCounts _ (BundlePrefixRAM.native b.thickBank) + (fun m i ↦ (BundlePrefixRAM.events_work b.thickBank m i).symm) b.thick.executed + have u := fixedScanCounts _ (BundlePrefixRAM.native b.motifBank) + (fun m i ↦ (BundlePrefixRAM.events_work b.motifBank m i).symm) b.motif.executed + have ab := fixedScanCounts _ (ABWidths.native b.abBank) (ABWidths.work b.abBank) b.ab.executed + have dm := fixedScanCounts (ticks := 24) (probes := 4) + (fun m i ↦ (ShrinkDemandGather.visits b.demandBank i m).events) + (fun m i ↦ ShrinkDemandGather.visit_run b.demandBank i m + (by decide : ShrinkDemandGather.cost < 25)) + (fun _ _ ↦ ⟨rfl,rfl⟩) b.demand.executed + have split : B*(K/4)+B*Q = A := by + rw [← Nat.mul_add, BundleKeys.bundle_row_lengths_add hc] + refine ⟨?_,?_,?_⟩ + · simp only [DenseShrinkScans.all,List.length_append,k.1,r.1,v.1,z.1,t.1,u.1,ab.1,dm.1] + change A+A+A+A+B*(K/4)+B*Q+B*Q+B*Q = _ + omega + · simp only [DenseShrinkScans.all,RAMBuckets.cost_append,k.2.1,r.2.1,v.2.1,z.2.1, + t.2.1,u.2.1,ab.2.1,dm.2.1] + change 4*A+(1+(Q+4))*A+5*A+5*A+5*(B*(K/4))+5*(B*Q)+4*(B*Q)+5*(B*Q) = _ + linarith only [congrArg (5*·) split] + · intro rep hr + simp only [DenseShrinkScans.all,List.mem_append] at hr + rcases hr with ((((((hh|hh)|hh)|hh)|hh)|hh)|hh)|hh + · exact (run_cap b.key.executed _ hh).trans ((by decide : 29 ≤ 30).trans (le_max_left ..)) + · apply le_trans (run_cap b.rank.executed _ hh) + rw [PortRankRAM.visit_length]; apply le_trans _ (le_max_right ..); dsimp [denseRankCap]; omega + · exact (run_cap b.width.executed _ hh).trans ((by decide : 19 ≤ 30).trans (le_max_left ..)) + · exact (run_cap b.absolute.executed _ hh).trans ((by decide : 25 ≤ 30).trans (le_max_left ..)) + · exact (run_cap b.thick.executed _ hh).trans ((by decide : 25 ≤ 30).trans (le_max_left ..)) + · exact (run_cap b.motif.executed _ hh).trans ((by decide : 25 ≤ 30).trans (le_max_left ..)) + · exact (run_cap b.ab.executed _ hh).trans (le_max_left ..) + · exact (run_cap b.demand.executed _ hh).trans ((by decide : 25 ≤ 30).trans (le_max_left ..)) + +open Greedy Greedy.WalkLayout in +/-- The actual two prepared greedy passes, before the shrinking layout is populated. -/ +structure GreedyPrepared (w : ℕ) {a l : ℕ} (X : State a l) where + /-- Bit length of a displacement tag assigned to a base vertex. -/ + j : ℕ + tagFits : j ≤ w + /-- The selected displacement-tag word for each base vertex. -/ + tags : X.Base → BitWord j + /-- Layout of the greedy color descriptor rows in the base-vertex order. -/ + colorLayout : WalkLayout w (Fintype.card X.Base) (2*2^a) + /-- Layout of the descriptor rows for the greedy displacement-tag pass. -/ + tagLayout : WalkLayout w (Fintype.card X.Base) (4*tagCount (2^a)) + /-- External memory supplying the operands and descriptors of the prepared color pass. -/ + colorMem : Memory w + /-- External memory supplying the operands and descriptors of the prepared tag pass. -/ + tagMem : Memory w + color : colorLayout.PreparedPass (colorOperandRows (2^a)) colorMem 1 (2*2^a) + (fun v : Fin (2*2^a+1) ↦ Fin.ofNat _ v.val) X.baseIndex (X.slots.base.orderedColor X.baseIndex) + offset : tagLayout.PreparedPass (tagOperandRows (2^a)) tagMem 4 (tagCount (2^a)) + (tagWord tagFits) X.baseIndex tags + +open Greedy Greedy.WalkLayout in +/-- Reports of all four native greedy workers, with the two preparer-to-reader handoffs. -/ +def GreedyPrepared.realizes {a l : ℕ} {X : State a l} (G : GreedyPrepared w X) + (log : List (Report w)) := + ∃ pc rc pt rt : List (Report w), log = (pc++rc)++(pt++rt) ∧ + runSegment (Greedy.prepareMachine w (Greedy.colorOperandRows (2^a))).program + (1+(Greedy.prepareCode (Greedy.colorOperandRows (2^a))).length) (some 0) G.colorMem + (List.replicate (Fintype.card X.Base) []) = some pc ∧ + runSegment (Greedy.visitMachine w 1 (2*2^a)).program (1+(Greedy.visitCode 1 (2*2^a)).length) + (some (G.colorLayout.base 0)) (after G.colorMem (eventLog pc)) + (List.replicate (Fintype.card X.Base) []) = some rc ∧ + runSegment (Greedy.prepareMachine w (Greedy.tagOperandRows (2^a))).program + (1+(Greedy.prepareCode (Greedy.tagOperandRows (2^a))).length) (some 0) G.tagMem + (List.replicate (Fintype.card X.Base) []) = some pt ∧ + runSegment (Greedy.visitMachine w 4 (tagCount (2^a))).program + (1+(Greedy.visitCode 4 (tagCount (2^a))).length) + (some (G.tagLayout.base 0)) (after G.tagMem (eventLog pt)) + (List.replicate (Fintype.card X.Base) []) = some rt + +theorem GreedyPrepared.reports {a l : ℕ} {X : State a l} (G : GreedyPrepared w X) : + ∃ rs, G.realizes rs ∧ rs.length = 4*Fintype.card X.Base ∧ + RAMBuckets.cost Report.probes rs ≤ X.positions*greedyShrinkRate (2^a) ∧ + ∀ r ∈ rs, r.events.length+1 ≤ greedyShrinkCap (2^a) := by + obtain ⟨pc,rc,pt,rt,hc,hr,ht,hu,n,_,cost,cap⟩ := + greedyStateCounts X G.tagFits G.colorLayout G.tagLayout G.colorMem G.tagMem G.tags G.color + G.offset + exact ⟨_,⟨pc,rc,pt,rt,rfl,hc,hr,ht,hu⟩,n,cost,cap⟩ + +/-- Bound for bulk descriptor scans including the fixed global key gather, full-stride +rank worker, scatter, both prefixes, absolute indices, AB widths, and dense demand +pairs. The coefficient is independent of the number of lanes and the base size. -/ +def bulkShrinkRate (s : SlotLevel.Shape) := + let d := s.oldDegree + let K := 2^s.colors*d + let Q := PackingData.pieceCount d s.colors + let U := 4*d*K*(∑ t, s.subdivisions t) + 14*K + 25*K*d + 18 + 22*U + 16*SlotLevel.pad s + 11*s.newDegree + ((Q+24)*d*K + 9*d*Q) + +/-- The largest opcode budget among the bulk and greedy workers. -/ +def bulkShrinkCap (s : SlotLevel.Shape) := max (greedyShrinkCap s.oldDegree) + (max 66 (denseRankCap s)) + +/-- All bulk shrink descriptors and both greedy scans on the actual incoming state. +The cost equality for the five endpoint passes is returned by `SlotLevel.run_selected`. +The rate counts the global rank scan once, alongside the fixed global key gather. -/ +theorem shrinkStateBulkTraffic {a g : ℕ} (X : State a (packingLaneBits a g)) (subdiv : Fin 4 → ℕ) + (degree : ℕ) (G : GreedyPrepared w X) (heads : SlotLevel.Heads) (m : Memory w) + (r : SlotLevel.Reports w) : + let s := shrinkShape X subdiv degree + ∀ (prep : ShrinkScans w s) (dense : DenseShrinkScans w s), r.Native s heads m → + ∃ greedy, G.realizes greedy ∧ + let all := greedy ++ (prep.reports ++ r.all) ++ dense.all + RAMBuckets.cost Report.probes all ≤ X.positions*(greedyShrinkRate (2^a)+bulkShrinkRate s) ∧ + ∀ rep ∈ all, rep.events.length+1 ≤ bulkShrinkCap s := by + intro s prep dense hn + have work := slotLevelExactCost hn + have hc : 2 ≤ s.colors := by + change 2 ≤ 2*2^a+1 + have := Nat.two_pow_pos a; omega + have hl : 1 ≤ s.lanes := Nat.two_pow_pos g + have hpos : 0 < SlotLevel.sites s := by + change 0 < Fintype.card X.Base*(2^(Shrink.J a)*2^g) + exact Nat.mul_pos Fintype.card_pos (Nat.mul_pos (Nat.two_pow_pos _) (Nat.two_pow_pos _)) + have small : SlotLevel.sites s ≤ X.positions := by + rw [← shrinkShape_positions X subdiv degree] + exact Nat.le_mul_of_pos_right _ (Nat.mul_pos (Nat.two_pow_pos _) (Nat.two_pow_pos _)) + let K := 2^s.colors*s.oldDegree + let Q := PackingData.pieceCount s.oldDegree s.colors + obtain ⟨_,cd,capD⟩ := denseShrinkCounts s hc dense + have boundD : RAMBuckets.cost Report.probes dense.all ≤ + SlotLevel.sites s*((Q+24)*s.oldDegree*K+9*s.oldDegree*Q) := by + rw [cd]; dsimp [Q,K]; apply le_of_eq; ring + obtain ⟨cb,capB⟩ := shrinkDescriptorTraffic s heads m r hn hl hpos prep work boundD + obtain ⟨greedy,hgr,_,cg,capG⟩ := G.reports + refine ⟨greedy,hgr,?_,?_⟩ + · simp only [RAMBuckets.cost_append] + have base : RAMBuckets.cost Report.probes (prep.reports++r.all) + + RAMBuckets.cost Report.probes dense.all ≤ X.positions*bulkShrinkRate s := + cb.trans (Nat.mul_le_mul_right _ small) + rw [RAMBuckets.cost_append] at base + rw [Nat.mul_add]; omega + · intro rep hr + simp only [List.mem_append] at hr + rcases hr with (hg | (hp | ho)) | hd + · exact (capG _ hg).trans (le_max_left ..) + · exact (capB _ (List.mem_append_left _ hp)).trans ((le_max_left ..).trans (le_max_right ..)) + · exact (capB _ (List.mem_append_right _ ho)).trans ((le_max_left ..).trans (le_max_right ..)) + · exact (capD _ hd).trans ((max_le_max_right _ (by decide : 30 ≤ 66)).trans (le_max_right ..)) + +open private preimage_scan_cost from OAI.Computability.VPVNP.CompressorSlotPhaseCosts + +/-- The placement and bundle classifier feed the two bounded append scans. The two +append runs are the ones supplied by `placementPreimages` and `BundleLists.fill_run`. -/ +theorem stateInputScanCounts {a l : ℕ} (X : State a l) (p : Fin 14 → Word w) + (c : Fin 11 → Word w) (p' c' : Fin 6 → Word w) (m n : Memory w) + (placed classified : List (Report w)) (preimages : NativeScan + ((PrimedStackRAM.template collectPreimage 3).instantiate w p').program 23 X.positions) + (bundles : NativeScan ((PrimedStackRAM.template collectPreimage 3).instantiate w c').program + 23 (X.positions * 2 ^ a)) + (hp : ShrinkRAM.ScanResult p X.positions 0 X.positions m placed) + (hc : BundleRAM.ScanResult c (X.positions * 2 ^ a) 0 (X.positions * 2 ^ a) n classified) : + let all := placed++preimages.reports++classified++bundles.reports + all.length = X.positions * (2+2*2^a) ∧ + RAMBuckets.cost Report.probes all = X.positions*(14+14*2^a) ∧ + ∀ r ∈ all, r.events.length+1 ≤ 66 := by + intro all + have np := (run_length preimages.executed).trans (List.length_replicate ..) + have nc := (run_length bundles.executed).trans (List.length_replicate ..) + have wp := preimage_scan_cost preimages.executed + have wc := preimage_scan_cost bundles.executed + have h₁ : RAMBuckets.cost Report.probes placed = 9*X.positions := hp.cost + have h₂ : RAMBuckets.cost Report.probes classified = 9*(X.positions * 2 ^ a) := hc.cost + refine ⟨?_,?_,?_⟩ + · simp only [all,List.length_append,hp.calls,np,hc.calls,nc]; ring + · simp only [all,RAMBuckets.cost_append,h₁,wp,h₂,wc]; ring + · intro r hr + simp only [all,List.mem_append] at hr + rcases hr with ((h|h)|h)|h + · rw [(hp.work r h).1]; decide + · exact (run_cap preimages.executed _ h).trans (by decide) + · rw [(hc.work r h).1]; decide + · exact (run_cap bundles.executed _ h).trans (by decide) + +open scoped Classical in +/-- Indexed input banks for the demand slice of each bundle and the subdivided output of +each role-edge. The widths in the old arrays come from the selected state. -/ +structure StateSliceInputs (w : ℕ) {a g : ℕ} (X : State a (packingLaneBits a g)) + (subdiv : Fin 4 → ℕ) where + /-- The enumeration used to lay out the motif entries of each bundle. -/ + number : X.packingData.BundleNumbering + /-- The enumeration used to lay out the thick-wire entries of each bundle. -/ + order : X.packingData.ThickNumbering + /-- Width of each of the four selected roles at each packing motif. -/ + roleWidth : Fin 4 × X.packingData.Motif → ℕ + /-- The slice-scan operands for intersecting ordered old thick-wire widths with ordered new + AB widths in each bundle. -/ + demand : ∀ b, SliceInput w (orderedWidths (order b) (fun x ↦ X.packingWidth x.1.1)) + (orderedWidths (number b) (fun x ↦ X.packingData.abWidth number X.packingWidth x.1)) + /-- The slice-scan operands for splitting each selected role width into its prescribed + subdivisions. -/ + divide : ∀ i, SliceInput w [roleWidth i] (List.ofFn (splitWidth (roleWidth i) (subdiv i.1))) + +/-- Per-position charge allowance for AB interval intersections and subdivision of the four +motif role widths. -/ +def sliceRate (d c : ℕ) (subdiv : Fin 4 → ℕ) := + let Q := PackingData.pieceCount d c + let H := 2^c*d/4 + let S := ∑ t, subdiv t + d*(4+7*(H+Q)+16*(H*Q)+4*Q*(4+7*(1+S)+16*S)) + +/-- The number of physical slice worker rows. Each native slice pass has five phases. -/ +def sliceRowsPerSite (d c : ℕ) := 5*d*(1+4*PackingData.pieceCount d c) + +/-- Total traffic and row count of all local slice inputs of one actual state. -/ +theorem stateSliceTraffic {a g : ℕ} (X : State a (packingLaneBits a g)) (subdiv : Fin 4 → ℕ) + (input : StateSliceInputs w X subdiv) : + ∃ (ds : Site X.Base (BitWord (Shrink.J a)) (BitWord g) × Fin (2^a) → SliceSchedule.Passes w) + (rs : Fin 4 × X.packingData.Motif → SliceSchedule.Passes w), + (∀ b, (input.demand b).produces (ds b) ∧ ∀ r ∈ (ds b).all, r.events.length+1 ≤ 38) ∧ + (∀ i, (input.divide i).produces (rs i) ∧ ∀ r ∈ (rs i).all, r.events.length+1 ≤ 38) ∧ + ((∑ b, RAMBuckets.cost Report.probes (ds b).all) + (∑ i, RAMBuckets.cost Report.probes + (rs i).all) ≤ + X.positions * sliceRate (2^a) (Shrink.colors a) subdiv) ∧ + 5*Fintype.card (Site X.Base (BitWord (Shrink.J a)) (BitWord g) × Fin (2^a)) + + 5*Fintype.card (Fin 4 × X.packingData.Motif) ≤ X.positions * sliceRowsPerSite (2^a) + (Shrink.colors a) := by + classical + let s := shrinkShape X subdiv 0 + let P := SlotLevel.sites s + let d := 2^a + let c := Shrink.colors a + let Q := PackingData.pieceCount d c + let S := ∑ t, subdiv t + let site := SlotSchedule.siteIndex X.baseIndex (bitWordFinEquiv (Shrink.J a)) (bitWordFinEquiv g) + have hport : Fintype.card (Site X.Base (BitWord (Shrink.J a)) (BitWord g) × Fin d) = P*d := by + rw [Fintype.card_prod,Fintype.card_congr site,Fintype.card_fin,Fintype.card_fin]; rfl + have hrole : Fintype.card (Fin 4 × X.packingData.Motif) = 4*(P*d*Q) := by + rw [Fintype.card_prod,Fintype.card_fin, + Fintype.card_congr (MotifAbsolute.denseIndex X.packingData site input.number), + Fintype.card_fin] + rfl + have hp : P ≤ X.positions := by + rw [← shrinkShape_positions X subdiv 0] + exact Nat.le_mul_of_pos_right _ (Nat.mul_pos (Nat.two_pow_pos _) (Nat.two_pow_pos _)) + obtain ⟨ds,hs,capD,_,cd,_⟩ := + demandSliceCosts X.packingData input.number input.order X.packingWidth input.demand + obtain ⟨rs,hr,capR,_,cr,_⟩ := subdivisionSliceCosts input.roleWidth subdiv Prod.fst input.divide + rw [hport] at cd + rw [hrole] at cr + refine ⟨ds,rs,fun b ↦ ⟨hs b,capD b⟩,fun i ↦ ⟨hr i,capR i⟩,?_,?_⟩ + · apply le_trans _ (Nat.mul_le_mul_right (sliceRate d c subdiv) hp) + change (∑ i, RAMBuckets.cost Report.probes (ds i).all) ≤ + P*d*(4+7*(2^c*d/4+Q)+16*((2^c*d/4)*Q)) at cd + change (∑ i, RAMBuckets.cost Report.probes (rs i).all) ≤ 4*(P*d*Q)*(4+7*(1+S)+16*(1*S)) at cr + change _ ≤ P*(d*(4+7*(2^c*d/4+Q)+16*((2^c*d/4)*Q)+4*Q*(4+7*(1+S)+16*S))) + linarith only [cd,cr] + · rw [hport,hrole] + apply le_trans _ (Nat.mul_le_mul_right (sliceRowsPerSite d c) hp) + change _ ≤ P*(5*d*(1+4*Q)); apply le_of_eq; ring + +/-- The coefficient for the shrinking descriptor catalog. The scheduler charges motif +coefficient evaluation and row framing separately. -/ +def shrinkRate (s : SlotLevel.Shape) := + greedyShrinkRate s.oldDegree + bulkShrinkRate s + sliceRate s.oldDegree s.colors s.subdivisions + +/-- End-to-end count of the physical preparation, greedy, slot, dense and slice workers +for one selected shrinking state. The report witnesses are retained for the scheduler. -/ +theorem shrinkStateTraffic {a g : ℕ} (X : State a (packingLaneBits a g)) (subdiv : Fin 4 → ℕ) + (degree : ℕ) (G : GreedyPrepared w X) (heads : SlotLevel.Heads) (m : Memory w) + (r : SlotLevel.Reports w) (slices : StateSliceInputs w X subdiv) : + let s := shrinkShape X subdiv degree + ∀ (prep : ShrinkScans w s) (dense : DenseShrinkScans w s), r.Native s heads m → + ∃ (greedy : List (Report w)) + (ds : Site X.Base (BitWord (Shrink.J a)) (BitWord g) × Fin (2^a) → SliceSchedule.Passes w) + (rs : Fin 4 × X.packingData.Motif → SliceSchedule.Passes w), + G.realizes greedy ∧ (∀ b, (slices.demand b).produces (ds b)) ∧ + (∀ i, (slices.divide i).produces (rs i)) ∧ + let bulk := greedy ++ (prep.reports ++ r.all) ++ dense.all + RAMBuckets.cost Report.probes bulk + ((∑ b, RAMBuckets.cost Report.probes (ds b).all) + + (∑ i, RAMBuckets.cost Report.probes (rs i).all)) ≤ X.positions*shrinkRate s ∧ + (∀ rep ∈ bulk, rep.events.length+1 ≤ bulkShrinkCap s) ∧ + (∀ b, ∀ rep ∈ (ds b).all, rep.events.length+1 ≤ 38) ∧ + (∀ i, ∀ rep ∈ (rs i).all, rep.events.length+1 ≤ 38) := by + intro s prep dense native + obtain ⟨greedy,run,cb,cap⟩ := shrinkStateBulkTraffic X subdiv degree G heads m r prep dense native + obtain ⟨ds,rs,hd,hr,cs,_⟩ := stateSliceTraffic X subdiv slices + refine ⟨greedy,ds,rs,run,fun b ↦ (hd b).1,fun i ↦ (hr i).1,?_,cap,fun b ↦ (hd b).2,fun i ↦ + (hr i).2⟩ + exact (Nat.add_le_add cb cs).trans_eq (Nat.mul_add ..).symm + +end CompressorRecords.CatalogRates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorChoiceGrid.lean b/lean/OAI/Computability/VPVNP/CompressorChoiceGrid.lean new file mode 100644 index 0000000000..4e01bf4548 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorChoiceGrid.lean @@ -0,0 +1,338 @@ +import OAI.Computability.VPVNP.CompressorChoicePreparation + +/-! +# Native lookup of the rounded demand-grid point + +For a fixed rational grid, the public data list the address offsets and the +two cleared coefficients of every comparison. The instruction table reads the +demand widths, tests each row in order and returns the first covering index. +The table length is the sentinel for a failed search. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GridRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM MotifAdmission +open scoped Fin.CommRing + +variable {D : Type*} {d t w : ℕ} + +private def slot (j : Fin t) (i : Fin d) (f : Fin 3) : Fin (t*d*3) := + finProdFinEquiv (finProdFinEquiv (j,i), f) + +/-- Fixed public words, ordered by grid row, demand coordinate and field. -/ +def coefficients [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) + (x : Fin (t*d*3)) : Word w := + let (a, f) := finProdFinEquiv.symm x + let (j, i) := finProdFinEquiv.symm a + let r := rows j (order i) + if f = 0 then i.val else if f = 1 then (r.den^2 * denominator p : ℕ) else (r.num.natAbs^2 : ℕ) + +private theorem coefficient_slot [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) + (rows : Fin t → D → ℚ) (j : Fin t) (i : Fin d) (f : Fin 3) : + coefficients (w := w) order p rows (slot j i f) = + if f = 0 then i.val else if f = 1 then ((rows j (order i)).den^2 * denominator p : ℕ) + else ((rows j (order i)).num.natAbs^2 : ℕ) := by + simp [coefficients,slot] + +/-- Word-fit conditions on the final products, allowing modular intermediate +products because the register arithmetic is a ring. -/ +def OperandsFit [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) + (b : D → ℕ) (w : ℕ) : Prop := + ∀ j i, b (order i)^2 * ((rows j (order i)).den^2 * denominator p) < 2^w ∧ + energy p b * (rows j (order i)).num.natAbs^2 < 2^w + +/-- This grid-dependent coefficient bounds all comparison operands after +multiplication by the squared input-width scale. -/ +def operandConstant [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) : ℕ := + ∑ j, ∑ i, ((rows j (order i)).den^2 * denominator p + + (∑ e, weight p e) * (rows j (order i)).num.natAbs^2) + +theorem operandsFit_of_width [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) + (b : D → ℕ) (M : ℕ) (hb : ∀ e, b e ≤ M) + (hfit : operandConstant order p rows * (M+1)^2 < 2^w) : OperandsFit order p rows b w := by + intro j i + let c := fun j i => (rows j (order i)).den^2 * denominator p + + (∑ e, weight p e) * (rows j (order i)).num.natAbs^2 + have h : c j i ≤ operandConstant order p rows := + (Finset.single_le_sum (f := c j) (fun _ _ => Nat.zero_le _) (Finset.mem_univ i)).trans + (Finset.single_le_sum (f := fun j => ∑ i, c j i) (fun _ _ => Nat.zero_le _) (Finset.mem_univ j)) + obtain ⟨hl,hr⟩ := grid_operands_le p b M hb (order i) (rows j (order i)) + rw [mul_pow, mul_assoc] at hl + exact ⟨hl.trans_lt ((Nat.mul_le_mul_right _ ((Nat.le_add_right ..).trans h)).trans_lt hfit), + hr.trans_lt ((Nat.mul_le_mul_right _ ((Nat.le_add_left ..).trans h)).trans_lt hfit)⟩ + +private def keep : Flow 8 (t*d*3) := .line (.copy 5 5) +private def clear : Flow 8 (t*d*3) := .line (.constant 5 0) + +/-- One coordinate comparison. The sign of a fixed rational is resolved at +table generation. A negative coordinate clears the row's validity bit. -/ +def compareCoordinate (order : Fin d ≃ D) (rows : Fin t → D → ℚ) (j : Fin t) (i : Fin d) : + Flow 8 (t*d*3) := + .seq (.line (.stateWord 2)) <| + .seq (.line (.publicWord 4 (slot j i 0))) <| + .seq (.line (.binary .add 2 2 4)) <| + .seq (.line (.read 3 2)) <| + .seq (.line (.binary .mul 3 3 3)) <| + .seq (.line (.publicWord 4 (slot j i 1))) <| + .seq (.line (.binary .mul 3 3 4)) <| + .seq (.line (.publicWord 4 (slot j i 2))) <| + .seq (.line (.binary .mul 7 0 4)) + (.ifLt 7 3 clear (if 0 ≤ rows j (order i) then keep else clear)) + +private def compareEvents (a x : Word w) : List (Event w) := + [.tick,.tick,.tick,.read a x,.tick,.tick,.tick,.tick,.tick,.tick,.tick] + +private theorem compare_exec [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) + (s : Word w) (mem : Memory w) (rs : Regs w 8) (j : Fin t) (i : Fin d) + (he : (rs 0).val = energy p (DemandPreparation.demandAt order s mem)) + (fit : OperandsFit order p rows (DemandPreparation.demandAt order s mem) w) : + let a := s + (i.val : Word w) + ∃ out, Flow.Exec (coefficients order p rows) s (compareCoordinate order rows j i) rs mem + (compareEvents a (mem a.val)) out mem ∧ + out 0 = rs 0 ∧ out 1 = rs 1 ∧ out 6 = rs 6 ∧ + out 5 = (if coversCoordinate p (DemandPreparation.demandAt order s mem) (order i) + (rows j (order i)) then rs 5 else 0) := by + dsimp only + let pub := coefficients (w := w) order p rows + let r := rows j (order i) + let b := DemandPreparation.demandAt order s mem + let a := s + (i.val : Word w) + let x := mem a.val + have hx : b (order i) = x.val := by simp [b,x,a,DemandPreparation.demandAt] + let u := Function.update rs 2 s + let v := Function.update u 4 (pub (slot j i 0)) + let z := Function.update v 2 (v 2 + v 4) + have hz : z 2 = a := by simp (config := {decide := true}) [z,v,u,a,pub,coefficient_slot,Function.update] + let g := Function.update z 3 x + let h := Function.update g 3 (g 3 * g 3) + let l := Function.update h 4 (pub (slot j i 1)) + let m := Function.update l 3 (l 3 * l 4) + let n := Function.update m 4 (pub (slot j i 2)) + let y := Function.update n 7 (n 0 * n 4) + have lhs : (y 3).val = b (order i)^2 * (r.den^2 * denominator p) := by + have hw : y 3 = ((b (order i)^2 * (r.den^2 * denominator p) : ℕ) : Word w) := by + simp (config := {decide := true}) [y,n,m,l,h,g,pub,coefficient_slot,Function.update,hx,r,pow_two] + rw [hw,Fin.val_natCast,Nat.mod_eq_of_lt (fit j i).1] + have rhs : (y 7).val = energy p b * r.num.natAbs^2 := by + have hw : y 7 = ((energy p b * r.num.natAbs^2 : ℕ) : Word w) := by + simp (config := {decide := true}) [y,n,m,l,h,g,z,v,u,pub,coefficient_slot, + Function.update,← he,r,b] + rw [hw,Fin.val_natCast,Nat.mod_eq_of_lt (fit j i).2] + have start (last : Regs w 8) (branch : Flow.Exec pub s + (.ifLt 7 3 clear (if 0 ≤ rows j (order i) then keep else clear)) y mem [.tick,.tick] last mem) : + Flow.Exec pub s (compareCoordinate order rows j i) rs mem (compareEvents a x) last mem := by + have rd : Flow.Exec pub s (.line (.read 3 2)) z mem [.read a x] g mem := by + apply Flow.Exec.line + simp only [Op.effect,hz,g,x] + exact .seq (.line (rs' := u) rfl) (.seq (.line (rs' := v) rfl) (.seq (.line (rs' := z) rfl) + (.seq rd (.seq (.line (rs' := h) rfl) (.seq (.line (rs' := l) rfl) + (.seq (.line (rs' := m) rfl) (.seq (.line (rs' := n) rfl) + (.seq (.line (rs' := y) rfl) branch)))))))) + have cov : coversCoordinate p b (order i) r = true ↔ 0 ≤ r ∧ ¬ y 7 < y 3 := by + simp [coversCoordinate,Fin.lt_def,lhs,rhs,mul_pow,mul_assoc,not_lt] + have common (dst : Fin 8) (h2 : dst ≠ 2) (h3 : dst ≠ 3) (h4 : dst ≠ 4) (h7 : dst ≠ 7) : + y dst = rs dst := by simp [y,n,m,l,h,g,z,v,u,Function.update,h2,h3,h4,h7] + change ∃ out, Flow.Exec pub s _ rs mem (compareEvents a x) out mem ∧ + out 0 = rs 0 ∧ out 1 = rs 1 ∧ out 6 = rs 6 ∧ + out 5 = (if coversCoordinate p b (order i) r then rs 5 else 0) + by_cases lt : y 7 < y 3 + · refine ⟨_,start _ (.ifLtYes lt (.line (rs' := Function.update y 5 0) rfl)),?_⟩ + simp (config := {decide := true}) [Function.update,common,cov,lt] + · by_cases sign : 0 ≤ r + · have hb : (if 0 ≤ rows j (order i) then keep else clear) = (keep : Flow 8 (t*d*3)) := ite_eq_left sign + refine ⟨_,start _ (.ifLtNo lt (by rw [hb]; exact .line (rs' := Function.update y 5 (y 5)) rfl)),?_⟩ + simp (config := {decide := true}) [Function.update,common,cov,lt,sign] + · have hb : (if 0 ≤ rows j (order i) then keep else clear) = (clear : Flow 8 (t*d*3)) := ite_eq_right sign + refine ⟨_,start _ (.ifLtNo lt (by rw [hb]; exact .line (rs' := Function.update y 5 0) rfl)),?_⟩ + simp (config := {decide := true}) [Function.update,common,cov,lt,sign] + +private def coordinates (order : Fin d ≃ D) (rows : Fin t → D → ℚ) (j : Fin t) : + List (Fin d) → Flow 8 (t*d*3) + | [] => keep + | i :: is => .seq (compareCoordinate order rows j i) (coordinates order rows j is) + +private theorem coordinates_exec [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) + (s : Word w) (mem : Memory w) (rs : Regs w 8) (j : Fin t) (ids : List (Fin d)) + (he : (rs 0).val = energy p (DemandPreparation.demandAt order s mem)) + (fit : OperandsFit order p rows (DemandPreparation.demandAt order s mem) w) : + ∃ es out, Flow.Exec (coefficients order p rows) s (coordinates order rows j ids) rs mem es out mem ∧ + choiceBits es = [] ∧ countProbes es = ids.length ∧ after mem es = mem ∧ + es.length = 11*ids.length + 1 ∧ out 0 = rs 0 ∧ out 1 = rs 1 ∧ out 6 = rs 6 ∧ + out 5 = (if ids.all fun i => coversCoordinate p (DemandPreparation.demandAt order s mem) + (order i) (rows j (order i)) then rs 5 else 0) := by + induction ids generalizing rs with + | nil => + refine ⟨_,_,.line (rs' := Function.update rs 5 (rs 5)) rfl,rfl,rfl,rfl,rfl,?_⟩ + simp (config := {decide := true}) [Function.update] + | cons i ids ih => + obtain ⟨mid,h1,e1,r1,o1,v1⟩ := compare_exec order p rows s mem rs j i he fit + obtain ⟨es,out,h2,bits,probes,mem',len,e2,r2,o2,v2⟩ := ih mid (e1 ▸ he) + refine ⟨_ ++ es,out,.seq h1 h2,?_,?_,?_,?_,e2.trans e1,r2.trans r1,o2.trans o1,?_⟩ + · simpa [compareEvents,choiceBits] using bits + · simp [compareEvents,countProbes,probes,Nat.add_comm] + · exact mem' + · simp [compareEvents,len]; omega + · rw [v2,v1,List.all_cons] + cases coversCoordinate p (DemandPreparation.demandAt order s mem) (order i) (rows j (order i)) <;> + cases ids.all (fun x => coversCoordinate p (DemandPreparation.demandAt order s mem) + (order x) (rows j (order x))) <;> rfl + +private def rowsFrom (order : Fin d ≃ D) (rows : Fin t → D → ℚ) : List (Fin t) → Flow 8 (t*d*3) + | [] => .line (.copy 1 1) + | j :: js => + .seq (.line (.constant 5 1)) <| + .seq (coordinates order rows j (List.finRange d)) <| + .ifEq 5 6 (.line (.copy 1 1)) + (.seq (.line (.binary .add 1 1 6)) (rowsFrom order rows js)) + +/-- Ordered first-cover search starting with the energy in register zero. +The first covering index, or the length sentinel, is returned in register one. -/ +def grid (order : Fin d ≃ D) (rows : Fin t → D → ℚ) : Flow 8 (t*d*3) := + .seq (.line (.constant 6 1)) (.seq (.line (.constant 1 0)) (rowsFrom order rows (List.finRange t))) + +private theorem coordinates_length (order : Fin d ≃ D) (rows : Fin t → D → ℚ) + (j : Fin t) (is : List (Fin d)) : + (coordinates order rows j is).length = 12 * is.length + 1 := by + induction is with + | nil => rfl + | cons i is ih => + by_cases h : 0 ≤ rows j (order i) <;> + simp [coordinates,compareCoordinate,Flow.length,h,keep,clear,ih] <;> omega + +/-- The text size depends only on the dimensions of the fixed grid. -/ +theorem grid_length (order : Fin d ≃ D) (rows : Fin t → D → ℚ) : + (grid order rows).length = (12*d+5)*t+3 := by + have h (ids : List (Fin t)) : (rowsFrom order rows ids).length = (12*d+5)*ids.length+1 := by + induction ids with + | nil => rfl + | cons j js ih => simp [rowsFrom,Flow.length,coordinates_length,ih,Nat.mul_succ]; omega + simp [grid,Flow.length,h]; omega + +private theorem probes_append (es fs : List (Event w)) : + countProbes (es ++ fs) = countProbes es + countProbes fs := by + induction es with + | nil => simp [countProbes] + | cons e es ih => cases e <;> simp [countProbes,ih,Nat.add_assoc] + +private def coversRow [Fintype D] (p : D → ℚ) (b : D → ℕ) (r : D → ℚ) : Bool := + decide (∀ e, coversCoordinate p b e (r e) = true) + +private theorem all_coversRow [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (b : D → ℕ) + (r : D → ℚ) : + (List.finRange d).all (fun i => coversCoordinate p b (order i) (r (order i))) = coversRow p b r := by + apply Bool.eq_iff_iff.mpr + simp [List.all_eq_true,coversRow, Equiv.forall_congr_left order] + +private theorem rows_exec [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) + (s : Word w) (mem : Memory w) (rs : Regs w 8) (ids : List (Fin t)) + (he : (rs 0).val = energy p (DemandPreparation.demandAt order s mem)) + (ho : rs 6 = 1) (hw : 1 < 2^w) + (fit : OperandsFit order p rows (DemandPreparation.demandAt order s mem) w) : + ∃ es out, Flow.Exec (coefficients order p rows) s (rowsFrom order rows ids) rs mem es out mem ∧ + choiceBits es = [] ∧ countProbes es ≤ ids.length*d ∧ after mem es = mem ∧ + es.length ≤ (11*d+4)*ids.length+1 ∧ out 1 = rs 1 + + ((ids.findIdx fun j => coversRow p (DemandPreparation.demandAt order s mem) (rows j) : ℕ) : Word w) := by + induction ids generalizing rs with + | nil => + refine ⟨_,_,.line (rs' := Function.update rs 1 (rs 1)) rfl,rfl,by simp [countProbes],rfl,by simp,?_⟩ + simp [Function.update] + | cons j js ih => + let b := DemandPreparation.demandAt order s mem + let start := Function.update rs 5 (1 : Word w) + have reset : Flow.Exec (coefficients order p rows) s (.line (.constant 5 1)) rs mem [.tick] start mem := .line rfl + have hs (i : Fin 8) (hi : i ≠ 5) : start i = rs i := Function.update_of_ne hi .. + obtain ⟨es,mid,h1,bits,probes,mem',len,hE,hR,hO,hV⟩ := + coordinates_exec order p rows s mem start j (List.finRange d) (hs 0 (by decide) ▸ he) fit + rw [List.length_finRange] at probes len + rw [all_coversRow] at hV + have ho' := hO.trans ((hs 6 (by decide)).trans ho) + have hr' := hR.trans (hs 1 (by decide)) + change mid 5 = (if coversRow p b (rows j) then start 5 else 0) at hV + by_cases hc : coversRow p b (rows j) = true + · have test : mid 5 = mid 6 := by simp [hV,hc,start,ho'] + have hyes : Flow.Exec (coefficients order p rows) s (.line (.copy 1 1)) mid mem + [.tick] (Function.update mid 1 (mid 1)) mem := .line rfl + refine ⟨_,_,.seq reset (.seq h1 (.ifEqYes test hyes)),?_,?_,?_,?_,?_⟩ + · simp [choiceBits,Flow.choiceBits_append,bits] + · simp [countProbes,probes_append,probes,Nat.succ_mul] + · change after mem (es ++ [.tick,.tick]) = mem + rw [show after mem (es ++ [.tick,.tick]) = after (after mem es) [.tick,.tick] from List.foldl_append,mem'] + rfl + · simp [len,Nat.mul_succ]; omega + · simp [List.findIdx_cons,hc,b,hr',Function.update] at * + · have hn : (0 : Word w) ≠ 1 := by + intro h + have h' := congrArg Fin.val h + simp [Nat.mod_eq_of_lt hw] at h' + have test : mid 5 ≠ mid 6 := by simp [hV,hc,ho',hn] + let next := Function.update mid 1 (mid 1 + mid 6) + have inc : Flow.Exec (coefficients order p rows) s (.line (.binary .add 1 1 6)) mid mem + [.tick] next mem := .line rfl + have en : (next 0).val = energy p b := by + rw [show next 0 = mid 0 from Function.update_of_ne (by decide) ..,hE,hs 0 (by decide)] + exact he + have on : next 6 = 1 := (Function.update_of_ne (by decide) ..).trans ho' + obtain ⟨fs,out,h2,fb,fp,fm,fl,fv⟩ := ih next en on + refine ⟨_,_,.seq reset (.seq h1 (.ifEqNo test (.seq inc h2))),?_,?_,?_,?_,?_⟩ + · simp [choiceBits,Flow.choiceBits_append,bits,fb] + · simp [countProbes,probes_append,probes,Nat.succ_mul]; omega + · change after mem (es ++ (.tick :: .tick :: fs)) = mem + rw [show after mem (es ++ (.tick :: .tick :: fs)) = + after (after mem es) (.tick :: .tick :: fs) from List.foldl_append,mem'] + exact fm + · simp [len,Nat.mul_succ]; omega + · change out 1 = rs 1 + (((j :: js).findIdx fun a => coversRow p b (rows a) : ℕ) : Word w) + rw [fv,List.findIdx_cons,ite_eq_right hc] + simp [next,ho',hr',b,add_assoc,add_comm,add_left_comm] + +/-- Row number returned by the grid instruction table. -/ +def firstRow [Fintype D] (p : D → ℚ) (b : D → ℕ) (rows : Fin t → D → ℚ) : ℕ := + (List.ofFn rows).findIdx (coversRow p b) + +theorem firstRow_getElem? [Fintype D] (p : D → ℚ) (b : D → ℕ) (rows : Fin t → D → ℚ) : + (List.ofFn rows)[firstRow p b rows]? = selectGrid p b (List.ofFn rows) := by + change (List.ofFn rows)[(List.ofFn rows).findIdx (coversRow p b)]? = (List.ofFn rows).find? (coversRow p b) + generalize List.ofFn rows = l + induction l with + | nil => rfl + | cons a l ih => + by_cases ha : coversRow p b a = true <;> simp [List.findIdx_cons,ha,ih] + +/-- Exact row-selection semantics and worst-case work for an arbitrary finite +ordered table, including empty tables and grids with negative coordinates. -/ +theorem grid_exec [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) + (s : Word w) (mem : Memory w) (rs : Regs w 8) + (he : (rs 0).val = energy p (DemandPreparation.demandAt order s mem)) + (hw : 1 < 2^w) (ht : t < 2^w) + (fit : OperandsFit order p rows (DemandPreparation.demandAt order s mem) w) : + ∃ es out, Flow.Exec (coefficients order p rows) s (grid order rows) rs mem es out mem ∧ + choiceBits es = [] ∧ countProbes es ≤ t*d ∧ after mem es = mem ∧ + es.length ≤ (11*d+4)*t+3 ∧ (out 1).val = firstRow p (DemandPreparation.demandAt order s mem) rows := by + let a := Function.update rs 6 (1 : Word w) + let c := Function.update a 1 (0 : Word w) + have init1 : Flow.Exec (coefficients order p rows) s (.line (.constant 6 1)) rs mem [.tick] a mem := .line rfl + have init2 : Flow.Exec (coefficients order p rows) s (.line (.constant 1 0)) a mem [.tick] c mem := .line rfl + have hE : (c 0).val = energy p (DemandPreparation.demandAt order s mem) := by + simpa (config := {decide := true}) [c,a,Function.update] using he + have hO : c 6 = 1 := by simp (config := {decide := true}) [c,a,Function.update] + obtain ⟨es,out,h,bits,probes,mem',len,hv⟩ := rows_exec order p rows s mem c (List.finRange t) hE hO hw fit + rw [List.length_finRange] at len probes + refine ⟨_,out,.seq init1 (.seq init2 h),bits,probes,mem',by simp; omega,?_⟩ + have hindex : (List.finRange t).findIdx (fun j => coversRow p (DemandPreparation.demandAt order s mem) (rows j)) = + firstRow p (DemandPreparation.demandAt order s mem) rows := by + have hm : (List.finRange t).map rows = List.ofFn rows := by simp [List.finRange,List.map_ofFn,Function.comp_def] + rw [firstRow,← hm,List.findIdx_map] + rfl + have hi : firstRow p (DemandPreparation.demandAt order s mem) rows < 2^w := + (List.findIdx_le_length (xs := List.ofFn rows) (p := _)).trans_lt (by simpa using ht) + rw [hv,hindex,show c 1 = 0 from Function.update_self ..,zero_add,Fin.val_natCast,Nat.mod_eq_of_lt hi] + +end CompressorRecords.GridRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorChoiceGridStage.lean b/lean/OAI/Computability/VPVNP/CompressorChoiceGridStage.lean new file mode 100644 index 0000000000..6f012e7608 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorChoiceGridStage.lean @@ -0,0 +1,223 @@ +import OAI.Computability.VPVNP.CompressorChoiceGrid +import OAI.Computability.VPVNP.RAMParameters +import OAI.Computability.VPVNP.PrimedCounterRenameRun + +/-! +# Executing rounded-grid selection and outer term choice on demand records + +The demand scanner and the fixed grid tests share a register file in one +compiled call. The call returns the first covering grid row. The term reader +computes its repetition count from the same demand records and chooses the +outer supply vector. The code uses the ordered grid fixed by Theorem 6.1. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DemandGridRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter + +variable {w r l k : ℕ} + +/-- The two fixed tables share a register file and occupy disjoint parts of +the public constants. Their normal control edge is the sequence instruction +link, so no dynamic memory entry is supplied for the energy. -/ +def join (left : Flow r l) (right : Flow r k) : Flow r (l+k) := + .seq (renameFlow id (Fin.castAdd k) left) (renameFlow id (Fin.natAdd l) right) + +private theorem widen {v K : ℕ} (a : Flow r v) (idx : Fin v → Fin K) (data : Fin K → Word w) + (values : Fin v → Word w) (hval : data ∘ idx = values) + {state : Word w} {rs mid : Regs w r} {mem mem' : Memory w} {es : List (Event w)} + (h : Flow.Exec values state a rs mem es mid mem') : + Flow.Exec data state (renameFlow id idx a) rs mem es mid mem' := by + obtain ⟨out, hr, ha, _⟩ := liftExec (Function.Embedding.refl (Fin r)) idx data + (hval ▸ h) rs rfl + change out = mid at ha + exact ha ▸ hr + +theorem join_exec {left : Flow r l} {right : Flow r k} {p : Fin l → Word w} {q : Fin k → Word w} + {state : Word w} {rs mid out : Regs w r} {m m' m'' : Memory w} {es fs : List (Event w)} + (h₁ : Flow.Exec p state left rs m es mid m') (h₂ : Flow.Exec q state right mid m' fs out m'') : + Flow.Exec (Fin.append p q) state (join left right) rs m (es ++ fs) out m'' := by + apply Flow.Exec.seq + · exact widen left (Fin.castAdd k) _ p (funext fun i => Fin.append_left ..) h₁ + · exact widen right (Fin.natAdd l) _ q (funext fun i => Fin.append_right ..) h₂ + + +variable {D : Type*} [Fintype D] {d t : ℕ} + +/-- Instruction sequence that prepares the demand energy before scanning the candidate grid +rows. -/ +def code (order : Fin d ≃ D) (rows : Fin t → D → ℚ) := + join (DemandPreparation.energyPrefix d) (GridRAM.grid order rows) + +/-- Instantiate the demand-grid program with the chosen demand order, energy weights and +candidate-row coefficients. -/ +def machine (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) (w : ℕ) := + ((code order rows).template (some 1)).instantiate w + (Fin.append (DemandPreparation.publicWords order p 1 w) (GridRAM.coefficients order p rows)) + +/-- This call begins at the ordinary machine entry point. Its return word +indexes the same first covering point as the mathematical grid search. -/ +theorem native (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) : + ∃ K : ℕ, ∀ M w, K + 4*Nat.clog 2 (M+1) ≤ w → ∀ (addr : Word w) (mem : Memory w), + (∀ i, DemandPreparation.demandAt order addr mem i ≤ M) → + let prog := machine order p rows w + let b := DemandPreparation.demandAt order addr mem + let fuel := 6*d + (11*d+4)*t + 8 + ∃ es, execute prog.program fuel (prog.program.start addr) mem [] = + some ⟨es, some (Fin.ofNat _ (GridRAM.firstRow p b rows))⟩ ∧ + choiceBits es = [] ∧ countProbes es ≤ d + t*d ∧ after mem es = mem ∧ es.length < fuel := by + obtain ⟨k₀,h₀⟩ := DemandPreparation.preparation_fit p 1 + let C := GridRAM.operandConstant order p rows + let K := max k₀ (max C.size t.size) + refine ⟨K,fun M w hW addr mem hD => ?_⟩ + let b := DemandPreparation.demandAt order addr mem + let pv := DemandPreparation.publicWords order p 1 w + have hk₀ : k₀ ≤ K := le_max_left _ _ + have hC : C.size ≤ K := (le_max_left _ _).trans (le_max_right _ _) + have ht : t.size ≤ K := (le_max_right _ _).trans (le_max_right _ _) + obtain ⟨htwo,hs,_,_,hweights⟩ := h₀ M b hD + have hp₀ := Nat.pow_le_pow_right (by decide : 0 < 2) + (show k₀ + 4*Nat.clog 2 (M+1) ≤ w by omega) + have hpub (i : Fin d) : (pv i.castSucc).val = MotifAdmission.weight p (order i) := by + simp [pv, DemandPreparation.publicWords, Nat.mod_eq_of_lt ((hweights (order i)).trans_le hp₀)] + obtain ⟨es,mid,he,heb,hep,hem,hel,energy,_⟩ := + DemandPreparation.energyPrefix_exec order p pv addr mem (fun _ => 0) hpub + have heval : (mid 0).val = MotifAdmission.energy p b := by + rw [energy]; apply Nat.mod_eq_of_lt + exact (Nat.le_mul_of_pos_left _ (by decide : 0 < 2)).trans_lt (hs.trans_le hp₀) + have hbox : C*(M+1)^2 < 2^w := by + apply lt_of_lt_of_le _ (Nat.pow_le_pow_right (by decide : 0 < 2) + (show C.size + 2*Nat.clog 2 (M+1) ≤ w by omega)) + rw [pow_add, Nat.mul_comm 2, pow_mul] + exact mul_lt_mul_of_lt_of_le_of_pos_of_nonneg (Nat.lt_size_self _) (Nat.pow_le_pow_left + (Nat.le_pow_clog (by decide) _) 2) (pow_pos (Nat.succ_pos _) _) (Nat.zero_le _) + obtain ⟨fs,out,hg,hgb,hgp,hgm,hgl,ho⟩ := GridRAM.grid_exec order p rows addr mem mid heval + ((by decide : 1 < 2).trans (htwo.trans_le hp₀)) (Nat.size_le.mp (by omega)) + (GridRAM.operandsFit_of_width order p rows b M hD hbox) + let budget := 6*d + (11*d+4)*t + 7 + have hl : (es ++ fs).length ≤ budget := by simp only [List.length_append,hel]; dsimp [budget]; omega + have hb : choiceBits (es++fs) = [] := by simp [Flow.choiceBits_append,heb,hgb] + have hrun := DemandPreparation.execute_return (code order rows) (Fin.append pv (GridRAM.coefficients order p rows)) + 1 addr mem mem (es++fs) out (join_exec he hg) hb budget hl + have ho' : out 1 = Fin.ofNat _ (GridRAM.firstRow p b rows) := by rw [← ho]; simp + refine ⟨es++fs,ho' ▸ hrun,hb,?_,?_,by change _ < budget+1; omega⟩ + · rw [DemandPreparation.probes_append, hep] + exact Nat.add_le_add_left hgp d + · rw [show after mem (es++fs) = after (after mem es) fs from List.foldl_append, hem, hgm] + + +open MotifGrid MotifBlocks MotifConversion MotifSelector + +variable {k₀ : Type*} [Field k₀] {J D₀ S : Type} [Fintype J] [Fintype D₀] [Fintype S] +variable {a b₀ : D₀ → J} {P : Supply J S} {p : D₀ → ℚ} {q : S → ℚ} {H H' : ℝ} +variable (B : FixedBlock k₀ a b₀ P (realWidths p) (realWidths q) H H') + +/-- Rows are ordered exactly as in the fixed rounded demand grid. -/ +noncomputable def fixedRows : Fin B.grid.demands.toList.length → D₀ → ℚ := B.grid.demands.toList.get + +theorem fixedRows_list : List.ofFn (fixedRows B) = B.grid.demands.toList := List.ofFn_get _ + +/-- Run the grid call followed by the demand-to-payload calls. The first +returned field identifies the fixed template used for the local maps. -/ +noncomputable def chooseTerm {d n : ℕ} (order : Fin d ≃ D₀) (supply : Fin n ≃ S) + (addr : BurstRAM.Word w) (mem : Memory w) (prepFuel : ℕ) (bits : List Bool) : + Option (BurstRAM.Word w × Report w) := do + let prog := machine order p (fixedRows B) w + let fuel := 6*d + (11*d+4)*B.grid.demands.toList.length + 8 + let grid ← execute prog.program fuel (prog.program.start addr) mem [] + let row ← grid.result + let chosen ← DemandPreparation.chooseFromDemand B order supply addr (after mem grid.events) prepFuel bits + return (row,chosen) + +/-- All dynamic motif data come from actual demand records. The three reset +calls choose the original fixed grid point and admit exactly the binary +streams of Theorem 6.1's outer indices, including its zero-width unit case. -/ +theorem chooseTerm_spec {d n : ℕ} (order : Fin d ≃ D₀) (supply : Fin n ≃ S) + (hp : ∀ i, 0 < p i) (hq : ∀ i, 0 < q i) : + ∃ K : ℕ, ∀ M w, K + 4*Nat.clog 2 (M+1) ≤ w → ∀ (addr : BurstRAM.Word w) (mem : Memory w), + (∀ i, DemandPreparation.demandAt order addr mem i ≤ M) → + let demand := DemandPreparation.demandAt order addr mem + let fuel := 6*d + 7*((∑ i, MotifAdmission.weight p i).size + 2*Nat.clog 2 (M+1)) + 10 + ∃ (hw : outerCap B demand < 2^w) (row : BurstRAM.Word w), + B.grid.demands.toList[row.val]? = some (demandGrid B hp demand).val ∧ + ∀ bits, (chooseTerm B order supply addr mem fuel bits).map Prod.fst = + (DemandPreparation.chooseFromDemand B order supply addr mem fuel bits).map (fun _ => row) ∧ + ((chooseTerm B order supply addr mem fuel bits).isSome ↔ + ∃ v, (outerReader B supply hq demand w hw).read bits = some (v, [])) := by + let table := B.grid.demands.toList + let rows := fixedRows B + obtain ⟨kG,hG⟩ := native order p rows + obtain ⟨kC,hC⟩ := DemandPreparation.chooseFromDemand_iff B order supply hq + refine ⟨max table.length.size (max kG kC),fun M w hW addr mem hD => ?_⟩ + let demand := DemandPreparation.demandAt order addr mem + let idx := GridRAM.firstRow p demand rows + have hiG := le_max_left kG kC + have hiC := le_max_right kG kC + have hm := le_max_right table.length.size (max kG kC) + have hlen := le_max_left table.length.size (max kG kC) + obtain ⟨es,hgrid,_,_,hmem,_⟩ := hG M w (by omega) addr mem hD + obtain ⟨hw,hchoice⟩ := hC M w (by omega) addr mem hD + have ht : table.length < 2^w := Nat.size_le.mp (by omega) + have hidx : idx < 2^w := (List.findIdx_le_length (xs := List.ofFn rows) (p := _)).trans_lt + (by simpa [rows,fixedRows_list,table] using ht) + have hz := GridRAM.firstRow_getElem? p demand rows + rw [show List.ofFn rows = table from fixedRows_list B, selectGrid_eq B hp demand] at hz + let row : BurstRAM.Word w := Fin.ofNat _ idx + refine ⟨hw,row,?_,fun bits => ?_⟩ + · have hv : row.val = idx := Nat.mod_eq_of_lt hidx + rw [hv] + exact hz + · let fuel := 6*d + 7*((∑ i, MotifAdmission.weight p i).size + 2*Nat.clog 2 (M+1)) + 10 + have he : chooseTerm B order supply addr mem fuel bits = + (DemandPreparation.chooseFromDemand B order supply addr mem fuel bits).map (fun r => (row,r)) := by + dsimp only [rows] at hgrid + simp only [chooseTerm, hgrid, bind, Option.bind_some, pure, hmem] + cases DemandPreparation.chooseFromDemand B order supply addr mem fuel bits <;> rfl + change _ ∧ ((chooseTerm B order supply addr mem fuel bits).isSome ↔ _) + rw [he, Option.isSome_map] + refine ⟨?_,hchoice bits⟩ + rw [Option.map_map] + rfl + +end CompressorRecords.DemandGridRAM + +namespace CompressorRecords.DemandPreparation + +/-- The fixed motif's word requirement is eventually met by the Section 9.1 +machine uniformly over every polynomial bound on intermediate demand widths. -/ +theorem eventually_live_word_fits (B : ℕ) (hB : 0 < B) (K L C A : ℕ) : + ∀ᶠ n : ℕ in Filter.atTop, ∀ M, M ≤ C * n^A → + K + L * Nat.clog 2 (M+1) ≤ (BurstRAM.addressWidth B n + 10)^4 := by + let c₀ := K + L * (C+1).size + L*A + 1 + filter_upwards [Filter.eventually_ge_atTop (2^c₀)] with n hn M hM + let c := Nat.clog 2 n + have hc : c₀ ≤ c := by simpa [c,Nat.clog_pow _ _ (by decide : 1 < 2)] using Nat.clog_mono_right 2 hn + have hpos : 0 < n := (Nat.two_pow_pos c₀).trans_le hn + have hbound : Nat.clog 2 (M+1) ≤ (C+1).size + A*c := by + apply Nat.clog_le_of_le_pow + rw [pow_add, Nat.mul_comm A c, pow_mul] + have hi : M+1 ≤ (C+1)*n^A := by + rw [Nat.add_mul, Nat.one_mul] + exact Nat.add_le_add hM (pow_pos hpos _) + exact hi.trans (Nat.mul_le_mul (Nat.lt_size_self (C+1)).le + (Nat.pow_le_pow_left (Nat.le_pow_clog Nat.one_lt_two n) A)) + have hC : K + L * (C+1).size ≤ c := (show K + L * (C+1).size ≤ c₀ by dsimp [c₀]; omega).trans hc + have hA : L*A ≤ c := (show L*A ≤ c₀ by dsimp [c₀]; omega).trans hc + have hR : c ≤ BurstRAM.addressWidth B n := Nat.le_mul_of_pos_left _ hB + calc + K + L*Nat.clog 2 (M+1) ≤ K + L*((C+1).size + A*c) := Nat.add_le_add_left (Nat.mul_le_mul_left _ hbound) K + _ = (K + L * (C+1).size) + (L*A)*c := by ring + _ ≤ c + c*c := Nat.add_le_add hC (Nat.mul_le_mul_right _ hA) + _ ≤ (c+10)^2 := by nlinarith + _ ≤ (BurstRAM.addressWidth B n+10)^2 := Nat.pow_le_pow_left (Nat.add_le_add_right hR _) 2 + _ ≤ _ := Nat.pow_le_pow_right (by omega) (by decide) + +end CompressorRecords.DemandPreparation + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorChoicePreparation.lean b/lean/OAI/Computability/VPVNP/CompressorChoicePreparation.lean new file mode 100644 index 0000000000..aeb4bb0074 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorChoicePreparation.lean @@ -0,0 +1,341 @@ +import OAI.Computability.VPVNP.CompressorChoiceRoot +import OAI.Computability.VPVNP.CompressorChoiceRAM + +/-! +# Reading actual demand widths and preparing a compressor term + +The local demand widths are contiguous words in external memory. Starting at +their base address, a fixed call reads each width once, accumulates the cleared +quadratic energy, and computes the repetition count by native bisection. The +next call uses that count for the actual motif's outer payload choice. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DemandPreparation + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {w d : ℕ} + +/-- The weights occupy the first public positions. The last position holds the +fixed squared block scale times the common denominator of the demand masses. -/ +def readCoordinate (i : Fin d) : Flow 8 (d+1) := + .seq (.line (.read 3 2)) <| + .seq (.line (.publicWord 4 i.castSucc)) <| + .seq (.line (.binary .mul 5 3 3)) <| + .seq (.line (.binary .mul 5 4 5)) <| + .seq (.line (.binary .add 0 0 5)) (.line (.binary .add 2 2 6)) + +/-- Reading the fixed denominator closes the scan. -/ +def scan : List (Fin d) → Flow 8 (d+1) + | [] => .line (.publicWord 1 (Fin.last d)) + | i :: is => .seq (readCoordinate i) (scan is) + +private def score (pub : Fin (d+1) → Word w) (mem : Memory w) (addr : Word w) : + List (Fin d) → Word w + | [] => 0 + | i :: is => pub i.castSucc * mem addr.val ^ 2 + score pub mem (addr + 1) is + +private theorem score_ofFn (pub : Fin (d+1) → Word w) (mem : Memory w) (n : ℕ) + (ids : Fin n → Fin d) (addr : Word w) : + score pub mem addr (List.ofFn ids) = ∑ j, pub (ids j).castSucc * mem (addr + (j.val : Word w)).val ^ 2 := by + induction n generalizing addr with + | zero => simp [score] + | succ n ih => + rw [List.ofFn_succ, score, Fin.sum_univ_succ, ih] + simp only [Fin.val_zero,Nat.cast_zero,add_zero,Fin.val_succ,Nat.cast_add,Nat.cast_one] + congr 1 + apply Finset.sum_congr rfl + intro i _ + rw [show addr + 1 + (i.val : Word w) = addr + (i.val + 1 : Word w) by abel] + +private def rowEvents (addr val : Word w) : List (Event w) := [.read addr val,.tick,.tick,.tick,.tick,.tick] + +private theorem read_exec (pub : Fin (d+1) → Word w) (s : Word w) (mem : Memory w) + (rs : Regs w 8) (one : rs 6 = 1) (i : Fin d) : + ∃ out, Flow.Exec pub s (readCoordinate i) rs mem (rowEvents (rs 2) (mem (rs 2).val)) out mem ∧ + out 0 = rs 0 + pub i.castSucc * (mem (rs 2).val)^2 ∧ out 2 = rs 2 + 1 ∧ out 6 = 1 := by + let a := Function.update rs 3 (mem (rs 2).val) + let b := Function.update a 4 (pub i.castSucc) + let c := Function.update b 5 (b 3 * b 3) + let f := Function.update c 5 (c 4 * c 5) + let g := Function.update f 0 (f 0 + f 5) + let out := Function.update g 2 (g 2 + g 6) + have h₁ : Flow.Exec pub s (.line (.read 3 2)) rs mem [.read (rs 2) (mem (rs 2).val)] a mem := .line rfl + have h₂ : Flow.Exec pub s (.line (.publicWord 4 i.castSucc)) a mem [.tick] b mem := .line rfl + have h₃ : Flow.Exec pub s (.line (.binary .mul 5 3 3)) b mem [.tick] c mem := .line rfl + have h₄ : Flow.Exec pub s (.line (.binary .mul 5 4 5)) c mem [.tick] f mem := .line rfl + have h₅ : Flow.Exec pub s (.line (.binary .add 0 0 5)) f mem [.tick] g mem := .line rfl + have h₆ : Flow.Exec pub s (.line (.binary .add 2 2 6)) g mem [.tick] out mem := .line rfl + exact ⟨out, .seq h₁ (.seq h₂ (.seq h₃ (.seq h₄ (.seq h₅ h₆)))), by + simp (config := {decide := true}) [out,g,f,c,b,a,Function.update,one,pow_two]⟩ + +private theorem scan_exec (pub : Fin (d+1) → Word w) (s : Word w) (mem : Memory w) + (is : List (Fin d)) (rs : Regs w 8) (one : rs 6 = 1) : + ∃ es out, Flow.Exec pub s (scan is) rs mem es out mem ∧ choiceBits es = [] ∧ + es.length = 6 * is.length + 1 ∧ countProbes es = is.length ∧ after mem es = mem ∧ + out 0 = rs 0 + score pub mem (rs 2) is ∧ out 1 = pub (Fin.last d) := by + induction is generalizing rs with + | nil => + refine ⟨[.tick],Function.update rs 1 (pub (Fin.last d)),.line rfl,rfl,rfl,rfl,rfl,?_⟩ + simp (config := {decide := true}) [score,Function.update] + | cons i is ih => + obtain ⟨mid,h₁,hs,ha,ho⟩ := read_exec pub s mem rs one i + obtain ⟨es,out,h₂,hb,hl,hp,hmem,hv,hd⟩ := ih mid ho + refine ⟨rowEvents _ _ ++ es,out,.seq h₁ h₂,?_,?_,?_,?_,?_,hd⟩ + · simpa [rowEvents,choiceBits] using hb + · simp [rowEvents,hl]; omega + · simp [rowEvents,countProbes,hp,Nat.add_comm] + · exact hmem + · rw [hv,hs,ha,score,add_assoc] + +/-- Recover the demand vector in the fixed order from actual machine memory. -/ +def demandAt {D : Type*} (order : Fin d ≃ D) (addr : Word w) (mem : Memory w) (e : D) : ℕ := + (mem (addr + ((order.symm e).val : Word w)).val).val + +theorem demandAt_address {D : Type*} (order : Fin d ≃ D) (addr : Word w) (mem : Memory w) + (fit : addr.val + d ≤ 2^w) (i : Fin d) : + demandAt order addr mem (order i) = (mem (addr.val + i.val)).val := by + simp only [demandAt,Equiv.symm_apply_apply,Fin.val_add,Fin.val_natCast,Nat.add_mod_mod] + rw [Nat.mod_eq_of_lt (by have := i.isLt; omega)] + +private theorem score_eq_energy {D : Type*} [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) + (pub : Fin (d+1) → Word w) (mem : Memory w) (addr : Word w) + (hw : ∀ i : Fin d, (pub i.castSucc).val = MotifAdmission.weight p (order i)) : + score pub mem addr (List.finRange d) = (MotifAdmission.energy p (demandAt order addr mem) : Word w) := by + rw [List.finRange,score_ofFn] + simp only [MotifAdmission.energy, Nat.cast_sum, Nat.cast_mul, Nat.cast_pow] + apply Fintype.sum_equiv order + intro i + simp [demandAt, ← hw] + +/-- Shared deterministic prefix for the rounded-grid and repetition procedures. +Its first register holds the quadratic energy of the actual demand words. -/ +def energyPrefix (d : ℕ) : Flow 8 (d+1) := + .seq (.line (.stateWord 2)) <| + .seq (.line (.constant 0 0)) <| + .seq (.line (.constant 6 1)) (scan (List.finRange d)) + +/-- After reading the fixed demand motif, bisection computes its copy count. -/ +def repetitionCall (d : ℕ) : Flow 8 (d+1) := (energyPrefix d).seq RepetitionRAM.root + +theorem energyPrefix_exec {D : Type*} [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) + (pub : Fin (d+1) → Word w) (addr : Word w) (mem : Memory w) (rs : Regs w 8) + (hw : ∀ i : Fin d, (pub i.castSucc).val = MotifAdmission.weight p (order i)) : + ∃ es out, Flow.Exec pub addr (energyPrefix d) rs mem es out mem ∧ choiceBits es = [] ∧ + countProbes es = d ∧ after mem es = mem ∧ es.length = 6*d+4 ∧ + out 0 = (MotifAdmission.energy p (demandAt order addr mem) : Word w) ∧ out 1 = pub (Fin.last d) := by + let a := Function.update rs 2 addr + let b := Function.update a 0 0 + let c := Function.update b 6 (Fin.ofNat (2^w) 1) + have init₁ : Flow.Exec pub addr (.line (.stateWord 2)) rs mem [.tick] a mem := .line rfl + have init₂ : Flow.Exec pub addr (.line (.constant 0 0)) a mem [.tick] b mem := .line rfl + have init₃ : Flow.Exec pub addr (.line (.constant 6 1)) b mem [.tick] c mem := .line rfl + obtain ⟨es,out,h,hb,hl,hp,hm,he,hd⟩ := scan_exec pub addr mem (List.finRange d) c rfl + refine ⟨.tick :: .tick :: .tick :: es,out,.seq init₁ (.seq init₂ (.seq init₃ h)),hb,by simpa [countProbes] using hp,hm, + by simp [hl],?_,hd⟩ + rw [he,show c 0 = 0 by simp (config := {decide := true}) [c,b,Function.update], zero_add] + exact score_eq_energy order p pub mem addr hw + +private theorem noChoices_ticks (t : ℕ) : choiceBits (List.replicate t (.tick : Event w)) = [] := by + induction t with + | zero => rfl + | succ t ih => simpa [List.replicate_succ,choiceBits] using ih + +theorem probes_append (es fs : List (Event w)) : + countProbes (es ++ fs) = countProbes es + countProbes fs := by + induction es with + | nil => simp [countProbes] + | cons e es ih => cases e <;> simp [countProbes, ih, Nat.add_assoc] + +private theorem ticks_after (mem : Memory w) (t : ℕ) : after mem (List.replicate t .tick) = mem := by + induction t with + | zero => rfl + | succ t ih => simpa [List.replicate_succ, after, BurstRAM.update] using ih + +private theorem noProbes_ticks (t : ℕ) : countProbes (List.replicate t (.tick : Event w)) = 0 := by + induction t with + | zero => rfl + | succ t ih => simpa [List.replicate_succ,countProbes] using ih + +/-- The complete demand-to-repetition execution preserves memory, reads exactly +the demand coordinates, and consumes no branch choices. -/ +theorem repetition_exec {D : Type*} [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) + (L : ℕ) (hL : 0 < L) (pub : Fin (d+1) → Word w) (addr : Word w) (mem : Memory w) (rs : Regs w 8) + (hw : ∀ i : Fin d, (pub i.castSucc).val = MotifAdmission.weight p (order i)) + (hden : (pub (Fin.last d)).val = L^2 * MotifAdmission.denominator p) (htwo : 2 < 2^w) + (hsum : 2 * MotifAdmission.energy p (demandAt order addr mem) < 2^w) + (hsq : (MotifAdmission.energy p (demandAt order addr mem))^2 * (L^2 * MotifAdmission.denominator p) < 2^w) : + ∃ es out, Flow.Exec pub addr (repetitionCall d) rs mem es out mem ∧ + choiceBits es = [] ∧ countProbes es = d ∧ after mem es = mem ∧ + es.length ≤ 6*d + 7*(MotifAdmission.energy p (demandAt order addr mem)).size + 9 ∧ + (out 2).val = MotifAdmission.copies p (demandAt order addr mem) L := by + obtain ⟨es,out,hr,hb,hp,hm,hl,he,hd⟩ := energyPrefix_exec order p pub addr mem rs hw + let n := MotifAdmission.energy p (demandAt order addr mem) + have he' : (out 0).val = n := by rw [he]; exact Nat.mod_eq_of_lt (by omega) + obtain ⟨t,last,hroot,ht,hval⟩ := RepetitionRAM.root_exec pub addr mem out n (L^2 * MotifAdmission.denominator p) + he' (hd ▸ hden) (Nat.mul_pos (pow_pos hL _) (MotifAdmission.denominator_pos p)) htwo hsum hsq + let ticks := List.replicate t (Event.tick : Event w) + refine ⟨es ++ ticks,last,.seq hr hroot,?_,?_,?_,?_,hval⟩ + · simp [Flow.choiceBits_append,hb,ticks,noChoices_ticks] + · simp [probes_append,hp,ticks,noProbes_ticks] + · rw [show after mem (es ++ ticks) = after (after mem es) ticks by simp [after], hm] + exact ticks_after mem t + · simp only [List.length_append, hl, ticks, List.length_replicate] + dsimp [n] at ht + omega + +/-- A fixed coefficient plus four logarithmic digits per demand-width bit +covers the midpoint sums, all squared comparisons, and the fixed public table. -/ +theorem preparation_fit {D : Type*} [Fintype D] (p : D → ℚ) (L : ℕ) : + ∃ K : ℕ, ∀ M (b : D → ℕ), (∀ i, b i ≤ M) → + let energy := MotifAdmission.energy p b + let den := L^2 * MotifAdmission.denominator p + let modulus := 2^(K + 4*Nat.clog 2 (M+1)) + 2 < modulus ∧ 2*energy < modulus ∧ energy^2*den < modulus ∧ den < modulus ∧ + ∀ i, MotifAdmission.weight p i < modulus := by + let W := ∑ i, MotifAdmission.weight p i + let den := L^2 * MotifAdmission.denominator p + let C := 2 + 2*W + W^2*den + den + W + refine ⟨C.size, fun M b hb => ?_⟩ + dsimp only + let A := M + 1 + let E := MotifAdmission.energy p b + have hE : E ≤ W * A^2 := MotifAdmission.energy_le p b A (fun i => (hb i).trans (Nat.le_succ _)) + have grow : A^2 ≤ A^4 := Nat.pow_le_pow_right (Nat.succ_pos _) (by decide) + have fit (z c : ℕ) (hz : z ≤ c*A^4) (hc : c ≤ C) : z < 2^(C.size + 4*Nat.clog 2 A) := by + rw [pow_add, Nat.mul_comm 4, pow_mul] + apply hz.trans_lt + apply mul_lt_mul_of_lt_of_le_of_pos_of_nonneg (hc.trans_lt (Nat.lt_size_self _)) + (Nat.pow_le_pow_left (Nat.le_pow_clog (by decide) _) 4) (pow_pos (Nat.succ_pos _) _) (Nat.zero_le _) + have fixed (c : ℕ) (hc : c ≤ C) : c < 2^(C.size + 4*Nat.clog 2 A) := + fit c c (Nat.le_mul_of_pos_right _ (pow_pos (Nat.succ_pos _) _)) hc + have hsum : 2*E ≤ (2*W)*A^4 := by rw [Nat.mul_assoc]; exact Nat.mul_le_mul_left _ (hE.trans (Nat.mul_le_mul_left _ grow)) + have hsq : E^2*den ≤ (W^2*den)*A^4 := + (Nat.mul_le_mul_right den (Nat.pow_le_pow_left hE 2)).trans_eq (by ring) + refine ⟨fixed 2 (by dsimp [C]; omega), fit _ _ hsum (by dsimp [C]; omega), + fit _ _ hsq (by dsimp [C]; omega), fixed den (by dsimp [C]; omega), fun i => ?_⟩ + apply fixed + exact (Finset.single_le_sum (f := MotifAdmission.weight p) (fun j _ => Nat.zero_le _) (Finset.mem_univ i)).trans + (show W ≤ C by dsimp [C]; omega) + +/-- The fixed integer data stored at the public indices of the preparation program. -/ +def publicWords {D : Type*} [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (L : ℕ) (w : ℕ) : + Fin (d+1) → Word w := + Fin.lastCases (Fin.ofNat _ (L^2 * MotifAdmission.denominator p)) + (fun i => Fin.ofNat _ (MotifAdmission.weight p (order i))) + +/-- Instantiate the repetition-count worker with the ordered demand weights and the supplied +repetition parameter. -/ +def repetitionMachine {D : Type*} [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (L : ℕ) (w : ℕ) := + ((repetitionCall d).template (some 2)).instantiate w (publicWords order p L w) + +/-- A deterministic structured derivation gives a complete native call at +every budget covering its executed instructions and the returning halt. -/ +theorem execute_return {r k : ℕ} (code : Flow r k) (pub : Fin k → Word w) (result : Fin r) + (state : Word w) (mem mem' : Memory w) (es : List (Event w)) (out : Regs w r) + (hr : Flow.Exec pub state code (fun _ => 0) mem es out mem') (hbits : choiceBits es = []) + (budget : ℕ) (hlen : es.length ≤ budget) : + let machine := (code.template (some result)).instantiate w pub + execute machine.program (budget+1) (machine.program.start state) mem [] = some ⟨es,some (out result)⟩ := by + let machine := (code.template (some result)).instantiate w pub + have hbad : machine.code code.rejectPC = .reject := by + change ((code.template (some result)).code code.rejectPC).resize w = _ + rw [Flow.template_reject]; rfl + have hout : machine.code code.exitPC = .returnState result := by + change ((code.template (some result)).code code.exitPC).resize w = _ + rw [Flow.template_exit]; rfl + have he := hr.execute (Flow.template_linked code (some result) pub) hbad (fun _ => 0) (budget-es.length+1) [] + simp only [hbits, List.nil_append] at he + change execute machine.program (es.length + (budget-es.length+1)) (machine.program.start state) mem [] = _ at he + change execute machine.program (budget+1) (machine.program.start state) mem [] = _ + rw [show budget+1 = es.length + (budget-es.length+1) by omega, he] + change (execute machine.program (budget-es.length+1) ⟨code.exitPC,state,out,fun _ => 0⟩ mem' []).map _ = _ + simp only [execute,Machine.program,hout,Instr.run,ite_true,Option.map_some,Flow.prependEvents,List.append_nil] + +/-- The first actual call returns the computed repetition word from the demand +array. Its event count is logarithmic in the largest demand width. -/ +theorem repetition_native {D : Type*} [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (L : ℕ) (hL : 0 < L) : + ∃ K : ℕ, ∀ M w, K + 4*Nat.clog 2 (M+1) ≤ w → ∀ (addr : Word w) (mem : Memory w), + (∀ i, demandAt order addr mem i ≤ M) → + let machine := repetitionMachine order p L w + let b := demandAt order addr mem + let budget := 6*d + 7*((∑ i, MotifAdmission.weight p i).size + 2*Nat.clog 2 (M+1)) + 9 + ∃ es, execute machine.program (budget+1) (machine.program.start addr) mem [] = + some ⟨es,some (Fin.ofNat _ (MotifAdmission.copies p b L))⟩ ∧ choiceBits es = [] ∧ + countProbes es = d ∧ after mem es = mem ∧ es.length ≤ budget := by + obtain ⟨K,hK⟩ := preparation_fit p L + refine ⟨K,fun M w hW addr mem hb => ?_⟩ + obtain ⟨ht,hs,hsq,hd,hweights⟩ := hK M (demandAt order addr mem) hb + have hpow := Nat.pow_le_pow_right (by decide : 0 < 2) hW + let pub := publicWords order p L w + have hpub (i : Fin d) : (pub i.castSucc).val = MotifAdmission.weight p (order i) := by + simp [pub, publicWords, Nat.mod_eq_of_lt ((hweights (order i)).trans_le hpow)] + have hden : (pub (Fin.last d)).val = L^2 * MotifAdmission.denominator p := by + simp only [pub,publicWords,Fin.lastCases_last] + exact Nat.mod_eq_of_lt (hd.trans_le hpow) + obtain ⟨es,out,hr,hb',hp,hm,hlen,ho⟩ := repetition_exec order p L hL pub addr mem (fun _ => 0) + hpub hden (ht.trans_le hpow) (hs.trans_le hpow) (hsq.trans_le hpow) + let budget := 6*d + 7*((∑ i, MotifAdmission.weight p i).size + 2*Nat.clog 2 (M+1)) + 9 + have hbits := MotifAdmission.operand_bits_le (MotifAdmission.energy p (demandAt order addr mem)) + (∑ i, MotifAdmission.weight p i) M + (MotifAdmission.energy_le p (demandAt order addr mem) (M+1) (fun i => (hb i).trans (Nat.le_succ M))) + have hl : es.length ≤ budget := hlen.trans (Nat.add_le_add_right + (Nat.add_le_add_left (Nat.mul_le_mul_left 7 hbits) _) _) + have hr' := execute_return (repetitionCall d) pub 2 addr mem mem es out hr hb' budget hl + refine ⟨es,?_,hb',hp,hm,hl⟩ + have ho' : out 2 = Fin.ofNat _ (MotifAdmission.copies p (demandAt order addr mem) L) := by + rw [← ho]; simp + exact ho' ▸ hr' + + +open MotifGrid MotifBlocks MotifConversion MotifSelector + +variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S] +variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ} +variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H') + +/-- Two ordinary calls, with the repetition call's returned word and external +memory passed to the payload reader. The sole dynamic input to the first call +is the base address of the motif's demand widths. -/ +def chooseFromDemand {n : ℕ} (demandOrder : Fin d ≃ D) (supplyOrder : Fin n ≃ S) + (addr : BurstRAM.Word w) (mem : Memory w) (prepFuel : ℕ) (bits : List Bool) : Option (Report w) := do + let first := repetitionMachine demandOrder p B.scale w + let rep ← execute first.program prepFuel (first.program.start addr) mem [] + let u ← rep.result + let factor := B.scale * B.radius.num.natAbs + let den := MotifAdmission.denominator q + let code := MotifChoiceRAM.choiceCall n factor den + let weights := fun i => Fin.ofNat (2^w) (MotifAdmission.weight q (supplyOrder i) * B.radius.den^2) + let next := (code.template none).instantiate w weights + let fuel := 1 + (MotifChoiceRAM.prepareBounds n factor den).length + (n*(4*w+10)+3) + execute next.program fuel (next.program.start u) (after mem rep.events) bits + +theorem chooseFromDemand_iff {n : ℕ} (demandOrder : Fin d ≃ D) (supplyOrder : Fin n ≃ S) + (hq : ∀ e, 0 < q e) : + ∃ K : ℕ, ∀ M w, K + 4*Nat.clog 2 (M+1) ≤ w → ∀ (addr : BurstRAM.Word w) (mem : Memory w), + (∀ i, demandAt demandOrder addr mem i ≤ M) → + let demand := demandAt demandOrder addr mem + let budget := 6*d + 7*((∑ i, MotifAdmission.weight p i).size + 2*Nat.clog 2 (M+1)) + 10 + ∃ hw : outerCap B demand < 2^w, ∀ bits, + (chooseFromDemand B demandOrder supplyOrder addr mem budget bits).isSome ↔ + ∃ v, (outerReader B supplyOrder hq demand w hw).read bits = some (v, []) := by + obtain ⟨k₀,h₀⟩ := repetition_native demandOrder p B.scale B.scale_pos + obtain ⟨k₁,h₁⟩ := MotifChoiceRAM.compiled_outer_choices B supplyOrder hq + refine ⟨max k₀ k₁,fun M w hW addr mem hD => ?_⟩ + have a := le_max_left k₀ k₁ + have b := le_max_right k₀ k₁ + obtain ⟨es,hr,_,_,hm,_⟩ := h₀ M w (by omega) addr mem hD + obtain ⟨hw,hchoose⟩ := h₁ M (demandAt demandOrder addr mem) hD w (by omega) + refine ⟨hw,fun bits => ?_⟩ + simpa [chooseFromDemand, hr, hm, repetitions] using hchoose mem bits + +end CompressorRecords.DemandPreparation + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorChoiceRAM.lean b/lean/OAI/Computability/VPVNP/CompressorChoiceRAM.lean new file mode 100644 index 0000000000..96669c30d6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorChoiceRAM.lean @@ -0,0 +1,929 @@ +import OAI.Computability.VPVNP.PrimedCounterGuessFlow +import OAI.Computability.VPVNP.CompressorRecordScores +import OAI.Computability.VPVNP.PrimedInputRAMFlowEval +import OAI.Computability.VPVNP.CompressorRecordChoices + +/-! +# Native RAM admission for a compressor motif + +Appendix E scans the outer indices of Theorem 6.1 in supply-edge order. This +finite instruction table reads each coordinate as a full machine word, checks +its cap, stores the payload, and accumulates the cleared quadratic score. Both +valid and rejected prefixes can be embedded in larger native programs. For a +complete call the successful streams are exactly the encodings admitted by +the motif inequality. The complete call reads the repetition count from persistent state and +computes its cap and energy limit using fixed motif coefficients. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM +open PrimedCounter.GuessWord + +namespace MotifChoiceRAM + +variable {w d p : ℕ} + +/-- Registers 0–2 implement the word reader, register 3 holds the exclusive +coordinate cap, register 4 the running energy, and register 5 the exclusive +energy limit. The following registers retain the complete guessed vector. -/ +def low (d : ℕ) (i : Fin 6) : Fin (6 + d) := i.castAdd d + +/-- Register retaining guessed supply coordinate `i`, after the six reader and score registers. -/ +def slot (i : Fin d) : Fin (6 + d) := i.natAdd 6 + +private def reader (d : ℕ) : Fin 3 ↪ Fin (6 + d) := + (Fin.castAddEmb 3).trans (Fin.castAddEmb d) + +@[simp] private theorem low_eq_low {i j : Fin 6} : low d i = low d j ↔ i = j := + (Fin.castAddEmb d).injective.eq_iff + +@[simp] private theorem slot_eq_slot {i j : Fin d} : slot i = slot j ↔ i = j := + (Fin.natAddEmb 6).injective.eq_iff + +@[simp] private theorem low_ne_slot (i : Fin 6) (j : Fin d) : low d i ≠ slot j := by + intro h + have h' := congrArg Fin.val h + change i.val = 6 + j.val at h' + omega + +@[simp] private theorem slot_ne_low (i : Fin 6) (j : Fin d) : slot j ≠ low d i := (low_ne_slot i j).symm + +private theorem outside_reader (i : Fin 6) (hi : 3 ≤ i.val) : low d i ∉ Set.range (reader d) := by + rintro ⟨j,h⟩ + have h' := congrArg Fin.val h + change j.val = i.val at h' + omega + +private theorem slot_outside (i : Fin d) : slot i ∉ Set.range (reader d) := by + rintro ⟨j,h⟩ + exact low_ne_slot (j.castAdd 3) i h + +/-- The public datum at a coordinate is its fixed cleared quadratic coefficient. +Only the three numerical bounds/counters in the incoming registers depend on the call. -/ +def coordinate (i : Fin d) : Flow (6+d) d := + let r := low d + .seq (PrimedCounter.GuessWord.flow (reader d)) <| + .seq (.line (.guardLt (r 0) (r 3))) <| + .seq (.line (.copy (slot i) (r 0))) <| + .seq (.line (.publicWord (r 1) i)) <| + .seq (.line (.binary .mul (r 0) (r 0) (r 0))) <| + .seq (.line (.binary .mul (r 0) (r 1) (r 0))) + (.line (.binary .add (r 4) (r 4) (r 0))) + +/-- The final comparison is performed even when the supply arity is zero. -/ +def scan : List (Fin d) → Flow (6+d) d + | [] => .line (.guardLt (low d 4) (low d 5)) + | i :: is => .seq (coordinate i) (scan is) + +private theorem bits_append {w : ℕ} (es fs : List (Event w)) : + choiceBits (es ++ fs) = choiceBits es ++ choiceBits fs := by + induction es with + | nil => rfl + | cons e es ih => cases e <;> simp [choiceBits, ih] + +private theorem line_step {r k : ℕ} {M : Machine w p r k} {op : Op r k} + {label : (Flow.line op).Label → Fin p} {stop bad : Fin p} + (h : Flow.Linked M (.line op) label stop bad) (c : Config w p r) + (hc : c.pc = label ()) : + M.program.step c = ((op.emit stop bad).resize w).run M.publicData c := by + change (M.code c.pc).run _ _ = _ + rw [hc, h.atLabel ()] + rfl + +private def entryPC {r k : ℕ} {M : Machine w p r k} {a : Flow r k} + {label : a.Label → Fin p} {stop bad : Fin p} (_ : Flow.Linked M a label stop bad) : Fin p := label a.entry + +/-- A successful coordinate choice executes the native eight-label word reader +and six deterministic instructions. The coordinate slot is retained for the descriptor. -/ +theorem coordinate_prefix {M : Machine w p (6+d) d} {i : Fin d} + {label : (coordinate i).Label → Fin p} {stop bad : Fin p} + (hc : Flow.Linked M (coordinate i) label stop bad) (c : Config w p (6+d)) + (hpc : c.pc = label (coordinate i).entry) (v : Word w) + (hcap : v < c.reg (low d 3)) : + ∃ out es, Prefix M c es out ∧ es.length = 4*w+10 ∧ choiceBits es = wordBits v ∧ + out.pc = stop ∧ out.reg (low d 3) = c.reg (low d 3) ∧ + out.reg (low d 4) = c.reg (low d 4) + M.publicData i * (v*v) ∧ + out.reg (low d 5) = c.reg (low d 5) ∧ + (∀ j, out.reg (slot j) = if j = i then v else c.reg (slot j)) ∧ + out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by + let g := hc.seqRight + let a := g.seqRight + let b := a.seqRight + let s := b.seqRight + let t := s.seqRight + obtain ⟨q,es,hpre,hlen,hbits,hq,hw,ho,hpriv,hstate⟩ := flow_native hc.seqLeft c hpc v + change q.reg (low d 0) = v at hw + have keep (j : Fin 6) (hj : 3 ≤ j.val) := ho _ (outside_reader j hj) + have slots (j : Fin d) := ho _ (slot_outside j) + have guard := line_step g.seqLeft q hq + let qa : Config w p (6+d) := {q with pc := entryPC a} + let qb := qa.put (entryPC b) (slot i) v + let qs := qb.put (entryPC s) (low d 1) (M.publicData i) + let qt := qs.put (entryPC t) (low d 0) (v*v) + let qu := qt.put (entryPC t.seqRight) (low d 0) (M.publicData i * (v*v)) + let qf := qu.put stop (low d 4) (c.reg (low d 4) + M.publicData i * (v*v)) + have hg : M.program.step q = .localStep qa := by + rw [guard]; simp only [Op.emit, Instr.resize, Instr.run, hw, keep 3 (by decide), hcap, ↓reduceIte] + rfl + have ha : M.program.step qa = .localStep qb := by + rw [line_step a.seqLeft qa rfl]; simp only [Op.emit, Instr.resize, Instr.run, qa, hw]; rfl + have hb : M.program.step qb = .localStep qs := by rw [line_step b.seqLeft qb rfl]; rfl + have hs : M.program.step qs = .localStep qt := by + rw [line_step s.seqLeft qs rfl] + simp (config := {decide := true}) [Op.emit, Instr.resize, Instr.run, BinaryOp.eval, qt, qs, qb, qa, + Config.put, hw, Function.update] + rfl + have ht : M.program.step qt = .localStep qu := by + rw [line_step t.seqLeft qt rfl] + simp (config := {decide := true}) [Op.emit, Instr.resize, Instr.run, BinaryOp.eval, qu, qt, qs, + Config.put, Function.update] + rfl + have hu : M.program.step qu = .localStep qf := by + rw [line_step t.seqRight qu rfl] + simp (config := {decide := true}) [Op.emit, Instr.resize, Instr.run, BinaryOp.eval, qf, qu, qt, qs, + qb, qa, Config.put, Function.update, keep 4 (by decide)] + let ticks : List (Event w) := [.tick,.tick,.tick,.tick,.tick,.tick] + have hticks : Prefix M q ticks qf := .tick hg (.tick ha (.tick hb (.tick hs (.tick ht (.tick hu (.nil _)))))) + refine ⟨qf, es ++ ticks, hpre.append hticks, ?_, ?_, rfl, ?_, by simp [qf], ?_, ?_, hpriv,hstate⟩ + · simp [ticks, hlen] + · simp [ticks, bits_append, hbits, choiceBits] + · simp (config := {decide := true}) [qf, qu, qt, qs, qb, qa, Config.put, Function.update, keep 3 (by decide)] + · simp (config := {decide := true}) [qf, qu, qt, qs, qb, qa, Config.put, Function.update, keep 5 (by decide)] + · intro j + simp [qf, qu, qt, qs, qb, qa, Config.put, Function.update, slots] + +/-- Full-word choices in the prescribed order of the descriptor scan. -/ +def encoding (is : List (Fin d)) (v : Fin d → Word w) : List Bool := + is.flatMap (fun i => wordBits (v i)) + +/-- Energy is accumulated over the coordinates actually visited by the scan. -/ +def score (is : List (Fin d)) (weights v : Fin d → Word w) : ℕ := + (is.map (fun i => (weights i).val * (v i).val ^ 2)).sum + +/-- The accepting prefix uses one final guard and `4*w+10` native steps per +coordinate, and every visited slot holds exactly its encoded coordinate. -/ +theorem scan_prefix {M : Machine w p (6+d) d} (is : List (Fin d)) + {label : (scan is).Label → Fin p} {stop bad : Fin p} + (hc : Flow.Linked M (scan is) label stop bad) (c : Config w p (6+d)) + (hpc : c.pc = label (scan is).entry) (v : Fin d → Word w) + (hcap : ∀ i ∈ is, v i < c.reg (low d 3)) + (hscore : (c.reg (low d 4)).val + score is M.publicData v < (c.reg (low d 5)).val) : + ∃ out es, Prefix M c es out ∧ es.length = is.length * (4*w+10) + 1 ∧ + choiceBits es = encoding is v ∧ out.pc = stop ∧ + (out.reg (low d 4)).val = (c.reg (low d 4)).val + score is M.publicData v ∧ + (∀ j, out.reg (slot j) = if j ∈ is then v j else c.reg (slot j)) ∧ + out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by + induction is generalizing c with + | nil => + have ht : c.reg (low d 4) < c.reg (low d 5) := by simpa [score] using hscore + have hs : M.program.step c = .localStep {c with pc := stop} := by + rw [line_step hc c hpc]; simp [Op.emit, Instr.resize, Instr.run, ht] + refine ⟨_, [.tick], .tick hs (.nil _), by simp, rfl, rfl, ?_, ?_, rfl, rfl⟩ + · simp [score] + · simp + | cons i is ih => + obtain ⟨q,es,hpre,hlen,hbits,hq,hcap',hs,hlimit,hslots,hpriv,hstate⟩ := + coordinate_prefix hc.seqLeft c hpc (v i) (hcap i (by simp)) + have htotal := hscore + simp only [score, List.map_cons, List.sum_cons] at htotal + have hbound := (c.reg (low d 5)).isLt + have hnew : (q.reg (low d 4)).val = (c.reg (low d 4)).val + + (M.publicData i).val * (v i).val ^ 2 := by rw [hs]; apply scoreWord_exact; omega + obtain ⟨out,fs,hpost,hflen,hfbits,ho,he,hvs,hp,ht⟩ := ih hc.seqRight q hq + (fun j hj => hcap' ▸ hcap j (List.mem_cons_of_mem _ hj)) + (by rw [hnew,hlimit]; simpa [score, Nat.add_assoc] using htotal) + refine ⟨out,es++fs,hpre.append hpost,?_,?_,ho,?_,?_,hp.trans hpriv,ht.trans hstate⟩ + · simp [hlen,hflen,Nat.add_mul]; omega + · simp [bits_append,hbits,hfbits,encoding] + · simp [he,hnew,score,Nat.add_assoc] + · intro j + by_cases hj : j ∈ is <;> by_cases hji : j = i <;> simp_all + +/-- An out-of-range coordinate transfers to the actual rejecting continuation +immediately after the word read and its guard, before performing arithmetic. -/ +theorem coordinate_reject {M : Machine w p (6+d) d} {i : Fin d} + {label : (coordinate i).Label → Fin p} {stop bad : Fin p} + (hc : Flow.Linked M (coordinate i) label stop bad) (c : Config w p (6+d)) + (hpc : c.pc = label (coordinate i).entry) (v : Word w) + (hcap : ¬ v < c.reg (low d 3)) : + ∃ out es, Prefix M c es out ∧ es.length = 4*w+5 ∧ choiceBits es = wordBits v ∧ out.pc = bad := by + obtain ⟨q,es,hpre,hlen,hbits,hq,hw,ho,_⟩ := flow_native hc.seqLeft c hpc v + change q.reg (low d 0) = v at hw + have hg : M.program.step q = .localStep {q with pc := bad} := by + rw [line_step hc.seqRight.seqLeft q hq] + simp [Op.emit, Instr.resize, Instr.run, hw, ho _ (outside_reader 3 (by decide)), hcap] + refine ⟨_,es ++ [.tick],hpre.append (.tick hg (.nil _)),?_,?_,rfl⟩ + · simp [hlen] + · simp [bits_append,hbits,choiceBits] + +/-- A rejected candidate reaches the rejecting label on a prefix of its encoding. +For candidates outside the coordinate box no fit assumption on their score is required. -/ +theorem scan_reject {M : Machine w p (6+d) d} (is : List (Fin d)) + {label : (scan is).Label → Fin p} {stop bad : Fin p} + (hc : Flow.Linked M (scan is) label stop bad) (c : Config w p (6+d)) + (hpc : c.pc = label (scan is).entry) (v : Fin d → Word w) + (hfit : (∀ i ∈ is, v i < c.reg (low d 3)) → + (c.reg (low d 4)).val + score is M.publicData v < 2 ^ w) + (hfail : (∀ i ∈ is, v i < c.reg (low d 3)) → + (c.reg (low d 5)).val ≤ (c.reg (low d 4)).val + score is M.publicData v) : + ∃ out es rest, Prefix M c es out ∧ es.length ≤ is.length * (4*w+10) + 1 ∧ + encoding is v = choiceBits es ++ rest ∧ out.pc = bad := by + induction is generalizing c with + | nil => + have h := hfail (by simp) + have ht : ¬ c.reg (low d 4) < c.reg (low d 5) := not_lt_of_ge (by simpa [score] using h) + have hs : M.program.step c = .localStep {c with pc := bad} := by + rw [line_step hc c hpc]; simp [Op.emit, Instr.resize, Instr.run, ht] + exact ⟨_, [.tick], [], .tick hs (.nil _), by simp, rfl, rfl⟩ + | cons i is ih => + by_cases hv : v i < c.reg (low d 3) + · obtain ⟨q,es,hpre,hlen,hbits,hq,hcap',hs,hlimit,_⟩ := coordinate_prefix hc.seqLeft c hpc _ hv + have aux (h : ∀ j ∈ is, v j < q.reg (low d 3)) : + (∀ j ∈ i :: is, v j < c.reg (low d 3)) ∧ + (q.reg (low d 4)).val + score is M.publicData v = + (c.reg (low d 4)).val + score (i :: is) M.publicData v := by + have hbox : ∀ j ∈ i :: is, v j < c.reg (low d 3) := by + intro j hj; rcases List.mem_cons.mp hj with rfl | ht + · exact hv + · rw [← hcap']; exact h j ht + refine ⟨hbox, ?_⟩ + have hf := hfit hbox + simp only [score, List.map_cons, List.sum_cons] at hf ⊢ + rw [hs, scoreWord_exact _ _ _ (by omega), Nat.add_assoc] + obtain ⟨out,fs,rest,hpost,hflen,hrest,ho⟩ := ih hc.seqRight q hq + (fun h => (aux h).2 ▸ hfit (aux h).1) (fun h => by rw [hlimit, (aux h).2]; exact hfail (aux h).1) + refine ⟨out, es++fs, rest, hpre.append hpost, ?_, ?_, ho⟩ + · simp only [List.length_append,hlen,List.length_cons,Nat.add_mul,Nat.one_mul]; omega + · change wordBits (v i) ++ encoding is v = _ + rw [hrest, bits_append, hbits, List.append_assoc] + · obtain ⟨q,es,hpre,hlen,hbits,hq⟩ := coordinate_reject hc.seqLeft c hpc _ hv + refine ⟨q,es,encoding is v,hpre,?_,?_,hq⟩ + · simp only [hlen,List.length_cons,Nat.add_mul,Nat.one_mul]; omega + · rw [hbits]; rfl + +private theorem reject_at {r k : ℕ} (M : Machine w p r k) (c : Config w p r) (m : Memory w) + (bits : List Bool) (fuel : ℕ) (h : M.code c.pc = .reject) : execute M.program fuel c m bits = none := by + cases fuel <;> simp [execute,Machine.program,h,Instr.run] + +private theorem score_mono (is : List (Fin d)) (weight v t : Fin d → Word w) + (h : ∀ i ∈ is, v i ≤ t i) : score is weight v ≤ score is weight t := by + induction is with + | nil => rfl + | cons i is ih => + change (weight i).val * (v i).val ^ 2 + score is weight v ≤ + (weight i).val * (t i).val ^ 2 + score is weight t + exact Nat.add_le_add (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (h i (by simp)) _)) + (ih fun j hj => h j (List.mem_cons_of_mem _ hj)) + +private theorem encoding_congr (is : List (Fin d)) {v t : Fin d → Word w} (h : ∀ i ∈ is, v i = t i) : + encoding is v = encoding is t := by + induction is with + | nil => rfl + | cons i is ih => + change wordBits (v i) ++ encoding is v = wordBits (t i) ++ encoding is t + rw [h i (by simp), ih fun j hj => h j (List.mem_cons_of_mem _ hj)] + +private theorem score_congr (is : List (Fin d)) (weights : Fin d → Word w) {v t : Fin d → Word w} + (h : ∀ i ∈ is, v i = t i) : score is weights v = score is weights t := by + apply Nat.le_antisymm <;> apply score_mono + · intro i hi; rw [h i hi] + · intro i hi; rw [h i hi] + +/-- Every successful machine stream consists of complete words, has exactly the +prescribed length, and passes both numerical tests. The fit condition covers the entire +box so that an overweight candidate cannot gain admission by wrapping around. -/ +theorem scan_sound {M : Machine w p (6+d) d} (is : List (Fin d)) (hnd : is.Nodup) + {label : (scan is).Label → Fin p} {stop bad : Fin p} + (hc : Flow.Linked M (scan is) label stop bad) (hstop : M.code stop = .accept) + (hbad : M.code bad = .reject) (c : Config w p (6+d)) (hpc : c.pc = label (scan is).entry) + (mem : Memory w) (bits : List Bool) + (hfit : (c.reg (low d 4)).val + score is M.publicData (fun _ => c.reg (low d 3)) < 2^w) + (hrun : (execute M.program (is.length * (4*w+10) + 2) c mem bits).isSome) : + ∃ v : Fin d → Word w, bits = encoding is v ∧ (∀ i ∈ is, v i < c.reg (low d 3)) ∧ + (c.reg (low d 4)).val + score is M.publicData v < (c.reg (low d 5)).val := by + induction is generalizing c bits with + | nil => + have hs := line_step hc c hpc + simp only [List.length_nil,Nat.zero_mul,Nat.zero_add] at hrun + rw [execute, hs] at hrun + by_cases ht : c.reg (low d 4) < c.reg (low d 5) + · have he : bits = [] := by + cases bits <;> simp_all [Op.emit, Instr.resize, Instr.run, execute, Machine.program] + exact ⟨fun _ => 0,he,by simp,by simpa [score] using ht⟩ + · simp [Op.emit, Instr.resize, Instr.run, ht, execute, Machine.program, hbad] at hrun + | cons i is ih => + let tailFuel := is.length * (4*w+10) + 2 + by_cases short : bits.length < w + · have hh := native_short (contains_flow hc.seqLeft.seqLeft) c hpc bits short + ((i :: is).length * (4*w+10) + 2) mem + rw [hh] at hrun; contradiction + obtain ⟨x,hx⟩ := exists_wordBits (w := w) (bits.take w) (by simp [Nat.le_of_not_gt short]) + let tail := bits.drop w + have hsplit : bits = wordBits x ++ tail := by rw [hx]; exact (List.take_append_drop w bits).symm + by_cases hcap : x < c.reg (low d 3) + · obtain ⟨q,es,hpre,hlen,hbits,hq,hcap',hs,hlimit,_⟩ := coordinate_prefix hc.seqLeft c hpc x hcap + have hlen' : (i :: is).length * (4*w+10) + 2 = tailFuel + es.length := by + simp [tailFuel,hlen,Nat.add_mul]; omega + rw [hsplit, ← hbits, hlen', hpre.execute] at hrun + have ht : (execute M.program tailFuel q mem tail).isSome := by simpa using hrun + have headLe : (M.publicData i).val * x.val ^ 2 ≤ + (M.publicData i).val * (c.reg (low d 3)).val ^ 2 := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (Fin.le_iff_val_le_val.mp hcap.le) _) + have hfit' := hfit + change (c.reg (low d 4)).val + ((M.publicData i).val * (c.reg (low d 3)).val ^ 2 + + score is M.publicData (fun _ => c.reg (low d 3))) < 2^w at hfit' + have hnew : (q.reg (low d 4)).val = (c.reg (low d 4)).val + (M.publicData i).val * x.val ^ 2 := by + rw [hs]; apply scoreWord_exact; omega + obtain ⟨v,he,hbox,hscore⟩ := ih (List.nodup_cons.mp hnd).2 hc.seqRight q hq tail + (by rw [hnew,hcap']; omega) ht + let v' := Function.update v i x + have same (j : Fin d) (hj : j ∈ is) : v' j = v j := + Function.update_of_ne (by rintro rfl; exact (List.nodup_cons.mp hnd).1 hj) .. + refine ⟨v',?_,?_,?_⟩ + · change bits = wordBits (v' i) ++ encoding is v' + rw [encoding_congr is same, ← he]; simpa [v'] using hsplit + · intro j hj + rcases List.mem_cons.mp hj with rfl | h + · simpa [v'] using hcap + · rw [same j h, ← hcap']; exact hbox j h + · change (c.reg (low d 4)).val + ((M.publicData i).val * (v' i).val ^ 2 + + score is M.publicData v') < _ + rw [score_congr is M.publicData same, ← Nat.add_assoc, ← hlimit] + simpa [v',hnew] using hscore + · obtain ⟨q,es,hpre,hlen,hbits,hq⟩ := coordinate_reject hc.seqLeft c hpc x hcap + have hlen' : (i :: is).length * (4*w+10) + 2 = (tailFuel+5) + es.length := by + simp [tailFuel,hlen,Nat.add_mul]; omega + rw [hsplit, ← hbits, hlen', hpre.execute, reject_at M q mem tail _ (hq ▸ hbad)] at hrun + contradiction + +/-- Complete calls of the linked native scan are exactly the canonical encodings +of admitted vectors. Extra or truncated streams fail, including at zero supply arity. -/ +theorem scan_execute_iff {M : Machine w p (6+d) d} (is : List (Fin d)) (hnd : is.Nodup) + {label : (scan is).Label → Fin p} {stop bad : Fin p} + (hc : Flow.Linked M (scan is) label stop bad) (hstop : M.code stop = .accept) + (hbad : M.code bad = .reject) (c : Config w p (6+d)) (hpc : c.pc = label (scan is).entry) + (mem : Memory w) (bits : List Bool) + (hfit : (c.reg (low d 4)).val + score is M.publicData (fun _ => c.reg (low d 3)) < 2^w) : + (execute M.program (is.length * (4*w+10) + 2) c mem bits).isSome ↔ + ∃ v : Fin d → Word w, bits = encoding is v ∧ (∀ i ∈ is, v i < c.reg (low d 3)) ∧ + (c.reg (low d 4)).val + score is M.publicData v < (c.reg (low d 5)).val := by + refine ⟨scan_sound is hnd hc hstop hbad c hpc mem bits hfit, ?_⟩ + rintro ⟨v,rfl,hcap,hscore⟩ + obtain ⟨out,es,hpre,hlen,hbits,hout,_⟩ := scan_prefix is hc c hpc v hcap hscore + have he := hpre.execute 1 mem [] + simp only [List.append_nil, hbits, hlen] at he + rw [show is.length * (4*w+10) + 2 = 1 + (is.length * (4*w+10) + 1) by omega, he] + simp [execute, Machine.program, hout, hstop, Instr.run] + +/-- The native prefix consists entirely of private ticks and binary choices. -/ +theorem prefix_probes {r k : ℕ} {M : Machine w p r k} {c out : Config w p r} {es : List (Event w)} + (h : Prefix M c es out) : countProbes es = 0 := by + induction h with + | nil => rfl + | tick _ _ ih | choice _ _ ih => exact ih + +/-- With supply slots in numerical order the scan consumes the concatenation +of the little-endian word representations, including leading zero bits. -/ +theorem full_encoding (v : Fin d → Word w) : + encoding (List.finRange d) v = (List.ofFn (fun i => wordBits (v i))).flatten := by + simp [encoding, List.flatMap_def, List.finRange, List.map_ofFn, Function.comp_def] + +/-- The public quadratic coefficients include the squared radius denominator; +the accumulator therefore computes the complete left side of the admission test. -/ +theorem full_score {S : Type*} [Fintype S] (order : Fin d ≃ S) (q : S → ℚ) (R : ℚ) + (weights v : Fin d → Word w) + (hweights : ∀ i, (weights i).val = MotifAdmission.weight q (order i) * R.den ^ 2) : + score (List.finRange d) weights v = + MotifAdmission.energy q (fun e => (v (order.symm e)).val) * R.den ^ 2 := by + simp only [score, List.finRange, List.map_ofFn, List.sum_ofFn, Function.comp_apply, hweights, + MotifAdmission.energy, Finset.sum_mul] + rw [← order.sum_comp (fun e => MotifAdmission.weight q e * (v (order.symm e)).val ^ 2 * R.den ^ 2)] + apply Finset.sum_congr rfl + intro i _ + rw [Equiv.symm_apply_apply] + ring + +/-- With positive supply masses and representable bounds, acceptance of the actual +machine agrees with the integer admission test used in the outer sum of Theorem 6.1. -/ +theorem scan_admit_iff {S : Type*} [Fintype S] (order : Fin d ≃ S) (q : S → ℚ) + (hq : ∀ e, 0 < q e) (u L : ℕ) (R : ℚ) {M : Machine w p (6+d) d} + {label : (scan (List.finRange d)).Label → Fin p} {stop bad : Fin p} + (hc : Flow.Linked M (scan (List.finRange d)) label stop bad) (hstop : M.code stop = .accept) + (hbad : M.code bad = .reject) (c : Config w p (6+d)) (hpc : c.pc = label (scan (List.finRange d)).entry) + (hweights : ∀ i, (M.publicData i).val = MotifAdmission.weight q (order i) * R.den ^ 2) + (hcap : (c.reg (low d 3)).val = MotifAdmission.payloadCap q u L R + 1) + (hzero : (c.reg (low d 4)).val = 0) + (hlimit : (c.reg (low d 5)).val = (u * L * R.num.natAbs) ^ 2 * MotifAdmission.denominator q + 1) + (hfit : score (List.finRange d) M.publicData (fun _ => c.reg (low d 3)) < 2^w) + (mem : Memory w) (bits : List Bool) : + (execute M.program (d * (4*w+10) + 2) c mem bits).isSome ↔ + ∃ v : Fin d → Word w, bits = encoding (List.finRange d) v ∧ + MotifAdmission.admit q (fun e => (v (order.symm e)).val) u L R = true := by + have he := scan_execute_iff (List.finRange d) (List.nodup_finRange _) hc hstop hbad c hpc mem bits + (by simpa [hzero] using hfit) + simp only [List.length_finRange, hzero, Nat.zero_add, hlimit, Nat.lt_succ_iff] at he + rw [he] + apply exists_congr + intro v + rw [full_score order q R M.publicData v hweights] + apply and_congr_right + intro _ + constructor + · rintro ⟨_,hv⟩; exact decide_eq_true hv + · intro hv + refine ⟨?_, of_decide_eq_true hv⟩ + intro i _ + apply Fin.lt_def.mpr + rw [hcap, Nat.lt_succ_iff] + simpa using MotifAdmission.payload_le_cap q hq (fun e => (v (order.symm e)).val) u L R hv (order i) + +end MotifChoiceRAM +end CompressorRecords + +namespace CompressorRecords.MotifChoiceRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter.GuessWord + +variable {n w pcCount : ℕ} + +/-- The unit term has no payload. Write the zero descriptor without guessing +bits, even when the incoming register file still holds the preceding motif. -/ +def unitSlots : List (Fin n) → Flow (6 + n) n + | [] => .line (.constant (low n 4) 0) + | i :: rest => .seq (.line (.constant (slot i) 0)) (unitSlots rest) + +private theorem constantStep {M : Machine w pcCount (6 + n) n} {dst : Fin (6 + n)} + {label : (Flow.line (k := n) (.constant dst 0)).Label → Fin pcCount} {stop bad : Fin pcCount} + (hc : Flow.Linked M (.line (.constant dst 0)) label stop bad) (c : Config w pcCount (6+n)) + (hpc : c.pc = label ()) : + M.program.step c = .localStep (c.put stop dst 0) := by + change (M.code c.pc).run _ _ = _ + rw [hpc, hc.atLabel ()] + rfl + +theorem unitSlots_prefix {M : Machine w pcCount (6+n) n} (is : List (Fin n)) + {label : (unitSlots is).Label → Fin pcCount} {stop bad : Fin pcCount} + (hc : Flow.Linked M (unitSlots is) label stop bad) (c : Config w pcCount (6+n)) + (hpc : c.pc = label (unitSlots is).entry) : + ∃ out es, Prefix M c es out ∧ es.length = is.length + 1 ∧ choiceBits es = [] ∧ + out.pc = stop ∧ (∀ j, out.reg (slot j) = if j ∈ is then 0 else c.reg (slot j)) ∧ + out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by + induction is generalizing c with + | nil => + have h := constantStep hc c hpc + refine ⟨_, [.tick], .tick h (.nil _), rfl, rfl, rfl, ?_, rfl, rfl⟩ + intro j + have hn : slot j ≠ low n 4 := by + intro he + have hval := congrArg Fin.val he + change 6 + j.val = 4 at hval + omega + simp [Config.put, hn] + | cons i is ih => + let q := c.put (label (.inr (unitSlots is).entry)) (slot i) 0 + have hs : M.program.step c = .localStep q := constantStep hc.seqLeft c hpc + obtain ⟨out,es,hpre,hlen,hbits,hdone,hslot,hpriv,hpersist⟩ := ih hc.seqRight q rfl + refine ⟨out, .tick :: es, .tick hs hpre, by simp [hlen], hbits, hdone, ?_, hpriv, hpersist⟩ + intro j + rw [hslot] + by_cases hj : j ∈ is + · simp [hj] + · by_cases he : j = i + · subst j + simp [hj, q, Config.put] + · have hne : slot j ≠ slot i := fun h => he ((Fin.natAddEmb 6).injective h) + simp [hj, he, q, Config.put, hne] + +/-- The repetition count arrives in scratch register two, and the energy +accumulator in register four starts at zero. Both branches have fixed code. -/ +def choosePayload (n : ℕ) : Flow (6+n) n := + .ifEq (low n 2) (low n 4) (unitSlots (List.finRange n)) (scan (List.finRange n)) + +private theorem dispatchStep {M : Machine w pcCount (6+n) n} {label : (choosePayload n).Label → Fin pcCount} + {stop bad : Fin pcCount} (hc : Flow.Linked M (choosePayload n) label stop bad) + (c : Config w pcCount (6+n)) (hpc : c.pc = label (choosePayload n).entry) : + let dest := if c.reg (low n 2) = c.reg (low n 4) then + label (.inr (.inl (unitSlots (List.finRange n)).entry)) else + label (.inr (.inr (scan (List.finRange n)).entry)) + M.program.step c = .localStep {c with pc := dest} := by + change (M.code c.pc).run _ _ = _ + rw [hpc, hc.atLabel _] + rfl + +theorem choosePayload_unit {M : Machine w pcCount (6+n) n} {label : (choosePayload n).Label → Fin pcCount} + {stop bad : Fin pcCount} (hc : Flow.Linked M (choosePayload n) label stop bad) + (c : Config w pcCount (6+n)) (hpc : c.pc = label (choosePayload n).entry) + (hzero : c.reg (low n 2) = c.reg (low n 4)) : + ∃ out es, Prefix M c es out ∧ es.length = n + 2 ∧ choiceBits es = [] ∧ out.pc = stop ∧ + (∀ i, out.reg (slot i) = 0) ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by + let next := {c with pc := label (.inr (.inl (unitSlots (List.finRange n)).entry))} + have hs : M.program.step c = .localStep next := by simp [dispatchStep hc c hpc, hzero, next] + obtain ⟨out, es, hp, hl, hb, ho, hslot, hpriv, hpersist⟩ := unitSlots_prefix _ hc.ifEqYes next rfl + exact ⟨out, .tick :: es, .tick hs hp, by simp [hl], hb, ho, fun i => by simpa using hslot i, hpriv, hpersist⟩ + +theorem choosePayload_vector {M : Machine w pcCount (6+n) n} {label : (choosePayload n).Label → Fin pcCount} + {stop bad : Fin pcCount} (hc : Flow.Linked M (choosePayload n) label stop bad) + (c : Config w pcCount (6+n)) (hpc : c.pc = label (choosePayload n).entry) + (hpos : c.reg (low n 2) ≠ c.reg (low n 4)) (v : Fin n → Word w) + (hcap : ∀ i, v i < c.reg (low n 3)) (hscore : (c.reg (low n 4)).val + + score (List.finRange n) M.publicData v < (c.reg (low n 5)).val) : + ∃ out es, Prefix M c es out ∧ es.length = n * (4*w+10) + 2 ∧ + choiceBits es = encoding (List.finRange n) v ∧ out.pc = stop ∧ + (∀ i, out.reg (slot i) = v i) ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by + let next := {c with pc := label (.inr (.inr (scan (List.finRange n)).entry))} + have hs : M.program.step c = .localStep next := by simp [dispatchStep hc c hpc, hpos, next] + obtain ⟨out, es, hp, hl, hb, ho, _, hslot, hpriv, hpersist⟩ := + scan_prefix _ hc.ifEqNo next rfl v (fun i _ => hcap i) hscore + exact ⟨out, .tick :: es, .tick hs hp, by simp [hl], hb, ho, fun i => by simpa using hslot i, hpriv, hpersist⟩ + +open MotifGrid MotifBlocks MotifConversion MotifSelector + +variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S] +variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ} +variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H') + +/-- The native call's complete streams are exactly those of the outer-index +reader, including the unit branch. All bound checks take place on machine +words whose exact numerical contents are given by the register hypotheses. -/ +theorem choosePayload_execute_iff (order : Fin n ≃ S) (hq : ∀ e, 0 < q e) (demand : D → ℕ) + {M : Machine w pcCount (6+n) n} {label : (choosePayload n).Label → Fin pcCount} + {stop bad : Fin pcCount} (hc : Flow.Linked M (choosePayload n) label stop bad) + (hstop : M.code stop = .accept) (hbad : M.code bad = .reject) (c : Config w pcCount (6+n)) + (hpc : c.pc = label (choosePayload n).entry) + (hweights : ∀ i, (M.publicData i).val = MotifAdmission.weight q (order i) * B.radius.den ^ 2) + (hreps : (c.reg (low n 2)).val = repetitions B demand) + (hcap : (c.reg (low n 3)).val = outerCap B demand + 1) + (hzero : (c.reg (low n 4)).val = 0) + (hlimit : (c.reg (low n 5)).val = + (repetitions B demand * B.scale * B.radius.num.natAbs) ^ 2 * MotifAdmission.denominator q + 1) + (hfit : score (List.finRange n) M.publicData (fun _ => c.reg (low n 3)) < 2^w) + (mem : Memory w) (bits : List Bool) : + let hw : outerCap B demand < 2^w := by have _hv := (c.reg (low n 3)).isLt; omega + (execute M.program (n * (4*w+10) + 3) c mem bits).isSome ↔ + ∃ v, (outerReader B order hq demand w hw).read bits = some (v, []) := by + dsimp only + have hcfit : outerCap B demand < 2 ^ w := by have _hv := (c.reg (low n 3)).isLt; omega + by_cases hu : repetitions B demand = 0 + · have hz : c.reg (low n 2) = c.reg (low n 4) := Fin.ext (hreps.trans (hu.trans hzero.symm)) + obtain ⟨out, es, hp, hl, hb, ho, _⟩ := choosePayload_unit hc c hpc hz + have hlen : es.length ≤ n * (4*w+10) + 2 := by + have h := Nat.le_mul_of_pos_right n (by omega : 0 < 4*w+10) + omega + let extra := n * (4*w+10) + 2 - es.length + have hrun := hp.execute (extra + 1) mem bits + simp only [hb, List.nil_append] at hrun + rw [show n * (4*w+10) + 3 = extra + 1 + es.length by dsimp [extra]; omega, hrun] + have hstopRun : M.program.step out = .finish none := by simp [Machine.program, ho, hstop, Instr.run] + have empty (v : ↥(outerIndices B demand)) : (outerReader B order hq demand w hcfit).encode v = [] := by + apply List.length_eq_zero_iff.mp + simp [outerReader_length, coordinateBits, hu] + have h₀ : (fun _ => 0) ∈ outerIndices B demand := (mem_outerIndices_iff B hq _ _).mpr (by + simp [MotifAdmission.admit, MotifAdmission.energy]) + simp only [execute, hstopRun, ChoiceReader.read_iff, List.append_nil] + by_cases hbits : bits = [] + · simpa [hbits, empty] using (show ∃ a, a ∈ outerIndices B demand from ⟨_, h₀⟩) + · simp [hbits, empty] + · have hn : c.reg (low n 2) ≠ c.reg (low n 4) := fun he => hu (hreps.symm.trans ((congrArg Fin.val he).trans hzero)) + let next := {c with pc := label (.inr (.inr (scan (List.finRange n)).entry))} + have hs : M.program.step c = .localStep next := by simp [dispatchStep hc c hpc, hn, next] + have hm := scan_admit_iff order q hq (repetitions B demand) B.scale B.radius hc.ifEqNo hstop hbad next rfl + hweights hcap hzero hlimit hfit mem bits + rw [execute, hs, Option.isSome_map, hm] + constructor + · rintro ⟨v, rfl, hv⟩ + let a := fun e => (v (order.symm e)).val + refine ⟨⟨a, (mem_outerIndices_iff B hq _ _).mpr hv⟩, (read_outer_iff B order hq demand w hcfit _ _ _).mpr ?_⟩ + rw [show coordinateBits B demand w = w from ite_eq_right hu, full_encoding, List.append_nil] + congr 2 + funext i + simp [a, PrimedCounter.digits] + · rintro ⟨v, hr⟩ + have hadm := (mem_outerIndices_iff B hq _ _).mp v.property + let z (i : Fin n) : BurstRAM.Word w := ⟨v.val (order i), (MotifAdmission.payload_le_cap q hq _ _ _ _ hadm _).trans_lt hcfit⟩ + refine ⟨z, ?_, ?_⟩ + · have he := (read_outer_iff B order hq demand w hcfit bits [] v).mp hr + rw [he, full_encoding, List.append_nil] + simp only [coordinateBits, hu, ↓reduceIte] + congr 2 + funext i + apply congrArg BurstRAM.wordBits + exact Fin.ext (Nat.mod_eq_of_lt (z i).isLt) + · simpa [z] using hadm + +/-- For fixed rational motif data a constant plus twice the binary logarithm of +`M+1` suffices for the entire native reader. This covers the one-past guards, +all public weights, and the largest energy considered in the overflow proof. -/ +theorem native_word_fit {D S : Type*} [Fintype D] [Fintype S] + (p : D → ℚ) (q : S → ℚ) (L : ℕ) (hL : 0 < L) (R : ℚ) : + ∃ K : ℕ, ∀ (M : ℕ) (b : D → ℕ), (∀ i, b i ≤ M) → + let u := MotifAdmission.copies p b L + let box := MotifAdmission.payloadCap q u L R + 1 + let limit := (u * L * R.num.natAbs) ^ 2 * MotifAdmission.denominator q + 1 + let modulus := 2 ^ (K + 2 * Nat.clog 2 (M + 1)) + u < modulus ∧ box < modulus ∧ limit < modulus ∧ + MotifAdmission.energy q (fun _ => box) * R.den ^ 2 < modulus ∧ + ∀ e, MotifAdmission.weight q e * R.den ^ 2 < modulus := by + let U := (∑ i, MotifAdmission.weight p i) + 1 + let V := U * L * R.num.natAbs * MotifAdmission.denominator q + let A := max U (V + 1) + let B := (∑ e, MotifAdmission.weight q e) * A ^ 2 * R.den ^ 2 + let C := (A * L * R.num.natAbs) ^ 2 * MotifAdmission.denominator q + let total := A + B + C + 1 + refine ⟨total.size, fun M b hb => ?_⟩ + dsimp only + let u := MotifAdmission.copies p b L + let box := MotifAdmission.payloadCap q u L R + 1 + have hu : u ≤ A * (M+1) := (MotifAdmission.copies_le p b L M hL hb).trans + (Nat.mul_le_mul_right _ (le_max_left U (V+1))) + have hcap : MotifAdmission.payloadCap q u L R ≤ V * (M+1) := + MotifAdmission.payloadCap_le p q b L M R hL hb + have hbox : box ≤ A * (M+1) := calc + box ≤ (V+1) * (M+1) := by dsimp [box]; rw [Nat.add_mul, Nat.one_mul]; omega + _ ≤ A * (M+1) := Nat.mul_le_mul_right _ (le_max_right U (V+1)) + obtain ⟨hleft,hright⟩ := MotifAdmission.admit_operands_le q (fun _ => box) u L R A M hu (fun _ => hbox) + change MotifAdmission.energy q (fun _ => box) * R.den ^ 2 ≤ B * (M+1)^2 at hleft + change (u * L * R.num.natAbs) ^ 2 * MotifAdmission.denominator q ≤ C * (M+1)^2 at hright + have fit (x c : ℕ) (hc : c ≤ total) (hx : x ≤ c * (M+1)^2) : x < 2^(total.size + 2 * Nat.clog 2 (M+1)) := + Nat.size_le.mp (MotifAdmission.operand_bits_le x total M (hx.trans (Nat.mul_le_mul_right _ hc))) + have grow : A * (M+1) ≤ A * (M+1)^2 := Nat.mul_le_mul_left _ (Nat.le_self_pow (by decide) _) + have positive : 0 < (M+1)^2 := by positivity + refine ⟨fit u A (by dsimp [total]; omega) (hu.trans grow), + fit box A (by dsimp [total]; omega) (hbox.trans grow), + fit _ (C+1) (by dsimp [total]; omega) ?_, + fit _ B (by dsimp [total]; omega) hleft, ?_⟩ + · change (u * L * R.num.natAbs) ^ 2 * MotifAdmission.denominator q + 1 ≤ (C+1) * (M+1)^2 + rw [Nat.add_mul, Nat.one_mul]; omega + · intro e + apply fit _ B (by dsimp [total]; omega) + apply le_trans _ hleft + apply Nat.mul_le_mul_right + calc + MotifAdmission.weight q e ≤ MotifAdmission.weight q e * box ^ 2 := + Nat.le_mul_of_pos_right _ (pow_pos (Nat.succ_pos _) _) + _ ≤ MotifAdmission.energy q (fun _ => box) := + Finset.single_le_sum (f := fun i => MotifAdmission.weight q i * box ^ 2) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ e) + +end CompressorRecords.MotifChoiceRAM + +namespace CompressorRecords.MotifChoiceRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM PrimedCounter.GuessWord +open scoped Fin.CommRing + +variable {r k w d : ℕ} + +/-- Multiply by a coefficient built into the fixed instruction table in binary. +The source survives, and the destination is initialized afresh. -/ +def scaleDigits (dst src : Fin r) : List Bool → Flow r k + | [] => .line (.constant dst 0) + | b :: bs => + let double := Flow.line (.binary .add dst dst dst) + let addSrc := Flow.line (.binary .add dst dst src) + .seq (scaleDigits dst src bs) (if b then double.seq addSrc else double) + +/-- Encode fixed motif coefficients in the code, independently of the actual +machine word width or the length-dependent public data. -/ +def scaleFixed (dst src : Fin r) (n : ℕ) : Flow r k := + scaleDigits dst src (wordBits (⟨n, Nat.lt_size_self n⟩ : Word n.size)) + +private abbrev Straight {r k w : ℕ} (pub : Fin k → Word w) (state : Word w) (mem : Memory w) + (code : Flow r k) (rs rs' : Regs w r) := + Flow.Exec pub state code rs mem (List.replicate code.length .tick) rs' mem + +private theorem seq_straight {pub : Fin k → Word w} {state : Word w} {mem : Memory w} + {a b : Flow r k} {x y z : Regs w r} (h : Straight pub state mem a x y) (h' : Straight pub state mem b y z) : + Straight pub state mem (a.seq b) x z := by + simpa only [Straight, Flow.length, List.replicate_add] using Flow.Exec.seq h h' + +private theorem scaleDigits_straight (dst src : Fin r) (hds : src ≠ dst) (digits : List Bool) + (pub : Fin k → Word w) (state : Word w) (mem : Memory w) (rs : Regs w r) : + Straight pub state mem (scaleDigits dst src digits) rs + (Function.update rs dst (rs src * (value digits : Word w))) := by + induction digits with + | nil => + apply Flow.Exec.line + simp [Op.effect, value] + | cons b bs ih => + let t := rs src * (value bs : Word w) + let mid := Function.update rs dst t + have hs : Straight pub state mem (.line (.binary .add dst dst dst)) mid + (Function.update rs dst (t+t)) := by + apply Flow.Exec.line + simp [Op.effect, BinaryOp.eval, mid] + cases b with + | false => + apply seq_straight ih + have hval : rs src * (value (false :: bs) : Word w) = t+t := by simp [value, t]; ring + rw [hval]; exact hs + | true => + apply seq_straight ih + apply seq_straight hs + have hval : rs src * (value (true :: bs) : Word w) = t+t+rs src := by simp [value, t]; ring + rw [hval] + apply Flow.Exec.line + simp [Op.effect, BinaryOp.eval, hds] + +theorem scaleFixed_length (dst src : Fin r) (n : ℕ) : (scaleFixed (k := k) dst src n).length ≤ 2*n.size+1 := by + have digits (bs : List Bool) : (scaleDigits (k := k) dst src bs).length ≤ 2 * bs.length + 1 := by + induction bs with + | nil => simp [scaleDigits, Flow.length] + | cons b bs ih => cases b <;> simp [scaleDigits, Flow.length] <;> omega + simpa [scaleFixed] using digits (wordBits (⟨n,Nat.lt_size_self n⟩ : Word n.size)) + +private theorem scaleFixed_straight (dst src : Fin r) (hds : src ≠ dst) (n : ℕ) + (pub : Fin k → Word w) (state : Word w) (mem : Memory w) (rs : Regs w r) : + Straight pub state mem (scaleFixed dst src n) rs (Function.update rs dst (rs src * (n : Word w))) := by + simpa only [scaleFixed, value_wordBits] using + scaleDigits_straight dst src hds (wordBits (⟨n,Nat.lt_size_self n⟩ : Word n.size)) pub state mem rs + +/-- The input repetition word is register 2. The code sets register 3 to one +past the coordinate cap, register 5 to one past the energy limit, and clears +the scratch and energy registers before dispatching on the repetition word. -/ +def prepareBounds (d : ℕ) (factor denominator : ℕ) : Flow (6+d) d := + let r := low d + .seq (scaleFixed (r 4) (r 2) factor) <| + .seq (scaleFixed (r 3) (r 4) denominator) <| + .seq (.line (.binary .mul (r 1) (r 4) (r 4))) <| + .seq (scaleFixed (r 5) (r 1) denominator) <| + .seq (.line (.constant (r 0) 1)) <| + .seq (.line (.binary .add (r 3) (r 3) (r 0))) <| + .seq (.line (.binary .add (r 5) (r 5) (r 0))) <| + .seq (.line (.constant (r 4) 0)) <| + .seq (.line (.constant (r 0) 0)) + (.line (.constant (r 1) 0)) + +/-- Constant instruction cost for a fixed motif. Only the binary lengths of the +fixed coefficients enter the bound, independently of the word size and of `u`. -/ +theorem prepareBounds_length (d factor denominator : ℕ) : + (prepareBounds d factor denominator).length ≤ 2*factor.size + 4*denominator.size + 10 := by + have ha := scaleFixed_length (k := d) (low d 4) (low d 2) factor + have hb := scaleFixed_length (k := d) (low d 3) (low d 4) denominator + have hc := scaleFixed_length (k := d) (low d 5) (low d 1) denominator + simp only [prepareBounds,Flow.length]; omega + +private theorem binary_straight (pub : Fin k → Word w) (s : Word w) (m : Memory w) (rs : Regs w r) + (op : BinaryOp) (dst x y : Fin r) : Straight pub s m (.line (.binary op dst x y)) rs + (Function.update rs dst (op.eval (rs x) (rs y))) := .line rfl + +private theorem const_straight (pub : Fin k → Word w) (s : Word w) (m : Memory w) (rs : Regs w r) + (dst : Fin r) (v : Word 2) : Straight pub s m (.line (.constant dst v)) rs + (Function.update rs dst (Fin.ofNat (2^w) v.val)) := .line rfl + +private def postRegs {code : Flow r k} {pub : Fin k → Word w} {s m rs out} + (_ : Straight pub s m code rs out) : Regs w r := out + +/-- Exact register effects at the continuation of threshold preparation. The +hypotheses concern only the two final natural bounds, since the intermediate +word computations agree with the integer expressions modulo the word modulus. -/ +theorem prepareBounds_exec (factor denominator u : ℕ) (pub : Fin d → Word w) + (s : Word w) (m : Memory w) (rs : Regs w (6+d)) (hu : (rs (low d 2)).val = u) + (hcap : u * factor * denominator + 1 < 2^w) + (hlimit : (u * factor)^2 * denominator + 1 < 2^w) : + ∃ out, Flow.Exec pub s (prepareBounds d factor denominator) rs m + (List.replicate (prepareBounds d factor denominator).length .tick) out m ∧ + out (low d 0) = 0 ∧ out (low d 1) = 0 ∧ out (low d 2) = rs (low d 2) ∧ + (out (low d 3)).val = u * factor * denominator + 1 ∧ out (low d 4) = 0 ∧ + (out (low d 5)).val = (u * factor)^2 * denominator + 1 ∧ ∀ j, out (slot j) = rs (slot j) := by + have h₁ := scaleFixed_straight (low d 4) (low d 2) (by simp (config := {decide := true})) factor pub s m rs + have h₂ := scaleFixed_straight (low d 3) (low d 4) (by simp (config := {decide := true})) denominator pub s m (postRegs h₁) + have h₃ := binary_straight pub s m (postRegs h₂) .mul (low d 1) (low d 4) (low d 4) + have h₄ := scaleFixed_straight (low d 5) (low d 1) (by simp (config := {decide := true})) denominator pub s m (postRegs h₃) + have h₅ := const_straight pub s m (postRegs h₄) (low d 0) 1 + have h₆ := binary_straight pub s m (postRegs h₅) .add (low d 3) (low d 3) (low d 0) + have h₇ := binary_straight pub s m (postRegs h₆) .add (low d 5) (low d 5) (low d 0) + have h₈ := const_straight pub s m (postRegs h₇) (low d 4) 0 + have h₉ := const_straight pub s m (postRegs h₈) (low d 0) 0 + have h₁₀ := const_straight pub s m (postRegs h₉) (low d 1) 0 + have hr := seq_straight h₁ (seq_straight h₂ (seq_straight h₃ (seq_straight h₄ (seq_straight h₅ + (seq_straight h₆ (seq_straight h₇ (seq_straight h₈ (seq_straight h₉ h₁₀)))))))) + have castu : (u : Word w) = rs (low d 2) := by rw [← hu]; simp + have hc : ((u * factor * denominator + 1 : ℕ) : Word w).val = u * factor * denominator + 1 := + Nat.mod_eq_of_lt hcap + have hl : (((u * factor)^2 * denominator + 1 : ℕ) : Word w).val = (u * factor)^2 * denominator + 1 := + Nat.mod_eq_of_lt hlimit + simp only [Nat.cast_add, Nat.cast_mul, Nat.cast_one, pow_two, castu] at hc hl + refine ⟨postRegs h₁₀, hr, ?_⟩ + simp (config := {decide := true}) [postRegs, BinaryOp.eval, Function.update, hc, hl, pow_two] + +private theorem tickBits (n : ℕ) : choiceBits (List.replicate n (Event.tick : Event w)) = [] := by + induction n with + | zero => rfl + | succ n ih => simpa [List.replicate_succ,choiceBits] using ih + +/-- Linked native execution of the preparation table reaches the choice block +with the exact cap and limit, without consuming a branch bit or making a probe. -/ +theorem prepareBounds_execute {p : ℕ} (factor denominator u : ℕ) {M : Machine w p (6+d) d} + {label : (prepareBounds d factor denominator).Label → Fin p} {stop bad : Fin p} + (hc : Flow.Linked M (prepareBounds d factor denominator) label stop bad) (hbad : M.code bad = .reject) + (s : Word w) (priv : Word w → Word w) (m : Memory w) (rs : Regs w (6+d)) (hu : (rs (low d 2)).val = u) + (hcap : u * factor * denominator + 1 < 2^w) + (hlimit : (u * factor)^2 * denominator + 1 < 2^w) : + ∃ out, (∀ (fuel : ℕ) (bits : List Bool), + execute M.program ((prepareBounds d factor denominator).length + fuel) + ⟨label (prepareBounds d factor denominator).entry,s,rs,priv⟩ m bits = + (execute M.program fuel ⟨stop,s,out,priv⟩ m bits).map + (Flow.prependEvents (List.replicate (prepareBounds d factor denominator).length .tick))) ∧ + out (low d 0) = 0 ∧ out (low d 1) = 0 ∧ out (low d 2) = rs (low d 2) ∧ + (out (low d 3)).val = u * factor * denominator + 1 ∧ out (low d 4) = 0 ∧ + (out (low d 5)).val = (u * factor)^2 * denominator + 1 ∧ ∀ j, out (slot j) = rs (slot j) := by + obtain ⟨out,hr,hs⟩ := prepareBounds_exec factor denominator u M.publicData s m rs hu hcap hlimit + refine ⟨out,fun fuel bits => ?_,hs⟩ + simpa only [List.length_replicate,tickBits,List.nil_append] using hr.execute hc hbad priv fuel bits + +end CompressorRecords.MotifChoiceRAM + +namespace CompressorRecords.MotifChoiceRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM +open MotifGrid MotifBlocks MotifConversion MotifSelector + +variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S] +variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ} +variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H') + +/-- The compiled call enters with the repetition count as its persistent word. +All private registers and memory start with the usual machine reset. -/ +def choiceCall (n : ℕ) (factor denominator : ℕ) : Flow (6+n) n := + .seq (.line (.stateWord (low n 2))) <| .seq (prepareBounds n factor denominator) (choosePayload n) + +/-- At every sufficiently wide word size the same fixed instruction table has +one successful stream per admitted outer index. This call begins at the native +machine entry point and includes all threshold preparation. -/ +theorem compiled_outer_choices {n : ℕ} (order : Fin n ≃ S) (hq : ∀ e, 0 < q e) : + ∃ K : ℕ, ∀ M (demand : D → ℕ), (∀ i, demand i ≤ M) → ∀ w, + K + 2 * Nat.clog 2 (M + 1) ≤ w → + let factor := B.scale * B.radius.num.natAbs + let denominator := MotifAdmission.denominator q + let code := choiceCall n factor denominator + let weights := fun i => Fin.ofNat (2^w) (MotifAdmission.weight q (order i) * B.radius.den^2) + let machine := (code.template none).instantiate w weights + let fuel := 1 + (prepareBounds n factor denominator).length + (n * (4*w+10) + 3) + let initial := machine.program.start (Fin.ofNat (2^w) (repetitions B demand)) + ∃ hw : outerCap B demand < 2^w, ∀ mem bits, + (execute machine.program fuel initial mem bits).isSome ↔ + ∃ v, (outerReader B order hq demand w hw).read bits = some (v, []) := by + obtain ⟨K, hK⟩ := native_word_fit p q B.scale B.scale_pos B.radius + refine ⟨K, fun M demand hD w hW => ?_⟩ + obtain ⟨hu, hc, hl, hs, ht⟩ := hK M demand hD + have hpow := Nat.pow_le_pow_right (by decide : 0 < 2) hW + let factor := B.scale * B.radius.num.natAbs + let denom := MotifAdmission.denominator q + let code := choiceCall n factor denom + let pub (i : Fin n) : BurstRAM.Word w := Fin.ofNat _ (MotifAdmission.weight q (order i) * B.radius.den^2) + let machine := (code.template none).instantiate w pub + let state : BurstRAM.Word w := Fin.ofNat _ (repetitions B demand) + let regs := Function.update (fun _ : Fin (6+n) => (0 : BurstRAM.Word w)) (low n 2) state + have hstate : state.val = repetitions B demand := Nat.mod_eq_of_lt (hu.trans_le hpow) + have hpub (i : Fin n) : (machine.publicData i).val = MotifAdmission.weight q (order i) * B.radius.den^2 := + Nat.mod_eq_of_lt ((ht (order i)).trans_le hpow) + have hstop : machine.code code.exitPC = .accept := by + change ((code.template none).code code.exitPC).resize w = _ + rw [Flow.template_exit]; rfl + have hbad : machine.code code.rejectPC = .reject := by + change ((code.template none).code code.rejectPC).resize w = _ + rw [Flow.template_reject]; rfl + have hlink := Flow.template_linked (w := w) code none pub + have hbox : outerCap B demand + 1 < 2^w := hc.trans_le hpow + refine ⟨(Nat.lt_succ_self _).trans hbox, fun mem bits => ?_⟩ + obtain ⟨out, hrun, _, _, h2, h3, h4, h5, _⟩ := prepareBounds_execute factor denom + (repetitions B demand) hlink.seqRight.seqLeft hbad state (fun _ => 0) mem regs (by simp [regs, hstate]) + (by simpa [factor, Nat.mul_assoc, MotifAdmission.payloadCap] using hbox) + (by simpa [factor, denom, repetitions, Nat.mul_assoc] using hl.trans_le hpow) + let cfg : Config w (code.length+2) (6+n) := + ⟨code.pc (.inr (.inr (choosePayload n).entry)),state,out,fun _ => 0⟩ + have cap : (cfg.reg (low n 3)).val = outerCap B demand + 1 := by + simpa [cfg, factor, denom, MotifAdmission.payloadCap, Nat.mul_assoc] using h3 + have sc : score (List.finRange n) machine.publicData (fun _ => cfg.reg (low n 3)) < 2 ^ w := by + rw [full_score order q B.radius _ _ hpub] + simpa [cap, outerCap, repetitions] using hs.trans_le hpow + have hchoose := choosePayload_execute_iff B order hq demand hlink.seqRight.seqRight hstop hbad cfg rfl + hpub (by simp [cfg, h2, regs, hstate]) cap (by simp [cfg, h4]) + (by simpa [cfg, factor, Nat.mul_assoc] using h5) sc mem bits + have hread : Flow.Exec pub state (.line (.stateWord (low n 2))) (fun _ => 0) mem [.tick] regs mem := .line rfl + let prep := prepareBounds n factor denom + let remaining := n * (4*w+10) + 3 + have hpre := hrun remaining bits + have hinit := hread.execute hlink.seqLeft hbad (fun _ => 0) (prep.length + remaining) bits + simp only [List.length_cons, List.length_nil, choiceBits, List.nil_append] at hinit + let mid : Config w (code.length+2) (6+n) := + ⟨code.pc (.inr (.inl prep.entry)),state,regs,fun _ => 0⟩ + change execute machine.program (1 + (prep.length + remaining)) (machine.program.start state) mem bits = + (execute machine.program (prep.length + remaining) mid mem bits).map _ at hinit + change execute machine.program (prep.length + remaining) mid mem bits = + (execute machine.program remaining cfg mem bits).map _ at hpre + change (execute machine.program (1 + prep.length + remaining) (machine.program.start state) mem bits).isSome ↔ _ + rw [Nat.add_assoc] + rw [hinit, Option.isSome_map, hpre, Option.isSome_map] + exact hchoose + +end CompressorRecords.MotifChoiceRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorChoiceRoot.lean b/lean/OAI/Computability/VPVNP/CompressorChoiceRoot.lean new file mode 100644 index 0000000000..3b8b8ac196 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorChoiceRoot.lean @@ -0,0 +1,181 @@ +import OAI.Computability.VPVNP.MotifAdmission +import OAI.Computability.VPVNP.PrimedInputRAMOnce + +/-! +# Native computation of the number of motif copies + +Binary search on the integer interval from zero to the demand energy computes +the least integer whose square, multiplied by the fixed denominator, reaches +that energy. The search runs the same native instruction table for all inputs. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RepetitionRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {w k : ℕ} + +/-- Registers 0 and 1 contain the numerator and denominator. Registers 2 and +3 hold the inclusive search interval, 4 and 5 hold one and two, and 6 and 7 +hold the midpoint and its test score. -/ +def body : Flow 8 k := + .seq (.line (.binary .add 6 2 3)) <| + .seq (.line (.binary .div 6 6 5)) <| + .seq (.line (.binary .mul 7 6 6)) <| + .seq (.line (.binary .mul 7 7 1)) <| + .ifLt 7 0 (.line (.binary .add 2 6 4)) (.line (.copy 3 6)) + +/-- Bisection includes the zero-energy case, for which the loop has no iterations. -/ +def root : Flow 8 k := + .seq (.line (.constant 2 0)) <| + .seq (.line (.copy 3 0)) <| + .seq (.line (.constant 4 1)) <| + .seq (.line (.constant 5 2)) (.whileLt 2 3 body) + +private def update (rs : Regs w 8) (i : Fin 8) (v : Word w) := Function.update rs i v + +private theorem bin (pub : Fin k → Word w) (s : Word w) (m : Memory w) (rs : Regs w 8) + (op : BinaryOp) (dst x y : Fin 8) : + Flow.Exec pub s (.line (.binary op dst x y)) rs m [.tick] (update rs dst (op.eval (rs x) (rs y))) m := + .line rfl + +private theorem next (pub : Fin k → Word w) (s : Word w) (m : Memory w) (rs : Regs w 8) + {n d lo hi : ℕ} (hn : (rs 0).val = n) (hd : (rs 1).val = d) + (hlo : (rs 2).val = lo) (hhi : (rs 3).val = hi) (h₁ : (rs 4).val = 1) (h₂ : (rs 5).val = 2) + (hlt : lo < hi) (hsum : lo + hi < 2^w) (hscore : hi^2 * d < 2^w) : + let mid := (lo + hi) / 2 + let below := mid^2 * d < n + ∃ out, Flow.Exec pub s body rs m (List.replicate 6 .tick) out m ∧ + (out 0).val = n ∧ (out 1).val = d ∧ (out 4).val = 1 ∧ (out 5).val = 2 ∧ + (out 2).val = (if below then mid + 1 else lo) ∧ + (out 3).val = (if below then hi else mid) := by + dsimp only + let mid := (lo+hi)/2 + let t := update rs 6 (rs 2 + rs 3) + let a := update t 6 (BinaryOp.div.eval (t 6) (t 5)) + let b := update a 7 (a 6 * a 6) + let c := update b 7 (b 7 * b 1) + have hm : mid < hi := by dsimp [mid]; omega + have hav : (a 6).val = mid := by + simp (config := {decide := true}) [a,t,update,BinaryOp.eval, + Fin.val_add,hlo,hhi,h₂,Nat.mod_eq_of_lt hsum,Nat.mod_eq_of_lt (hm.trans (hhi ▸ (rs 3).isLt)),mid] + have hcv : (c 7).val = mid^2 * d := by + have hfit := (Nat.mul_le_mul_right d (Nat.pow_le_pow_left hm.le 2)).trans_lt hscore + have hab : b 1 = rs 1 := by simp (config := {decide := true}) [b,a,t,update,Function.update] + change ((b 7 * b 1) : Word w).val = _ + rw [hab] + change ((a 6 * a 6) * rs 1).val = _ + rw [Fin.val_mul, Fin.val_mul, Nat.mod_mul_mod, hav, hd, ← pow_two, Nat.mod_eq_of_lt hfit] + have common (i : Fin 8) (hi₆ : i ≠ 6) (hi₇ : i ≠ 7) : c i = rs i := by + simp [c,b,a,t,update,Function.update_of_ne hi₆, Function.update_of_ne hi₇] + have midReg : (c 6).val = mid := by simpa (config := {decide := true}) [c,b,update,Function.update] using hav + have prefixExec (out : Regs w 8) + (h : Flow.Exec pub s (.ifLt 7 0 (.line (.binary .add 2 6 4)) (.line (.copy 3 6))) + c m [.tick,.tick] out m) : Flow.Exec pub s body rs m (List.replicate 6 .tick) out m := + .seq (bin pub s m rs .add 6 2 3) (.seq (bin pub s m t .div 6 6 5) + (.seq (bin pub s m a .mul 7 6 6) (.seq (bin pub s m b .mul 7 7 1) h))) + by_cases hz : mid^2 * d < n + · have ht : c 7 < c 0 := by rw [Fin.lt_def, hcv, common 0 (by decide) (by decide), hn]; exact hz + let out := update c 2 (c 6 + c 4) + have hnext : (out 2).val = mid+1 := by + change (c 6 + c 4).val = _ + rw [Fin.val_add,midReg,common 4 (by decide) (by decide),h₁,Nat.mod_eq_of_lt + ((show mid+1 ≤ hi by omega).trans_lt (hhi ▸ (rs 3).isLt))] + refine ⟨out, prefixExec out (.ifLtYes ht (bin pub s m c .add 2 6 4)), ?_⟩ + change _ ∧ _ ∧ _ ∧ _ ∧ (out 2).val = (if mid^2*d < n then mid+1 else lo) ∧ + (out 3).val = (if mid^2*d < n then hi else mid) + rw [ite_eq_left hz, ite_eq_left hz, hnext] + simp (config := {decide := true}) [out, update, common, hn, hd, hhi, h₁, h₂] + · have ht : ¬ c 7 < c 0 := by rw [Fin.lt_def,hcv,common 0 (by decide) (by decide),hn]; exact hz + let out := update c 3 (c 6) + refine ⟨out, prefixExec out (.ifLtNo ht (.line rfl)), ?_⟩ + simp (config := {decide := true}) [out,update,common, hn,hd,hlo,h₁,h₂,hz,midReg,mid] + +private theorem search (pub : Fin k → Word w) (s : Word w) (m : Memory w) {n d : ℕ} + (hdpos : 0 < d) (hfit : 2*n < 2^w) (hsq : n^2 * d < 2^w) (steps : ℕ) : + ∀ (rs : Regs w 8), (rs 0).val = n → (rs 1).val = d → (rs 4).val = 1 → (rs 5).val = 2 → + (rs 2).val ≤ MotifAdmission.ceilRoot n d → MotifAdmission.ceilRoot n d ≤ (rs 3).val → + (rs 3).val ≤ n → (rs 3).val - (rs 2).val < 2^steps → + ∃ count out, Flow.Exec pub s (.whileLt 2 3 body) rs m (List.replicate count .tick) out m ∧ + count ≤ 7*steps+1 ∧ (out 2).val = MotifAdmission.ceilRoot n d := by + induction steps with + | zero => + intro rs _ _ _ _ hlo hhi _ hspan + have heq : rs 2 = rs 3 := Fin.ext (by simp at hspan; omega) + exact ⟨1, rs, .whileDone (by simp [heq]), by simp, by simpa [heq] using Nat.le_antisymm hlo (heq ▸ hhi)⟩ + | succ steps ih => + intro rs hn hd h₁ h₂ hlo hhi hmax hspan + by_cases ht : rs 2 < rs 3 + · let lo := (rs 2).val + let hi := (rs 3).val + let mid := (lo+hi)/2 + have hlt : lo < hi := ht + have hsum : lo+hi < 2^w := by dsimp [lo,hi]; omega + have hscore := (Nat.mul_le_mul_right d (Nat.pow_le_pow_left hmax 2)).trans_lt hsq + obtain ⟨out, hrun, hn', hd', h₁', h₂', ha,hb⟩ := next pub s m rs hn hd rfl rfl h₁ h₂ hlt hsum hscore + change (out 2).val = (if mid^2*d < n then mid+1 else lo) at ha + change (out 3).val = (if mid^2*d < n then hi else mid) at hb + have hbounds : (out 2).val ≤ MotifAdmission.ceilRoot n d ∧ MotifAdmission.ceilRoot n d ≤ (out 3).val ∧ + (out 3).val ≤ n ∧ (out 3).val - (out 2).val < 2^steps := by + have hs : hi-lo < 2^steps * 2 := by simpa [lo, hi, pow_succ] using hspan + change lo ≤ _ at hlo + change _ ≤ hi at hhi + change hi ≤ n at hmax + by_cases hz : mid^2*d < n + · have hr : mid < MotifAdmission.ceilRoot n d := + lt_of_not_ge fun h => (Nat.not_le_of_gt hz) ((MotifAdmission.ceilRoot_le_iff _ _ _ hdpos).mp h) + simp only [hz, ↓reduceIte] at ha hb + dsimp [mid] at * + omega + · have hr := (MotifAdmission.ceilRoot_le_iff n d mid hdpos).mpr (Nat.le_of_not_gt hz) + simp only [hz, ↓reduceIte] at ha hb + dsimp [mid] at * + omega + obtain ⟨t,last,hloop,hlen,he⟩ := ih out hn' hd' h₁' h₂' hbounds.1 hbounds.2.1 hbounds.2.2.1 hbounds.2.2.2 + refine ⟨7+t,last,?_,by omega,he⟩ + simpa only [List.replicate_add, List.replicate_succ, List.replicate_zero, List.cons_append, List.nil_append] using Flow.Exec.whileStep ht hrun hloop + · have heq : (rs 2).val = MotifAdmission.ceilRoot n d := Nat.le_antisymm hlo (hhi.trans (Fin.not_lt.mp ht)) + exact ⟨1,rs,.whileDone ht,by omega,heq⟩ + +/-- Complete computation of the integral ceiling test with at most seven +instructions per binary digit of the numerator, including all loop tests. +Every recorded event is a private deterministic tick. -/ +theorem root_exec (pub : Fin k → Word w) (s : Word w) (m : Memory w) (rs : Regs w 8) + (n d : ℕ) (hn : (rs 0).val = n) (hd : (rs 1).val = d) (hdpos : 0 < d) + (htwo : 2 < 2^w) (hsum : 2*n < 2^w) (hsq : n^2*d < 2^w) : + ∃ count out, Flow.Exec pub s root rs m (List.replicate count .tick) out m ∧ + count ≤ 7*n.size+5 ∧ (out 2).val = MotifAdmission.ceilRoot n d := by + let a := update rs 2 0 + let b := update a 3 (a 0) + let c := update b 4 (Fin.ofNat (2^w) 1) + let t := update c 5 (Fin.ofNat (2^w) 2) + have hr : MotifAdmission.ceilRoot n d ≤ n := (MotifAdmission.ceilRoot_le_iff _ _ _ hdpos).mpr + ((Nat.le_self_pow (by decide) n).trans (Nat.le_mul_of_pos_right _ hdpos)) + have one : 1 % 2^w = 1 := Nat.mod_eq_of_lt (by omega) + have two : 2 % 2^w = 2 := Nat.mod_eq_of_lt htwo + have hn' : (t 0).val = n := by simp (config := {decide := true}) [t,c,b,a,update,Function.update, hn] + have hd' : (t 1).val = d := by simp (config := {decide := true}) [t,c,b,a,update,Function.update, hd] + have hlo : (t 2).val = 0 := by simp (config := {decide := true}) [t,c,b,a,update,Function.update] + have hhi : (t 3).val = n := by simp (config := {decide := true}) [t,c,b,a,update,Function.update,hn] + have h₁ : (t 4).val = 1 := by simpa (config := {decide := true}) [t,c,update,Function.update] using one + have h₂ : (t 5).val = 2 := by simpa [t,update] using two + obtain ⟨count,out,he,hlen,hroot⟩ := search pub s m hdpos hsum hsq n.size t hn' hd' h₁ h₂ + (hlo ▸ Nat.zero_le _) (hhi ▸ hr) (hhi ▸ le_rfl) (by simpa [hhi,hlo] using Nat.lt_size_self n) + refine ⟨4+count,out,?_,by omega,hroot⟩ + have init₁ : Flow.Exec pub s (.line (.constant 2 0)) rs m [.tick] a m := .line rfl + have init₂ : Flow.Exec pub s (.line (.copy 3 0)) a m [.tick] b m := .line rfl + have init₃ : Flow.Exec pub s (.line (.constant 4 1)) b m [.tick] c m := .line rfl + have init₄ : Flow.Exec pub s (.line (.constant 5 2)) c m [.tick] t m := .line rfl + simpa only [root, List.replicate_add, List.replicate_succ, List.replicate_zero, List.cons_append, List.nil_append] + using Flow.Exec.seq init₁ (.seq init₂ (.seq init₃ (.seq init₄ he))) + +end CompressorRecords.RepetitionRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorChronologicalRate.lean b/lean/OAI/Computability/VPVNP/CompressorChronologicalRate.lean new file mode 100644 index 0000000000..d4bd8bc2b5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorChronologicalRate.lean @@ -0,0 +1,71 @@ +import OAI.Computability.VPVNP.CompressorInitialBoundary +import OAI.Computability.VPVNP.CompressorInitialTraceEquiv +import OAI.Computability.VPVNP.CompressorNativePassRates + +/-! # A single communication rate for the selected chronological descriptor run -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM Compression PairSimulation.LocalHistory + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- The initial four rows, one native pass rate for each of the fixed substeps, +and the final calendar call. This coefficient is fixed before the input length. -/ +noncomputable def chronologicalRate (raw : ℕ) : ℕ := + 2 * initialRate B + (S.steps+1) * nativePassRate (BlockProgram.script B) raw + 4 + +theorem chronological_charge (raw positions T n : ℕ) (positive : 0 < positions) + (blocks : T ≤ n.log2+1) : + initialRate B*(positions+1) + (T*(S.steps+1))*(nativePassRate (BlockProgram.script B) raw*positions)+4 ≤ + chronologicalRate B raw * positions * (n.log2+1) := by + let L := n.log2+1 + have hL : 0 < L := Nat.succ_pos _ + have init : initialRate B*(positions+1) ≤ (2*initialRate B*positions)*L := calc + _ ≤ initialRate B*(2*positions) := Nat.mul_le_mul_left _ (by omega) + _ = 2*initialRate B*positions := by ring + _ ≤ _ := Nat.le_mul_of_pos_right _ hL + have repeatCharge := Nat.mul_le_mul_right ((S.steps+1)*(nativePassRate (BlockProgram.script B) raw*positions)) blocks + have last : 4 ≤ 4*positions*L := + (Nat.le_mul_of_pos_right 4 positive).trans (Nat.le_mul_of_pos_right _ hL) + unfold chronologicalRate + change _ ≤ (2*initialRate B+(S.steps+1)*nativePassRate (BlockProgram.script B) raw+4)*positions*L + change T*_ ≤ L*_ at repeatCharge + calc + _ = initialRate B*(positions+1) + T*((S.steps+1)*(nativePassRate (BlockProgram.script B) raw*positions)) + 4 := by ring + _ ≤ 2*initialRate B*positions*L + L*((S.steps+1)*(nativePassRate (BlockProgram.script B) raw*positions)) + 4*positions*L := + Nat.add_le_add (Nat.add_le_add init repeatCharge) last + _ = _ := by ring + +variable {B} {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} +variable {w base T cap small b l width n : ℕ} {pub : Fin 11 → Word w} {m : Memory w} +variable {X : State (S.degreeExponent 0) l} {a g : ℕ} {E : StateExecution R a g X} +variable {origin : PassOrigins B f hf E} {W : E.MapWitnesses f} {readers : ExecutionReaders E W} +variable {resident : Resident B f hf w} {pitch : Word w} {total : ℕ} {past : List (SelectedLevel B f hf)} + +/-- Charge the reports of the initial native interval and the recursive +scheduled result on this same branch. Repeated passes appear with their +multiplicity in the budget carried by the result. -/ +theorem InitialInterval.chronologicalRate_le (raw : ℕ) + (init : InitialInterval B base X.positions T cap small b l width pub m) + (cursor : BlockStartupPrefix.Resident (BlockProgram.layout B base X.positions T) (S.degreeExponent 0) + b l width n (pub 2) m X) + (result : Result resident pub pitch total cap small + (T*(S.steps+1)*(nativePassRate (BlockProgram.script B) raw*X.positions)+4) + E origin W readers past init.interval.segment.state init.interval.segment.memory) + (blocks : T ≤ n.log2+1) (z : E.Choices) : + RAMBuckets.cost Report.probes (init.interval.combinedCore result.trace result.source z).logs ≤ + chronologicalRate B raw * X.positions * (n.log2+1) := by + rw [init.interval.combinedCost] + exact (Nat.add_le_add (init.rate cursor) (result.cost z)).trans (by + simpa only [Nat.add_assoc] using chronological_charge B raw X.positions T n X.positions_pos blocks) + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCompiledResident.lean b/lean/OAI/Computability/VPVNP/CompressorCompiledResident.lean new file mode 100644 index 0000000000..3d4f1b4baf --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCompiledResident.lean @@ -0,0 +1,149 @@ +import OAI.Computability.VPVNP.CompressorDetailedResident +import OAI.Computability.VPVNP.CompressorSelectedChildDirectory +import OAI.Computability.VPVNP.CompressorSelectedPayloadReadback +import OAI.Computability.VPVNP.CompressorRefreshPayloadHistory +import OAI.Computability.VPVNP.PairShrinkResidentHeaderWords +import OAI.Computability.VPVNP.PairShrinkResidentSources +import OAI.Computability.VPVNP.PairShrinkPhysicalSourceBounds + +/-! +# Resident data from the two compiled compressor passes + +The selected origin fixes the input state and the type of its choice. +A shrink stores its term, ranking and slot tables together with the +published party header words. A refresh stores its demand and term records, +input and output incidence, and traversal geometry. The chronological +level gives the addresses at which later site workers read these records. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.CompiledResident + +open BurstRAM Compression DescriptorSpace PairSimulation PairSimulation.LocalHistory +open SelectedPayloadHistory +open scoped Fin.CommRing + +variable {w : ℕ} {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) +variable (workspace : Word w) (positions blocks n : ℕ) +local notation "L" => BlockProgram.layout B workspace.val positions blocks + +/-- The selected shrinking sources, address bounds and published headers. -/ +structure ShrinkPayload (cur : ℕ) (i : Fin S.steps) {g : ℕ} + (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) + (sel : SelectedScore.Selection B X) (m : Memory w) : Prop where + bounds : ShrinkResidentSources.Bounds B i X workspace positions blocks cur + sources : ShrinkResidentSources.Data B i X (S.shrink i) sel workspace positions blocks cur m + words : ShrinkResidentHeaders.Words B i X sel workspace positions blocks cur n m + child : SelectedChildDirectory.Stored B L cur n X m + termRun : ∃ (dense : Word w) (fuel : ℕ) (before : Memory w) (reports : List (Report w)), + ShrinkTermSelection.Written B.shrink X dense + (ShrinkInput.termHead X (tableBase L cur (0 : Fin 6))) 10 fuel sel before reports + +/-- The selected refresh sources and their readback bounds. The placement +publisher also records the DFS row stride for this chronological level. -/ +structure RefreshPayload (cur : ℕ) {g : ℕ} (X : State S.portExponent (S.portExponent+g)) + (choice : Refresh.DyadicRefreshChoice (a₀ := S.degreeExponent 0) (g := g) X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (m : Memory w) : Prop where + live : cur+1 < (L).levels + size : X.positions ≤ positions + fit : endAddress L < 2^w + sources : RefreshPayloadHistory.Data B L cur n X choice m + child : SelectedChildDirectory.Stored B L cur n X m + +private def shrinking : Shrinking (w := w) B f hf := by + intro cur i g lanes h X sel _ m + subst lanes + exact ShrinkPayload B workspace positions blocks n cur i X sel m + +private def refreshing : Refreshing (w := w) B := + fun cur {_} X choice _ m => RefreshPayload B workspace positions blocks n cur X choice m + +/-- Select the native payload corresponding to the pass that was actually +executed and the term that its branch selected. -/ +def payload : Data (w := w) B f hf := + byOrigin (shrinking B f hf workspace positions blocks n) (refreshing B workspace positions blocks n) + +theorem shrink_payload (cur : ℕ) (i : Fin S.steps) {g : ℕ} + (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) + (sel : SelectedScore.Selection B X) (bits : List Bool) (m : Memory w) : + payload B f hf workspace positions blocks n cur ⟨_,_,_,_,X,_,.shrink i rfl X,sel,bits⟩ m ↔ + ShrinkPayload B workspace positions blocks n cur i X sel m := Iff.rfl + +theorem refresh_payload (cur : ℕ) {g : ℕ} (X : State S.portExponent (S.portExponent+g)) + (choice : Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (bits : List Bool) (m : Memory w) : + payload B f hf workspace positions blocks n cur ⟨_,_,_,_,X,_,.refresh X,choice,bits⟩ m ↔ + RefreshPayload B workspace positions blocks n cur X choice m := Iff.rfl + +/-- The concrete boundary predicate for the compiled calendar. -/ +abbrev resident (initial : TraversalRoles.TaggedLayer) (initialFrame : Fin 8 → Word w) : + ScheduledTrace.Resident B f hf w := + DetailedResident.resident B f hf initial L (endAddress L) n initialFrame + (payload B f hf workspace positions blocks n) + +variable {B f hf workspace positions blocks n} + +/-- All fields read by either kind of site parser transfer from its +producing memory on the region retained for this particular occurrence. -/ +theorem payload_transfer {cur : ℕ} {v : SelectedLevel B f hf} {m out : Memory w} + (h : payload B f hf workspace positions blocks n cur v m) (same : SourceTransport.Agree (Cells L cur) m out) : + payload B f hf workspace positions blocks n cur v out := by + obtain ⟨a,g,b,l,X,p,o,c,bits⟩ := v + cases o with + | shrink i eq X => + subst eq + have d := (shrink_payload ..).mp h + exact (shrink_payload ..).mpr ⟨d.bounds,d.sources.transfer d.bounds same,d.words.transfer same, + d.child.transfer same,d.termRun⟩ + | refresh X => + have d := (refresh_payload ..).mp h + exact (refresh_payload ..).mpr ⟨d.live,d.size,d.fit,d.sources.transfer rfl d.live d.size d.fit same, + d.child.transfer same⟩ + +/-- Recover the concrete native sources directly in the current memory. -/ +theorem read {past : List (SelectedLevel B f hf)} {m : Memory w} + (h : Past B f hf L (payload B f hf workspace positions blocks n) past m) (i : Fin past.length) : + payload B f hf workspace positions blocks n i.val past[i] m := + h.atLevel i (fun _ d same => payload_transfer d same) + +/-- The child scan's operands are available for every selected pass. -/ +theorem child_directory {cur : ℕ} {v : SelectedLevel B f hf} {m : Memory w} + (h : payload B f hf workspace positions blocks n cur v m) : + SelectedChildDirectory.Stored B L cur n v.input m := by + obtain ⟨a,g,b,l,X,p,o,c,bits⟩ := v + cases o with + | shrink i eq X => + subst eq + exact ((shrink_payload ..).mp h).child + | refresh X => exact ((refresh_payload ..).mp h).child + +/-- Every selected pass publishes the same DFS row stride. -/ +theorem stride_word {cur : ℕ} {v : SelectedLevel B f hf} {m : Memory w} + (h : payload B f hf workspace positions blocks n cur v m) : + m (levelStart L cur+15) = ((B.recordLimit+2 : ℕ) : Word w) := + (child_directory h).stride + +/-- The parser for a shrinking occurrence can read its successor's stride +from the actual selected history, including the shrink just before refresh. -/ +theorem shrink_successor_stride {lanes : ℕ} {hT : blocks*S.laneBits ≤ lanes} + {X : State (S.degreeExponent 0) lanes} {z : (B.execute f hf blocks hT X).Choices} {m : Memory w} + (h : Past B f hf L (payload B f hf workspace positions blocks n) (executeLevels B f hf blocks hT X z) m) + (i : Fin (executeLevels B f hf blocks hT X z).length) + (shrink : (executeLevels B f hf blocks hT X z)[i].origin.ordinal < S.steps) : + m (levelStart L (i.val+1)+15) = ((B.recordLimit+2 : ℕ) : Word w) := + SelectedPayloadHistory.shrink_successor_stride h i shrink + (by change 15 < 66 + _ + _; omega) (fun _ _ published => stride_word published) + +end CompressorRecords.CompiledResident + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCompleteShrinkRates.lean b/lean/OAI/Computability/VPVNP/CompressorCompleteShrinkRates.lean new file mode 100644 index 0000000000..ae0ffd0c9f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCompleteShrinkRates.lean @@ -0,0 +1,257 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkBuild +import OAI.Computability.VPVNP.CompressorShrinkLevelSpace +import OAI.Computability.VPVNP.CompressorScheduledSlotRates +import OAI.Computability.VPVNP.CompressorScheduledGreedyRates +import OAI.Computability.VPVNP.CompressorOrdinalProgress + +/-! +# Uniform traffic of a complete admitted shrinking branch + +The source trace includes the relocated greedy program, all dense rank and width +scans, the admitted motif calls, chosen scores, roles and preimages, and the +physical surviving-width and slot outputs. The coefficients precede the state +and its term choices. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledRates + +open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif +open PhaseCosts ShrinkBranch + +open private packed_le motif_le selected_motifs positions_eq from + OAI.Computability.VPVNP.CompressorShrinkLevelSpace + +/-- The source-slot bound for the degree transition, evaluated on its fixed +role subdivisions and chosen output degree. -/ +private noncomputable def transitionSlotRate (a b : ℕ) := + let d := 2 ^ a + let c := Shrink.colors a + let sub := subdivisions d c (2 ^ b) + let u := 4*d*(2^c*d)*(∑ t, sub t) + 30+26*u+20*(2^b-survivingDegree d c sub)+44*2^b + +/-- All shrinking reports up through the chosen role and preimage directories, +before the AB, surviving-width, and ordered-slot passes. -/ +noncomputable def selectedRate {k : Type*} [_root_.Field k] {S : BlockSchedule k} + (B : S.Templates) (a : ℕ) := + let d := 2 ^ a + let Q := ShrinkRankSpace.cap a + greedyRate d + 32 + (Q+53)*d + (50+TermRecordScan.probesPerRow B.shrink 2 8)*(d*Q) + +/-- Complete source calls plus probes per incoming position. -/ +noncomputable def completeRate {k : Type*} [_root_.Field k] {S : BlockSchedule k} + (B : S.Templates) (a b : ℕ) := + let d := 2 ^ a + let Q := ShrinkRankSpace.cap a + let k₀ := TermRecordScan.probesPerRow B.shrink 2 8 + greedyRate d + 32 + (Q+53)*d + (50+k₀+18*ShrinkLevelSpace.subdivisionSum a b)*(d*Q) + + transitionSlotRate a b + +/-- Fixed deterministic clocks and the supplied admission clock. -/ +def completeCap (a termCap : ℕ) := + max (max (max 66 (20+9*ShrinkRankSpace.cap a)) (CatalogRates.greedyShrinkCap (2 ^ a))) + (max (ShrinkSliceSweep.SurvivingNative.ops.length+1) termCap) + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {a b g w : ℕ} {δ : ℝ} (X : State a (packingLaneBits a g)) +variable (ready : Ready (2 ^ a) (Shrink.colors a) (2 ^ b) δ) +variable (T : IncidenceDirectory w) (start : ℕ) (stride selectors : Word w) (cap : ℕ) + +private theorem scoreAxesCap (L : TermScores.Tables w) (n : ℕ) (as : List (TermScores.Axis w)) + (m : Memory w) (rs : List (Report w)) (h : TermScores.runAxes L n as m = some rs) : + ∀ r ∈ rs, r.events.length+1 ≤ 27 := by + induction as generalizing m rs with + | nil => + have e : [] = rs := Option.some.inj h + simp [← e] + | cons a as ih => + simp only [TermScores.runAxes,Bind.bind] at h + cases h₁ : runSegment (TermScores.workerMachine L a).program 27 (some 0) m + (List.replicate n []) with + | none => simp [h₁] at h + | some first => + cases h₂ : TermScores.runAxes L n as (after m (eventLog first)) with + | none => simp [h₁,h₂] at h + | some last => + have e : first++last = rs := by simpa [h₁,h₂] using h + subst rs + intro r hr + exact (List.mem_append.mp hr).elim (run_cap h₁ r) (ih _ _ h₂ r) + +private theorem scoreCap (L : TermScores.Tables w) (n : ℕ) (as : List (TermScores.Axis w)) + (m : Memory w) (rs : List (Report w)) (h : TermScores.run L n as m = some rs) : + ∀ r ∈ rs, r.events.length+1 ≤ 27 := by + simp only [TermScores.run,TermScores.execute_clear,Bind.bind,Option.bind_some] at h + let m₁ := after m (TermScores.clearReport L).events + cases hs : TermScores.runAxes L n as m₁ with + | none => rw [hs] at h; contradiction + | some rows => + let m₂ := after m₁ (eventLog rows) + rw [hs] at h + simp only [Option.bind_some,TermScores.execute_compare, pure, Option.some.injEq] at h + subst rs + intro rep hr + simp only [List.mem_cons,List.mem_append,List.mem_nil_iff,or_false] at hr + rcases hr with rfl|hh|rfl + · exact (by decide : 6+1 ≤ 27) + · exact scoreAxesCap L n as m₁ rows hs rep hh + · rw [(TermScores.compare_report_cost L m₂).1]; decide + +private theorem inputClock {m : Memory w} (p : ShrinkInput.Run X T start m) (cap : ℕ) : + ∀ r ∈ p.reports, r.events.length+1 ≤ completeCap a cap := by + classical + have fixed : 66 ≤ completeCap a cap := + ((le_max_left ..).trans (le_max_left ..)).trans (le_max_left ..) + have rank : 20+9*ShrinkRankSpace.cap a ≤ completeCap a cap := + ((le_max_right ..).trans (le_max_left ..)).trans (le_max_left ..) + have greedy : max 14 (CatalogRates.greedyShrinkCap (2^a)) ≤ completeCap a cap := + max_le ((by decide : 14 ≤ 66).trans fixed) ((le_max_right ..).trans (le_max_left ..)) + intro r hr + simp only [ShrinkInput.Run.reports,List.mem_append] at hr + rcases hr with (((((((((g|p₀)|cl)|cf)|ap)|ga)|rk)|sc)|th)|cd)|ab + · exact ((greedyProgram X T start m p.greedy).2.2 r g).trans greedy + · exact (run_cap p.positions r p₀).trans ((by decide : 65 ≤ 66).trans fixed) + · exact (run_cap p.ranking.clear r cl).trans ((by decide : 8 ≤ 66).trans fixed) + · exact (run_cap p.ranking.ranked.classify r cf).trans ((by decide : 66 ≤ 66).trans fixed) + · exact (run_cap p.ranking.ranked.append r ap).trans ((by decide : 23 ≤ 66).trans fixed) + · exact (run_cap p.ranking.ranked.gather r ga).trans ((by decide : 29 ≤ 66).trans fixed) + · rw [(p.ranking.ranked.rank.calls r rk).2,PortRankRAM.visit_length] + exact (by omega : 19+9*ShrinkRankSpace.cap a+1 ≤ 20+9*ShrinkRankSpace.cap a).trans rank + · exact (run_cap p.widths.scatter r sc).trans ((by decide : 19 ≤ 66).trans fixed) + · exact (run_cap p.widths.prefixes.thick.executed r th).trans ((by decide : 25 ≤ 66).trans fixed) + · exact (run_cap p.widths.prefixes.motif.executed r cd).trans ((by decide : 25 ≤ 66).trans fixed) + · exact (run_cap p.widths.ab r ab).trans ((by decide : 30 ≤ 66).trans fixed) + +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "role" => SelectedArena.roleBase X term stride +local notation "retained" => SelectedFinish.stop X term stride +local notation "sh" => ShrinkSlots.levelShape (b := b) X +local notation "M" => ShrinkOutput.motifCount X + +/-- Charge and instruction clock of the real pre-slice execution. The +coefficient depends on the transition degree and the finite term block. -/ +theorem selectedReports {m : Memory w} {p : Prefix X T start cap m} {s : SelectedScore.Selection B X} + (selected : Selected B X T start stride selectors cap m p s) : + RAMBuckets.cost Report.probes (p.reports++selected.reports) ≤ X.positions*selectedRate B a ∧ + ∀ rep ∈ p.reports++selected.reports, rep.events.length+1 ≤ completeCap a cap := by + classical + let d := 2^a + let Q := ShrinkRankSpace.cap a + let N := Fintype.card X.Base + let V := X.positions + let P := ShrinkPreimages.newCount X + let D := P*d + let A := V*d + let Tm := TermRecordScan.probesPerRow B.shrink 2 8 + let t := Greedy.WalkLayout.tagCount d + let G := 16+7*d+8*d^2+5*t+8*t^2 + have hN : N ≤ V := by + change Fintype.card X.Base ≤ X.positions + rw [← positions_eq X]; exact Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _) + have hP : P ≤ V := packed_le X + have hD : D ≤ V*d := Nat.mul_le_mul_right _ hP + have hM : ShrinkOutput.motifCount X ≤ V*(d*Q) := motif_le X + have pre := p.input.reports_cost + change RAMBuckets.cost Report.probes p.input.reports = + 2+N*G+9*ShrinkPreimages.oldCount X+4*D+(Q+33)*(ShrinkPreimages.oldCount X*d)+4*(ShrinkOutput.motifCount X) at pre + rw [show ShrinkPreimages.oldCount X = V from positions_eq X] at pre + have abs : RAMBuckets.cost Report.probes p.absolute = 5*A := by + rw [p.absoluteRun.charge]; change 5*(ShrinkPreimages.oldCount X*d) = 5*A + rw [show ShrinkPreimages.oldCount X = V from positions_eq X] + have gather : RAMBuckets.cost Report.probes p.gather = 5*(ShrinkOutput.motifCount X) := by + rw [SourceOnline.packet_cost,p.gatherRun.count,p.gatherRun.probes]; change (ShrinkOutput.motifCount X)+4*(ShrinkOutput.motifCount X) = 5*(ShrinkOutput.motifCount X); ring + have terms : RAMBuckets.cost Report.probes selected.terms ≤ (ShrinkOutput.motifCount X)*(1+Tm) := by + have n : ShrinkTermInputs.motifCount X = ShrinkOutput.motifCount X := selected_motifs X + have small := selected.termRun.probes + rw [n] at small + rw [SourceOnline.packet_cost,selected.termRun.count,n,Nat.mul_add,Nat.mul_one] + exact Nat.add_le_add_left small _ + have geometry := ChosenGeometry.Run.charge B X term stride selectors _ T s _ _ + selected.geometry selected.postTerm + change RAMBuckets.cost Report.probes selected.geometry.reports = + (40*SelectedArena.motifs X+7)+9*SelectedArena.positions X+11*DemandRAM.oldCount X+ + (2*P+5*ShrinkPreimages.oldCount X) at geometry + rw [selected_motifs X,show SelectedArena.positions X = V from positions_eq X, + show DemandRAM.oldCount X = A from congrArg (·*d) (positions_eq X), + show ShrinkPreimages.oldCount X = V from positions_eq X] at geometry + have eqRate : selectedRate B a = G+2+32+(Q+53)*d+(50+Tm)*(d*Q) := by + dsimp only [selectedRate,greedyRate,G,d,Q,Tm,t]; ring + constructor + · simp only [Prefix.reports,Selected.reports,RAMBuckets.cost_append] + rw [pre,abs,gather,geometry,eqRate] + change _ ≤ V*_ + dsimp only [A] at * + linarith only [terms,hD,hP,Nat.mul_le_mul_right G hN,X.positions_pos, + Nat.mul_le_mul_right (50+Tm) hM] + · have fixed : 66 ≤ completeCap a cap := + ((le_max_left ..).trans (le_max_left ..)).trans (le_max_left ..) + have cap' : cap ≤ completeCap a cap := (le_max_right ..).trans (le_max_right ..) + intro rep hr + simp only [Prefix.reports,Selected.reports, + ChosenGeometry.Construction.reports,SelectedStage.Passes.all,List.mem_append] at hr + rcases hr with ((ip|ia)|ig)|(it|((hs|hp)|hd)|hc|hf) + · exact inputClock X T start p.input cap rep ip + · exact (run_cap p.absoluteRun.native rep ia).trans ((by decide : 25 ≤ 66).trans fixed) + · exact (run_cap p.gatherRun.run rep ig).trans cap' + · exact (run_cap selected.termRun.run rep it).trans cap' + · exact (scoreCap _ _ _ _ _ selected.postTerm.placed.scores rep hs).trans + ((by decide : 27 ≤ 66).trans fixed) + · exact (run_cap selected.postTerm.placed.positions rep hp).trans + ((by decide : 65 ≤ 66).trans fixed) + · exact (run_cap selected.postTerm.placed.roles rep hd).trans + ((by decide : 65 ≤ 66).trans fixed) + · exact (run_cap selected.postTerm.geometry.raw.clear rep hc).trans + ((by decide : 8 ≤ 66).trans fixed) + · exact (run_cap selected.postTerm.geometry.raw.collect rep hf).trans + ((by decide : 23 ≤ 66).trans fixed) + +/-- A bound on the exact complete run built by `ShrinkBranch.build_complete`. +The returned coefficient and per-call clock are uniform over admitted branches. -/ +theorem completeReports {m : Memory w} {p : Prefix X T start cap m} + {s : SelectedScore.Selection B X} (r : Complete B X ready T start stride selectors cap m p s) : + RAMBuckets.cost Report.probes r.reports ≤ X.positions*completeRate B a b ∧ + ∀ rep ∈ r.reports, rep.events.length+1 ≤ completeCap a cap := by + classical + let d := 2^a + let Q := ShrinkRankSpace.cap a + let V := X.positions + let U := ShrinkLevelSpace.subdivisionSum a b + have hM : M ≤ V*(d*Q) := motif_le X + have selected := selectedReports B X T start stride selectors cap r.selected + let bank := ShrinkOutput.splitBank (b := b) X B.shrink s term stride.val role retained + let heads := ShrinkOutput.slotHeads (b := b) X (term).val stride.val role retained + have slot := selectedSlotProgram X B.shrink ready s heads bank.widthBase T r.output.postWidths + r.output.slots r.outputRun.construction.slots + have slotWork : RAMBuckets.cost Report.probes r.output.slots.all ≤ V*transitionSlotRate a b := by + have more := slot.2.1 + rw [RAMBuckets.cost_append] at more + exact (Nat.le_add_right ..).trans more + have out := r.outputRun.probes + change RAMBuckets.cost Report.probes r.output.reports = 18*(M*U)+ShrinkOutput.slotProbes sh at out + rw [← r.outputRun.construction.probes] at out + have eqRate : completeRate B a b = selectedRate B a + 18*U*(d*Q) + transitionSlotRate a b := by + dsimp only [completeRate,selectedRate,d,Q,U]; ring + constructor + · change RAMBuckets.cost Report.probes ((p.reports++r.selected.reports)++r.output.reports) ≤ _ + rw [RAMBuckets.cost_append,out,eqRate] + linarith only [selected.1,slotWork,Nat.mul_le_mul_right (18*U) hM] + · intro rep hr + change rep ∈ (p.reports++r.selected.reports)++r.output.reports at hr + rcases List.mem_append.mp hr with hi|ho + · exact selected.2 rep hi + have fixed : 66 ≤ completeCap a cap := + ((le_max_left ..).trans (le_max_left ..)).trans (le_max_left ..) + rcases List.mem_append.mp ho with os|ot + · obtain ⟨_,_,site⟩ := r.outputRun.sweep.sites os + rw [site.length]; exact (le_max_left ..).trans (le_max_right ..) + · exact (slot.2.2 rep (List.mem_append_left _ ot)).trans ((by decide : 49 ≤ 66).trans fixed) + +end CompressorRecords.ScheduledRates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCoordinateBudgets.lean b/lean/OAI/Computability/VPVNP/CompressorCoordinateBudgets.lean new file mode 100644 index 0000000000..95716462d7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCoordinateBudgets.lean @@ -0,0 +1,127 @@ +import OAI.Computability.VPVNP.CompressorReaderBudgets +import OAI.Computability.VPVNP.RankQueryPrepareResources +import OAI.Computability.VPVNP.RankQueryReaderFits + +/-! +# Uniform coordinate-reader resources for the compressor evaluator + +The base matrix and the prepared Frobenius or label target share the raw +entry budget. The common address width also covers every weighted-Gram +rank query in both orientations. The bounds below are chosen before the +prime, affine slice and entry ordinals. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open LabelEvaluator JointLabelSystem RadicalCertificate.MonomialIndex RankQuery.Stack.Coordinate +open ConcreteResources + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Word width required by the compressor's coordinate reader plan at the given characteristic, +exponent bound and input length. -/ +noncomputable def coordinateWidth (q c n : ℕ) := planWidth (B.compressorReaderPlan q c n) + +theorem coordinateWidth_polynomial (q c : ℕ) : PolynomiallyBounded (B.coordinateWidth q c) := + (planSizes (B.compressorReaderWidths q c).1).2.2 + +local instance coordinateBudgetsPrimeFact (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩ + +/-- All numerical premises for the physical coordinate query at the prime +selected for this length, including each operation's powered target. -/ +theorem compressorCanonicalFits (q c : ℕ) {n : ℕ} (hn : 2 ≤ n) (p : Nat.Primes) + [DecidableEq (Ground p (B.compressorLabelCount c n) (B.compressorDegree n))] + (model : Model p (B.compressorDegree n) (B.compressorEquations hn c)) + (hq : q ≠ 0 → p.val = q) (hz : q = 0 → p.val ≤ 2^(B.compressorPrimeBits c n)) + {w : ℕ} (hw : B.coordinateWidth q c n ≤ w) (sp ex : ℕ) : + let plan := B.compressorReaderPlan q c n + let data := model.queryData (B.compressorCoeff hn c) + let degree := B.readerDegreeBudget q c n + let limb := B.readerLimbBudget q c n + let e := SliceField.extensionDegree p.val (columnCountBound (B.compressorLabelCount c n) (B.compressorDegree n)) + CanonicalFits data (planDepth plan) w limb e (plan.live degree limb w sp) + (plan.armSpace degree limb w sp) (plan.readTime degree limb w sp ex) ∧ SliceArithmetic.Word.workingWidth p.val ≤ limb := by + obtain ⟨covers,he,hv⟩ := B.compressorReaderCovers q c hn p model hq hz + exact ⟨canonicalFits covers hw he le_rfl sp ex,hv⟩ + +/-- The physical coefficient-counting leaf must fit the same raw budget for +every prime, field representation, and input length. -/ +def SignedCallFits (q c : ℕ) (w signedSpace signedExp : ℕ → ℕ) : Prop := + ∀ n (hn : 2 ≤ n) (p e v : ℕ), e ≤ B.readerDegreeBudget q c n → v ≤ B.readerLimbBudget q c n → + let layout := JointScalar.Leaf.layout B.Entry B.EquationIndex B.equation c hn (w n) p e v + let counter := JointScalar.checker B.Entry B.EquationIndex B.equation c hn (w n) + let bank := JointScalar.Leaf.bankSize layout (w n) (B.compressorLabelCount c n*w n) + let work := JointScalar.Leaf.localCost layout bank + max (UniversalCountStack.stackLimit counter) bank + work ≤ signedSpace n ∧ + 2*(2^layout.witnessBits * UniversalCountStack.perChoice counter) + work ≤ 2^(signedExp n) + +/-- Space and time budget for a prepared compressor coordinate query, combining the reader +plan's depth, address range, arithmetic sizes and label count. -/ +noncomputable def coordinateBudget (P H K : Type) [Fintype P] [Fintype H] [Fintype K] + (q c n w signedSpace signedExp : ℕ) : Cost.Budget := + let plan := B.compressorReaderPlan q c n + let e := B.readerDegreeBudget q c n + let v := B.readerLimbBudget q c n + let A := plan.live e v w signedSpace + let S := plan.armSpace e v w signedSpace + let T := plan.readTime e v w signedSpace signedExp + preparedMaximum P H K plan.addressLimit (planDepth plan) w e v T A S T (B.compressorLabelCount c n) + +/-- A single length-indexed budget dominates the complete mounted scalar +reader, including its Cramer setup and its recursive calls to the Macaulay +coefficient reader. It allows any polynomial enlargement of the address +width needed by the enclosing evaluator. -/ +theorem coordinateBudgets (P H K : Type) [Fintype P] [Fintype H] [Fintype K] + (q c : ℕ) {w : ℕ → ℕ} (hw : PolynomiallyBounded w) : + ∃ signedSpace signedExp : ℕ → ℕ, PolynomiallyBounded signedSpace ∧ PolynomiallyBounded signedExp ∧ + B.SignedCallFits q c w signedSpace signedExp ∧ + Cost.Feasible (fun n => B.coordinateBudget P H K q c n (w n) (signedSpace n) (signedExp n)) := by + obtain ⟨sp,ex,hsp,hex,hA,hS,hT,fits⟩ := B.compressorRawReaderBudgets q c hw + obtain ⟨hraw,he,hv⟩ := B.compressorReaderWidths q c + obtain ⟨hlim,hd,_⟩ := planSizes hraw + exact ⟨sp,ex,hsp,hex,fits,preparedMaximum_feasible P H K hlim hd hw he hv hT hA hS hT + (B.compressorLabelCount_polynomial c)⟩ + +/-- For every concrete slice covered by the plan, the actual mounted +reader budget fits the length-only maximum. The finite box covers the +order of the square minor even when the augmented matrix is rectangular. -/ +theorem coordinateBudget_covers (P H K : Type) [Fintype P] [Fintype H] [Fintype K] + (q c n w signedSpace signedExp : ℕ) {F : Type} [Field F] [DecidableEq F] + (data : QueryData (B.compressorReaderPlan q c n).arity + ((B.compressorReaderPlan q c n).equations+(B.compressorReaderPlan q c n).pins) F) + (hplan : (B.compressorReaderPlan q c n).Covers data) {e v : ℕ} + (he : e ≤ B.readerDegreeBudget q c n) (hv : v ≤ B.readerLimbBudget q c n) : + let plan := B.compressorReaderPlan q c n + let nrows := (plan.equations+plan.pins)*size plan.arity data.multiplierDegree + size plan.arity data.pointBound + let ncols := size plan.arity data.columnDegree + let r := RankQuery.rankQuery (RankQuery.appendRows data.equations data.monomials) + let ext := B.readerDegreeBudget q c n + let limb := B.readerLimbBudget q c n + let A := plan.live ext limb w signedSpace + let S := plan.armSpace ext limb w signedSpace + let T := plan.readTime ext limb w signedSpace signedExp + let actual := preparedBudget P H K nrows ncols r (planDepth plan) w v e T A S T (B.compressorLabelCount c n) + let bound := B.coordinateBudget P H K q c n w signedSpace signedExp + actual.time ≤ bound.time ∧ actual.space ≤ bound.space := by + obtain ⟨hr,hc,ho,_⟩ := plan_query_shapes hplan + exact preparedMaximum_covers P H K hr hc ho he hv _ _ _ _ _ _ _ + +/-- The clock exponent and space exponent can be fixed together, before +the eventual input length and before every prime or model at that length. -/ +theorem exists_coordinateClock (P H K : Type) [Fintype P] [Fintype H] [Fintype K] (q c : ℕ) : + ∃ signedSpace signedExp : ℕ → ℕ, B.SignedCallFits q c (B.coordinateWidth q c) signedSpace signedExp ∧ + ∃ u N : ℕ, ∀ n ≥ N, + let cost := B.coordinateBudget P H K q c n (B.coordinateWidth q c n) (signedSpace n) (signedExp n) + cost.time ≤ 2^(n^u) ∧ cost.space ≤ n^u := by + obtain ⟨sp,ex,_,_,hs,h⟩ := B.coordinateBudgets P H K q c (B.coordinateWidth_polynomial q c) + exact ⟨sp,ex,hs,eventual_power h⟩ + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCurrentGraph.lean b/lean/OAI/Computability/VPVNP/CompressorCurrentGraph.lean new file mode 100644 index 0000000000..4a71242975 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCurrentGraph.lean @@ -0,0 +1,190 @@ +import OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders +import OAI.Computability.VPVNP.CompressorRecordsShrinkFrame + +/-! # The current graph at a selected compression boundary + +A boundary carries the actual terminal scalars and the packed incidence +columns of its current state. The initial position count is retained at +level zero. Publishing the next header preserves the current graph's old +incidence columns, even at the first shrinking substep. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CurrentGraph + +open BurstRAM Compression DescriptorSpace BlockHeaderRun PortRefresh.TraversalHeaders SourceTransport +open scoped Fin.CommRing + +variable {w a g : ℕ} + +/-- The part of the initial physical header used at subsequent levels. -/ +structure Startup (L : Layout) (n : ℕ) (m : Memory w) : Prop where + counts : ∃ V D lanes, DescriptorHeads.CountsAt (header w L 0) m V D lanes ∧ V*lanes=L.positions + arena : (m (levelStart L 0+14)).val=endAddress L + levels : (m (levelStart L 0+28)).val=L.levels + length : (m (levelStart L 0+29)).val=n + +/-- The current level's terminal scalars, pointer bank and packed incidence represent its +state, with the startup data still present at level zero. -/ +structure Current (L : Layout) (i : ℕ) (X : State a g) (n : ℕ) (m : Memory w) : Prop where + terminal : Scalars.Present (.terminal a) (Fintype.card X.Base) g (header w L i) m + heads : HeadBank L i (IncidenceDirectory.slotCount X) m + incidence : (packedIncidence L w i (IncidenceDirectory.slotCount X)).Represents X m + startup : Startup L n m + +open private keep_counts keep_present address_val from OAI.Computability.VPVNP.CompressorBlockHeaderRun +open private incidence_end_le from OAI.Computability.VPVNP.CompressorDescriptorSpace + +/-- Every occupied column word lies between the end of this level's header +and the beginning of its scratch arrays. -/ +theorem column_range (L : Layout) (i : Fin L.levels) (rows : ℕ) (size : rows ≤ slotCapacity L) + (fit : endAddress L < 2^w) (c : Fin 6) (j : Word w) (hj : j.val < rows) : + let x := ((packedIncidence L w i rows).column c+j).val + incidenceStart L i ≤ x ∧ x < arrayBase L i := by + have room := packed_incidence_room L fit i size + have mul := Nat.mul_le_mul_right rows c.isLt + rw [Nat.succ_mul] at mul + have pos : incidenceBase L i rows c+j.val < incidenceStart L i+6*rows := by + dsimp only [incidenceBase]; omega + rw [packed_column,Fin.val_add,show (CursorRAM.encode w (incidenceBase L i rows c)).val=incidenceBase L i rows c + from Nat.mod_eq_of_lt ((Nat.le_add_right ..).trans_lt (pos.trans room)),Nat.mod_eq_of_lt (pos.trans room)] + exact ⟨(Nat.le_add_right ..).trans (Nat.le_add_right ..),pos.trans_le (Nat.add_le_add_left (Nat.mul_le_mul_left 6 size) _)⟩ + +theorem incidence_keep (L : Layout) (i : Fin L.levels) (X : State a g) {m out : Memory w} + (fit : endAddress L < 2^w) (size : IncidenceDirectory.slotCount X ≤ slotCapacity L) + (rep : (packedIncidence L w i (IncidenceDirectory.slotCount X)).Represents X m) + (keep : ∀ x, incidenceStart L i ≤ x → x < arrayBase L i → out x = m x) : + (packedIncidence L w i (IncidenceDirectory.slotCount X)).Represents X out := by + let T := packedIncidence L w i (IncidenceDirectory.slotCount X) + have atCell (c : Fin 6) (j : Word w) (hj : j.val < IncidenceDirectory.slotCount X) : + out (T.column c+j).val=m (T.column c+j).val := by + have h := column_range L i _ size fit c j hj + exact keep _ h.1 h.2 + have hb (c : Fin 6) (e : X.Base × Fin (2^a)) := atCell c _ (IncidenceDirectory.basePort_lt X e) + have ha (c : Fin 6) (e : (X.Base × BitWord g) × Fin (2^a)) := atCell c _ (IncidenceDirectory.actualPort_lt X e) + exact ⟨fun e => (hb 0 e).trans (rep.baseOut e),fun e => (hb 1 e).trans (rep.baseIn e), + fun e => (hb 2 e).trans (rep.shift e),fun e => (ha 3 e).trans (rep.actualOut e), + fun e => (ha 4 e).trans (rep.actualIn e),fun e => (ha 5 e).trans (rep.width e)⟩ + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} {B : S.Templates} + {f : B.Entry → R} {hf : B.IsSolution f} + +/-- The stored current state supplies the source data of all three physical +header bursts. The old graph and the new head bank coexist in their output. -/ +theorem Current.publish {L : Layout} {n : ℕ} (v : SelectedLevel B f hf) (old new : Fin L.levels) + {m : Memory w} (cur : Current L old v.input n m) (next : old.val+1=new.val) + (six : 6 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (size : IncidenceDirectory.slotCount v.input ≤ slotCapacity L) + (sites : v.input.positions < 2^w) (degree : slotDegree S < 2^w) : + let out := finalMemory v L old new m + Substep v L old new six m ∧ + (packedIncidence L w old (IncidenceDirectory.slotCount v.input)).Represents v.input out ∧ + HeadBank L old (IncidenceDirectory.slotCount v.input) out ∧ HeadBank L new v.outputSlots out := by + obtain ⟨V,D,lanes,cnt,hpos⟩ := cur.startup.counts + have run := substep_run v L old new next six fit m cur.terminal cnt hpos sites degree + have banks := headBanks_of_substep run (by omega) cur.heads + refine ⟨run,incidence_keep L old v.input fit size cur.incidence ?_,banks⟩ + intro x low high + have nextAddr := incidence_end_le L old + rw [next] at nextAddr + have lower : levelStart L old+6 ≤ incidenceStart L old := by unfold incidenceStart levelHeaderWords; omega + exact run.outside x (.inr (lower.trans low)) (.inl (high.trans_le nextAddr)) + (.inl ((high.trans_le nextAddr).trans_le (Nat.le_add_right ..))) + + +/-- All first-level cells needed from startup, including the saved length and +the immutable descriptor arena end. -/ +def startupCell (L : Layout) (x : ℕ) := ∃ offset ∈ ([0,1,2,14,28,29] : List ℕ), x=levelStart L 0+offset + +/-- The six scalar words and the two families of pointers that describe a +current graph. The remaining header words hold local traversal metadata. -/ +def graphCell (L : Layout) (i x : ℕ) := + (levelStart L i ≤ x ∧ x < levelStart L i+6) ∨ + (levelStart L i+L.shape.scalarFields ≤ x ∧ x < incidenceStart L i) + +private theorem cell_val (L : Layout) {i j : ℕ} (h : levelStart L i+j < 2^w) : + (header w L i + (j : Word w)).val=levelStart L i+j := by + change (((levelStart L i : ℕ) : Word w)+(j : Word w)).val = _ + rw [← Nat.cast_add,Fin.val_natCast,Nat.mod_eq_of_lt h] + +theorem Startup.keep {L : Layout} {n : ℕ} {m out : Memory w} (s : Startup L n m) + (room : levelStart L 0+2 < 2^w) + (keep : ∀ x, startupCell L x → out x=m x) : Startup L n out := by + obtain ⟨V,D,lanes,old,number⟩ := s.counts + refine ⟨⟨V,D,lanes,keep_counts old ?_,number⟩, + (congrArg Fin.val (keep _ ⟨14,by decide,rfl⟩)).trans s.arena,(congrArg Fin.val (keep _ ⟨28,by decide,rfl⟩)).trans s.levels, + (congrArg Fin.val (keep _ ⟨29,by decide,rfl⟩)).trans s.length⟩ + intro j + rw [cell_val L (by have := j.isLt; omega)] + apply keep _ ⟨j.val,?_,rfl⟩ + fin_cases j <;> decide + +private theorem graph_keep {L : Layout} (i : Fin L.levels) {X : State a g} {m out : Memory w} + (scalars : Scalars.Present (.terminal a) (Fintype.card X.Base) g (header w L i) m) + (heads : HeadBank L i (IncidenceDirectory.slotCount X) m) + (six : 6 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (keep : ∀ x, graphCell L i x → out x=m x) : + Scalars.Present (.terminal a) (Fintype.card X.Base) g (header w L i) out ∧ + HeadBank L i (IncidenceDirectory.slotCount X) out := by + have room := level_room L fit i + have span : levelStart L i+6 ≤ levelStart L (i.val+1) := by + simp only [levelStart,Nat.succ_mul,levelWords,levelHeaderWords]; omega + refine ⟨keep_present scalars (fun j => ?_),⟨fun c => ?_,fun c => ?_⟩⟩ + · rw [cell_val L (by have := j.isLt; omega)] + exact keep _ (.inl ⟨Nat.le_add_right ..,Nat.add_lt_add_left j.isLt _⟩) + · apply (keep _ (.inr ⟨Nat.le_add_right ..,?_⟩)).trans (heads.incidence c) + unfold incidenceStart levelHeaderWords + have := c.isLt; omega + · apply (keep _ (.inr ⟨?_,?_⟩)).trans (heads.tables c) + · unfold tableHead; omega + · unfold tableHead incidenceStart levelHeaderWords + have := c.isLt; omega + +theorem Current.transfer {L : Layout} {i : Fin L.levels} {X : State a g} {n : ℕ} {m out : Memory w} + (cur : Current L i X n m) (fit : endAddress L < 2^w) (six : 6 ≤ L.shape.scalarFields) + (size : IncidenceDirectory.slotCount X ≤ slotCapacity L) (agree : Agree (levelStart L 0 ≤ ·) m out) : + Current L i X n out := by + have lower := levelStart_mono L (Nat.zero_le i.val) + have room := level_room L fit i + have span : levelStart L i+6 ≤ levelStart L (i.val+1) := by + simp only [levelStart,Nat.succ_mul,levelWords,levelHeaderWords]; omega + obtain ⟨term,heads⟩ := graph_keep i cur.terminal cur.heads six fit (fun x hx => by + rcases hx with hx|hx <;> exact (agree _ (by omega)).symm) + refine ⟨term,heads,incidence_keep L i X fit size cur.incidence (fun x lo _ => ?_),cur.startup.keep (by omega) ?_⟩ + · exact (agree x (lower.trans ((Nat.le_add_right ..).trans lo))).symm + · rintro x ⟨j,_,rfl⟩; exact (agree _ (Nat.le_add_right ..)).symm + +/-- Replaying the post-header kernels may install the next graph's incidence +columns and traversal metadata. Only its scalar words, pointers and six +startup words are needed to reconstruct the full current boundary. -/ +theorem Current.successor {L : Layout} {n : ℕ} (v : SelectedLevel B f hf) (old new : Fin L.levels) + {m out : Memory w} (cur : Current L old v.input n m) (next : old.val+1=new.val) + (fields : 30 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (sub : Substep v L old new (by omega) m) + (rep : (packedIncidence L w new (IncidenceDirectory.slotCount (v.pass.next v.term))).Represents (v.pass.next v.term) out) + (frame : ∀ x, graphCell L new x ∨ startupCell L x → out x=finalMemory v L old new m x) : + Current L new (v.pass.next v.term) n out := by + have bank := (headBanks_of_substep sub (by omega) cur.heads).2 + have slots : v.outputSlots=IncidenceDirectory.slotCount (v.pass.next v.term) := by + rw [SelectedLevel.outputSlots,SelectedLevel.outputSites,State.positions,Fintype.card_prod, + Fintype.card_congr (bitWordFinEquiv _),Fintype.card_fin] + obtain ⟨term,heads⟩ := graph_keep new sub.output (slots ▸ bank) (by omega) fit (fun x h => frame x (.inl h)) + obtain ⟨V,D,lanes,cnt,hpos⟩ := cur.startup.counts + have afterStartup : Startup L n (finalMemory v L old new m) := + ⟨⟨V,D,lanes,keep_counts cnt sub.firstCounts,hpos⟩, + (congrArg Fin.val (sub.firstScalarTail v next 14 (by decide) (by omega))).trans cur.startup.arena, + (congrArg Fin.val (sub.firstScalarTail v next 28 (by decide) (by omega))).trans cur.startup.levels, + (congrArg Fin.val (sub.firstScalarTail v next 29 (by decide) (by omega))).trans cur.startup.length⟩ + have hspan : levelStart L 0+2 ≤ levelStart L 1 := by + simp only [levelStart,Nat.zero_mul,Nat.add_zero,Nat.one_mul,levelWords,levelHeaderWords]; omega + have hi : 1 ≤ L.levels := by have := old.isLt; omega + exact ⟨term,heads,rep,afterStartup.keep (hspan.trans_lt ((levelStart_mono L hi).trans_lt fit)) (fun x h => frame x (.inr h))⟩ + +end CompressorRecords.CurrentGraph + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCurrentGraphFrame.lean b/lean/OAI/Computability/VPVNP/CompressorCurrentGraphFrame.lean new file mode 100644 index 0000000000..5da985e05c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCurrentGraphFrame.lean @@ -0,0 +1,49 @@ +import OAI.Computability.VPVNP.CompressorCurrentGraph + +/-! # Retaining the original cursor frame at all selected boundaries -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CurrentGraph + +open BurstRAM Compression DescriptorSpace BlockHeaderRun SourceTransport +open scoped Fin.CommRing + +variable {w : ℕ} {L : Layout} {m out : Memory w} + +/-- The eight persistent input words begin at level zero, scalar offset six. -/ +def frameCell (L : Layout) (x : ℕ) := levelStart L 0+6 ≤ x ∧ x < levelStart L 0+14 + +theorem frame_keep (room : levelStart L 0+13 < 2^w) (same : ∀ x, frameCell L x → out x=m x) : + (Frame.data (header w L 0+6) out : Fin 8 → Word w)=Frame.data (header w L 0+6) m := by + funext j + change out (header w L 0+6+(j.val : Word w)).val = m (header w L 0+6+(j.val : Word w)).val + apply same + have addr : (header w L 0+6+(j.val : Word w)).val=levelStart L 0+(6+j.val) := by + rw [show header w L 0+6+(j.val : Word w)=((levelStart L 0+(6+j.val) : ℕ) : Word w) by + simp [header,add_assoc]] + exact Nat.mod_eq_of_lt (by have := j.isLt; omega) + rw [addr] + unfold frameCell + have := j.isLt; omega + +theorem frame_transfer (room : levelStart L 0+13 < 2^w) (agree : Agree (levelStart L 0 ≤ ·) m out) : + (Frame.data (header w L 0+6) out : Fin 8 → Word w)=Frame.data (header w L 0+6) m := + frame_keep room (fun x hx => (agree x ((Nat.le_add_right ..).trans hx.1)).symm) + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} {B : S.Templates} + {f : B.Entry → R} {hf : B.IsSolution f} + +theorem frame_publish (v : SelectedLevel B f hf) {old new : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} + (run : Substep v L old new six m) (next : old.val+1=new.val) + (fields : 14 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) : + (Frame.data (header w L 0+6) (finalMemory v L old new m) : Fin 8 → Word w)=Frame.data (header w L 0+6) m := + run.cursorFrame v next fields fit + +end CompressorRecords.CurrentGraph + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCurrentGraphInitial.lean b/lean/OAI/Computability/VPVNP/CompressorCurrentGraphInitial.lean new file mode 100644 index 0000000000..29c3c10040 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCurrentGraphInitial.lean @@ -0,0 +1,79 @@ +import OAI.Computability.VPVNP.CompressorCurrentGraph +import OAI.Computability.VPVNP.CompressorBlockStartupPrefix + +/-! +# The current graph after the four initial block packets + +The true startup supplies the number of positions. The two publishers, the +cursor scan and the role store leave the six scalar words, both head banks, +and the six incidence columns of the initial cursor state. The same fields +are available in the linked interval's post-memory at data addresses. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockStartupPrefix.Resident + +open BurstRAM Compression DescriptorSpace BlockHeaderRun CurrentGraph CursorNetwork +open scoped Fin.CommRing + +variable {w a b l width n : ℕ} {L : Layout} {base : Word w} {m : Memory w} + {X : State a l} (h : Resident L a b l width n base m X) + +include h + +private theorem base_count : Fintype.card X.Base = (b+l)*2^b := by + have eqn := h.rows + change Fintype.card X.Base * 2^l * 2^a = (b+l)*2^b * 2^l * 2^a at eqn + exact Nat.mul_right_cancel (Nat.two_pow_pos l) (Nat.mul_right_cancel (Nat.two_pow_pos a) eqn) + +/-- The raw worker reports leave the initial graph in the exact representation +used by the subsequent selected compression steps. -/ +theorem current : Current L 0 X n (BlockInitialPackets.post L a b l width m) := by + have cnt := present_counts h.scalars + refine ⟨(h.base_count.symm ▸ h.scalars), ?_, h.rows.symm ▸ h.incidence, + ⟨⟨_,_,_,cnt,h.positions⟩,h.arena,h.levels,h.length⟩⟩ + exact ⟨h.rows.symm ▸ h.incidenceHeads,h.tableHeads⟩ + +/-- The linked interval preserves the cursor frame and the role word as +well as the complete graph at its first compression boundary. -/ +theorem current_live (live : Memory w) + (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) (BlockInitialPackets.post L a b l width m) live) + (nonempty : 0 < L.levels) (fields : 14 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) : + Current L 0 X n live ∧ Frame.data (header w L 0+6) live = + CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L)) (CursorRAM.encode w 1) b l a width + (incidenceStart L 0) ∧ live (levelStart L 0+27) = 0 := by + obtain ⟨inc,scalars,frame,heads,tables,role,arena,levels,length⟩ := h.live live agree nonempty fields fit + refine ⟨⟨h.base_count.symm ▸ scalars, ?_, h.rows.symm ▸ inc, ?_⟩,frame,role⟩ + · exact ⟨h.rows.symm ▸ heads,tables⟩ + · exact ⟨⟨_,_,_,present_counts scalars,h.positions⟩,arena,levels,length⟩ + +end CompressorRecords.BlockStartupPrefix.Resident + +namespace CompressorRecords.CurrentGraph + +open BurstRAM Compression DescriptorSpace CursorNetwork BlockHeaderRun +open scoped Fin.CommRing + +/-- Construct the genuine initial source walk and its graph directly from +the startup post-memory, including the zero-block case. -/ +theorem initial {w a b l pad : ℕ} {T : Type} [Fintype T] (L : Layout) (n : ℕ) (base : Word w) + (m : Memory w) (hD : 1 < b+l) (hd : 2+pad = 2^a) (bits : T → ℕ) + (ready : BlockHeaderStartup.Ready L a b l (∑ t, bits t) n base m) (fields : 30 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (room : incidenceStart L 0+6*CursorRAM.rowCount b l a ≤ 2^w) + (width : (∑ t, bits t) < 2^w) : + let W := ∑ t, bits t + let X := cursorState (cursorCoordinateLabels b l) hD hd bits + SourceWalk (BlockInitialPackets.Source L a (Workspace.ports L.shape.arity base).data (header w L 0)) + (BlockInitialPackets.order L a) m (BlockInitialPackets.logs L a b l W m) ∧ + Current L 0 X n (BlockInitialPackets.post L a b l W m) := by + have h := BlockStartupPrefix.resident L n base m hD hd bits ready fields fit room width + exact ⟨h.walk,h.current⟩ + +end CompressorRecords.CurrentGraph + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCurrentResident.lean b/lean/OAI/Computability/VPVNP/CompressorCurrentResident.lean new file mode 100644 index 0000000000..3327336a3c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCurrentResident.lean @@ -0,0 +1,127 @@ +import OAI.Computability.VPVNP.CompressorCurrentGraphFrame +import OAI.Computability.VPVNP.CompressorCurrentGraphInitial +import OAI.Computability.VPVNP.CompressorSelectedDirectoryHistory +import OAI.Computability.VPVNP.CompressorScheduledTraceData + +/-! +# The graph and selected directory history at a calendar boundary + +At each selected pass, the resident memory contains both the earlier +placement directories and the six incidence columns of the current graph. +Publishing the pass adds its occurrence to the history and installs the next +graph. Agreement on the data region carries both records to the memory of +the scheduled online worker. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CurrentResident + +open BurstRAM Compression DescriptorSpace PairSimulation.LocalHistory PairSimulation.TraversalRows +open PairSimulation.TraversalRoles BlockHeaderRun +open scoped Fin.CommRing +open private fit_fields from OAI.Computability.VPVNP.CompressorBlockHeaderRun + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) {w : ℕ} + +/-- The current level index is the number of previously selected passes. -/ +def resident (initial : TaggedLayer) (L : Layout) (base n : ℕ) (initialFrame : Fin 8 → Word w) : + ScheduledTrace.Resident B f hf w := + fun past {_ _} X m => + SelectedDirectoryHistory.Prefix B f hf initial L base past X m ∧ + CurrentGraph.Current L past.length X n m ∧ Frame.data (header w L 0 + 6) m = initialFrame + +variable {B f hf} {initial : TaggedLayer} {L : Layout} {base n a g : ℕ} +variable {initialFrame : Fin 8 → Word w} {past : List (SelectedLevel B f hf)} +variable {X : State a g} {m out : Memory w} + +/-- Level zero starts at the cursor layer and at the published DFS base. -/ +theorem empty (cur : CurrentGraph.Current L 0 X n m) (role : m (levelStart L 0 + 27) = 0) + (frame : Frame.data (header w L 0 + 6) m = initialFrame) : + resident B f hf ⟨leafLayer (siteOrder X), .cursor⟩ L (endAddress L) n initialFrame [] X m := by + have word : m (levelStart L 0 + 14) = (endAddress L : Word w) := by + apply Fin.ext + rw [Fin.val_natCast, ← cur.startup.arena, Nat.mod_eq_of_lt (m _).isLt] + exact ⟨SelectedDirectoryHistory.Prefix.empty word role, cur, frame⟩ + +/-- The cursor publisher initializes all three resident records in the +actual post-memory of the linked four-row interval. -/ +theorem initial_live {b width : ℕ} {workspace : Word w} + (cursor : BlockStartupPrefix.Resident L a b g width n workspace m X) + (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) + (BlockInitialPackets.post L a b g width m) out) + (positive : 0 < L.levels) (fields : 14 ≤ L.shape.scalarFields) (fit : endAddress L < 2 ^ w) : + resident B f hf ⟨leafLayer (siteOrder X), .cursor⟩ L (endAddress L) n + (CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L)) (CursorRAM.encode w 1) + b g a width (incidenceStart L 0)) [] X out := by + obtain ⟨cur, frame, role⟩ := cursor.current_live out agree positive fields fit + exact empty cur role frame + +/-- Scheduler traffic below the first level leaves every recorded directory +and every current-state field intact. -/ +theorem transfer (h : resident B f hf initial L base n initialFrame past X m) + (index : past.length < L.levels) + (fit : endAddress L < 2 ^ w) (fields : 14 ≤ L.shape.scalarFields) + (slots : IncidenceDirectory.slotCount X ≤ slotCapacity L) + (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) m out) : + resident B f hf initial L base n initialFrame past X out := by + have pos : 0 < L.levels := (Nat.zero_le _).trans_lt index + have room := fit_fields L ⟨0, pos⟩ fit + change levelStart L 0 + L.shape.scalarFields < 2 ^ w at room + exact ⟨h.1.transfer agree, + CurrentGraph.Current.transfer (i := ⟨past.length, index⟩) h.2.1 fit (by omega) slots agree, + (CurrentGraph.frame_transfer (by omega) agree).trans h.2.2⟩ + +/-- Append one selected occurrence. Its output incidence data and its +history directory are read at the same post-memory. -/ +theorem append {v : SelectedLevel B f hf} + (h : resident B f hf initial L base n initialFrame past v.input m) + (emission : SelectedDirectoryHistory.Emission L past.length v m out) + (wide : 28 ≤ levelWords L) (room : levelStart L (past.length + 1) ≤ base) + (previous : ∀ x, levelsBase L ≤ x → x < levelStart L past.length → out x = m x) + (next : CurrentGraph.Current L (past.length + 1) (v.pass.next v.term) n out) + (frame : Frame.data (header w L 0 + 6) out = initialFrame) : + resident B f hf initial L base n initialFrame (past ++ [v]) (v.pass.next v.term) out := by + exact ⟨h.1.append emission wide room previous, + by simpa only [List.length_append, List.length_singleton] using next, frame⟩ + +/-- Recover the next resident graph from the concrete scalar substep, six +new incidence columns, the emitted traversal directory, and the physical +memory frame of this pass. -/ +theorem append_substep {v : SelectedLevel B f hf} (old new : Fin L.levels) + (oldAt : past.length = old.val) (newAt : old.val + 1 = new.val) + (h : resident B f hf initial L (endAddress L) n initialFrame past v.input m) + (fields : 30 ≤ L.shape.scalarFields) (fit : endAddress L < 2 ^ w) + (sub : Substep v L old new (by omega) m) + (emission : SelectedDirectoryHistory.Emission L past.length v m out) + (columns : (packedIncidence L w new + (IncidenceDirectory.slotCount (v.pass.next v.term))).Represents + (v.pass.next v.term) out) + (graph : ∀ x, CurrentGraph.graphCell L new x ∨ CurrentGraph.startupCell L x + ∨ CurrentGraph.frameCell L x → + out x = finalMemory v L old new m x) + (previous : ∀ x, levelsBase L ≤ x → x < levelStart L past.length → out x = m x) : + resident B f hf initial L (endAddress L) n initialFrame (past ++ [v]) + (v.pass.next v.term) out := by + have current : CurrentGraph.Current L old v.input n m := by rw [← oldAt]; exact h.2.1 + have successor := current.successor v old new newAt fields fit sub columns + (fun x hx => graph x (hx.imp_right Or.inl)) + have index : past.length + 1 = new.val := by omega + have wide : 28 ≤ levelWords L := by unfold levelWords levelHeaderWords; omega + have room := levelStart_mono L + (show past.length + 1 ≤ L.levels from by rw [index]; exact new.isLt.le) + have pos : 0 < L.levels := (Nat.zero_le _).trans_lt old.isLt + have span := fit_fields L ⟨0, pos⟩ fit + change levelStart L 0 + L.shape.scalarFields < 2 ^ w at span + apply append h emission wide room previous (by rw [index]; exact successor) + exact (CurrentGraph.frame_keep (by omega) (fun x hx => graph x (.inr (.inr hx)))).trans + ((CurrentGraph.frame_publish v sub newAt (by omega) fit).trans h.2.2) + +end CompressorRecords.CurrentResident + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorCursorFrameTransfers.lean b/lean/OAI/Computability/VPVNP/CompressorCursorFrameTransfers.lean new file mode 100644 index 0000000000..9af672a386 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorCursorFrameTransfers.lean @@ -0,0 +1,183 @@ +import OAI.Computability.VPVNP.CompressorCalendarTransfers + +/-! +# Cursor-frame startup across external stage transfers + +The row-count call, raw parameter writer, framed loader and bank copy enter in +state zero. At each accepting exit the stage linker writes the next stage number +below the workspace. The loader's read transcript uses the memory left by both +the raw writer and its transfer. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CursorFrameTransfers + +open BurstRAM BurstRAM.PrivateRAM DescriptorSpace CursorBounds OnlineCursorStartup +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Reports of the four accepting components before their transfer instructions. -/ +structure Trace (w : ℕ) where + /-- Report computing and storing the descriptor calendar's row count. -/ + row : Report w + /-- Report writing the raw cursor parameters into the startup workspace. -/ + raw : Report w + /-- Report loading the raw frame and computing the cursor's derived operands. -/ + loaded : Report w + /-- Report copying the completed cursor operands into the persistent frame. -/ + copied : Report w + +/-- Memory after the row-count report and the transfer to stage one. -/ +def Trace.postRow (t : Trace w) (tag : Word w) (m : Memory w) := transfer m t.row tag 1 +/-- Memory after the raw cursor parameters are published and control advances to stage two. -/ +def Trace.postRaw (t : Trace w) (tag : Word w) (m : Memory w) := transfer (t.postRow tag m) t.raw tag 2 +/-- Memory after the parameter loader runs and control advances to stage three. -/ +def Trace.postLoad (t : Trace w) (tag : Word w) (m : Memory w) := transfer (t.postRaw tag m) t.loaded tag 3 +/-- Memory after the persistent frame copy and the transfer to stage four. -/ +def Trace.post (t : Trace w) (tag : Word w) (m : Memory w) := transfer (t.postLoad tag m) t.copied tag 4 + +/-- Construct the four cursor-frame reports using the memory produced by each preceding tagged +transfer. -/ +noncomputable def trace (D : CalendarRows.Spec) (L : Layout) (B n a lanes : ℕ) + (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) : Trace w := + let row := CalendarRows.report D pub n + let counted := transfer m row tag 1 + let R := DescriptorParameters.raw L.shape a D.initialRows D.phaseRows lanes + let raw := closed (R.recipe.report (pub ∘ DescriptorParameters.operand) 0 counted) + let prepared := transfer counted raw tag 2 + let loaded := closed (DescriptorParameters.loaderReport L B n a (roundedDown D.p D.q n * lanes) pub 0 prepared) + let published := transfer prepared loaded tag 3 + let copied := closed ((DescriptorParameters.copy L.shape).recipe.report (pub ∘ DescriptorParameters.operand) 0 published) + ⟨row, raw, loaded, copied⟩ + +/-- The four calls and the memory passed to the stride calculator. -/ +structure Runs (D : CalendarRows.Spec) (L : Layout) (B n a lanes : ℕ) + (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) : Prop where + callRow : + let t := trace D L B n a lanes pub tag m + Call (CalendarRows.table D) pub (CalendarRows.ticks D n+2) 0 m t.row + callRaw : + let t := trace D L B n a lanes pub tag m + Call (LiveOneShot.oneShot (DescriptorParameters.table L.shape a D.initialRows D.phaseRows lanes)) + pub ((DescriptorParameters.raw L.shape a D.initialRows D.phaseRows lanes).recipe.code.length+1) + 0 (t.postRow tag m) t.raw + callLoad : + let t := trace D L B n a lanes pub tag m + Call (LiveOneShot.oneShot DescriptorParameters.loader) pub (VirtualParameters.ticks n+43+4*17) + 0 (t.postRaw tag m) t.loaded + callCopy : + let t := trace D L B n a lanes pub tag m + Call (LiveOneShot.oneShot (DescriptorParameters.copyTable L.shape)) + pub ((DescriptorParameters.copy L.shape).recipe.code.length+1) 0 (t.postLoad tag m) t.copied + saved : Frame.data (DescriptorParameters.saved L w) ((trace D L B n a lanes pub tag m).post tag m) = + DescriptorParameters.outputs L B n a (roundedDown D.p D.q n * lanes) w + active : Frame.data (pub 2+9) ((trace D L B n a lanes pub tag m).post tag m) = + DescriptorParameters.outputs L B n a (roundedDown D.p D.q n * lanes) w + count : (trace D L B n a lanes pub tag m).post tag m (pub 2+8).val = (CalendarRows.rows D n : Word w) + reserved : levelStart L 0+14 ≤ levelStart L 0+L.shape.scalarFields + tagged : (trace D L B n a lanes pub tag m).post tag m tag.val = 4 + source_below : ∀ x < L.base, let t := trace D L B n a lanes pub tag m + after m t.row.events x = m x ∧ + after (t.postRow tag m) t.raw.events x = t.postRow tag m x ∧ + after (t.postRaw tag m) t.loaded.events x = t.postRaw tag m x ∧ + after (t.postLoad tag m) t.copied.events x = t.postLoad tag m x + +private theorem oneShot_call {p r cap : ℕ} {T : Template p r 11} {pub : Fin 11 → Word w} + {m : Memory w} {out : Report w} (h : Call T pub cap 0 m out) : + Call (LiveOneShot.oneShot T) pub cap 0 m (closed out) := by + dsimp only [Call] at h ⊢ + rw [LiveOneShot.execute_oneShot] + change (execute _ _ ((T.instantiate w pub).program.start 0) m []).map _ = _ + rw [h] + rfl + +/-- From any external memory, the four native components and their transfers +leave both cursor banks populated, the calendar count intact, and stage four selected. -/ +theorem run (D : CalendarRows.Spec) (L : Layout) (B n a lanes : ℕ) + (pub : Fin 11 → Word w) (tag : Word w) (m : Memory w) (input : Input D L B n pub) + (hw : w = wordBits B n) (hB : 1 ≤ B) (hL : roundedDown D.p D.q n * lanes ≤ virtualBits B n) + (arity : 7 ≤ L.shape.arity) (scalars : 14 ≤ L.shape.scalarFields) + (capacity : CursorRAM.ParametersInit.Capacity B n a (roundedDown D.p D.q n * lanes) + (directoryBase L) 1 (incidenceStart L 0) (levelStart L 0+6)) (lower : tag.val < L.base) : + Runs D L B n a lanes pub tag m := by + let t := trace D L B n a lanes pub tag m + let countAddr := (pub 2+8).val + let T := roundedDown D.p D.q n + let out := DescriptorParameters.outputs L B n a (T*lanes) w + have frameEnd : frameBase L+8 ≤ levelStart L 0+6 := by + have h := frame_before_directory L + simp only [levelStart, levelsBase, Nat.zero_mul, Nat.add_zero] + omega + have savedFit : levelStart L 0+6+8 < 2^w := hw ▸ capacity.frame_end + have fit : frameBase L+8 < 2^w := by omega + have baseFit : L.base+9+8 < 2^w := fit + have rawBase : (pub 2+9).val = frameBase L := by + change _ = L.base+9 + have h := offset_value (pub 2) 9 (by rw [input.base]; omega) + exact h.trans (by rw [input.base]) + have savedBase : (DescriptorParameters.saved L w).val = levelStart L 0+6 := + Nat.mod_eq_of_lt (by omega) + have countVal : countAddr = L.base+8 := by + have h := offset_value (pub 2) 8 (by rw [input.base]; omega) + exact h.trans (by rw [input.base]) + have belowRaw : countAddr < frameBase L := by rw [countVal, frameBase]; omega + have belowSaved : countAddr < levelStart L 0+6 := by omega + have keepCount (mem : Memory w) (v : Word w) : + writeMemory mem tag v countAddr = mem countAddr := by + rw [writeMemory, ite_eq_right (by omega)] + have keepRaw (mem : Memory w) (v : Word w) : + (Frame.data (pub 2+9) (writeMemory mem tag v) : Fin 8 → Word w) = Frame.data (pub 2+9) mem := + lower_write_frame _ _ _ _ (by rw [rawBase]; omega) (by rw [rawBase]; omega) + have keepSaved (mem : Memory w) (v : Word w) : + (Frame.data (DescriptorParameters.saved L w) (writeMemory mem tag v) : Fin 8 → Word w) = + Frame.data (DescriptorParameters.saved L w) mem := + lower_write_frame _ _ _ _ (by rw [savedBase]; omega) (by rw [savedBase]; omega) + obtain ⟨row, ready⟩ := count_ready D L B n pub 0 m input + have readyRow : DescriptorParameters.Ready L B n D.initialRows D.phaseRows T pub (t.postRow tag m) := + { ready with total := (congrArg Fin.val (keepCount _ _)).trans ready.total } + obtain ⟨raw, _, rawBank, rawPreserves, _⟩ := DescriptorParameters.prepare readyRow 0 a lanes fit + have ⟨load, _, published, loadPreserves, _⟩ := + DescriptorParameters.publish hw hB hL capacity pub 0 (t.postRaw tag m) ((keepRaw _ _).trans rawBank) + have countAfterLoad : t.postLoad tag m countAddr = t.postRow tag m countAddr := + (keepCount _ _).trans ((loadPreserves _ (Or.inl belowSaved)).trans + ((keepCount _ _).trans (rawPreserves _ (Or.inl belowRaw)))) + have readyLoad : DescriptorParameters.Ready L B n D.initialRows D.phaseRows T pub (t.postLoad tag m) := + { readyRow with total := (congrArg Fin.val countAfterLoad).trans readyRow.total } + obtain ⟨copy, _, copied, copyPreserves, _⟩ := DescriptorParameters.copy_run readyLoad 0 fit + have savedLoad : Frame.data (DescriptorParameters.saved L w) (t.postLoad tag m) = out := + (keepSaved _ _).trans published + have savedCopy : (Frame.data (DescriptorParameters.saved L w) + (after (t.postLoad tag m) t.copied.events) : Fin 8 → Word w) = + Frame.data (DescriptorParameters.saved L w) (t.postLoad tag m) := by + have room : (DescriptorParameters.saved L w).val+8 ≤ 2^w := by omega + funext j + rw [Frame.data_at _ _ room, Frame.data_at _ _ room] + exact copyPreserves _ (Or.inr (by omega)) + have before (x : ℕ) (hx : x < L.base) : + after m t.row.events x = m x ∧ + after (t.postRow tag m) t.raw.events x = t.postRow tag m x ∧ + after (t.postRaw tag m) t.loaded.events x = t.postRaw tag m x ∧ + after (t.postLoad tag m) t.copied.events x = t.postLoad tag m x := by + have belowCount : x < countAddr := by omega + refine ⟨?_,rawPreserves x (.inl (by omega)),loadPreserves x (.inl (by omega)),copyPreserves x (.inl (by omega))⟩ + change after m (CalendarRows.report D pub n).events x = m x + rw [CalendarRows.after_report,writeMemory,ite_eq_right (ne_of_lt belowCount)] + refine ⟨row, oneShot_call raw, oneShot_call load, oneShot_call copy, + (keepSaved _ _).trans (savedCopy.trans savedLoad), + (keepRaw _ _).trans (copied.trans savedLoad), ?_, Nat.add_le_add_left scalars _, transfer_tag .., before⟩ + apply (keepCount _ _).trans + apply (copyPreserves _ (Or.inl belowRaw)).trans + apply countAfterLoad.trans + apply (keepCount _ _).trans + change after m (CalendarRows.report D pub n).events (pub 2+8).val = _ + rw [CalendarRows.after_report, writeMemory, ite_eq_left rfl] + +end CompressorRecords.CursorFrameTransfers + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDefaultSelection.lean b/lean/OAI/Computability/VPVNP/CompressorDefaultSelection.lean new file mode 100644 index 0000000000..da3e27bd27 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDefaultSelection.lean @@ -0,0 +1,35 @@ +import OAI.Computability.VPVNP.PairSimulationSelectorReindex + +/-! # A common pre-selection state for the physical compressor + +Each motif admits the zero supply vector. This gives a selected level whose +header can be constructed before the first guessed bit, at every input +state and in either kind of compressor pass. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace PairSimulation.LocalHistory + +open Compression CompressorRecords CompressorRecords.SelectedTerms +open scoped Classical + +variable {k R : Type*} [Field k] [CommRing R] {S : BlockSchedule k} +variable {B : S.Templates} {f : B.Entry → R} {hf : B.IsSolution f} +variable {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} + +/-- The outer term with all supply payload widths zero is admitted independently +of the current demand vector. -/ +noncomputable def defaultSelection (o : PassOrigin B f hf p) : p.step.Choice := + (termRows o).rows.symm fun j => + ⟨fun _ => 0, by + apply (MotifConversion.mem_outerIndices_iff (grid o).block (grid o).qPos _ _).mpr + simp [MotifAdmission.admit,MotifAdmission.energy]⟩ + +end PairSimulation.LocalHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDemandFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorDemandFootprint.lean new file mode 100644 index 0000000000..2725d42835 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDemandFootprint.lean @@ -0,0 +1,205 @@ +import OAI.Computability.VPVNP.CompressorChoiceGridStage +import OAI.Computability.VPVNP.CompressorSourceTransport +import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete +import OAI.Computability.VPVNP.CompressorFlowFootprint + +/-! +# External addresses read by the motif preparation calls + +Every successful execution of the demand-energy scan, the repetition program +and the first-cover search probes only the input demand cells. The proof +tracks the energy scan's advancing cursor and the grid's public offsets and +also applies when comparison arithmetic wraps. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DemandFootprint + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM SourceTransport +open scoped Fin.CommRing +open private rowEvents read_exec from OAI.Computability.VPVNP.CompressorChoicePreparation +open private rowsFrom coordinates keep clear coefficient_slot slot from OAI.Computability.VPVNP.CompressorChoiceGrid + +variable {w d t k : ℕ} {D : Type*} + +/-- Modular address of an actual demand coordinate. -/ +def demandCell (base : Word w) (d address : ℕ) : Prop := + ∃ i : Fin d, address = (base + (i.val : Word w)).val + +/-- All external reads target the input rectangle and no external writes occur. -/ +abbrev Footprint (base : Word w) (d : ℕ) (es : List (Event w)) := + Reads (demandCell base d) es ∧ Writes (fun _ => False) es + +theorem Footprint.interval {base : Word w} {es : List (Event w)} (h : Footprint base d es) + (fit : base.val+d ≤ 2^w) : + Reads (fun n => base.val ≤ n ∧ n < base.val+d) es ∧ Writes (fun _ => False) es := by + refine ⟨fun a v hv => ?_,h.2⟩ + obtain ⟨i,hi⟩ := h.1 a v hv + rw [hi,Fin.val_add,Fin.val_natCast,Nat.add_mod_mod,Nat.mod_eq_of_lt (by have := i.isLt; omega)] + exact ⟨Nat.le_add_right ..,Nat.add_lt_add_left i.isLt _⟩ + +private theorem append {base : Word w} {es fs : List (Event w)} (h : Footprint base d es) + (h' : Footprint base d fs) : Footprint base d (es++fs) := + ⟨fun a v hv => (List.mem_append.mp hv).elim (h.1 a v) (h'.1 a v), + fun a v hv => (List.mem_append.mp hv).elim (h.2 a v) (h'.2 a v)⟩ + +private theorem tick {base : Word w} {es : List (Event w)} (h : Footprint base d es) : + Footprint base d (.tick :: es) := by + constructor <;> intro a v hv <;> simp only [List.mem_cons,reduceCtorEq,false_or] at hv + · exact h.1 _ _ hv + · exact h.2 _ _ hv + +private theorem read {base a : Word w} {es : List (Event w)} (h : Footprint base d es) + (ha : demandCell base d a.val) (x : Word w) : Footprint base d (.read a x :: es) := by + constructor <;> intro addr v hv <;> rcases List.mem_cons.mp hv with hv | hv + · cases hv; exact ha + · exact h.1 _ _ hv + · contradiction + · exact h.2 _ _ hv + +private theorem of_zero {base : Word w} {es : List (Event w)} (hz : countProbes es = 0) : Footprint base d es := + FlowFootprint.bounds_of_noProbes _ _ hz + +private theorem scan_exists (pub : Fin (d+1) → Word w) (base : Word w) (m : Memory w) + (ids : List (Fin d)) (off : ℕ) (fit : off+ids.length ≤ d) (rs : Regs w 8) + (cursor : rs 2 = base + (off : Word w)) (one : rs 6 = 1) : + ∃ es out, Flow.Exec pub base (DemandPreparation.scan ids) rs m es out m ∧ + choiceBits es = [] ∧ Footprint base d es := by + induction ids generalizing off rs with + | nil => exact ⟨[.tick],_,.line rfl,rfl,of_zero rfl⟩ + | cons i ids ih => + obtain ⟨mid,hr,_,inc,o⟩ := read_exec pub base m rs one i + have ha : demandCell base d (rs 2).val := ⟨⟨off,by simp only [List.length_cons] at fit; omega⟩,by rw [cursor]⟩ + have cur : mid 2 = base + ((off+1 : ℕ) : Word w) := by rw [inc,cursor,Nat.cast_add,Nat.cast_one,add_assoc] + obtain ⟨es,out,hs,bits,fp⟩ := ih (off+1) (by simp only [List.length_cons] at fit; omega) mid cur o + refine ⟨_++es,out,.seq hr hs,?_,append (read (of_zero (by rfl)) ha _) fp⟩ + simpa [rowEvents,choiceBits] using bits + +theorem energyPrefix (pub : Fin (d+1) → Word w) (base : Word w) {rs out : Regs w 8} {m m' es} + (run : Flow.Exec pub base (DemandPreparation.energyPrefix d) rs m es out m') : Footprint base d es := by + let a := Function.update rs 2 base + let b := Function.update a 0 0 + let c := Function.update b 6 (1 : Word w) + have h₁ : Flow.Exec pub base (.line (.stateWord 2)) rs m [.tick] a m := .line rfl + have h₂ : Flow.Exec pub base (.line (.constant 0 0)) a m [.tick] b m := .line rfl + have h₃ : Flow.Exec pub base (.line (.constant 6 1)) b m [.tick] c m := .line rfl + obtain ⟨fs,last,hr,hb,fp⟩ := scan_exists pub base m (List.finRange d) 0 (by simp) + c (by simp (config := {decide := true}) [c,b,a,Function.update]) (Function.update_self ..) + have generated : Flow.Exec pub base (DemandPreparation.energyPrefix d) rs m + (.tick :: .tick :: .tick :: fs) last m := .seq h₁ (.seq h₂ (.seq h₃ hr)) + rw [← FlowFootprint.events_eq generated hb run] + exact tick (tick (tick fp)) + +private theorem private_exec {base : Word w} {r : ℕ} {pub : Fin k → Word w} {a : Flow r k} + {rs m es out m'} (h : Flow.Exec pub base a rs m es out m') (pure : FlowFootprint.privateOnly a = true) : + Footprint base d es := of_zero (FlowFootprint.noProbes pure h) + +theorem repetition (pub : Fin (d+1) → Word w) (base : Word w) {rs out : Regs w 8} {m m' es} + (run : Flow.Exec pub base (DemandPreparation.repetitionCall d) rs m es out m') : Footprint base d es := by + cases run with + | seq he hr => exact append (energyPrefix pub base he) (private_exec hr rfl) + +private theorem compare (order : Fin d ≃ D) [Fintype D] (p : D → ℚ) (rows : Fin t → D → ℚ) + (base : Word w) (j : Fin t) (i : Fin d) {rs out : Regs w 8} {m m' es} + (run : Flow.Exec (GridRAM.coefficients order p rows) base (GridRAM.compareCoordinate order rows j i) + rs m es out m') : Footprint base d es := by + unfold GridRAM.compareCoordinate at run + cases run with | seq h0 rest => + cases h0 with | line h0 => + simp only [Op.effect,Option.some.injEq,Prod.mk.injEq] at h0 + obtain ⟨rfl,rfl,rfl⟩ := h0 + cases rest with | seq h1 rest => + cases h1 with | line h1 => + simp only [Op.effect,Option.some.injEq,Prod.mk.injEq] at h1 + obtain ⟨rfl,rfl,rfl⟩ := h1 + cases rest with | seq h2 rest => + cases h2 with | line h2 => + simp only [Op.effect,Option.some.injEq,Prod.mk.injEq] at h2 + obtain ⟨rfl,rfl,rfl⟩ := h2 + cases rest with | seq h3 rest => + cases h3 with | line h3 => + simp only [Op.effect,Option.some.injEq,Prod.mk.injEq] at h3 + obtain ⟨rfl,rfl,rfl⟩ := h3 + apply tick ∘ tick ∘ tick + apply read (private_exec rest ?_) + · refine ⟨i,?_⟩ + simp (config := {decide := true}) [Function.update,coefficient_slot,BinaryOp.eval] + · by_cases h : 0 ≤ rows j (order i) <;> simp only [h,↓reduceIte] <;> rfl + +private theorem coords (order : Fin d ≃ D) [Fintype D] (p : D → ℚ) (rows : Fin t → D → ℚ) + (base : Word w) (j : Fin t) (ids : List (Fin d)) {rs out : Regs w 8} {m m' es} + (run : Flow.Exec (GridRAM.coefficients order p rows) base (coordinates order rows j ids) + rs m es out m') : Footprint base d es := by + induction ids generalizing rs m es with + | nil => exact private_exec run rfl + | cons i ids ih => + cases run with + | seq hr hs => exact append (compare order p rows base j i hr) (ih hs) + +private theorem table (order : Fin d ≃ D) [Fintype D] (p : D → ℚ) (rows : Fin t → D → ℚ) + (base : Word w) (ids : List (Fin t)) {rs out : Regs w 8} {m m' es} + (run : Flow.Exec (GridRAM.coefficients order p rows) base (rowsFrom order rows ids) + rs m es out m') : Footprint base d es := by + induction ids generalizing rs m es with + | nil => exact private_exec run rfl + | cons j js ih => + cases run with | seq init rest => + cases rest with | seq row choice => + apply append (private_exec init rfl) (append (coords order p rows base j _ row) ?_) + cases choice with + | ifEqYes _ h => exact tick (private_exec h rfl) + | ifEqNo _ h => + cases h with | seq inc next => exact tick (append (private_exec inc rfl) (ih next)) + +theorem grid (order : Fin d ≃ D) [Fintype D] (p : D → ℚ) (rows : Fin t → D → ℚ) + (base : Word w) {rs out : Regs w 8} {m m' es} + (run : Flow.Exec (GridRAM.coefficients order p rows) base (GridRAM.grid order rows) rs m es out m') : + Footprint base d es := by + cases run with | seq h rest => + cases rest with | seq h' scan => + exact append (private_exec h rfl) (append (private_exec h' rfl) (table order p rows base _ scan)) + +theorem gridCode (order : Fin d ≃ D) [Fintype D] (p : D → ℚ) (rows : Fin t → D → ℚ) + (pub : Fin (d+1) → Word w) (base : Word w) {rs out : Regs w 8} {m m' es} + (run : Flow.Exec (Fin.append pub (GridRAM.coefficients order p rows)) base + (DemandGridRAM.code order rows) rs m es out m') : Footprint base d es := by + cases run with | seq energy test => + let data := Fin.append pub (GridRAM.coefficients order p rows) + have left := (PrimedCounter.restrictExec (Function.Embedding.refl (Fin 8)) (Fin.castAdd (t*d*3)) + data (DemandPreparation.energyPrefix d) energy).1 + have right := (PrimedCounter.restrictExec (Function.Embedding.refl (Fin 8)) (Fin.natAdd (d+1)) + data (GridRAM.grid order rows) test).1 + have hl : data ∘ Fin.castAdd (t*d*3) = pub := funext fun _ => Fin.append_left .. + have hr : data ∘ Fin.natAdd (d+1) = GridRAM.coefficients order p rows := funext fun _ => Fin.append_right .. + exact append (energyPrefix pub base (hl ▸ left)) (grid order p rows base (hr ▸ right)) + +/-- Every successful native repetition call, at any fuel and choice input, +probes only the demand cells. -/ +theorem repetitionMachine [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (L : ℕ) (base : Word w) + (mem : Memory w) (fuel : ℕ) (bits : List Bool) (rep : Report w) + (run : let machine := DemandPreparation.repetitionMachine order p L w + execute machine.program fuel (machine.program.start base) mem bits = some rep) : + Footprint base d rep.events := by + obtain ⟨_,_,he,_⟩ := (Flow.template_execute_iff (DemandPreparation.repetitionCall d) (some 2) + (DemandPreparation.publicWords order p L w) base (fun _ => 0) (fun _ => 0) mem fuel bits rep).mp run + exact repetition _ base he + +/-- Every successful native grid call reads within the same input rectangle. -/ +theorem gridMachine [Fintype D] (order : Fin d ≃ D) (p : D → ℚ) (rows : Fin t → D → ℚ) + (base : Word w) (mem : Memory w) (fuel : ℕ) (bits : List Bool) (rep : Report w) + (run : let machine := DemandGridRAM.machine order p rows w + execute machine.program fuel (machine.program.start base) mem bits = some rep) : + Footprint base d rep.events := by + obtain ⟨_,_,he,_⟩ := (Flow.template_execute_iff (DemandGridRAM.code order rows) (some 1) + (Fin.append (DemandPreparation.publicWords order p 1 w) (GridRAM.coefficients order p rows)) + base (fun _ => 0) (fun _ => 0) mem fuel bits rep).mp run + exact gridCode order p rows _ base he + +end CompressorRecords.DemandFootprint + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorBranchSpace.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorBranchSpace.lean new file mode 100644 index 0000000000..5e2c745abf --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorBranchSpace.lean @@ -0,0 +1,112 @@ +import OAI.Computability.VPVNP.CompressorDescriptorSpace +import OAI.Computability.VPVNP.CompressorLevelCounts +import OAI.Computability.VPVNP.CursorBranchBudget + +/-! +# Descriptor capacity on actual compressor branches + +Each substep on the selected cursor execution fits the level and slot ranges +of Appendix E. The final wire bits and the DFS row arena fit after the last +descriptor array, with one threshold for every coefficient specialization +and admissible branch. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorSpace + +open Compression CursorBounds CursorNetwork Filter +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} + +/-- The reserved levels, site rows, and slot rows cover every substep of +the genuine selected compressor execution, including both endpoint graphs +of the substep and all of its motifs. -/ +theorem selected_level_capacity (L : Layout) (B : S.Templates) {A : Type*} [CommRing A] + (f : B.Entry → A) (hf : B.IsSolution f) {lanes : ℕ} (T : ℕ) (hT : T * S.laneBits ≤ lanes) + (X : State (S.degreeExponent 0) lanes) (z : (B.execute f hf T hT X).Choices) + (hsteps : (S.steps + 1) * T < L.levels) (hpos : X.positions ≤ L.positions) + (hslots : slotDegree S ≤ L.shape.slots) : + (executeLevels B f hf T hT X z).length < L.levels ∧ + ∀ v ∈ executeLevels B f hf T hT X z, + v.input.positions ≤ L.positions ∧ v.outputSites ≤ L.positions ∧ + v.oldSlots ≤ slotCapacity L ∧ v.outputSlots ≤ slotCapacity L ∧ + v.origin.motifCount ≤ slotCapacity L := by + refine ⟨(executeLevels_length B f hf T hT X z).trans_lt hsteps, fun v hv ↦ ?_⟩ + have hin := ((executeLevels_limits B f hf T hT X z v hv).1).trans hpos + have hout := v.outputSites_le.trans hin + have hold := Nat.mul_le_mul hin (v.oldDegree_le.trans hslots) + exact ⟨hin, hout, hold, Nat.mul_le_mul hout (v.outputDegree_le.trans hslots), + v.origin.motifCount_le.trans hold⟩ + +/-- After all descriptor arrays there is room for the selected final wires, +the DFS row arena and an additional polynomial suffix. The length threshold +precedes the coordinate split, specialization, and branch choice. -/ +theorem eventually_selected_room (F : Shape) (B : S.Templates) (u : PairExponents B.growthConstant) + (b : ℕ) (hb : max S.laneBits 5 ≤ b) {start suffix : ℕ → ℕ} + (hstart : PolynomiallyBounded start) (hsuffix : PolynomiallyBounded suffix) : + ∀ᶠ n : ℕ in atTop, + ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) + (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes) + (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f), + let T := blockCount (u.θ : ℝ) n + let X := pairInput S labels hD + let E := B.execute f hf T hT X + let L := cursorLayout F b S.steps (u.θ : ℝ) (start n) n + ∀ z : E.Choices, let Y := E.finalState z + endAddress L + Y.totalWidth + (B.recordLimit + 2) * Y.positions * B.growthConstant ^ T + + suffix n < 2 ^ wordBits b n := by + have hθ : (u.θ : ℝ) ≤ 1 := by + have := (Rat.cast_lt (K := ℝ)).mpr u.theta_lt + norm_num at this + linarith only [this] + let K := B.recordLimit + 2 + let P := initialPositions b + let cap n := endAddress (cursorLayout F b S.steps (u.θ : ℝ) (start n) n) + + P n * n + K * (P n * n) + suffix n + have hp := CursorRAM.bounded_positions b + have hc : PolynomiallyBounded cap := + (((bounded_cursorEnd F b S.steps hθ hstart).add (hp.mul PolynomiallyBounded.id)).add + ((PolynomiallyBounded.const K).mul (hp.mul PolynomiallyBounded.id))).add hsuffix + have hb' := (le_max_right S.laneBits 5).trans hb + filter_upwards [CursorRAM.eventual_word_room b (by omega) hc, + eventually_pairBranchBounds B u b hb, eventually_ge_atTop 3] with n hroom branch hn + intro base lanes labels hD hT A _ f hf T X E L z Y + have bounds := branch.2.2 labels hD hT A f hf z + have hn₁ : (1 : ℝ) ≤ n := by exact_mod_cast (show 1 ≤ n by omega) + have hproc : processorCount b n ≤ P n := by + apply (Nat.pow_le_pow_right Nat.zero_lt_two (addressBits_le_virtualBits b n hn)).trans + exact Nat.le_mul_of_pos_right _ (zero_lt_one.trans hD) + have hwidth : Y.totalWidth ≤ P n * n := by + have ht := bounds.2.1 + change (Y.totalWidth : ℝ) ≤ (processorCount b n : ℝ) * (n : ℝ) ^ (1 - u.θ / 2 : ℝ) at ht + have he : (1 - (u.θ : ℝ) / 2 : ℝ) ≤ 1 := by + have hpθ := (Rat.cast_pos (K := ℝ)).mpr u.theta_pos + linarith only [hpθ] + have hpow : (n : ℝ) ^ (1 - u.θ / 2 : ℝ) ≤ n := by + simpa using Real.rpow_le_rpow_of_exponent_le hn₁ he + apply Nat.cast_le (α := ℝ) |>.mp + rw [Nat.cast_mul] + exact ht.trans (mul_le_mul (Nat.cast_le.mpr hproc) hpow + (Real.rpow_nonneg (Nat.cast_nonneg n) _) (Nat.cast_nonneg _)) + have hhist : B.growthConstant ^ T ≤ n := by + have hfield := bounds.2.2.2.2.2.1 + change ((B.growthConstant ^ T * (X.maxWireWidth + 1) : ℕ) : ℝ) ≤ (n : ℝ) ^ (3/10 : ℝ) at hfield + have hpow : (n : ℝ) ^ (3/10 : ℝ) ≤ n := by + simpa using Real.rpow_le_rpow_of_exponent_le hn₁ (by norm_num : (3/10 : ℝ) ≤ 1) + have : B.growthConstant ^ T * (X.maxWireWidth + 1) ≤ n := Nat.cast_le (α := ℝ) |>.mp (hfield.trans hpow) + exact (Nat.le_mul_of_pos_right _ (Nat.succ_pos _)).trans this + have hy : Y.positions ≤ P n := bounds.1 + have hdfs := Nat.mul_le_mul_left K (Nat.mul_le_mul hy hhist) + apply lt_of_le_of_lt _ hroom + change endAddress L + Y.totalWidth + K * Y.positions * B.growthConstant ^ T + suffix n ≤ + endAddress L + P n * n + K * (P n * n) + suffix n + rw [Nat.mul_assoc] + exact Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add_left hwidth _) hdfs) _ + +end CompressorRecords.DescriptorSpace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorCursorFrame.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorCursorFrame.lean new file mode 100644 index 0000000000..16ac658135 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorCursorFrame.lean @@ -0,0 +1,287 @@ +import OAI.Computability.VPVNP.CompressorDescriptorParameters + +/-! +# Persistent cursor parameters from the pair ABI + +The native parameter body reads the eight inputs prepared at workspace +offset nine. A seventeen-word loader starts at the workspace base, using +the last eight cached words for the body. The body publishes the eight +computed cursor fields at level zero, scalar offset six. A final native +copy restores the computed fields to the active frame for the stride pass. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorParameters + +open BurstRAM BurstRAM.PrivateRAM CursorBounds DescriptorSpace PhaseRecipe +open CursorRAM.ParametersInit +open scoped Fin.CommRing + +variable {w : ℕ} + +private def sourceSlot (j : Fin 8) : Fin 17 := j.natAdd 9 +private abbrev body := CursorRAM.ParametersInit.program.template (some 9) +private def padded := LiveStageLink.widen body (Function.Embedding.refl _) sourceSlot + +/-- The loader uses workspace public slot two and the input bank at offset nine. -/ +def loader := LiveStageLink.widen (Frame.compile padded) (Function.Embedding.refl _) + (fun _ : Fin 1 ↦ (2 : Fin 11)) + +private theorem offset_bank (base : Word w) (m : Memory w) : + (Frame.data base m : Fin 17 → Word w) ∘ sourceSlot = Frame.data (base+9) m := by + funext j + change m (base+((9+j.val : ℕ) : Word w)).val = m (base+9+(j.val : Word w)).val + rw [Nat.cast_add, Nat.cast_ofNat, add_assoc] + +private theorem execute_loader (pub : Fin 11 → Word w) (fuel : ℕ) (s : Word w) (m : Memory w) : + let M := loader.instantiate w pub + let Q := body.instantiate w (Frame.data (pub 2+9) m) + execute M.program (fuel+4*17) (M.program.start s) m [] = + (execute Q.program fuel (Q.program.start s) m []).map + (LiveStageLink.prependLog (Frame.loadEvents (pub 2) m 0 17)) := by + dsimp only + rw [loader, LiveStageLink.execute_widen_start] + change execute (Frame.machine padded (pub 2)).program (fuel+4*17) + ((Frame.machine padded (pub 2)).program.start s) m [] = _ + rw [Frame.execute_frame padded (pub 2) s fuel m [], padded, LiveStageLink.execute_widen_start, offset_bank] + +/-- The eight reserved scalar cells begin immediately after the six live level scalars. -/ +def saved (L : Layout) (w : ℕ) : Word w := CursorRAM.encode w (levelStart L 0+6) + +/-- The cursor parameters consumed by the scalar, stride and incidence passes. -/ +noncomputable def outputs (L : Layout) (B n a l w : ℕ) : Fin 8 → Word w := + CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L)) (CursorRAM.encode w 1) + (virtualBits B n-l) l a (initialWidth B n) (incidenceStart L 0) + +/-- The parameter-loader report, including its reads of the external frame, writes of the +computed operands and returned cursor. -/ +noncomputable def loaderReport (L : Layout) (B n a l : ℕ) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) : Report w := + LiveStageLink.prependLog (Frame.loadEvents (pub 2) m 0 17) + ⟨events n (saved L w) (outputs L B n a l w), some (s+1)⟩ + +private theorem frame_native (pub : Fin 11 → Word w) (f : ℕ) (s : Word w) (m : Memory w) + (rep : Report w) (run : let M := body.instantiate w (Frame.data (pub 2+9) m) + execute M.program f (M.program.start s) m [] = some rep) : + let M := loader.instantiate w pub + execute M.program (f+4*17) (M.program.start s) m [] = + some (LiveStageLink.prependLog (Frame.loadEvents (pub 2) m 0 17) rep) := + (execute_loader pub f s m).trans (congrArg (Option.map (LiveStageLink.prependLog (Frame.loadEvents (pub 2) m 0 17))) run) + +private theorem frame_effect (base dest s : Word w) (n : ℕ) (m : Memory w) (fields : Fin 8 → Word w) + (room : dest.val+8 ≤ 2^w) : + let bodyR : Report w := ⟨events n dest fields,some (s+1)⟩ + let r := LiveStageLink.prependLog (Frame.loadEvents base m 0 17) bodyR + let out := after m r.events + r.result = some (s+1) ∧ Frame.data dest out = fields ∧ + (∀ addr, addr < dest.val ∨ dest.val+8 ≤ addr → out addr = m addr) ∧ + r.events.length = VirtualParameters.ticks n+110 ∧ r.probes = 25 ∧ choiceBits r.events = [] := by + intro bodyR r out + have effect := Frame.frame_cost base m 0 17 bodyR + have afterBody : out = after m bodyR.events := effect.2.2.2.1 + have stored := frame_ready m n dest fields room + have wk := work n dest fields + refine ⟨rfl,(congrArg (Frame.data (k := 8) dest) afterBody).trans stored.1, + fun addr ha ↦ (congrFun afterBody addr).trans (stored.2 addr ha), ?_, ?_, effect.2.2.1.trans wk.2.2⟩ + · have small : ∀ t : ℕ, 4*17+(t+42) = t+110 := fun t ↦ by omega + exact effect.1.trans ((congrArg (4*17+·) wk.1).trans (small _)) + · exact effect.2.1.trans (congrArg (17+·) wk.2.1) + +set_option maxHeartbeats 300000 in +/-- With the prepared bank in memory, the compiled pair-ABI call writes the +persistent bank, changes no other external word and uses 25 probes. -/ +theorem publish {L B n a l} (hw : w = wordBits B n) (hB : 1 ≤ B) (hl : l ≤ virtualBits B n) + (h : Capacity B n a l (directoryBase L) 1 (incidenceStart L 0) (levelStart L 0+6)) + (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bank : Frame.data (pub 2+9) m = (fun i ↦ CursorRAM.encode w + (inputValues n (addressBits B n) a l (directoryBase L) 1 (incidenceStart L 0) (levelStart L 0+6) i))) : + let M := loader.instantiate w pub + let r := loaderReport L B n a l pub s m + let out := after m r.events + execute M.program (VirtualParameters.ticks n+43+4*17) (M.program.start s) m [] = some r ∧ + r.result = some (s+1) ∧ Frame.data (saved L w) out = outputs L B n a l w ∧ + (∀ addr, addr < levelStart L 0+6 ∨ levelStart L 0+14 ≤ addr → out addr = m addr) ∧ + r.events.length = VirtualParameters.ticks n+110 ∧ r.probes = 25 ∧ choiceBits r.events = [] := by + intro M r out + let p : Fin 8 → Word w := Frame.data (pub 2+9) m + have pv (i : Fin 8) : (p i).val = inputValues n (addressBits B n) a l (directoryBase L) 1 + (incidenceStart L 0) (levelStart L 0+6) i := + (congrArg Fin.val (congrFun bank i)).trans (Nat.mod_eq_of_lt (hw ▸ h.public_lt i)) + have rowEq : p 4 = CursorRAM.encode w (directoryBase L) := congrFun bank 4 + have tagEq : p 5 = CursorRAM.encode w 1 := congrFun bank 5 + have columnEq : (p 6).val = incidenceStart L 0 := pv 6 + have fields : CursorRAM.ScheduleInit.inputs (p 4) (p 5) (virtualBits B n-l) l a + (initialWidth B n) (p 6).val = outputs L B n a l w := by + rw [rowEq, tagEq, columnEq]; rfl + have dest : p 7 = saved L w := congrFun bank 7 + have nativeBody := native (B := B) (n := n) (a := a) (l := l) (pub := p) s m hB + ((by decide : 2 ≤ 3).trans h.length_ge) hw (pv 0) (pv 1) (pv 2) (pv 3) (hw ▸ h.degree_lt) hl + have sameLog := congrArg₂ (events n) dest fields + have result := nativeBody.trans + (congrArg some (congrArg (fun es ↦ (⟨es,some (s+1)⟩ : Report w)) sameLog)) + have hv : (saved L w).val = levelStart L 0+6 := (congrArg Fin.val dest.symm).trans (pv 7) + have room : (saved L w).val+8 ≤ 2^w := hv ▸ (hw ▸ h.frame_end.le) + have ef := frame_effect (pub 2) (saved L w) s n m (outputs L B n a l w) room + refine ⟨frame_native pub (VirtualParameters.ticks n+43) s m _ result, ef.1, ef.2.1, ?_, ef.2.2.2⟩ + intro addr ha + apply ef.2.2.1 addr + simpa only [hv,Nat.add_assoc,Nat.reduceAdd] using ha + +/-- Read the computed persistent words into registers before writing their +active-frame copies. -/ +def copy (F : Shape) : FormulaRow 5 where + dest := (.publicWord 0 : Expr).add (.lit 9) + fields j := .load ((persistentBank F.arity).add (.lit j.val)) + +/-- The persistent-frame copy instruction table with its public operands embedded in the pair +machine's eleven-word bank. -/ +def copyTable (F : Shape) := LiveStageLink.widen (copy F).recipe.table (Function.Embedding.refl _) operand + +/-- Copying uses the stored chronological row count to locate the first level. -/ +theorem copy_run {L B n initial phases T pub m} (h : Ready (w := w) L B n initial phases T pub m) + (s : Word w) (fit : frameBase L + 8 < 2^w) : + let R := copy L.shape + let M := (copyTable L.shape).instantiate w pub + let r := R.recipe.report (pub ∘ operand) s m + let out := after m r.events + execute M.program (R.recipe.code.length+1) (M.program.start s) m [] = some r ∧ + r.result = some (s+1) ∧ + (Frame.data (pub 2+9) out : Fin 8 → Word w) = Frame.data (saved L w) m ∧ + (∀ addr, addr < frameBase L ∨ frameBase L+8 ≤ addr → out addr = m addr) ∧ + r.events.length = R.recipe.code.length ∧ r.probes = R.recipe.reads+8 ∧ choiceBits r.events = [] := by + intro R M r out + have hx : (pub 2+9).val = frameBase L := by + change _ = L.base+9 + change L.base+9+8 < 2^w at fit + have h9 : (9 : Word w).val = 9 := Nat.mod_eq_of_lt (by omega : 9 < 2^w) + rw [Fin.val_add,h.workspace,h9,Nat.mod_eq_of_lt (by omega : L.base+9 < 2^w)] + have room : (pub 2+9).val+8 ≤ 2^w := hx ▸ fit.le + have ⟨hr,ret,store,keep,work⟩ := R.execute (pub ∘ operand) s m room + refine ⟨(LiveStageLink.execute_widen_start ..).trans hr, ret, ?_, ?_, work⟩ + · funext j + rw [Frame.data_at _ _ room j] + apply (store j).trans + change m (((firstLevel L.shape.arity).eval (pub ∘ operand) s m + 6) + (j.val : Word w)).val = + m ((saved L w)+(j.val : Word w)).val + rw [eval_level h, saved] + congr 2 + change ((levelStart L 0 : ℕ) : Word w) + 6 + (j.val : Word w) = + ((levelStart L 0 + 6 : ℕ) : Word w) + (j.val : Word w) + rw [Nat.cast_add, Nat.cast_ofNat] + · intro addr ha + apply keep addr + change addr < (pub 2+9).val ∨ (pub 2+9).val+8 ≤ addr + rwa [hx] + +/-- The reports refer to the actual entry memory of each successive stage. -/ +structure Trace (w : ℕ) where + /-- Report publishing the raw input-length, geometry and address operands of the cursor + frame. -/ + raw : Report w + /-- Report loading the raw frame and computing the final cursor parameters. -/ + loaded : Report w + /-- Report copying the final cursor parameters to their persistent level-zero locations. -/ + copied : Report w + +/-- External memory after executing the raw parameter publisher's report. -/ +def Trace.postRaw (t : Trace w) (m : Memory w) := after m t.raw.events +/-- External memory after the raw publisher and parameter loader reports. -/ +def Trace.postLoad (t : Trace w) (m : Memory w) := after (t.postRaw m) t.loaded.events +/-- External memory after the raw publisher, parameter loader and persistent frame copy. -/ +def Trace.post (t : Trace w) (m : Memory w) := after (t.postLoad m) t.copied.events +/-- The three descriptor-parameter reports in their execution order. -/ +def Trace.log (t : Trace w) := [t.raw, t.loaded, t.copied] + +/-- Construct the raw, loader and copy reports using the specified cursors and each preceding +report's output memory. -/ +noncomputable def trace (L : Layout) (B n a initial phases T lanes : ℕ) (pub : Fin 11 → Word w) + (s₀ s₁ s₂ : Word w) (m : Memory w) : Trace w := + let r₀ := (raw L.shape a initial phases lanes).recipe.report (pub ∘ operand) s₀ m + let m₁ := after m r₀.events + let r₁ := loaderReport L B n a (T*lanes) pub s₁ m₁ + let r₂ := (copy L.shape).recipe.report (pub ∘ operand) s₂ (after m₁ r₁.events) + ⟨r₀,r₁,r₂⟩ + +set_option maxHeartbeats 600000 in +/-- Execute the three fixed pair-ABI tables. Each entry state may be chosen +by its enclosing linker. Both banks contain the actual cursor parameters, +and all other memory, including the row count, is preserved. -/ +theorem run {L B n initial phases T pub m} (h : Ready (w := w) L B n initial phases T pub m) + (hw : w = CursorBounds.wordBits B n) (hB : 1 ≤ B) (a lanes : ℕ) + (hl : T*lanes ≤ virtualBits B n) (arity : 7 ≤ L.shape.arity) (scalars : 14 ≤ L.shape.scalarFields) + (hc : Capacity B n a (T*lanes) (directoryBase L) 1 (incidenceStart L 0) (levelStart L 0+6)) + (s₀ s₁ s₂ : Word w) : + let t := trace L B n a initial phases T lanes pub s₀ s₁ s₂ m + let A := (table L.shape a initial phases lanes).instantiate w pub + let M := loader.instantiate w pub + let C := (copyTable L.shape).instantiate w pub + let R := raw L.shape a initial phases lanes + let Q := copy L.shape + execute A.program (R.recipe.code.length+1) (A.program.start s₀) m [] = some t.raw ∧ + execute M.program (VirtualParameters.ticks n+43+4*17) (M.program.start s₁) (t.postRaw m) [] = some t.loaded ∧ + execute C.program (Q.recipe.code.length+1) (C.program.start s₂) (t.postLoad m) [] = some t.copied ∧ + t.raw.result = some (s₀+1) ∧ t.loaded.result = some (s₁+1) ∧ t.copied.result = some (s₂+1) ∧ + Frame.data (saved L w) (t.post m) = outputs L B n a (T*lanes) w ∧ + Frame.data (pub 2+9) (t.post m) = outputs L B n a (T*lanes) w ∧ + (∀ addr, (addr < frameBase L ∨ frameBase L+8 ≤ addr) → + (addr < levelStart L 0+6 ∨ levelStart L 0+14 ≤ addr) → t.post m addr = m addr) ∧ + levelStart L 0+14 ≤ levelStart L 0+L.shape.scalarFields ∧ + RAMBuckets.cost Report.probes t.log = R.recipe.reads + Q.recipe.reads + 44 ∧ + (eventLog t.log).length = R.recipe.code.length + (VirtualParameters.ticks n+110) + Q.recipe.code.length ∧ + branchPaths t.log = [[],[],[]] := by + intro t A M C R Q + have before : frameBase L+8 ≤ levelStart L 0+6 := by + calc + frameBase L+8 ≤ frameBase L+(L.shape.arity+1) := Nat.add_le_add_left (by omega) _ + _ ≤ directoryBase L := frame_before_directory L + _ ≤ levelStart L 0+6 := by + simp only [levelStart, Nat.zero_mul, Nat.add_zero, levelsBase] + exact (Nat.le_add_right ..).trans (Nat.le_add_right ..) + have savedFit : levelStart L 0+6+8 < 2^w := hw ▸ hc.frame_end + have activeFit := before.trans_lt ((Nat.le_add_right ..).trans_lt savedFit) + have ⟨h₀,r₀,rawBank,k₀,sz₀,p₀,c₀⟩ := prepare h s₀ a lanes activeFit + have ⟨h₁,r₁,bank,k₁,sz₁,p₁,c₁⟩ := publish hw hB hl hc pub s₁ (t.postRaw m) rawBank + have countAddr : (pub 2+8).val = L.base+8 := by + change L.base+9+8 < 2^w at activeFit + rw [Fin.val_add,h.workspace,show (8 : Word w).val = 8 from Nat.mod_eq_of_lt (by omega : 8 < 2^w), + Nat.mod_eq_of_lt (by omega : L.base+8 < 2^w)] + have countLow : (pub 2+8).val < frameBase L := countAddr ▸ (Nat.add_lt_add_left (by decide : 8 < 9) L.base) + have countSaved : (pub 2+8).val < levelStart L 0+6 := countLow.trans_le ((Nat.le_add_right ..).trans before) + have sameCount : t.postLoad m (pub 2+8).val = m (pub 2+8).val := + (k₁ _ (Or.inl countSaved)).trans (k₀ _ (Or.inl countLow)) + have h' : Ready L B n initial phases T pub (t.postLoad m) := + { h with total := (congrArg Fin.val sameCount).trans h.total } + have ⟨h₂,r₂,active,k₂,sz₂,p₂,c₂⟩ := copy_run h' s₂ activeFit + have savedVal : (saved L w).val = levelStart L 0+6 := + Nat.mod_eq_of_lt ((Nat.le_add_right ..).trans_lt savedFit) + have room : (saved L w).val+8 ≤ 2^w := savedVal ▸ savedFit.le + have permanent : (Frame.data (saved L w) (t.post m) : Fin 8 → Word w) = Frame.data (saved L w) (t.postLoad m) := by + funext j + rw [Frame.data_at _ _ room, Frame.data_at _ _ room] + exact k₂ _ (Or.inr (before.trans (savedVal ▸ Nat.le_add_right ..))) + refine ⟨h₀,h₁,h₂,r₀,r₁,r₂,permanent.trans bank,active.trans bank,?_,Nat.add_le_add_left scalars _,?_,?_,?_⟩ + · intro addr ha hs + exact (k₂ _ ha).trans ((k₁ _ hs).trans (k₀ _ ha)) + · change 1+t.raw.probes+(1+t.loaded.probes+(1+t.copied.probes+0)) = R.recipe.reads+Q.recipe.reads+44 + change t.raw.probes = R.recipe.reads+8 at p₀ + change t.loaded.probes = 25 at p₁ + change t.copied.probes = Q.recipe.reads+8 at p₂ + rw [p₀,p₁,p₂]; omega + · simp only [Trace.log,eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil,List.length_append] + change t.raw.events.length = R.recipe.code.length at sz₀ + change t.loaded.events.length = VirtualParameters.ticks n+110 at sz₁ + change t.copied.events.length = Q.recipe.code.length at sz₂ + simp only [sz₀,sz₁,sz₂,Nat.add_assoc] + · change [choiceBits t.raw.events, choiceBits t.loaded.events, choiceBits t.copied.events] = _ + change choiceBits t.raw.events = [] at c₀ + change choiceBits t.loaded.events = [] at c₁ + change choiceBits t.copied.events = [] at c₂ + rw [c₀,c₁,c₂] + +end CompressorRecords.DescriptorParameters + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorHeads.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorHeads.lean new file mode 100644 index 0000000000..03e2b38568 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorHeads.lean @@ -0,0 +1,127 @@ +import OAI.Computability.VPVNP.CompressorDescriptorSpace +import OAI.Computability.VPVNP.CompressorFormulaRow + +/-! +# Publishing the pointer words of a compressor level + +After the scalar publisher has installed the current base count, degree and +lane count, a fixed burst writes the six incidence column heads and the heads +of all fixed-width record tables. The current row count comes from the current +header. The rectangular table capacity comes from the initial header, whose +base count times lane count gives the initial number of positions. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorHeads + +open BurstRAM BurstRAM.PrivateRAM DescriptorSpace PhaseRecipe +open scoped Fin.CommRing + +variable {w : ℕ} + +private def loadAt (p : Fin 5) (j : ℕ) : Expr := .load ((Expr.publicWord p).add (.lit j)) + +private def rowCount : Expr := ((loadAt 0 0).mul (loadAt 0 2)).mul (loadAt 0 1) + +private def capacity (F : Shape) : Expr := ((loadAt 1 0).mul (loadAt 1 2)).mul (.lit F.slots) + +private def firstColumn (F : Shape) : Expr := (Expr.publicWord 0).add (.lit (F.scalarFields+6+F.tables)) + +/-- The shape is compiled into the worker. Public words zero and one hold +the current level header address and the level-zero header address. -/ +def publisher (F : Shape) : FormulaRow (F.tables + 3) where + dest := (Expr.publicWord 0).add (.lit F.scalarFields) + fields j := if j.val < 6 then (firstColumn F).add ((Expr.lit j.val).mul rowCount) + else ((firstColumn F).add ((Expr.lit 6).mul (capacity F))).add + ((Expr.lit (j.val-6)).mul ((capacity F).mul (.lit F.fields))) + +/-- Catalog entry for one guarded call at cursor zero. -/ +def worker (F : Shape) : Schedule.Pass := + ⟨_, _, _, (publisher F).recipe.table⟩ + +/-- The three live scalar cells shared with the scalar publisher. -/ +structure CountsAt (base : Word w) (m : Memory w) (V D lanes : ℕ) : Prop where + vertices : m base.val = (V : Word w) + degree : m (base + 1).val = (D : Word w) + replicas : m (base + 2).val = (lanes : Word w) + +variable (L : Layout) (i : Fin L.levels) (pub : Fin 5 → Word w) (m : Memory w) + +/-- Natural addresses calculated by the native code, expressed in the same +level-major coordinates as the cursor, shrink and refresh consumers. -/ +theorem publish (s : Word w) (fit : endAddress L < 2^w) + (current : pub 0 = (levelStart L i : Word w)) (first : pub 1 = (levelStart L 0 : Word w)) + {V D lanes V₀ D₀ lanes₀ : ℕ} (h : CountsAt (levelStart L i : Word w) m V D lanes) + (h₀ : CountsAt (levelStart L 0 : Word w) m V₀ D₀ lanes₀) + (hP : V₀ * lanes₀ = L.positions) : + let R := publisher L.shape + let M := R.recipe.table.instantiate w pub + let rep := R.recipe.report pub s m + let out := after m rep.events + execute M.program (R.recipe.code.length+1) (M.program.start s) m [] = some rep ∧ + rep.result = some (s+1) ∧ + (∀ c : Fin 6, out (incidenceHead L i c) = (incidenceBase L i (V*lanes*D) c : Word w)) ∧ + (∀ a : Fin L.shape.tables, out (tableHead L i a) = (tableBase L i a : Word w)) ∧ + (∀ a, a < levelStart L i + L.shape.scalarFields ∨ incidenceStart L i ≤ a → out a = m a) ∧ + rep.events.length = R.recipe.code.length ∧ rep.probes = R.recipe.reads + (L.shape.tables+3+3) ∧ + choiceBits rep.events = [] := by + intro R M rep out + have hs := level_room L fit i + have hh : incidenceStart L i ≤ levelStart L (i.val+1) := by + simp only [incidenceStart, levelStart, Nat.succ_mul, levelWords] + omega + have hroom := hh.trans_lt hs + change levelStart L i + (L.shape.scalarFields + 6 + L.shape.tables) < 2^w at hroom + have dest : R.dest.eval pub s m = ((levelStart L i + L.shape.scalarFields : ℕ) : Word w) := by + simp [R, publisher, Expr.eval, Expr.add, BinaryOp.eval, current] + have hv : (R.dest.eval pub s m).val = levelStart L i + L.shape.scalarFields := by + rw [dest, Fin.val_natCast, Nat.mod_eq_of_lt (by omega)] + have hfit : (R.dest.eval pub s m).val + (L.shape.tables+3+3) ≤ 2^w := by rw [hv]; omega + have run := R.execute pub s m hfit + have hV : m (levelStart L i % 2^w) = (V : Word w) := h.vertices + have hV₀ : m (levelStart L 0 % 2^w) = (V₀ : Word w) := h₀.vertices + have rows : rowCount.eval pub s m = ((V * lanes * D : ℕ) : Word w) := by + simp [rowCount, loadAt, Expr.add, Expr.mul, Expr.eval, BinaryOp.eval, current, + hV, h.degree, h.replicas] + have cap : (capacity L.shape).eval pub s m = (slotCapacity L : Word w) := by + simp [capacity, loadAt, Expr.add, Expr.mul, Expr.eval, BinaryOp.eval, first, + hV₀, h₀.replicas, slotCapacity, ← hP] + have col : (firstColumn L.shape).eval pub s m = (incidenceStart L i : Word w) := by + simp [firstColumn, Expr.eval, Expr.add, BinaryOp.eval, current, incidenceStart, levelHeaderWords] + refine ⟨run.1, run.2.1, ?_, ?_, ?_, run.2.2.2.2⟩ + · intro c + let j : Fin (L.shape.tables+3+3) := ⟨c.val, by have := c.isLt; omega⟩ + have hw := run.2.2.1 j + rw [hv] at hw + change out (incidenceHead L i c) = _ + have hf : (R.fields j).eval pub s m = + (incidenceBase L i (V * lanes * D) c : Word w) := by + change (if c.val < 6 then _ else _ : Expr).eval pub s m = _ + rw [ite_eq_left c.isLt] + simp only [j, Expr.add, Expr.mul, Expr.eval, BinaryOp.eval, col, rows, incidenceBase, Nat.cast_add, + Nat.cast_mul] + exact hw.trans hf + · intro a + let j : Fin (L.shape.tables+3+3) := ⟨6+a.val, by have := a.isLt; omega⟩ + have hw := run.2.2.1 j + rw [hv] at hw + have hf : (R.fields j).eval pub s m = (tableBase L i a : Word w) := by + change (if 6+a.val < 6 then _ else _ : Expr).eval pub s m = _ + rw [ite_eq_right (by omega)] + simp only [j, Expr.add, Expr.mul, Expr.eval, BinaryOp.eval, col, cap, + Nat.add_sub_cancel_left, tableBase, tableWords, arrayBase, Nat.cast_add, Nat.cast_mul, + Nat.cast_ofNat] + simpa only [j, tableHead, Nat.add_assoc] using hw.trans hf + · intro a ha + apply run.2.2.2.1 + rw [hv] + simpa only [incidenceStart, levelHeaderWords, Nat.add_assoc, Nat.add_comm 6 L.shape.tables] using ha + +end CompressorRecords.DescriptorHeads + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorParameterCapacity.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorParameterCapacity.lean new file mode 100644 index 0000000000..d1266e590c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorParameterCapacity.lean @@ -0,0 +1,88 @@ +import OAI.Computability.VPVNP.CompressorDescriptorParameters +import OAI.Computability.VPVNP.CompressorCalendarRows + +/-! +# Space for the cursor parameters in the chronological directory + +The first level follows the exact number of rows published by the calendar. +Its address depends only on the polynomially bounded workspace base, the +fixed row pitch and that row count. Hence one threshold works independently +of the allocated position and level counts. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorParameters + +open BurstRAM CursorBounds DescriptorSpace LevelFields Filter CursorRAM.ParametersInit + +private theorem bounded_blocks (D : CalendarRows.Spec) : PolynomiallyBounded (roundedDown D.p D.q) := + (PolynomiallyBounded.id.pow D.p).of_le fun n ↦ Nat.log_le_self (2^D.q) (n^D.p) + +private theorem bounded_rows (D : CalendarRows.Spec) : PolynomiallyBounded (CalendarRows.rows D) := + (PolynomiallyBounded.const D.initialRows).add ((PolynomiallyBounded.const D.phaseRows).mul (bounded_blocks D)) + +theorem eventually_tight_capacity (D : CalendarRows.Spec) (F : Shape) (B a lanes : ℕ) + (hB : 1 ≤ B) (hθ : (D.p : ℝ) / D.q ≤ 1) (hlanes : lanes ≤ B) + {base : ℕ → ℕ} (hb : PolynomiallyBounded base) : + ∀ᶠ n : ℕ in atTop, ∀ positions levels : ℕ, + let L := tightDirectory ⟨F,base n,positions,levels⟩ (CalendarRows.rows D n) + let l := roundedDown D.p D.q n * lanes + l ≤ virtualBits B n ∧ + Capacity B n a l (directoryBase L) 1 (incidenceStart L 0) (levelStart L 0+6) := by + let dir n := base n+9+(F.arity+1)+1 + let first n := dir n + CalendarRows.rows D n * (F.arity+3) + let columns n := first n + (F.scalarFields+6+F.tables) + let dest n := first n+6 + have hd : PolynomiallyBounded dir := + ((hb.add (PolynomiallyBounded.const 9)).add (PolynomiallyBounded.const (F.arity+1))).add + (PolynomiallyBounded.const 1) + have hfirst : PolynomiallyBounded first := hd.add ((bounded_rows D).mul (PolynomiallyBounded.const (F.arity+3))) + have hcols : PolynomiallyBounded columns := hfirst.add (PolynomiallyBounded.const (F.scalarFields+6+F.tables)) + have hdest : PolynomiallyBounded dest := hfirst.add (PolynomiallyBounded.const 6) + filter_upwards [eventually_ge_atTop 3, eventually_capacity B a hB hd (PolynomiallyBounded.const 1) + hcols hdest] with n hn hc + intro positions levels + have hl : roundedDown D.p D.q n * lanes ≤ virtualBits B n := by + rw [roundedDown_eq, Nat.mul_comm] + exact laneBudget B lanes n hlanes hθ hn + refine ⟨hl, ?_⟩ + let L := tightDirectory ⟨F,base n,positions,levels⟩ (CalendarRows.rows D n) + have eqFirst : levelStart L 0 = first n := by + simp only [L,levelStart,levelsBase,tight_rows,Nat.zero_mul,Nat.add_zero] + rfl + change Capacity B n a (roundedDown D.p D.q n * lanes) (directoryBase L) 1 + (levelStart L 0+levelHeaderWords L) (levelStart L 0+6) + rw [eqFirst] + exact hc _ hl + +/-- The exclusive descriptor end placed in the history-arena scalar fits +even if the chronological calendar differs from the reserved pass schedule. -/ +theorem eventually_tight_end (D : CalendarRows.Spec) (F : Shape) (B steps : ℕ) (hB : 1 ≤ B) + {base : ℕ → ℕ} (hb : PolynomiallyBounded base) : + ∀ᶠ n : ℕ in atTop, + endAddress (tightDirectory (cursorLayout F B steps ((D.p : ℝ)/D.q) (base n) n) + (CalendarRows.rows D n)) < 2^wordBits B n := by + let dir n := base n+9+(F.arity+1)+1 + let first n := dir n + CalendarRows.rows D n * (F.arity+3) + have hd : PolynomiallyBounded dir := + ((hb.add (PolynomiallyBounded.const 9)).add (PolynomiallyBounded.const (F.arity+1))).add + (PolynomiallyBounded.const 1) + have hf : PolynomiallyBounded first := hd.add ((bounded_rows D).mul (PolynomiallyBounded.const (F.arity+3))) + have levels := (PolynomiallyBounded.const 1).add ((PolynomiallyBounded.const (steps+1)).mul (bounded_blocks D)) + have slots := (CursorRAM.bounded_positions B).mul (PolynomiallyBounded.const F.slots) + have tables := (PolynomiallyBounded.const F.tables).mul (slots.mul (PolynomiallyBounded.const F.fields)) + have stride := ((PolynomiallyBounded.const (F.scalarFields+6+F.tables)).add + ((PolynomiallyBounded.const 6).mul slots)).add tables + filter_upwards [CursorRAM.eventual_word_room B hB (hf.add (levels.mul stride))] with n h + simp only [endAddress,levelStart,levelsBase,tight_rows,tight_stride] + rw [roundedDown_eq] at h + exact h + +end CompressorRecords.DescriptorParameters + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorParameters.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorParameters.lean new file mode 100644 index 0000000000..f9597014a6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorParameters.lean @@ -0,0 +1,164 @@ +import OAI.Computability.VPVNP.CompressorFormulaRow +import OAI.Computability.VPVNP.CompressorRecordsCursorParameterBounds +import OAI.Computability.VPVNP.CompressorRecordsLevelFields + +/-! +# Computing the cursor input frame in the tight descriptor layout + +The chronological row count is already in the workspace at offset eight. +From that count the pair-ABI program recovers the number of compression +blocks, the lane exponent and the first level address. It places eight raw +words in the active frame. Their destination points to eight persistent +scalar cells in the first level, starting at offset six. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorParameters + +open BurstRAM BurstRAM.PrivateRAM CursorBounds DescriptorSpace PhaseRecipe +open CursorRAM.ParametersInit +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- The formula compiler uses the actual pair ABI's workspace, input length and address width. -/ +def operand : Fin 5 → Fin 11 := ![2, 6, 7, 2, 2] + +private def base : Expr := .publicWord 0 +private def count : Expr := .load (base.add (.lit 8)) +private def directory (g : ℕ) := base.add (.lit (11+g)) +/-- Expression locating the first level header immediately after the calendar's fixed-width +directory rows. -/ +def firstLevel (g : ℕ) := (directory g).add (count.mul (.lit (g+3))) +/-- Expression locating the persistent cursor bank six words into the first level header. -/ +def persistentBank (g : ℕ) := (firstLevel g).add (.lit 6) +/-- Recover the number of complete repeated blocks from the published row count. -/ +def calendarBlocks (initial phases : ℕ) := (count.sub (.lit initial)).div (.lit phases) + +private def laneExponent (initial phases lanes : ℕ) := (calendarBlocks initial phases).mul (.lit lanes) + +/-- Eight published raw words consumed by the cursor parameter program. -/ +def raw (F : Shape) (a initial phases lanes : ℕ) : FormulaRow 5 where + dest := base.add (.lit 9) + fields := ![.publicWord 1, .publicWord 2, .lit a, laneExponent initial phases lanes, + directory F.arity, .lit 1, (firstLevel F.arity).add (.lit (F.scalarFields+6+F.tables)), + persistentBank F.arity] + +/-- The pair ABI exposes all the operands of the native frame publisher. -/ +def table (F : Shape) (a initial phases lanes : ℕ) := + LiveStageLink.widen (raw F a initial phases lanes).recipe.table (Function.Embedding.refl _) operand + +private theorem word_eq {v : Word w} {n : ℕ} (hv : v.val = n) : v = (n : Word w) := by + subst n + exact Fin.ext (Nat.mod_eq_of_lt v.isLt).symm + +/-- Inputs available at normal entry after the calendar has published its count. -/ +structure Ready (L : Layout) (B n initial phases T : ℕ) (pub : Fin 11 → Word w) (m : Memory w) : Prop where + workspace : (pub 2).val = L.base + length : (pub 6).val = n + address : (pub 7).val = addressBits B n + total : (m (pub 2+8).val).val = initial + T*phases + layoutCount : directoryRows L = initial + T*phases + phase_pos : 0 < phases + phase_fit : phases < 2^w + +theorem eval_level {L B n initial phases T pub m} (h : Ready (w := w) L B n initial phases T pub m) + (s : Word w) : + (firstLevel L.shape.arity).eval (pub ∘ operand) s m = (levelStart L 0 : Word w) := by + change pub 2 + ((11+L.shape.arity : ℕ) : Word w) + + m (pub 2+8).val * ((L.shape.arity+3 : ℕ) : Word w) = _ + rw [word_eq h.total, word_eq h.workspace] + simp only [levelStart, Nat.zero_mul, Nat.add_zero, levelsBase, directoryBase, plannerTag, frameBase, + h.layoutCount, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat, Nat.cast_one] + ring + +private theorem eval_lanes {L B n initial phases T pub m} (h : Ready (w := w) L B n initial phases T pub m) + (s : Word w) (lanes : ℕ) : + (laneExponent initial phases lanes).eval (pub ∘ operand) s m = (T*lanes : ℕ) := by + let c := m (pub 2+8).val + have ht : c.val = initial + T*phases := h.total + have hi : (initial : Word w).val = initial := Nat.mod_eq_of_lt + ((Nat.le_add_right ..).trans_lt (ht ▸ c.isLt)) + have hsub : (c-(initial : Word w)).val = T*phases := by + rw [Fin.sub_val_of_le (by change (initial : Word w).val ≤ c.val; omega), ht, hi, Nat.add_sub_cancel_left] + have hdiv : (BinaryOp.div.eval (c-(initial : Word w)) (phases : Word w)).val = T := by + change ((c-(initial : Word w)).val / (phases : Word w).val) % (2^w) = T + rw [hsub, show (phases : Word w).val = phases from Nat.mod_eq_of_lt h.phase_fit, + Nat.mul_div_cancel _ h.phase_pos, Nat.mod_eq_of_lt] + exact (Nat.le_mul_of_pos_right _ h.phase_pos).trans_lt + ((Nat.le_add_left ..).trans_lt (ht ▸ c.isLt)) + change BinaryOp.div.eval (c-(initial : Word w)) (phases : Word w) * (lanes : Word w) = _ + rw [word_eq hdiv, Nat.cast_mul] + +theorem eval_blocks {L B n initial phases T pub m} (h : Ready (w := w) L B n initial phases T pub m) + (s : Word w) : (calendarBlocks initial phases).eval (pub ∘ operand) s m = (T : Word w) := by + have eqn := eval_lanes h s 1 + change (calendarBlocks initial phases).eval (pub ∘ operand) s m * 1 = ((T*1 : ℕ) : Word w) at eqn + simpa using eqn + +/-- The row's eight native word expressions are exactly the raw cursor parameters. -/ +theorem raw_values {L B n initial phases T pub m} (h : Ready (w := w) L B n initial phases T pub m) + (s : Word w) (a lanes : ℕ) : + (fun i ↦ ((raw L.shape a initial phases lanes).fields i).eval (pub ∘ operand) s m) = + (fun i ↦ CursorRAM.encode w + (inputValues n (addressBits B n) a (T*lanes) (directoryBase L) 1 (incidenceStart L 0) + (levelStart L 0+6) i)) := by + funext i + fin_cases i + · exact word_eq h.length + · exact word_eq h.address + · rfl + · exact eval_lanes h s lanes + · change pub 2 + ((11+L.shape.arity : ℕ) : Word w) = ((directoryBase L : ℕ) : Word w) + rw [word_eq h.workspace] + simp only [directoryBase, plannerTag, frameBase, Nat.cast_add, Nat.cast_one, Nat.cast_ofNat] + ring + · rfl + · change (firstLevel L.shape.arity).eval (pub ∘ operand) s m + + ((L.shape.scalarFields+6+L.shape.tables : ℕ) : Word w) = ((incidenceStart L 0 : ℕ) : Word w) + rw [eval_level h, incidenceStart, levelHeaderWords] + push_cast + rfl + · change (firstLevel L.shape.arity).eval (pub ∘ operand) s m + (6 : Word w) = ((levelStart L 0+6 : ℕ) : Word w) + rw [eval_level h, Nat.cast_add, Nat.cast_ofNat] + +/-- Executing the pair-ABI publisher writes the raw bank at workspace offset nine. +It preserves the calendar count, the controller header and all other cells. -/ +theorem prepare {L B n initial phases T pub m} (h : Ready (w := w) L B n initial phases T pub m) + (s : Word w) (a lanes : ℕ) (fit : frameBase L + 8 < 2^w) : + let R := raw L.shape a initial phases lanes + let M := (table L.shape a initial phases lanes).instantiate w pub + let r := R.recipe.report (pub ∘ operand) s m + let out := after m r.events + execute M.program (R.recipe.code.length+1) (M.program.start s) m [] = some r ∧ + r.result = some (s+1) ∧ + Frame.data (pub 2+9) out = (fun i ↦ CursorRAM.encode w + (inputValues n (addressBits B n) a (T*lanes) (directoryBase L) 1 (incidenceStart L 0) + (levelStart L 0+6) i)) ∧ + (∀ addr, addr < frameBase L ∨ frameBase L+8 ≤ addr → out addr = m addr) ∧ + r.events.length = R.recipe.code.length ∧ r.probes = R.recipe.reads+8 ∧ choiceBits r.events = [] := by + intro R M r out + have hx : (pub 2+9).val = frameBase L := by + change _ = L.base+9 + change L.base+9+8 < 2^w at fit + have h9 : (9 : Word w).val = 9 := Nat.mod_eq_of_lt (by omega : 9 < 2^w) + rw [Fin.val_add, h.workspace, h9, Nat.mod_eq_of_lt (by omega : L.base+9 < 2^w)] + have room : (pub 2+9).val+8 ≤ 2^w := hx ▸ fit.le + have ⟨hr,ret,store,keep,work⟩ := R.execute (pub ∘ operand) s m room + refine ⟨(LiveStageLink.execute_widen_start ..).trans hr, ret, ?_, ?_, work⟩ + · funext j + rw [Frame.data_at _ _ room j] + exact (store j).trans (congrFun (raw_values h s a lanes) j) + · intro addr ha + apply keep addr + change addr < (pub 2+9).val ∨ (pub 2+9).val+8 ≤ addr + rwa [hx] + +end CompressorRecords.DescriptorParameters + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorScalars.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorScalars.lean new file mode 100644 index 0000000000..afcc35fd87 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorScalars.lean @@ -0,0 +1,327 @@ +import OAI.Computability.VPVNP.CompressorFormulaRow +import OAI.Computability.VPVNP.CompressorDescriptorSpace +import OAI.Computability.VPVNP.CompressorRecordsCursorParameters +import OAI.Computability.VPVNP.CompressorLevelCounts + +/-! +# Publishing the six level scalars for the online compressor + +A header describes the current graph and the fixed pass that will consume it. +The initial burst reads the generated cursor parameter frame. Each subsequent +burst reads the preceding level header. Its vertex count grows by the tag radix +for a shrink and by the old degree for a refresh. Its lane count is the preceding +residual radix. The destination address is the worker's first public operand. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorSpace.Scalars + +open BurstRAM BurstRAM.PrivateRAM PhaseRecipe Compression +open scoped Fin.CommRing + +/-- The input and output indices are degree exponents. A terminal level spends +no lanes and records its current degree as the output degree. -/ +inductive Pass : ℕ → ℕ → Type + | shrink (a b : ℕ) : Pass a b + | refresh (a b expanderExponent : ℕ) : Pass a b + | terminal (a : ℕ) : Pass a a + +variable {a b c w : ℕ} + +/-- Number of binary lane coordinates consumed by this pass, with zero consumption at a +terminal level. -/ +def Pass.spent : Pass a b → ℕ + | .shrink _ _ => packingLaneBits a 0 + | .refresh _ _ _ => a + | .terminal _ => 0 + +/-- Multiplier for the input base-vertex count when publishing the successor header. Shrinking +uses the tag radix and refresh uses the old degree. -/ +def Pass.baseFactor : Pass a b → ℕ + | .shrink _ _ => 2 ^ packingTagBits (2^a) + | .refresh _ _ _ => 2^a + | .terminal _ => 1 + +/-- Expander degree published for a refresh, with zero in the corresponding header field for +other passes. -/ +def Pass.expanderDegree : Pass a b → ℕ + | .refresh _ _ e => 2^e + | _ => 0 + +/-- Vertex count, degree, lane radix, residual radix, output degree, expander degree. -/ +def values (p : Pass a b) (vertices laneBits : ℕ) : Fin 6 → ℕ := + ![vertices, 2^a, 2^laneBits, 2^(laneBits-p.spent), 2^b, p.expanderDegree] + +/-- All six scalar values for this pass and input size fit in words of width `w`. -/ +def Fits (p : Pass a b) (vertices laneBits w : ℕ) : Prop := + ∀ j, values p vertices laneBits j < 2^w + +/-- Each scalar can be recovered by its ordinary header load without truncation. -/ +def Present (p : Pass a b) (vertices laneBits : ℕ) (src : Word w) (m : Memory w) : Prop := + ∀ j : Fin 6, (headerCell m src j.val).val = values p vertices laneBits j + +private def fields (p : Pass a b) (vertices degree lanes : Expr) : Fin 6 → Expr := + ![vertices, degree, lanes, lanes.div (.lit (2^p.spent)), .lit (2^b), .lit p.expanderDegree] + +/-- The source state points at the eight-word frame installed by the cursor +parameter program. Frame cells 3, 4 and 5 are the cursor count and the two radices. -/ +def initialRow (p : Pass a b) : FormulaRow 3 where + dest := .publicWord 0 + fields := fields p ((Expr.header 3).mul (.header 4)) (.header 2) (.header 5) + +private def nextVertices : Pass a b → Expr + | .shrink _ _ => (Expr.header 0).mul (.lit (2^packingTagBits (2^a))) + | .refresh _ _ _ => (Expr.header 0).mul (.header 1) + | .terminal _ => .header 0 + +/-- Read old header cells 0, 1, 3 and 4 as needed. In particular the old +output degree is the new input degree. -/ +def advanceRow (p : Pass a b) (q : Pass b c) : FormulaRow 3 where + dest := .publicWord 0 + fields := fields q (nextVertices p) (.header 4) (.header 3) + +private theorem word_of_val {z : Word w} {n : ℕ} (h : z.val = n) : z = (n : Word w) := by + subst n + exact Fin.ext (Nat.mod_eq_of_lt z.isLt).symm + +private theorem eval_fields (p : Pass a b) (V l : ℕ) (vertices degree lanes : Expr) + (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (hv : vertices.eval pub s m = (V : Word w)) (hd : degree.eval pub s m = ((2^a : ℕ) : Word w)) + (hl : lanes.eval pub s m = ((2^l : ℕ) : Word w)) (spent : p.spent ≤ l) + (laneFit : 2^l < 2^w) (j : Fin 6) : + (fields p vertices degree lanes j).eval pub s m = (values p V l j : Word w) := by + have divisor : 2^p.spent < 2^w := (Nat.pow_le_pow_right (by decide) spent).trans_lt laneFit + have quot : 2^l / 2^p.spent = 2^(l-p.spent) := by + conv_lhs => rw [← Nat.sub_add_cancel spent, pow_add] + exact Nat.mul_div_cancel _ (Nat.two_pow_pos _) + fin_cases j + · exact hv + · exact hd + · exact hl + · change Fin.ofNat _ ((lanes.eval pub s m).val / ((2^p.spent : ℕ) : Word w).val) = _ + rw [hl, Fin.val_natCast, Fin.val_natCast, Nat.mod_eq_of_lt laneFit, Nat.mod_eq_of_lt divisor, quot] + rfl + · rfl + · rfl + +theorem initial_fields (p : Pass a b) (pub : Fin 5 → Word w) (src : Word w) (m : Memory w) + {row tag : Word w} {low l W start : ℕ} + (frame : Frame.data src m = CursorRAM.ScheduleInit.inputs row tag low l a W start) + (spent : p.spent ≤ l) (laneFit : 2^l < 2^w) (j : Fin 6) : + ((initialRow p).fields j).eval pub src m = (values p ((low+l)*2^low) l j : Word w) := by + have read (i : Fin 8) : (Expr.header i.val).eval pub src m = + CursorRAM.ScheduleInit.inputs row tag low l a W start i := congrFun frame i + apply eval_fields p _ l _ _ _ pub src m _ _ _ spent laneFit j + · change (Expr.header 3).eval pub src m * (Expr.header 4).eval pub src m = _ + change (Expr.header (3 : Fin 8).val).eval pub src m * (Expr.header (4 : Fin 8).val).eval pub src m = _ + rw [read, read, Nat.cast_mul] + rfl + · exact read (2 : Fin 8) + · exact read (5 : Fin 8) + +theorem advance_fields (p : Pass a b) (q : Pass b c) (pub : Fin 5 → Word w) (src : Word w) + (m : Memory w) {V l : ℕ} (input : Present p V l src m) (spent : q.spent ≤ l-p.spent) + (j : Fin 6) : ((advanceRow p q).fields j).eval pub src m = + (values q (V*p.baseFactor) (l-p.spent) j : Word w) := by + have read (i : Fin 6) : (Expr.header i.val).eval pub src m = (values p V l i : Word w) := + word_of_val (input i) + have laneFit : values p V l 3 < 2^w := by rw [← input]; exact Fin.isLt _ + apply eval_fields q _ _ _ _ _ pub src m _ _ _ spent laneFit j + · cases p with + | shrink b => + change (Expr.header 0).eval pub src m * ((2^packingTagBits (2^a) : ℕ) : Word w) = _ + change (Expr.header (0 : Fin 6).val).eval pub src m * _ = _ + rw [read, Nat.cast_mul] + rfl + | refresh b e => + change (Expr.header 0).eval pub src m * (Expr.header 1).eval pub src m = _ + change (Expr.header (0 : Fin 6).val).eval pub src m * (Expr.header (1 : Fin 6).val).eval pub src m = _ + rw [read, read, Nat.cast_mul] + rfl + | terminal => + change (Expr.header 0).eval pub src m = ((V*1 : ℕ) : Word w) + rw [Nat.mul_one] + exact read (0 : Fin 6) + · exact read (4 : Fin 6) + · exact read (3 : Fin 6) + +/-- Link the natural scalar count to the mathematical state selected by a real +kernel. The growth of the base is independent of all term choices. -/ +def ofOrigin {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} {l g : ℕ} + {X : State a l} {pass : StatePass R X b g} : PassOrigin B f hf pass → Pass a b + | .shrink i _ _ => .shrink (S.degreeExponent i.castSucc) (S.degreeExponent i.succ) + | .refresh _ => .refresh S.portExponent (S.degreeExponent 0) S.expanderExponent + +theorem origin_counts {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} {l g : ℕ} + {X : State a l} {pass : StatePass R X b g} (o : PassOrigin B f hf pass) + (term : pass.step.Choice) : + l = (ofOrigin o).spent+g ∧ Fintype.card (pass.next term).Base = + Fintype.card X.Base * (ofOrigin o).baseFactor := by + cases o with + | shrink i h X => + subst h + refine ⟨by simp only [ofOrigin, Pass.spent, packingLaneBits]; omega, ?_⟩ + change Fintype.card (X.Base × BitWord (packingTagBits (2^S.degreeExponent i.castSucc))) = _ + rw [Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv _), Fintype.card_fin] + rfl + | refresh X => + refine ⟨rfl, ?_⟩ + change Fintype.card (X.Base × Fin (2^S.portExponent)) = _ + rw [Fintype.card_prod, Fintype.card_fin] + rfl + +/-- Scalar fields occupy the first six words of the persistent level header. -/ +def fieldIndex (L : Layout) (six : 6 ≤ L.shape.scalarFields) (i : Fin 6) : Fin L.shape.scalarFields := + i.castLE six + +private theorem headerRoom (L : Layout) {i : Fin L.levels} (six : 6 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) : levelStart L i.val+6 ≤ 2^w := by + have h := level_room L fit i + have hstep : levelStart L (i.val+1) = levelStart L i.val + levelWords L := by + simp only [levelStart, Nat.succ_mul, Nat.add_assoc] + rw [hstep] at h + have hhead : 6 ≤ levelWords L := by unfold levelWords levelHeaderWords; omega + omega + +/-- Complete normal-entry specification, including the six natural values, +the frame for the next pass, and preservation of all other addresses. -/ +def Publishes (L : Layout) (i : Fin L.levels) (six : 6 ≤ L.shape.scalarFields) + (row : FormulaRow 3) (p : Pass a b) (V l : ℕ) (pub : Fin 5 → Word w) + (src : Word w) (m : Memory w) : Prop := + let M := row.recipe.table.instantiate w pub + let rep := row.recipe.report pub src m + let out := after m rep.events + BurstRAM.execute M.program (row.recipe.code.length+1) (M.program.start src) m [] = some rep ∧ + rep.result = some (src+1) ∧ + (∀ j : Fin 6, (out (scalarHead L i (fieldIndex L six j))).val = values p V l j) ∧ + Present p V l (pub 0) out ∧ + (∀ address, address < levelStart L i ∨ levelStart L i + 6 ≤ address → out address = m address) ∧ + rep.events.length = row.recipe.code.length ∧ rep.probes = row.recipe.reads+6 ∧ choiceBits rep.events = [] + +private theorem publish (L : Layout) (i : Fin L.levels) (six : 6 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (row : FormulaRow 3) (p : Pass a b) (V l : ℕ) + (pub : Fin 5 → Word w) (src : Word w) (m : Memory w) + (dst : (pub 0).val = levelStart L i) (address : row.dest = .publicWord 0) + (words : ∀ j, (row.fields j).eval pub src m = (values p V l j : Word w)) + (fits : Fits p V l w) : Publishes L i six row p V l pub src m := by + have room := headerRoom L (i := i) six fit + have atDst : (row.dest.eval pub src m).val = levelStart L i := by rw [address]; exact dst + obtain ⟨run,ret,fields,outside,cost⟩ := row.execute pub src m (by rw [atDst]; exact room) + rw [atDst] at fields outside + let out := after m (row.recipe.report pub src m).events + have read (j : Fin 6) : (out (levelStart L i+j.val)).val = values p V l j := by + rw [show out (levelStart L i+j.val) = _ from fields j, words j, Fin.val_natCast, Nat.mod_eq_of_lt (fits j)] + refine ⟨run,ret,read,?_,outside,cost⟩ + intro j + have hj := j.isLt + change (out ((pub 0)+(j.val : Word w)).val).val = _ + rw [Fin.val_add, dst, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : j.val < 2^w), + Nat.mod_eq_of_lt (by omega : levelStart L i+j.val < 2^w)] + exact read j + +theorem initialize_level (L : Layout) (levels : 0 < L.levels) (six : 6 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (p : Pass a b) (pub : Fin 5 → Word w) (src : Word w) + (m : Memory w) {row tag : Word w} {low l W start : ℕ} + (dst : (pub 0).val = levelStart L 0) + (frame : Frame.data src m = CursorRAM.ScheduleInit.inputs row tag low l a W start) + (spent : p.spent ≤ l) (fits : Fits p ((low+l)*2^low) l w) : + Publishes L ⟨0,levels⟩ six (initialRow p) p ((low+l)*2^low) l pub src m := + publish L ⟨0,levels⟩ six fit _ p _ l pub src m dst rfl + (initial_fields p pub src m frame spent (fits 2)) fits + +theorem advance (L : Layout) (i : Fin L.levels) (six : 6 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (p : Pass a b) (q : Pass b c) (pub : Fin 5 → Word w) + (src : Word w) (m : Memory w) {V l : ℕ} (dst : (pub 0).val = levelStart L i) + (input : Present p V l src m) (spent : q.spent ≤ l-p.spent) + (fits : Fits q (V*p.baseFactor) (l-p.spent) w) : + Publishes L i six (advanceRow p q) q (V*p.baseFactor) (l-p.spent) pub src m := + publish L i six fit _ q _ _ pub src m dst rfl (advance_fields p q pub src m input spent) fits + +/-- The fixed pass's scalars fit whenever the current graph and the two +degree bounds fit. No condition on the remaining lane length is needed. -/ +theorem fits_state (p : Pass a b) {l : ℕ} (X : State a l) + (sites : X.positions < 2^w) (degree : 2^a < 2^w) (nextDegree : 2^b < 2^w) + (expander : p.expanderDegree < 2^w) : Fits p (Fintype.card X.Base) l w := by + have pos : X.positions = Fintype.card X.Base * 2^l := by + rw [State.positions, Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv l), Fintype.card_fin] + have lanes : 2^l < 2^w := (Nat.le_mul_of_pos_left _ Fintype.card_pos).trans_lt (pos ▸ sites) + intro j + fin_cases j + · exact (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos l)).trans_lt (pos ▸ sites) + · exact degree + · exact lanes + · exact (Nat.pow_le_pow_right (by decide) (Nat.sub_le _ _)).trans_lt lanes + · exact nextDegree + · exact expander + +/-- Every selected input level fits under the schedule's common maximum degree. -/ +theorem fits_selected {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + (v : SelectedLevel B f hf) (sites : v.input.positions < 2^w) (slots : slotDegree S < 2^w) : + Fits (ofOrigin v.origin) (Fintype.card v.input.Base) v.inputLanes w := by + apply fits_state _ _ sites (v.oldDegree_le.trans_lt slots) (v.outputDegree_le.trans_lt slots) + obtain ⟨a,l,b,g,X,p,o,term,selector⟩ := v + cases o with + | shrink => exact Nat.two_pow_pos _ + | refresh => + exact ((Nat.le_of_succ_le S.degree_bounds.2).trans_lt + (Finset.le_sup (f := fun j : Fin (S.steps+1) ↦ 2^S.degreeExponent j) (Finset.mem_univ 0) + |>.trans (le_max_right _ _) |>.trans_lt slots)) + +/-- The cursor generator supplies the scalar publisher directly from its real +normal-entry report. Both calls use the external memory produced by their +predecessor. -/ +theorem initialize_from_parameters (L : Layout) (levels : 0 < L.levels) + (six : 6 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (p : Pass a b) (pub : Fin 5 → Word w) (params : Fin 8 → Word w) + (state : Word w) (m : Memory w) {B n l : ℕ} (hB : 1 ≤ B) (hn : 2 ≤ n) + (hw : w = CursorBounds.wordBits B n) (hpN : (params 0).val = n) + (hpR : (params 1).val = CursorBounds.addressBits B n) (hpA : (params 2).val = a) + (hpL : (params 3).val = l) (ha : a < w) (hl : l ≤ CursorBounds.virtualBits B n) + (frameRoom : (params 7).val+8 ≤ 2^w) (dst : (pub 0).val = levelStart L 0) + (spent : p.spent ≤ l) + (fits : Fits p (CursorBounds.virtualBits B n * 2^(CursorBounds.virtualBits B n-l)) l w) : + let low := CursorBounds.virtualBits B n-l + let fields := CursorRAM.ScheduleInit.inputs (params 4) (params 5) low l a + (CursorBounds.initialWidth B n) (params 6).val + let es := CursorRAM.ParametersInit.events n (params 7) fields + let M := (CursorRAM.ParametersInit.program.template (some 9)).instantiate w params + BurstRAM.execute M.program (VirtualParameters.ticks n+43) (M.program.start state) m [] = + some ⟨es,some (state+1)⟩ ∧ + Publishes L ⟨0,levels⟩ six (initialRow p) p + (CursorBounds.virtualBits B n*2^low) l pub (params 7) (after m es) := by + intro low fields es M + have hlow : low+l = CursorBounds.virtualBits B n := Nat.sub_add_cancel hl + refine ⟨CursorRAM.ParametersInit.native state m hB hn hw hpN hpR hpA hpL ha hl, ?_⟩ + have hframe := (CursorRAM.ParametersInit.frame_ready m n (params 7) fields frameRoom).1 + exact hlow ▸ initialize_level L levels six fit p pub (params 7) (after m es) dst + hframe spent (hlow ▸ fits) + +/-- The next published vertex count is the base cardinality of the actual +output state, even when its topology and widths depend on the selected term. -/ +theorem advance_selected {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + {a b l g : ℕ} {X : State a l} {pass : StatePass R X b g} (o : PassOrigin B f hf pass) + (term : pass.step.Choice) (q : Pass b c) (L : Layout) (i : Fin L.levels) + (six : 6 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (pub : Fin 5 → Word w) (src : Word w) (m : Memory w) + (dst : (pub 0).val = levelStart L i) (input : Present (ofOrigin o) (Fintype.card X.Base) l src m) + (spent : q.spent ≤ g) (fits : Fits q (Fintype.card (pass.next term).Base) g w) : + Publishes L i six (advanceRow (ofOrigin o) q) q (Fintype.card (pass.next term).Base) + g pub src m := by + obtain ⟨hg,hv⟩ := origin_counts o term + have rem : l-(ofOrigin o).spent = g := by omega + rw [hv] at fits ⊢ + have h := advance L i six fit _ q pub src m dst input (by rwa [rem]) (by rwa [rem]) + rwa [rem] at h + +end CompressorRecords.DescriptorSpace.Scalars + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorSpace.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorSpace.lean new file mode 100644 index 0000000000..6d63b67824 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorSpace.lean @@ -0,0 +1,416 @@ +import OAI.Computability.VPVNP.CompressorRecordsDirectory +import OAI.Computability.VPVNP.CompressorRecordsWorkspace +import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout + +/-! +# Descriptor addresses across compressor levels + +Appendix E uses a fixed number of words per slot and position. We allocate +the controller header, its active frame and its directory first. Each level +then has a persistent header, six packed incidence columns, and rectangular +tables of fixed-width slot records. The old levels remain addressable +after the next level has been written. The initial column addresses agree +with the native cursor scan. Both exclusive cursors and addresses fit a +machine word throughout the logarithmic block schedule. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorSpace + +open BurstRAM CursorBounds Filter +open scoped Fin.CommRing + +/-- Fixed record dimensions of the program. A directory can contain both +whole-level passes and site-specific rows. The native workspace reserves +the runtime level stride immediately after the active frame. -/ +structure Shape where + /-- Number of parameter words in the planner's active frame and in each directory row. -/ + arity : ℕ + /-- Number of directory rows reserved for initialization before any per-level visits. -/ + initialRows : ℕ + /-- Number of whole-level passes scheduled at each level, independently of the number of + positions. -/ + levelPasses : ℕ + /-- Number of site-specific directory rows reserved per position at each level. -/ + sitePasses : ℕ + /-- Number of scalar words preceding the incidence and table pointers in a level header. -/ + scalarFields : ℕ + /-- Number of rectangular slot-record tables reserved at each level. -/ + tables : ℕ + /-- Maximum number of slots reserved per position in a level's incidence columns and tables. -/ + slots : ℕ + /-- Number of words in a single slot record of a rectangular table. -/ + fields : ℕ + +/-- All levels use the initial position count as their rectangular capacity. -/ +structure Layout where + /-- Fixed dimensions of the directory, level headers, incidence columns, and slot records. -/ + shape : Shape + /-- Starting address of the controller workspace that precedes the active frame and + directory. -/ + base : ℕ + /-- Initial position count used as the common rectangular capacity across levels. -/ + positions : ℕ + /-- Number of persistent level regions allocated after the directory. -/ + levels : ℕ + +variable (L : Layout) + +/-- Starting address of the active frame, nine words past the controller workspace base. -/ +def frameBase := L.base + 9 +/-- Address reserved immediately after the active frame and immediately before the directory. -/ +def plannerTag := frameBase L + (L.shape.arity + 1) +/-- Starting address of the first scheduler directory row, just past the planner tag cell. -/ +def directoryBase := plannerTag L + 1 +/-- Number of directory rows per level, combining whole-level passes and site passes for every +position. -/ +def passesPerLevel := L.shape.levelPasses + L.shape.sitePasses * L.positions +/-- Total directory row count for initialization and all allocated levels. -/ +def directoryRows := L.shape.initialRows + L.levels * passesPerLevel L +/-- Address of the first level header, after all fixed-width directory rows. -/ +def levelsBase := directoryBase L + directoryRows L * (L.shape.arity + 3) +/-- Size in words of the scalar header, six incidence pointers, and one pointer per table. -/ +def levelHeaderWords := L.shape.scalarFields + 6 + L.shape.tables +/-- Number of slots available in a full level, obtained by multiplying positions by slots per +position. -/ +def slotCapacity := L.positions * L.shape.slots +/-- Size in words of one rectangular table containing a fixed-width record for every reserved +slot. -/ +def tableWords := slotCapacity L * L.shape.fields +/-- Word stride between successive levels, including the header, all incidence columns, and all +tables. -/ +def levelWords := levelHeaderWords L + 6 * slotCapacity L + L.shape.tables * tableWords L +/-- Address of the header at the given zero-based level index. -/ +def levelStart (level : ℕ) := levelsBase L + level * levelWords L +/-- First address beyond the final allocated level. -/ +def endAddress := levelStart L L.levels + +/-- Persistent level scalars, including vertex count, degree, row count, +residual lane count and the operands of the next refresh. -/ +def scalarHead (level : ℕ) (j : Fin L.shape.scalarFields) := levelStart L level + j.val + +/-- Pointers to the six incidence columns in the native directory order. -/ +def incidenceHead (level : ℕ) (c : Fin 6) := levelStart L level + L.shape.scalarFields + c.val + +/-- Pointers to the record tables of the particular compressor pass. -/ +def tableHead (level : ℕ) (a : Fin L.shape.tables) := + levelStart L level + L.shape.scalarFields + 6 + a.val + +/-- Address of the first incidence column immediately after this level's header. -/ +def incidenceStart (level : ℕ) := levelStart L level + levelHeaderWords L + +/-- Native scans pack the incidence columns with their actual row count. The +unused part of the reserved region stays available as blank space. -/ +def incidenceBase (level rows : ℕ) (c : Fin 6) := incidenceStart L level + c.val * rows + +/-- Starting address of the rectangular tables after the six incidence columns of this level. -/ +def arrayBase (level : ℕ) := incidenceStart L level + 6 * slotCapacity L + +/-- Starting address of the specified rectangular table within the level. -/ +def tableBase (level : ℕ) (a : Fin L.shape.tables) := arrayBase L level + a.val * tableWords L + +/-- Coordinates of a table word, indexed by table, position, slot, and record field. -/ +abbrev Cell := Fin L.shape.tables × Fin L.positions × Fin L.shape.slots × Fin L.shape.fields + +/-- Site-major, slot-major, field-minor addressing within each array. -/ +def cellAddress (level : ℕ) (k : Cell L) := + tableBase L level k.1 + (k.2.1.val * L.shape.slots + k.2.2.1.val) * L.shape.fields + k.2.2.2.val + +/-- Disjoint scalar, incidence-head and array-head fields, with a finite +equivalence giving their word offsets from the start of the level. -/ +def headerIndex : ((Fin L.shape.scalarFields ⊕ Fin 6) ⊕ Fin L.shape.tables) ≃ + Fin (levelHeaderWords L) := + ((finSumFinEquiv (m := L.shape.scalarFields) (n := 6)).sumCongr (Equiv.refl _)).trans finSumFinEquiv + +theorem scalarHead_index (level : ℕ) (j : Fin L.shape.scalarFields) : + scalarHead L level j = levelStart L level + (headerIndex L (.inl (.inl j))).val := rfl + +theorem incidenceHead_index (level : ℕ) (c : Fin 6) : + incidenceHead L level c = levelStart L level + (headerIndex L (.inl (.inr c))).val := by + change _ = _ + (L.shape.scalarFields + c.val) + simp [incidenceHead, Nat.add_assoc] + +theorem tableHead_index (level : ℕ) (a : Fin L.shape.tables) : + tableHead L level a = levelStart L level + (headerIndex L (.inr a)).val := by + change _ = _ + (L.shape.scalarFields + 6 + a.val) + simp [tableHead, Nat.add_assoc] + +theorem directoryAddress_lt (i : Fin (directoryRows L)) (j : Fin (L.shape.arity + 3)) : + Schedule.Directory.address (directoryBase L) L.shape.arity i.val j < levelsBase L := by + have h := Nat.mul_le_mul_right (L.shape.arity + 3) i.isLt + rw [Nat.succ_mul] at h + have hj := j.isLt + unfold Schedule.Directory.address levelsBase + omega + +theorem levelOrdinal_lt (level : Fin L.levels) (pass : Fin (passesPerLevel L)) : + Schedule.Directory.levelOrdinal L.shape.initialRows level.val pass < directoryRows L := by + have h := Nat.mul_le_mul_right (passesPerLevel L) level.isLt + rw [Nat.succ_mul] at h + have hp := pass.isLt + unfold Schedule.Directory.levelOrdinal directoryRows + omega + +private def cellIndex : Cell L ≃ Fin (L.shape.tables * (L.positions * (L.shape.slots * L.shape.fields))) := + ((Equiv.refl _).prodCongr (((Equiv.refl _).prodCongr finProdFinEquiv).trans finProdFinEquiv)).trans + finProdFinEquiv + +private theorem cell_eq (level : ℕ) (k : Cell L) : + cellAddress L level k = arrayBase L level + (cellIndex L k).val := by + change arrayBase L level + k.1.val * tableWords L + + (k.2.1.val * L.shape.slots + k.2.2.1.val) * L.shape.fields + k.2.2.2.val = + arrayBase L level + (k.2.2.2.val + L.shape.fields * k.2.2.1.val + + (L.shape.slots * L.shape.fields) * k.2.1.val + + (L.positions * (L.shape.slots * L.shape.fields)) * k.1.val) + simp only [tableWords, slotCapacity] + ring + +theorem cellAddress_injective (level : ℕ) : Function.Injective (cellAddress L level) := by + intro k k' hk + rw [cell_eq, cell_eq] at hk + exact (cellIndex L).injective (Fin.ext (Nat.add_left_cancel hk)) + +theorem cellAddress_bounds (level : ℕ) (k : Cell L) : + arrayBase L level ≤ cellAddress L level k ∧ cellAddress L level k < levelStart L (level + 1) := by + rw [cell_eq] + refine ⟨Nat.le_add_right .., ?_⟩ + have hi : (cellIndex L k).val < L.shape.tables * tableWords L := by + simpa only [tableWords, slotCapacity, Nat.mul_assoc] using (cellIndex L k).isLt + simp only [arrayBase, incidenceStart, levelStart, Nat.succ_mul, levelWords] at * + omega + +/-- Consecutive table IDs give nonoverlapping physical intervals. -/ +theorem tableEnd_le_tableBase (level : ℕ) {a b : Fin L.shape.tables} (h : a < b) : + tableBase L level a + tableWords L ≤ tableBase L level b := by + have hmul := Nat.mul_le_mul_right (tableWords L) (Nat.succ_le_of_lt h) + rw [Nat.succ_mul] at hmul + simp only [tableBase] + omega + +theorem tableEnd_le_nextLevel (level : ℕ) (a : Fin L.shape.tables) : + tableBase L level a + tableWords L ≤ levelStart L (level+1) := by + have hmul := Nat.mul_le_mul_right (tableWords L) a.isLt + rw [Nat.succ_mul] at hmul + simp only [tableBase, arrayBase, incidenceStart, levelStart, Nat.succ_mul, levelWords] + omega + +theorem incidence_bounds (level rows : ℕ) (hr : rows ≤ slotCapacity L) (c : Fin 6) (i : Fin rows) : + incidenceStart L level ≤ incidenceBase L level rows c + i.val ∧ + incidenceBase L level rows c + i.val < arrayBase L level := by + have hc := Nat.mul_le_mul_right rows c.isLt + have hcap := Nat.mul_le_mul_left 6 hr + rw [Nat.succ_mul] at hc + have hi := i.isLt + simp only [incidenceBase, arrayBase] + omega + +theorem levelStart_mono : Monotone (levelStart L) := by + intro i j hij + exact Nat.add_le_add_left (Nat.mul_le_mul_right _ hij) _ + +/-- A store in a later level cannot overwrite a word in an earlier level. +The statement applies to an entire chronological native event trace. -/ +theorem olderLevel_preserved {w : ℕ} (m : Memory w) (es : List (Event w)) {i j addr : ℕ} + (hij : i < j) (hbase : levelsBase L ≤ addr) (ha : addr < levelStart L (i + 1)) + (writes : ∀ a v, Event.write a v ∈ es → a.val < levelsBase L ∨ levelStart L j ≤ a.val) : + after m es addr = m addr := by + have hlt := ha.trans_le (levelStart_mono L hij) + induction es generalizing m with + | nil => rfl + | cons e es ih => + change after (update m e) es addr = _ + rw [ih _ (fun a v he ↦ writes a v (List.mem_cons_of_mem _ he))] + cases e with + | write a v => + have hne : addr ≠ a.val := (writes a v (List.mem_cons_self ..)).elim + (fun hw ↦ (hw.trans_le hbase).ne') (fun hw ↦ (hlt.trans_le hw).ne) + simp [update, writeMemory, hne] + | _ => rfl + +/-- The exclusive upper end and every intermediate level start fit under +one common bound. -/ +theorem level_room {w : ℕ} (fit : endAddress L < 2^w) (i : Fin L.levels) : + levelStart L (i.val + 1) < 2^w := + (levelStart_mono L i.isLt).trans_lt fit + +private theorem incidence_end_le (level : ℕ) : + arrayBase L level ≤ levelStart L (level + 1) := by + simp only [arrayBase, incidenceStart, levelStart, Nat.succ_mul, levelWords] + omega + +theorem packed_incidence_room {w : ℕ} (fit : endAddress L < 2^w) (i : Fin L.levels) + {rows : ℕ} (hr : rows ≤ slotCapacity L) : + incidenceStart L i + 6 * rows < 2^w := by + apply lt_of_le_of_lt _ (level_room L fit i) + exact (Nat.add_le_add_left (Nat.mul_le_mul_left 6 hr) _).trans (incidence_end_le L i) + +/-- Packed column heads as used by the typed incidence directory. -/ +def packedIncidence (w level rows : ℕ) : IncidenceDirectory w := + let col (c : Fin 6) := CursorRAM.encode w (incidenceBase L level rows c) + ⟨col 0, col 1, col 2, col 3, col 4, col 5⟩ + +theorem packed_column (w level rows : ℕ) (c : Fin 6) : + (packedIncidence L w level rows).column c = CursorRAM.encode w (incidenceBase L level rows c) := by + fin_cases c <;> rfl + +theorem packed_layout {w a l : ℕ} (X : Compression.State a l) (level : Fin L.levels) + (fit : endAddress L < 2^w) + (hrows : Fintype.card X.Base * 2^l * 2^a ≤ slotCapacity L) : + (packedIncidence L w level (Fintype.card X.Base * 2^l * 2^a)).Layout X := by + let rows := Fintype.card X.Base * 2^l * 2^a + have room := packed_incidence_room L fit level hrows + apply IncidenceDirectory.Layout.packed X (incidenceStart L level) room.le + intro c + rw [packed_column] + have hc := Nat.mul_le_mul_right rows c.isLt.le + exact Nat.mod_eq_of_lt (lt_of_le_of_lt (Nat.add_le_add_left hc _) room) + +/-- The native scheduler's published frame, directory and control addresses. -/ +def ports (w : ℕ) : Schedule.Ports w := + Workspace.ports L.shape.arity (CursorRAM.encode w L.base) + +theorem frame_before_directory : frameBase L + (L.shape.arity + 1) ≤ directoryBase L := + Nat.le_add_right .. + +theorem directoryBase_le_end : directoryBase L ≤ endAddress L := + (Nat.le_add_right .. : directoryBase L ≤ levelsBase L).trans (Nat.le_add_right ..) + +private theorem word_add_val {w : ℕ} (base : Word w) {j : ℕ} (fit : base.val + j < 2^w) : + (base + (j : Word w)).val = base.val + j := by + rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : j < 2^w), Nat.mod_eq_of_lt fit] + +theorem ports_values {w : ℕ} (fit : endAddress L < 2^w) : + (ports L w).activeFrame.val = frameBase L ∧ (ports L w).directory.val = directoryBase L ∧ + (ports L w).ordinal.val = L.base + 7 ∧ (ports L w).rows.val = L.base + 8 ∧ + (ports L w).tag.val = L.base + 6 := by + have hdir := (directoryBase_le_end L).trans_lt fit + have hframe := (frame_before_directory L).trans_lt hdir + dsimp only [frameBase] at hframe + have hb : (CursorRAM.encode w L.base).val = L.base := Nat.mod_eq_of_lt (by omega) + have add (j : ℕ) (hj : j ≤ 9) : (CursorRAM.encode w L.base + (j : Word w)).val = L.base + j := by + rw [word_add_val, hb] + omega + have dir : (ports L w).directory.val = directoryBase L := by + change (CursorRAM.encode w L.base + ((11 + L.shape.arity : ℕ) : Word w)).val = _ + rw [word_add_val, hb] + · simp only [directoryBase, plannerTag, frameBase] + omega + · rw [hb] + simp only [directoryBase, plannerTag, frameBase] at hdir + omega + exact ⟨add 9 le_rfl, dir, add 7 (by decide), add 8 (by decide), add 6 (by decide)⟩ + +theorem frameFits {w d : ℕ} (C : Schedule.Catalog d) (hC : Schedule.arity C = L.shape.arity) + (fit : endAddress L < 2^w) : Schedule.Directory.FrameFits C (ports L w) := by + have hval := ports_values L fit + have hfit := ((frame_before_directory L).trans (directoryBase_le_end L)).trans_lt fit + rw [← hC] at hfit + constructor + · omega + · intro j + have hj := j.isLt + have haddr := word_add_val (ports L w).activeFrame (j := j.val) (by rw [hval.1]; omega) + rw [hval.1] at haddr + have h₁ := hval.2.2.1 + have h₂ := hval.2.2.2.2 + unfold frameBase at haddr + constructor <;> intro e <;> have := congrArg Fin.val e <;> omega + +theorem cursor_directory_eq (w level b l a : ℕ) : + packedIncidence L w level (CursorRAM.rowCount b l a) = + CursorRAM.directory w b l a (incidenceStart L level) := rfl + +/-- One workspace prefix, before accounting for the per-level rows. -/ +def Shape.fixedWords (F : Shape) := 11 + F.arity + F.initialRows * (F.arity + 3) + +/-- Constant words per level, comprising header fields and level-wide pass rows. -/ +def Shape.levelFixed (F : Shape) := F.scalarFields + 6 + F.tables + F.levelPasses * (F.arity + 3) + +/-- Words per position at each level, including native directory rows, +six incidence columns and all rectangular slot records. -/ +def Shape.siteWords (F : Shape) := + F.sitePasses * (F.arity + 3) + F.slots * (6 + F.tables * F.fields) + +theorem endAddress_eq : + endAddress L = L.base + L.shape.fixedWords + + L.levels * (L.shape.levelFixed + L.positions * L.shape.siteWords) := by + simp only [endAddress, levelStart, levelsBase, directoryBase, plannerTag, frameBase, directoryRows, + passesPerLevel, levelWords, levelHeaderWords, slotCapacity, tableWords, + Shape.fixedWords, Shape.levelFixed, Shape.siteWords] + ring + +/-- The allocated words are bounded by a fixed constant times positions +times levels whenever both counts are positive. -/ +theorem endAddress_le (hp : 0 < L.positions) (hl : 0 < L.levels) : + endAddress L ≤ L.base + (L.shape.fixedWords + L.shape.levelFixed + L.shape.siteWords) * + L.positions * L.levels := by + rw [endAddress_eq] + have h₁ := Nat.le_mul_of_pos_right L.shape.fixedWords (Nat.mul_pos hp hl) + have h₂ := Nat.mul_le_mul_left L.levels (Nat.le_mul_of_pos_right L.shape.levelFixed hp) + nlinarith only [h₁, h₂] + +/-- The initial level and one level per substep in the repeated block schedule. -/ +noncomputable def cursorLayout (F : Shape) (b steps : ℕ) (θ : ℝ) (base n : ℕ) : Layout := + ⟨F, base, initialPositions b n, 1 + (steps + 1) * Compression.blockCount θ n⟩ + +private theorem bounded_blockCount {θ : ℝ} (hθ : θ ≤ 1) : + PolynomiallyBounded (Compression.blockCount θ) := by + apply PolynomiallyBounded.id.of_eventually_le 1 + intro n hn + have hn' : (1 : ℝ) ≤ n := by exact_mod_cast hn + have hlog := Real.logb_nonneg (by norm_num : 1 < (2 : ℝ)) hn' + have h : Compression.blockCount θ n ≤ Nat.clog 2 n := by + rw [Compression.blockCount, ← Real.natCeil_logb_natCast 2 n] + exact (Nat.floor_le_floor (mul_le_of_le_one_left hlog hθ)).trans (Nat.floor_le_ceil _) + exact h.trans (Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le) + +theorem bounded_cursorEnd (F : Shape) (b steps : ℕ) {θ : ℝ} (hθ : θ ≤ 1) + {base : ℕ → ℕ} (hb : PolynomiallyBounded base) : + PolynomiallyBounded (fun n ↦ endAddress (cursorLayout F b steps θ (base n) n)) := by + simp only [endAddress_eq, cursorLayout] + exact (hb.add (PolynomiallyBounded.const F.fixedWords)).add + (((PolynomiallyBounded.const 1).add ((PolynomiallyBounded.const (steps+1)).mul + (bounded_blockCount hθ))).mul ((PolynomiallyBounded.const F.levelFixed).add + ((CursorRAM.bounded_positions b).mul (PolynomiallyBounded.const F.siteWords)))) + +theorem cursor_initial_room (F : Shape) (b steps n start a : ℕ) (θ : ℝ) (hd : 2^a ≤ F.slots) + {baseBits laneBits : ℕ} (he : baseBits + laneBits = virtualBits b n) + (fit : endAddress (cursorLayout F b steps θ start n) < 2 ^ wordBits b n) : + let layout := cursorLayout F b steps θ start n + incidenceStart layout 0 + 6 * CursorRAM.rowCount baseBits laneBits a < 2 ^ wordBits b n := by + let layout := cursorLayout F b steps θ start n + let first : Fin layout.levels := ⟨0, by simp [layout, cursorLayout]⟩ + apply packed_incidence_room layout fit first + rw [CursorRAM.rowCount_eq_positions he] + exact Nat.mul_le_mul_left _ hd + +/-- At the actual cursor dimensions the descriptor workspace and a polynomial +suffix, including their exclusive end cursors, fit in a word. The same threshold +also certifies the first native scan and its timestamps for every base/lane split. -/ +theorem eventually_cursor_room (F : Shape) (b a steps : ℕ) (hb : 1 ≤ b) {θ : ℝ} (hθ : θ ≤ 1) + {base suffix : ℕ → ℕ} (hbase : PolynomiallyBounded base) (hsuffix : PolynomiallyBounded suffix) : + ∀ᶠ n : ℕ in atTop, let layout := cursorLayout F b steps θ (base n) n + endAddress layout + suffix n < 2 ^ wordBits b n ∧ + ∀ baseBits laneBits, baseBits + laneBits = virtualBits b n → + 1 < baseBits + laneBits ∧ initialWidth b n < 2 ^ wordBits b n ∧ + incidenceStart layout 0 + 7 * CursorRAM.rowCount baseBits laneBits a ≤ 2 ^ wordBits b n := by + let L n := cursorLayout F b steps θ (base n) n + have he := bounded_cursorEnd F b steps hθ hbase + have hstart : PolynomiallyBounded (fun n ↦ incidenceStart (L n) 0) := by + apply he.of_le + intro n + have h₁ := Nat.le_add_right (incidenceStart (L n) 0) (6 * slotCapacity (L n)) + have h₂ := incidence_end_le (L n) 0 + exact (h₁.trans h₂).trans (levelStart_mono (L n) (by simp [cursorLayout])) + filter_upwards [CursorRAM.eventual_word_room b hb (he.add hsuffix), + CursorRAM.eventually_cursorCapacity b a hb hstart] with n hn hi + exact ⟨hn, fun b' l heq ↦ ⟨(hi b' l heq).1, (hi b' l heq).2.2⟩⟩ + +end CompressorRecords.DescriptorSpace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorSquare.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorSquare.lean new file mode 100644 index 0000000000..fe4e4de34a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorSquare.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.CompressorDescriptorSpace +import OAI.Computability.VPVNP.PairWorkspace + +/-! +# Relative square arena for the complete descriptor and evaluation workspaces + +The directory reserves old-site capacity at every level, independently of +the selected placements. Its level count contributes another logarithm. +This arena, the selected depth-first rows and the final wire bits fit +together inside the square of the live processor count, relative to any +starting address. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorSpace + +open Compression CursorNetwork CursorBounds Filter + +private theorem cursor_positions_le {b n : ℕ} (hn : 2 ≤ n) : + initialPositions b n ≤ (2*(b+2))*processorCount b n*n*(n.log2+1)^2 := by + have hn₁ : (1 : ℝ) ≤ n := by exact_mod_cast (show 1 ≤ n by omega) + have hpow : (n : ℝ) ^ (3/4 : ℝ) ≤ n := by + simpa using Real.rpow_le_rpow_of_exponent_le hn₁ (by norm_num : (3/4 : ℝ) ≤ 1) + have h := (initialPositions_bound b n hn).trans (mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_left hpow (by positivity)) (sq_nonneg _)) + exact_mod_cast h + +private theorem cursor_level_count_le (F : Shape) {b n : ℕ} (hn : 2 ≤ n) (steps start : ℕ) + {θ : ℝ} (hθ : θ ≤ 1) : (cursorLayout F b steps θ start n).levels ≤ (steps+2)*n := by + have hn₁ : (1 : ℝ) ≤ n := by exact_mod_cast (show 1 ≤ n by omega) + have hT : blockCount θ n ≤ Nat.clog 2 n := by + rw [blockCount, ← Real.natCeil_logb_natCast 2 n] + exact (Nat.floor_le_floor (mul_le_of_le_one_left (Real.logb_nonneg (by norm_num) hn₁) hθ)).trans + (Nat.floor_le_ceil _) + have ht := hT.trans (Nat.clog_le_of_le_pow Nat.lt_two_pow_self.le) + change 1+(steps+1)*blockCount θ n ≤ (steps+2)*n + exact (Nat.add_le_add (show 1 ≤ n by omega) (Nat.mul_le_mul_left _ ht)).trans_eq (by ring) + +/-- The length threshold precedes every memory start, coordinate split, +coefficient specialization and compressor term. The final summand accommodates +fixed-stride traversal rows, final bits, and processor-local work cells. -/ +theorem eventually_selected_square {k : Type*} [_root_.Field k] {S : BlockSchedule k} (F : Shape) + (B : S.Templates) (u : PairExponents B.growthConstant) (b : ℕ) (hb : max S.laneBits 5 ≤ b) + (K : ℕ) : ∀ᶠ n : ℕ in atTop, + ∀ (start : ℕ) {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) + (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes) + (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f), + let X := pairInput S labels hD + let T := blockCount (u.θ : ℝ) n + let E := B.execute f hf T hT X + let L := cursorLayout F b S.steps (u.θ : ℝ) start n + ∀ z : E.Choices, let Y := E.finalState z + endAddress L + K * (X.positions + processorCount b n + + Y.positions * B.growthConstant ^ T + Y.totalWidth) + 1 < start + (processorCount b n)^2 := by + let C := F.fixedWords + F.levelFixed + F.siteWords + let p := 2*(b+2) + filter_upwards [eventually_pairWorkspace_lt_square b ((le_max_right _ _).trans hb) + (2*C*p*(S.steps+2)), eventually_pairArenaFitBoth B u b hb (2*K+2), eventually_ge_atTop 2] + with n hs he hn + intro start base lanes labels hD hT A _ f hf X T E L z Y + have hp := pairInput_positions S labels hD + change X.positions = initialPositions b n at hp + have hθ : (u.θ : ℝ) ≤ 1 := by + have := (Rat.cast_lt (K := ℝ)).mpr u.theta_lt + norm_num at this; linarith + have hL := cursor_level_count_le F (b := b) hn S.steps start hθ + have hpos : 0 < L.positions := X.positions_pos.trans_le hp.le + have hlev : 0 < L.levels := by dsimp [L,cursorLayout]; omega + have hd := endAddress_le L hpos hlev + change endAddress L ≤ start + C*initialPositions b n * L.levels at hd + let Q := C * initialPositions b n * L.levels + have hmul : 2*Q ≤ 2*C*p*(S.steps+2)*processorCount b n*n^2*(n.log2+1)^2 := by + calc + _ = 2*C*initialPositions b n * L.levels := by dsimp only [Q]; ring + _ ≤ 2*C*(p*processorCount b n*n*(n.log2+1)^2) * ((S.steps+2)*n) := + Nat.mul_le_mul (Nat.mul_le_mul_left _ (cursor_positions_le hn)) hL + _ = _ := by ring + let Z := X.positions + processorCount b n + Y.positions*B.growthConstant^T + Y.totalWidth + have he' := (he labels hD hT A f hf z).trans_le (min_le_right _ _) + change (2*K+2)*Z+1 < (processorCount b n)^2 at he' + have hZ : 0 < Z := Nat.lt_add_right _ (Nat.lt_add_right _ (Nat.lt_add_right _ X.positions_pos)) + change endAddress L ≤ start + Q at hd + change endAddress L + K*Z + 1 < start + (processorCount b n)^2 + rw [Nat.add_mul,Nat.mul_assoc] at he' + omega + +end CompressorRecords.DescriptorSpace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorStride.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorStride.lean new file mode 100644 index 0000000000..b66b7004f0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorStride.lean @@ -0,0 +1,147 @@ +import OAI.Computability.VPVNP.CompressorDescriptorSpace +import OAI.Computability.VPVNP.CompressorFormulaRow +import OAI.Computability.VPVNP.CompressorRecordsCursorParameters + +/-! +# Bootstrapping the runtime descriptor stride + +The calendar multiplies the selected level number by a word stored immediately +before its directory. This deterministic burst reads the three coordinate +counts produced in the cursor parameter frame, computes the level stride, +and writes that single word. Only the pair workspace pointer is public. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorStride + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM RowRecipe +open scoped Fin.CommRing +open private low ptr one Assign.code lines_trace zeros eval_cost update_right from + OAI.Computability.VPVNP.CompressorRecordsRowRecipe + +variable {r k g w : ℕ} + +/-- Evaluate the recipe's expressions, store the first field alone, and return +the next cursor. This form is used for the single stride word between the +active parameter frame and the directory. -/ +def singleCode (R : Recipe r k g) : List (Op (r+2) k) := + R.lines.map Assign.code ++ [.write (low R.dest) (low R.tag), + .stateWord (ptr r), .constant (one r) 1, .binary .add (ptr r) (ptr r) (one r)] + +/-- Instruction template that evaluates a recipe, writes its selected field once, and returns +the advanced cursor. -/ +def singleTable (R : Recipe r k g) := template (singleCode R) (ptr r) + +/-- Report for a single-field recipe burst, including evaluation, the external write, and the +successor state. -/ +def singleReport (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) : Report w := + ⟨(evaluate pub s m R.lines (fun _ ↦ 0)).1 ++ + [.write (R.address pub s m) (R.values pub s m R.tag), .tick, .tick, .tick], some (s+1)⟩ + +private theorem single_trace (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) : + ∃ out, trace pub s (singleCode R) (fun _ ↦ 0) m = some ((singleReport R pub s m).events, out, + writeMemory m (R.address pub s m) (R.values pub s m R.tag)) ∧ out (ptr r) = s + 1 := by + rw [singleCode, zeros, trace_append, lines_trace] + simp [trace, Op.effect, low, ptr, one, singleReport, Recipe.address, Recipe.values, BinaryOp.eval, + Function.update, Fin.append_left] + +theorem single_native (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) : + let M := (singleTable R).instantiate w pub + let rep := singleReport R pub s m + execute M.program (1 + (singleCode R).length) (M.program.start s) m [] = some rep ∧ + after m rep.events = writeMemory m (R.address pub s m) (R.values pub s m R.tag) ∧ + rep.result = some (s+1) ∧ rep.events.length = (singleCode R).length ∧ + rep.probes = R.reads+1 ∧ choiceBits rep.events = [] := by + obtain ⟨out,ht,hs⟩ := single_trace R pub s m + intro M rep + have hn : execute M.program (1 + (singleCode R).length) (M.program.start s) m [] = some rep := by + change execute ((template (singleCode R) (ptr r)).instantiate w pub).program _ + ⟨((template (singleCode R) (ptr r)).instantiate w pub).entry, s, fun _ ↦ 0, fun _ ↦ 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hs, rep, singleReport] + obtain ⟨hl,hp⟩ := eval_cost pub s m R.lines (fun _ ↦ 0) + refine ⟨hn, Greedy.trace_after ht, rfl, ?_, ?_, (execute_spec hn).2.2⟩ + · simp [rep, singleReport, singleCode, hl] + · simp [rep, singleReport, Report.probes, Greedy.probes_append, countProbes, Recipe.reads, hp] + +open PhaseRecipe DescriptorSpace + +private def workspace : Expr := .publicWord 0 +private def frame : Expr := workspace.add (.lit 9) +private def cursorCount (j : ℕ) : Expr := .load (frame.add (.lit j)) + +private def positionExpr := ((cursorCount 3).mul (cursorCount 4)).mul (cursorCount 5) + +private def strideExpr (F : Shape) : Expr := + let slots := positionExpr.mul (.lit F.slots) + let tables := (Expr.lit F.tables).mul (slots.mul (.lit F.fields)) + ((Expr.lit (F.scalarFields + 6 + F.tables)).add ((Expr.lit 6).mul slots)).add tables + +/-- Only the first field is emitted by the single-cell store. -/ +private def calculation (F : Shape) : FormulaRow 0 := + ⟨workspace.add (.lit (10 + F.arity)), ![strideExpr F, .lit 0, .lit 0]⟩ + +/-- Public operand two of the live pair is the workspace base. -/ +def table (F : Shape) := LiveStageLink.widen (singleTable (calculation F).recipe) + (Function.Embedding.refl _) (fun _ : Fin 5 ↦ (2 : Fin 11)) + +/-- Report of the level-stride calculation using the pair workspace pointer in public operand +two. -/ +def report (F : Shape) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) := + singleReport (calculation F).recipe (fun _ ↦ pub 2) s m + +/-- Instruction count of the fixed program that computes and publishes the runtime level +stride. -/ +def cost (F : Shape) := (singleCode (calculation F).recipe).length + +/-- Run the actual Fin 11 bootstrap table. The input frame is the output +of `CursorRAM.ParametersInit.frame_ready`. No field of the directory itself +is required on entry. -/ +theorem native (L : Layout) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + {row tag : Word w} {b l a W start : ℕ} + (ready : Frame.data (pub 2 + 9) m = CursorRAM.ScheduleInit.inputs row tag b l a W start) + (positions : (b+l) * 2^b * 2^l = L.positions) : + let M := (table L.shape).instantiate w pub + let rep := report L.shape pub s m + execute M.program (1 + cost L.shape) (M.program.start s) m [] = some rep ∧ + rep.result = some (s+1) ∧ + after m rep.events = writeMemory m (pub 2 + ((10 + L.shape.arity : ℕ) : Word w)) + (levelWords L : Word w) ∧ rep.events.length = cost L.shape ∧ choiceBits rep.events = [] := by + intro M rep + let p : Fin 5 → Word w := fun _ ↦ pub 2 + let R := calculation L.shape + have run := single_native R.recipe p s m + have exec : execute M.program (1 + cost L.shape) (M.program.start s) m [] = some rep := by + dsimp only [M, table] + rw [LiveStageLink.execute_widen_start] + exact run.1 + have hdest : R.recipe.address p s m = pub 2 + ((10 + L.shape.arity : ℕ) : Word w) := by + rw [FormulaRow.recipe_address]; rfl + have hw : R.recipe.values p s m R.recipe.tag = (strideExpr L.shape).eval p s m := by + have h := congrArg List.head? (R.recipe_words p s m) + simpa only [Recipe.words, Recipe.fields, List.map_cons, List.head?_cons, List.ofFn_succ, + R, calculation, Matrix.cons_val_zero, Option.some.injEq] using h + have h3 := congrFun ready (3 : Fin 8) + have h4 := congrFun ready (4 : Fin 8) + have h5 := congrFun ready (5 : Fin 8) + change m (pub 2 + 9 + 3).val = ((b + l : ℕ) : Word w) at h3 + change m (pub 2 + 9 + 4).val = ((2 ^ b : ℕ) : Word w) at h4 + change m (pub 2 + 9 + 5).val = ((2 ^ l : ℕ) : Word w) at h5 + have hp : positionExpr.eval p s m = (L.positions : Word w) := by + simp only [positionExpr, cursorCount, frame, workspace, Expr.eval, Expr.mul, Expr.add, BinaryOp.eval, + p, Nat.cast_ofNat, h3, h4, h5, ← positions, Nat.cast_mul] + have hs : (strideExpr L.shape).eval p s m = (levelWords L : Word w) := by + simp only [strideExpr, Expr.eval, Expr.mul, Expr.add, BinaryOp.eval, hp, levelWords, levelHeaderWords, + slotCapacity, tableWords, Nat.cast_mul, Nat.cast_add, Nat.cast_ofNat] + refine ⟨exec, run.2.2.1, ?_, run.2.2.2.1, run.2.2.2.2.2⟩ + rw [← hdest, ← hs, ← hw] + exact run.2.1 + +end CompressorRecords.DescriptorStride + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDescriptorTableFits.lean b/lean/OAI/Computability/VPVNP/CompressorDescriptorTableFits.lean new file mode 100644 index 0000000000..aaad3281c3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDescriptorTableFits.lean @@ -0,0 +1,98 @@ +import OAI.Computability.VPVNP.CompressorDescriptorSpace +import OAI.Computability.VPVNP.CompressorRecordRefreshAllocation + +/-! +# Packed suballocations of the descriptor tables + +Fixed fields per initial position suffice for all the subarrays of one degree refresh. +The bound includes all segment scratch columns, demands, strided terms, supplies, +expander ROM columns and the six output incidence columns. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DescriptorSpace + +open Compression PortRefresh.Allocation + +variable (L : Layout) + +/-- Any packed suballocation with a fixed linear bound on its length fits this table. -/ +theorem tableFits {K amount : ℕ} (h : amount ≤ K*L.positions+K) (pos : 0 < L.positions) + (capacity : 2*K ≤ L.shape.slots*L.shape.fields) : amount ≤ tableWords L := by + have k : K ≤ K*L.positions := Nat.le_mul_of_pos_right _ pos + change amount ≤ L.positions*L.shape.slots*L.shape.fields + rw [Nat.mul_assoc] + exact (by rw [Nat.mul_assoc]; omega : amount ≤ (2*K)*L.positions).trans + ((Nat.mul_le_mul_right L.positions capacity).trans_eq (Nat.mul_comm ..)) + +/-- The exclusive end of a packed suballocation is representable as a word. -/ +theorem tableStop_lt {bits amount : ℕ} (level : Fin L.levels) (table : Fin L.shape.tables) + (bound : amount ≤ tableWords L) (room : endAddress L < 2^bits) : + tableBase L level.val table + amount < 2^bits := + ((Nat.add_le_add_left bound _).trans ((tableEnd_le_nextLevel L _ _).trans + (levelStart_mono L level.isLt))).trans_lt room + +/-- Exact allocation bound per current site of an elementary degree refresh. -/ +theorem refresh_plan_bound {a g : ℕ} (X : State a (a+g)) (a₀ dH t stride start : ℕ) : + let P := plan X a₀ dH t stride start + P.stop ≤ start + P.sites * (7*2^a + t + stride + 3*dH + 6*2^a₀) := by + intro P + have blocks : P.blocks ≤ P.sites := by + change Fintype.card X.Base * 2^g ≤ Fintype.card X.Base * 2^a * 2^g + exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)) + have ports : P.ports ≤ P.sites := by + change 2^a ≤ Fintype.card X.Base * 2^a * 2^g + exact (Nat.le_mul_of_pos_left _ Fintype.card_pos).trans (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g)) + have ht := Nat.mul_le_mul_right t blocks + have hs := Nat.mul_le_mul_right stride blocks + have hr := Nat.mul_le_mul_right dH ports + change start + 7*(P.sites*2^a) + P.blocks*t + P.blocks*stride + P.sites*dH + P.ports*dH + P.ports*dH + + 6*(P.sites*2^a₀) ≤ _ + ring_nf at * + omega + +/-- At a chosen refresh table base, the entire realized pass remains in that level, +and its exclusive end is a word. -/ +theorem refresh_table_room {a g w : ℕ} (X : State a (a+g)) (a₀ dH t stride : ℕ) + (level : Fin L.levels) (table : Fin L.shape.tables) + (sites : (plan X a₀ dH t stride (tableBase L level table)).sites ≤ L.positions) + (capacity : 7*2^a+t+stride+3*dH+6*2^a₀ ≤ L.shape.slots*L.shape.fields) + (room : endAddress L < 2^w) : + let P := plan X a₀ dH t stride (tableBase L level table) + P.stop ≤ tableBase L level table + tableWords L ∧ P.stop < 2^w := by + intro P + have mul := Nat.mul_le_mul sites capacity + rw [← Nat.mul_assoc] at mul + have le := (refresh_plan_bound X a₀ dH t stride (tableBase L level table)).trans (Nat.add_le_add_left mul _) + exact ⟨le,le.trans_lt (tableStop_lt L level table le_rfl room)⟩ + +end CompressorRecords.DescriptorSpace + +namespace CompressorRecords.DescriptorSpace +open BurstRAM +open scoped Fin.CommRing + +/-- The terminal prefix table starts after the final width column, and its final +prefix entry precedes the high header containing the cumulative total word. -/ +theorem prefix_bounds (L : Layout) {w : ℕ} (level : Fin L.levels) (table : Fin L.shape.tables) + (slots H : ℕ) (cap : slots ≤ slotCapacity L) (cells : slots ≤ tableWords L) + (end_le : endAddress L ≤ H) (room : H+12 < 2^w) : + ((incidenceBase L level slots 5 : ℕ) : Word w).val+slots ≤ tableBase L level table ∧ + tableBase L level table+slots ≤ H+12 ∧ tableBase L level table+slots < 2^w := by + have size := Nat.mul_le_mul_left 6 cap + have low : incidenceBase L level slots 5+slots ≤ tableBase L level table := by + change incidenceStart L level+5*slots+slots ≤ incidenceStart L level + 6*slotCapacity L + table.val*tableWords L + omega + have high : tableBase L level table+slots ≤ H := + (Nat.add_le_add_left cells _).trans ((tableEnd_le_nextLevel L _ _).trans ((levelStart_mono L level.isLt).trans end_le)) + rw [Fin.val_natCast,Nat.mod_eq_of_lt (show incidenceBase L level slots 5 < 2^w by omega)] + exact ⟨low,by omega,by omega⟩ + +end CompressorRecords.DescriptorSpace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDetailedResident.lean b/lean/OAI/Computability/VPVNP/CompressorDetailedResident.lean new file mode 100644 index 0000000000..a0ea0a5c5e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDetailedResident.lean @@ -0,0 +1,99 @@ +import OAI.Computability.VPVNP.CompressorCurrentResident +import OAI.Computability.VPVNP.CompressorSelectedPayloadHistory + +/-! +# Selected payloads at a compressor boundary + +The current incidence graph and placement directories share their memory +with the parser data produced by earlier passes. Appending a selected pass +retains its post-memory as the new snapshot. For older snapshots, only the +completed levels and the current graph's pointer and incidence bank need +to agree with the previous boundary. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DetailedResident + +open BurstRAM Compression DescriptorSpace PairSimulation.LocalHistory PairSimulation.TraversalRows +open PairSimulation.TraversalRoles +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) {w : ℕ} + +/-- Readable current graph, placement directories and selected parser snapshots. -/ +def resident (initial : TaggedLayer) (L : Layout) (base n : ℕ) (initialFrame : Fin 8 → Word w) + (data : SelectedPayloadHistory.Data (w := w) B f hf) : ScheduledTrace.Resident B f hf w := + fun past {_ _} X m => + CurrentResident.resident B f hf initial L base n initialFrame past X m ∧ + SelectedPayloadHistory.Past B f hf L data past m + +variable {B f hf} {initial : TaggedLayer} {L : Layout} {base n a g : ℕ} +variable {initialFrame : Fin 8 → Word w} {data : SelectedPayloadHistory.Data (w := w) B f hf} +variable {past : List (SelectedLevel B f hf)} {X : State a g} {m out : Memory w} + +theorem current (h : resident B f hf initial L base n initialFrame data past X m) : + CurrentResident.resident B f hf initial L base n initialFrame past X m := h.1 + +theorem payloads (h : resident B f hf initial L base n initialFrame data past X m) : + SelectedPayloadHistory.Past B f hf L data past m := h.2 + +/-- The first cursor publisher creates the current graph with an empty +list of completed parser passes. -/ +theorem initial_live {b width : ℕ} {workspace : Word w} + (cursor : BlockStartupPrefix.Resident L a b g width n workspace m X) + (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) (BlockInitialPackets.post L a b g width m) out) + (positive : 0 < L.levels) (fields : 14 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) : + resident B f hf ⟨leafLayer (siteOrder X),.cursor⟩ L (endAddress L) n + (CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase L)) (CursorRAM.encode w 1) + b g a width (incidenceStart L 0)) data [] X out := + ⟨CurrentResident.initial_live cursor agree positive fields fit, SelectedPayloadHistory.Past.empty⟩ + +theorem transfer (h : resident B f hf initial L base n initialFrame data past X m) + (index : past.length < L.levels) (fit : endAddress L < 2^w) (fields : 14 ≤ L.shape.scalarFields) + (slots : IncidenceDirectory.slotCount X ≤ slotCapacity L) + (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) m out) : + resident B f hf initial L base n initialFrame data past X out := by + refine ⟨CurrentResident.transfer h.1 index fit fields slots agree, h.2.transfer ?_⟩ + intro x lo _ + exact (agree x (by simpa only [levelStart,Nat.zero_mul,Nat.add_zero] using lo)).symm + +/-- Both the newly published graph and its parser data are read from the +same post-memory. The predecessor frame keeps the last pass's output graph +as well as the full data of strictly earlier levels. -/ +theorem append {v : SelectedLevel B f hf} + (h : resident B f hf initial L base n initialFrame data past v.input m) + (next : CurrentResident.resident B f hf initial L base n initialFrame + (past ++ [v]) (v.pass.next v.term) out) + (emitted : data past.length v out) + (previous : ∀ x, levelsBase L ≤ x → x < levelStart L past.length → out x = m x) + (input : SourceTransport.Agree (SelectedPayloadHistory.GraphCells L past.length) m out) : + resident B f hf initial L base n initialFrame data (past ++ [v]) (v.pass.next v.term) out := + ⟨next, h.2.append emitted previous input⟩ + +variable {pub : Fin 11 → Word w} {pitch : Word w} {total ordinal : ℕ} + +/-- Project a detailed boundary to the current graph expected by the +terminal bootstrap, preserving the concrete scheduler words. -/ +theorem currentBoundary (h : ScheduledTrace.Boundary (resident B f hf initial L base n initialFrame data) + pub pitch total ordinal past X m) : + ScheduledTrace.Boundary (CurrentResident.resident B f hf initial L base n initialFrame) + pub pitch total ordinal past X m := + ⟨h.bank,h.tag,h.ordinalValue,h.totalValue,h.stride,h.stored.1⟩ + +/-- The existing cursor interval supplies the detailed initial boundary +for any selected parser predicate. -/ +theorem initialBoundary (h : ScheduledTrace.Boundary (CurrentResident.resident B f hf initial L base n initialFrame) + pub pitch total ordinal [] X m) : + ScheduledTrace.Boundary (resident B f hf initial L base n initialFrame data) + pub pitch total ordinal [] X m := + ⟨h.bank,h.tag,h.ordinalValue,h.totalValue,h.stride,h.stored,SelectedPayloadHistory.Past.empty⟩ + +end CompressorRecords.DetailedResident + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDeterministicGroup.lean b/lean/OAI/Computability/VPVNP/CompressorDeterministicGroup.lean new file mode 100644 index 0000000000..00520094d2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDeterministicGroup.lean @@ -0,0 +1,113 @@ +import OAI.Computability.VPVNP.CompressorPassIntervalData +import OAI.Computability.VPVNP.CompressorSourceGroups +import OAI.Computability.VPVNP.CompressorIntervalCost + +/-! # Executing a deterministic group of source packets + +The scheduled interval uses the public pointer bank and starts in the +calendar state. Its private-clock reports come from the native scheduler. +They include the control calls surrounding each packet. At the return +boundary the live memory agrees with the source on every data address. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM BlockPlanner DescriptorSpace Schedule SourceTransport +open scoped Fin.CommRing + +variable {w small cap ordinal total : ℕ} {A : Script} {L : Layout} + {pub : Fin 11 → Word w} {m raw : Memory w} {ps : List (SourceOnline.Packet A w)} +local notation "pt" => Workspace.ports (arity A.catalog) (pub 2) +local notation "tag" => LiveStageLink.tagWord w (Online.calendarIndex A.size A.size) + +/-- The total data calls and probes, with the descriptor and recipe charge +for every visited row. This includes the four control calls of an empty row. -/ +def groupCost (A : Script) (ps : List (SourceOnline.Packet A w)) : ℕ := + RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) * (arity A.catalog+3) + + ps.length * (Online.Run.maxReads A.plan+4*arity A.catalog+26) + +/-- A deterministic flattened tape witnesses determinism of each source visit. -/ +theorem packet_quiet_of_flat {n : ℕ} + (empty : ps.flatMap (fun p => p.stage.choices) = List.replicate n []) + (p : SourceOnline.Packet A w) (hp : p ∈ ps) : + p.stage.choices = List.replicate p.stage.choices.length [] := by + apply List.eq_replicate_length.mpr + intro b hb + have mem : b ∈ ps.flatMap (fun p => p.stage.choices) := List.mem_flatMap.mpr ⟨p,hp,hb⟩ + rw [empty] at mem + exact (List.mem_replicate.mp mem).2 + +private theorem interval_mono {steps : List (Online.Run.Step A.size A.size w)} + (h : Online.Run.Interval A.plan pt small m steps) (le : small ≤ cap) : + Online.Run.Interval A.plan pt cap m steps := by + induction steps generalizing m with + | nil => trivial + | cons s ss ih => + obtain ⟨v, rest⟩ := h + exact ⟨⟨v.phase,v.active,v.input,v.source,v.recipeCap.trans le,v.dataCap.trans le⟩, ih rest⟩ + +private theorem final_tag {steps : List (Online.Run.Step A.size A.size w)} (h : m (pt).tag.val = tag) : + (Online.Run.finalMemory (C := A.catalog) pt m steps) (pt).tag.val = tag := by + induction steps generalizing m with + | nil => exact h + | cons s ss ih => exact ih (by simp [Online.post,writeMemory]) + +/-- Run the packets under the smaller source clock, replay them at the +enclosing workspace clock, and recover all persistent boundary fields. -/ +theorem deterministicGroup (group : SourceOnline.Group A L (pub 2) small ordinal total raw ps) + (quiet : ∀ p ∈ ps, p.stage.choices = List.replicate p.stage.choices.length []) + (clock : small ≤ cap) (bounds : Online.Run.ControlBounds A.plan small (w := w)) + (arityEq : arity A.catalog = L.shape.arity) (baseEq : (pub 2).val = L.base) + (fit : levelStart L 0 < 2^w) (count : ordinal+ps.length ≤ total) (room : total ≤ directoryRows L) + (agree : Agree (levelStart L 0 ≤ ·) raw m) (bank : Workspace.Installed (arity A.catalog) (pub 2) m) + (htag : m (pt).tag.val = tag) (ord : (m (pt).ordinal.val).val = ordinal) + (rows : (m (pt).rows.val).val = total) (stride : m ((pt).directory-1).val = (levelWords L : Word w)) : + ∃ out : QuietInterval A pub cap small (some 0) m, + Agree (levelStart L 0 ≤ ·) (SourceOnline.post raw ps) out.segment.memory ∧ + Workspace.Installed (arity A.catalog) (pub 2) out.segment.memory ∧ + out.segment.memory (pt).tag.val = tag ∧ + (out.segment.memory (pt).ordinal.val).val = ordinal+ps.length ∧ + (out.segment.memory (pt).rows.val).val = total ∧ + out.segment.memory ((pt).directory-1).val = (levelWords L : Word w) ∧ + RAMBuckets.cost Report.probes out.source.logs ≤ groupCost A ps := by + obtain ⟨steps,v,phases,reports,tapes,mem,ord',rows',stride',stable⟩ := + SourceOnline.interval_stable A L (pub 2) arityEq baseEq fit small ordinal total m raw ps + group.chronological group.checked group.prepared count room agree ord rows htag stride + have big : Online.Run.ControlBounds A.plan cap (w := w) := + ⟨bounds.tags,bounds.calendar.trans clock,bounds.launch.trans clock⟩ + have valid := interval_mono v clock + let seg := OnlineWorkspace.intervalSegment A pub big htag steps valid stable bank + let core : OnlineWorkspace.Core A pub seg small := + ⟨Online.Run.intervalLog A.plan pt m steps,(Online.Run.intervalSegment A.plan pt (state := 0) bounds htag steps v).run,rfl⟩ + have deterministic (s : Online.Run.Step A.size A.size w) (hs : s ∈ steps) : + s.row.choices = List.replicate s.row.choices.length [] := by + have seen := List.mem_map_of_mem (f := fun q : Online.Run.Step A.size A.size w => q.row.choices) hs + rw [tapes] at seen + obtain ⟨p,hp,eq⟩ := List.mem_map.mp seen + rw [← eq] + exact quiet p hp + let out : QuietInterval A pub cap small (some 0) m := + ⟨seg,OnlineWorkspace.intervalSegment_quiet A pub big htag steps valid stable bank deterministic, + OnlineWorkspace.intervalSegment_stable A pub big htag steps valid stable bank, + OnlineWorkspace.intervalSegment_state A pub big htag steps valid stable bank, core⟩ + have actual : out.segment.memory = Online.Run.finalMemory (C := A.catalog) pt m steps := + OnlineWorkspace.intervalSegment_memory A pub big htag steps valid stable bank + refine ⟨out,actual.symm ▸ mem,OnlineWorkspace.intervalSegment_bank A pub big htag steps valid stable bank, + actual.symm ▸ final_tag htag,actual.symm ▸ ord',actual.symm ▸ (congrArg Fin.val rows').trans rows, + actual.symm ▸ stride'.trans stride,?_⟩ + have lengthEq : steps.length = ps.length := by simpa only [List.length_map] using congrArg List.length phases + have logs : steps.flatMap (fun s => s.row.reports) = ps.flatMap SourceWalk.Packet.reports := by + simpa only [List.flatMap_def] using congrArg List.flatten reports + have cost := Online.Run.interval_cost_bound A.plan pt steps m v + rw [Online.Run.sourceCost_eq_flatMap,logs,lengthEq] at cost + exact cost + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorDirectoryBudget.lean b/lean/OAI/Computability/VPVNP/CompressorDirectoryBudget.lean new file mode 100644 index 0000000000..a9d0f2d531 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorDirectoryBudget.lean @@ -0,0 +1,119 @@ +import OAI.Computability.VPVNP.CompressorPhaseVisits +import OAI.Computability.VPVNP.CompressorRecordsOnline +import OAI.Computability.VPVNP.CompressorRecordsDirectoryCursor +import OAI.Computability.VPVNP.CursorBranchCommunication + +/-! +# Uniform cost of the selected branch's linked descriptor scans + +The native calendar makes three calls before each scan and one closing +call. The scan consumes the source worker's complete tape. The theorem +charges these four calls even when that tape is empty. The constant is +chosen from the initial rows, the finite block's multiplicities, and the +native instruction cap, before any input length or term choice. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PhaseVisits + +open BurstRAM Compression Schedule CursorNetwork CursorBounds Filter +open private count_le_events cost_cap from OAI.Computability.VPVNP.CompressorPhaseVisits + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} +variable {d w : ℕ} + +private theorem source_length {C : Catalog d} {ports : Ports w} {row : Directory.Row d w} + (h : row.Valid C ports) : row.choices.length = row.reports.length := by + have hv := ((runSegment_iff ..).mp h.sourceRun).2.2 + simpa [branchPaths] using (congrArg List.length hv).symm + +private theorem online_tape_length (C : Catalog d) (ports : Ports w) (rows : List (Directory.Row d w)) + (h : ∀ r ∈ rows, r.Valid C ports) : + (rows.flatMap Online.rowChoices ++ [[]]).length ≤ 2*calls rows+1 := by + have bound : (rows.flatMap Online.rowChoices).length ≤ 2*calls rows := by + induction rows with + | nil => simp [calls] + | cons r rs ih => + have hl := source_length (h r (by simp)) + have ht := ih (fun r hr ↦ h _ (by simp [hr])) + rw [List.flatMap_cons,List.length_append] + change (Online.rowChoices r).length+_ ≤ 2*((r.reports.length+2)+calls rs) + simp only [Online.rowChoices,List.length_cons,List.length_append,List.length_nil,hl] + omega + simpa only [List.length_append,List.length_cons,List.length_nil] using Nat.add_le_add_right bound 1 + +/-- Source-data calls and both control calls in the initial cursor directory. -/ +theorem cursorRow_calls (m : Memory w) (base lanes a width columns : ℕ) : + calls [Directory.Cursor.row m base lanes a width columns] = CursorRAM.rowCount base lanes a + 2 := by + simp [calls,Directory.Cursor.row,CursorRAM.scanReports_length] + +private theorem blocks_le_log (B : S.Templates) (u : PairExponents B.growthConstant) {n : ℕ} (hn : 1 ≤ n) : + blockCount (u.θ : ℝ) n ≤ n.log2+1 := by + have hθ : (u.θ : ℝ) ≤ 1 := by + have := (Rat.cast_lt (K := ℝ)).mpr u.theta_lt + norm_num at this; linarith + have hn₁ : 1 ≤ (n : ℝ) := by exact_mod_cast hn + apply le_trans _ (BurstRAM.clog_le_log2_succ n) + rw [blockCount,← Real.natCeil_logb_natCast 2 n] + exact (Nat.floor_le_floor (mul_le_of_le_one_left (Real.logb_nonneg (by norm_num) hn₁) hθ)).trans + (Nat.floor_le_ceil _) + +/-- Charged accesses for the online controller and worker reports of one +whole selected branch. The successful run and individual source runs are +the native caller's semantic obligations. There is no traffic hypothesis on +their combined reports. -/ +theorem online_run_budget (B : S.Templates) (u : PairExponents B.growthConstant) (P : Plan S) + (H I q b n : ℕ) (hn : 1 ≤ n) {base lanes : ℕ} + (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n) + (hT : blockCount (u.θ : ℝ) n*S.laneBits ≤ lanes) + {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f) + (z : (B.execute f hf _ hT (pairInput S labels hD)).Choices) + (C : Catalog d) (ports : Ports w) (initial : List (Directory.Row d w)) + (groups : ∀ v : SelectedLevel B f hf, LevelRows (d := d) (w := w) (pairInput S labels hD).positions v) + (hinit : calls initial ≤ I*(pairInput S labels hD).positions) : + let X := pairInput S labels hD + let T := blockCount (u.θ : ℝ) n + let rows := branchRows P X.positions (executeLevels B f hf T hT X z) initial groups + let K := (2*(I + (S.steps+1)*max 1 (slotDegree S)*P.levelRate)+1)*H + ∀ {V : Type*} (M : BurstRAM.Program w V) (s : Word w) (mem : Memory w) (cap : ℕ) + (rs : List (Report w)), + (∀ r ∈ rows, r.Valid C ports) → cap ≤ H*(n.log2+1)^q → + runSegment M cap (some s) mem (rows.flatMap Online.rowChoices ++ [[]]) = some rs → + (∀ r ∈ rs, r.events.length < cap ∧ r.probes < cap) ∧ + RAMBuckets.cost Report.probes rs ≤ K * initialPositions b n * (n.log2+1)^(q+1) := by + intro X T rows K V M s mem cap rs hrows hcap hr + let L := n.log2+1 + have ht := blocks_le_log B u hn + change T ≤ L at ht + have hc := branchRows_calls P hT X z initial groups + let F := I + (S.steps+1)*max 1 (slotDegree S)*P.levelRate + have hcharged : calls rows ≤ F*X.positions*L := by + apply hc.trans + calc + _ ≤ I*X.positions*L + (S.steps+1)*L*(X.positions*max 1 (slotDegree S)*P.levelRate) := + Nat.add_le_add (hinit.trans (Nat.le_mul_of_pos_right _ (Nat.succ_pos _))) + (Nat.mul_le_mul_right _ (Nat.mul_le_mul_left _ ht)) + _ = _ := by dsimp only [F]; ring + have hnum := online_tape_length C ports rows hrows + have he := congrArg List.length ((runSegment_iff ..).mp hr).2.2 + have hlen : rs.length ≤ 2*calls rows+1 := (by simpa [branchPaths] using he : rs.length = _).le.trans hnum + have hP : 1 ≤ X.positions*L := Nat.mul_pos X.positions_pos (Nat.succ_pos _) + have hcalls : rs.length ≤ (2*F+1)*X.positions*L := hlen.trans (by + have hh := Nat.add_le_add (Nat.mul_le_mul_left 2 hcharged) hP + exact hh.trans_eq (by ring)) + have hstep := localSegment_event_bound ((runSegment_iff ..).mp hr).1 + refine ⟨fun r h ↦ ⟨hstep r h,(count_le_events r.events).trans_lt (hstep r h)⟩, + (cost_cap rs cap hstep).trans ((Nat.mul_le_mul hcalls hcap).trans_eq ?_)⟩ + have hx := pairInput_positions S labels hD + change X.positions = initialPositions b n at hx + rw [hx] + dsimp only [F,K,L]; ring + +end CompressorRecords.PhaseVisits + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorEvaluatorAdvice.lean b/lean/OAI/Computability/VPVNP/CompressorEvaluatorAdvice.lean new file mode 100644 index 0000000000..5d9474b3ca --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorEvaluatorAdvice.lean @@ -0,0 +1,90 @@ +import OAI.Computability.VPVNP.CompressorLabelEvaluator +import OAI.Computability.VPVNP.EvaluatorAdviceSerialization + +/-! +# Polynomial-length slice advice for the joint compressor labels + +The prime header allows the fixed positive characteristic, as well as the +good prime chosen at the current length in characteristic zero. With that +header width one fixed padding exponent accommodates the actual serialized +finite-field presentation and all affine-slice pin data. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open JointLabelSystem LabelEvaluator EvaluatorAdviceSerialization SliceArithmetic + +local instance advicePrimeFact (p : Nat.Primes) : Fact p.val.Prime := ⟨p.property⟩ +/-- Finite enumeration of the slice ground field used to encode the evaluator's advice. -/ +noncomputable local instance adviceGroundFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := + Fintype.ofFinite _ + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- The extra high bit ensures the prime fits even at equality in the +characteristic-zero estimate. -/ +noncomputable def compressorHeaderWidth (q c n : ℕ) := + Nat.clog 2 q + B.compressorPrimeBits c n + 1 + +theorem compressorHeaderWidth_polynomial (q c : ℕ) : + PolynomiallyBounded (B.compressorHeaderWidth q c) := + ((PolynomiallyBounded.const _).add (B.compressorPrimeBits_polynomial c)).add (.const 1) + +theorem prime_fits_compressorHeader {q c n : ℕ} (p : Nat.Primes) (hp : q ≠ 0 → p.val = q) + (hzero : q = 0 → p.val ≤ 2 ^ B.compressorPrimeBits c n) : + p.val < 2 ^ B.compressorHeaderWidth q c n := by + unfold compressorHeaderWidth + apply lt_of_le_of_lt _ (Nat.pow_lt_pow_right (by decide : 1 < 2) (Nat.lt_succ_self _)) + by_cases hq : q = 0 + · exact (hzero hq).trans (Nat.pow_le_pow_right (by decide) (Nat.le_add_left ..)) + · rw [hp hq] + exact (Nat.le_pow_clog (by decide) _).trans + (Nat.pow_le_pow_right (by decide) (Nat.le_add_right ..)) + +/-- A single length exponent works for the slice advice of every eventual +small circuit and every admitted prime of the fixed characteristic. -/ +theorem exists_compressorAdvicePadding (q c : ℕ) : + ∃ a N : ℕ, ∀ n ≥ N, ∀ p : Nat.Primes, + (q ≠ 0 → p.val = q) → (q = 0 → p.val ≤ 2 ^ B.compressorPrimeBits c n) → + let t := B.compressorLabelCount c n + let d := B.compressorDegree n + length (B.compressorHeaderWidth q c n) p.val (degree p.val t d) t ≤ n ^ a := by + obtain ⟨a, N, ha⟩ := exists_advice_padding (B.compressorHeaderWidth_polynomial q c) + (B.compressorLabelCount_polynomial c) B.compressorDegree_polynomial.clog + exact ⟨a, N, fun n hn p hp hz ↦ ha n hn p (B.prime_fits_compressorHeader p hp hz)⟩ + +/-- The actual finite-slice advice decoded by the evaluator. The prescribed +padding may be followed by additional public fields. The field presentation +preserves the coordinate used for the final prime-field tally. -/ +theorem exists_compressorEvaluatorTape (q c : ℕ) : + ∃ a N : ℕ, ∀ n ≥ N, ∀ (hn : 2 ≤ n) (p : Nat.Primes) + (M : Model p (B.compressorDegree n) (B.compressorEquations hn c)), + (q ≠ 0 → p.val = q) → (q = 0 → p.val ≤ 2 ^ B.compressorPrimeBits c n) → + let t := B.compressorLabelCount c n + let d := B.compressorDegree n + let e := degree p.val t d + ∃ (tape : List Bool) (advice : Fields p.val e t), tape.length ≤ n ^ a ∧ + (∀ tail, parse (B.compressorHeaderWidth q c n) t d (tape ++ tail) = some ⟨p, advice⟩) ∧ + ∃ φ : AdjoinRoot (modulus advice.coefficients) ≃ₐ[ZMod p.val] Ground p t d, + Irreducible (modulus advice.coefficients) ∧ + (∀ i, advice.pins i = decide (i ∈ M.pins)) ∧ + (∀ i, φ (value (modulus advice.coefficients) (advice.values i)) = M.values i) ∧ + ∀ v : SliceArithmetic.Vector p.val e, + SliceEvaluator.primeCoordinate p.val (Ground p t d) + (φ (value (modulus advice.coefficients) v)) = + ((v ⟨0, Nat.succ_pos _⟩).val : ZMod p.val) := by + obtain ⟨a, N, hsize⟩ := B.exists_compressorAdvicePadding q c + refine ⟨a, N, fun n hN hn p M hp hz ↦ ?_⟩ + obtain ⟨tape, hlen, advice, hparse, φ, hirr, hpins, hvals, hcoord⟩ := + exists_model_advice M (B.prime_fits_compressorHeader p hp hz) + exact ⟨tape, advice, hlen.le.trans (hsize n hN p hp hz), hparse, φ, hirr, hpins, hvals, hcoord⟩ + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorEvaluatorChain.lean b/lean/OAI/Computability/VPVNP/CompressorEvaluatorChain.lean new file mode 100644 index 0000000000..9daa3a5623 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorEvaluatorChain.lean @@ -0,0 +1,89 @@ +import OAI.Computability.VPVNP.CompressorLabelEvaluator +import OAI.Computability.VPVNP.PairedChain + +/-! +# The two coefficient identities used by the diagonal chain + +The joint label algebra evaluates the primed contraction to the original +integer count, and its monomial evaluator reads the production and compressor +exponents together. Accumulating the exponents across pairs permits a single +application of the functional to the entire product in the evaluator tail. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open MvPolynomial JointLabelSystem LabelEvaluator +local instance chainPrimeFact (p : Nat.Primes) : Fact p.val.Prime := ⟨p.property⟩ +/-- Finite enumeration of the slice ground field used in the joint coefficient evaluation. -/ +noncomputable local instance chainGroundFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := + Fintype.ofFinite _ +/-- Scalar action of the slice ground field on the ambient field through the chosen slice +embedding. -/ +noncomputable local instance chainGroundAlgebra (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) := + (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) +variable {n c : ℕ} (hn : 2 ≤ n) {p : Nat.Primes} +variable (M : Model p (B.compressorDegree n) (B.compressorEquations hn c)) + +/-- Grammar specialization in the algebra chosen for both compressor blocks. -/ +noncomputable abbrev productionValues := M.labels ∘ leftIndex (Production n c) B.Entry + +/-- The same slice point specifies all shrinking and refresh map entries. -/ +noncomputable abbrev compressorValues := M.labels ∘ rightIndex (Production n c) B.Entry + +theorem compressorValues_solution : B.IsSolution (B.compressorValues hn M) := + (B.compressorEvaluator_readback hn c M).2 + +/-- The primed chain uses the actual grammar solution in the common finite algebra. -/ +theorem compressorEvaluator_primed {h Δ a r bucket w : ℕ} (program : UniversalMachine.Program) + (hfit : BurstRAM.ProcessorInput.Fits program n r bucket w) (advice : CutSchedule.Bits a) : + eval₂Hom (Int.castRingHom M.algebra) (B.productionValues hn M) + (PairedChain.primed (h := h) (Δ := Δ) program hfit advice + ⟨n - 1, by omega⟩ ⟨0, pow_pos (by omega) _⟩) = + (PairedChain.original (h := h) (Δ := Δ) program hfit advice : M.algebra) := + PairedChain.primed_eq_original program hfit advice _ _ _ (B.compressorEvaluator_readback hn c M).1 + +/-- Evaluate a single monomial consisting of production labels and fixed +compressor labels. The coordinate numbering agrees with the joint equations. -/ +theorem compressorEvaluator_monomial (width : ℕ) (μ : Production n c → ℕ) (ν : B.Entry → ℕ) + (hμ : ∀ i, μ i < 2 ^ width) (hν : ∀ i, ν i < 2 ^ width) : + (M.presentation.branchCount p.val width (joinAssignment μ ν) : ZMod p.val) = + M.functional ((∏ i, (B.productionValues hn M i) ^ μ i) * + ∏ i, (B.compressorValues hn M i) ^ ν i) := by + have h e : joinAssignment μ ν e < 2 ^ width := by + obtain ⟨i, rfl⟩ := (Fintype.equivFin (Production n c ⊕ B.Entry)).surjective e + cases i with + | inl v => simpa [joinAssignment] using hμ v + | inr v => simpa [joinAssignment] using hν v + rw [M.branchCount_mod width _ h] + apply congrArg M.functional + rw [← (Fintype.equivFin (Production n c ⊕ B.Entry)).prod_comp + (fun i ↦ M.labels i ^ joinAssignment μ ν i)] + rw [Fintype.prod_sum_type] + simp [productionValues, compressorValues, leftIndex, rightIndex, joinAssignment] + +/-- After the chain accumulates one pair's exponents at a time, the tail +counts precisely the functional applied to the product of all pair weights. -/ +theorem compressorEvaluator_pair_product {I : Type*} [Fintype I] (width : ℕ) + (μ : I → Production n c → ℕ) (ν : I → B.Entry → ℕ) + (hμ : ∀ v, (∑ i, μ i v) < 2 ^ width) (hν : ∀ v, (∑ i, ν i v) < 2 ^ width) : + (M.presentation.branchCount p.val width + (joinAssignment (fun v ↦ ∑ i, μ i v) (fun v ↦ ∑ i, ν i v)) : ZMod p.val) = + M.functional (∏ i, (∏ v, (B.productionValues hn M v) ^ μ i v) * + ∏ v, (B.compressorValues hn M v) ^ ν i v) := by + rw [B.compressorEvaluator_monomial hn M width _ _ hμ hν] + apply congrArg M.functional + rw [Finset.prod_mul_distrib] + simp only [← Finset.prod_pow_eq_pow_sum] + exact congrArg₂ (· * ·) Finset.prod_comm Finset.prod_comm + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorEvaluatorInput.lean b/lean/OAI/Computability/VPVNP/CompressorEvaluatorInput.lean new file mode 100644 index 0000000000..76854aa350 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorEvaluatorInput.lean @@ -0,0 +1,152 @@ +import OAI.Computability.VPVNP.CompressorEvaluatorWidths +import OAI.Computability.VPVNP.EvaluatorUniformBounds +import OAI.Computability.VPVNP.LiveEvaluatorRadius +import OAI.Computability.VPVNP.RAMTapePhysicalHalting + +/-! +# Advised coordinate readers for the compressor label system + +This record describes the exact binary interface between the deterministic +coordinate queries and the fixed nondeterministic evaluator. All fields are +selected at the input length, before the exponent vector and its width. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open LabelEvaluator SliceArithmetic RAMTape Evaluator Evaluator.MatrixCallbacks +open EvaluatorProgramRawInput Evaluator.BinaryMachine LiveEvaluatorEncoding UniversalMachine + +local instance readerInputPrime (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩ +/-- Finite enumeration of the ground field used by the matrix-entry readers. -/ +noncomputable local instance readerInputFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _ +/-- Decidable equality of slice ground-field elements for the evaluator input construction. -/ +noncomputable local instance readerInputDecidableEq (p : Nat.Primes) (t d : ℕ) : DecidableEq (Ground p t d) := Classical.decEq _ +/-- Ambient algebra structure induced by the ground-field embedding used in the reader +presentation. -/ +noncomputable local instance readerInputAmbientAlgebra (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) := + (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) + {n c : ℕ} {hn : 2 ≤ n} {p : Nat.Primes} {P : Type} [DecidableEq P] + (M : Model p (B.compressorDegree n) (B.compressorEquations hn c)) + (frob label : FiniteRoutine (ReadPort P)) + +/-- The physical advice and two verified entry readers for this particular +finite slice. The counters and field inputs are common to all later calls. -/ +structure SliceReaderAdvice where + /-- One less than the extension degree in the polynomial presentation supplied to the reader. -/ + degreePred : ℕ + /-- Prime-field coefficients specifying the monic modulus for the advised field presentation. -/ + coefficients : Vector p.val (degreePred+1) + /-- Algebra isomorphism identifying residue classes modulo the advised modulus with elements + of the slice ground field. -/ + fieldMap : AdjoinRoot (modulus coefficients) ≃ₐ[ZMod p.val] Ground p (B.compressorLabelCount c n) (B.compressorDegree n) + primeCoordinate (y) : SliceEvaluator.primeCoordinate p.val _ (fieldMap (value (modulus coefficients) y)) = + ((y (0 : Fin (degreePred+1))).val : ZMod p.val) + /-- Bit width used to address rows and columns of the advised query matrices. -/ + indexWidth : ℕ + dimensionFits : (M.queryData (B.compressorCoeff hn c)).dimension < 2^indexWidth + /-- Width of the arithmetic limbs used by the entry readers, large enough for their + prime-field operations. -/ + limbWidth : ℕ + widthFits : Word.workingWidth p.val ≤ limbWidth + /-- Auxiliary input stacks made available to the Frobenius and label matrix readers. -/ + extra : Stacks P + /-- Common upper bound on the length of each auxiliary reader stack. -/ + extraSpace : ℕ + extraFits (a : P) : (extra a).length ≤ extraSpace + /-- Peak space bound shared by the Frobenius and label entry-reading routines. -/ + peak : ℕ + /-- Exponent specifying the power-of-two time budget for one advised matrix-entry query. -/ + queryExponent : ℕ + frobeniusRead : ReadsEntryWithin fieldMap (M.dimensionWord dimensionFits) extra frob limbWidth 0 + (2^queryExponent) peak (fun src dest ↦ (M.queryData (B.compressorCoeff hn c)).matrixEntry .frobenius dest src) + labelRead (j : Fin (B.compressorLabelCount c n)) : + ReadsEntryWithin fieldMap (M.dimensionWord dimensionFits) extra label limbWidth j.val (2^queryExponent) peak + (fun src dest ↦ (M.queryData (B.compressorCoeff hn c)).matrixEntry (.label j) dest src) + +variable {B M frob label} (H : B.SliceReaderAdvice M frob label) (ps : List (WeightedStep.Port P)) + +local notation "t" => B.compressorLabelCount c n +local notation "divisor" => cardinalBits p (B.compressorLabelCount c n) (B.compressorDegree n) +local notation "dimWord" => M.dimensionWord H.dimensionFits +local notation "D" => B.compressorCanonical hn c M +local notation "ports" => MachinePort (WeightedStep.Port P) + +/-- All persistent advice fields of the actual evaluator at this length. -/ +noncomputable def SliceReaderAdvice.binary : List Bool := + let u := (D).ordinal.symm (D).presentation.unitIndex + advice ps (t) (divisor) (payload H.fieldMap dimWord H.extra H.limbWidth (u,1)) + +/-- Joint width, workspace and query-time exponent envelope for this length. -/ +noncomputable def SliceReaderAdvice.envelope [Fintype P] : ℕ := + lengthEnvelope (t) (divisor).length ps.length (Fintype.card ports) + H.indexWidth (H.degreePred+1) H.limbWidth H.extraSpace H.peak H.queryExponent + +theorem SliceReaderAdvice.binary_le [Fintype P] : (H.binary ps).length ≤ H.envelope ps := by + apply (advice_le H.fieldMap dimWord H.extra (divisor) H.extraSpace H.extraFits ps _).trans + dsimp only [envelope, lengthEnvelope] + omega + +/-- At every exponent width, the fixed table returns the canonical model's +functional and its literal computation stays inside a polynomial tape window. -/ +theorem SliceReaderAdvice.resources_and_value [Fintype P] (hps : ps.Nodup) (hall : ∀ k, k ∈ ps) {Z : ℕ} + (es : Fin (t) → BurstRAM.Word Z) (ticks : ℕ) (hticks : 2^(6*H.envelope ps+23)*(Z+1)^4 ≤ ticks) : + let E := MatrixCallbacks.program ps frob label + let raw := H.binary ps ++ runtime es + UniversalMachine.AllHalt E ticks (UniversalMachine.initial E raw) ∧ + (UniversalMachine.paths E ticks (UniversalMachine.initial E raw) : ZMod p.val) = + (M.withCanonicalPresentation (D)).functional (∏ j, M.labels j^(es j).val) ∧ + (∀ choices, let disp := choiceDisplacement E (UniversalMachine.initial E raw) choices + StackCompiler.HeadBox (2240*(Fintype.card ports+1)*(H.envelope ps+Z+1)^4) disp.1 disp.2) ∧ + ∀ time (bits : Fin time → Bool) (i : Fin (time+1)), StateFits + (2240*(Fintype.card ports+1)*(H.envelope ps+Z+1)^4) (EvaluatorTail.history E time (UniversalMachine.initial E raw) bits i) := by + let A := adviceCap ps.length (t) (divisor).length (WeightedStep.bankSpace H.indexWidth (H.degreePred+1) + H.limbWidth H.extraSpace) + let raw := H.binary ps ++ runtime es + have hraw : raw.length ≤ A+(2*((t)*Z)+6*Z+4) := by + rw [show raw = H.binary ps ++ runtime es from rfl, List.length_append, runtime_length] + apply Nat.add_le_add_right + exact advice_le H.fieldMap dimWord H.extra (divisor) H.extraSpace H.extraFits ps _ + have htime := uniform_tape_clock (t) Z (divisor).length ps.length (Fintype.card ports) + H.indexWidth (H.degreePred+1) H.limbWidth H.extraSpace H.peak H.queryExponent + (TapeWord.value (divisor)) (2^H.queryExponent) (2^H.queryExponent) raw.length + (TapeWord.value_lt _).le le_rfl le_rfl hraw + obtain ⟨count, bound⟩ := M.canonical_literal_evaluator (D) H.dimensionFits H.fieldMap H.primeCoordinate + ps hps hall frob label H.extra H.extraSpace H.extraFits H.widthFits (divisor) (value_cardinalBits ..) + _ _ H.peak H.frobeniusRead H.labelRead es ticks (htime.trans hticks) + have hq : 2 ≤ TapeWord.value (divisor) := (value_cardinalBits ..) ▸ + Fintype.one_lt_card (α := Ground p (t) (B.compressorDegree n)) + have stack := stack_from_bounded_matrices ps frob label H.fieldMap dimWord H.extra H.extraSpace H.extraFits + ((D).ordinal.symm (D).presentation.unitIndex) es (divisor) hps hall H.widthFits _ _ H.peak hq + _ _ H.frobeniusRead H.labelRead + have halt := StackCompiler.input_allHalt_labeled none _ _ raw _ ticks stack.1 (htime.trans hticks) + have hwindow := uniform_window (t) Z (divisor).length ps.length (Fintype.card ports) + H.indexWidth (H.degreePred+1) H.limbWidth H.extraSpace H.peak H.queryExponent raw.length hraw + refine ⟨halt,count,fun choices ↦ ?_, fun time bits i ↦ + LiveEvaluatorRadius.fits_mono hwindow _ (LiveEvaluatorSpace.history_fits _ raw _ bound time bits i)⟩ + have small := bound choices + exact small.mono ((Nat.le_add_left _ _).trans hwindow) + +/-- The algebra value and full history window for callers which execute the +table at their own clock. -/ +theorem SliceReaderAdvice.evaluate [Fintype P] (hps : ps.Nodup) (hall : ∀ k, k ∈ ps) {Z : ℕ} + (es : Fin (t) → BurstRAM.Word Z) (ticks : ℕ) (hticks : 2^(6*H.envelope ps+23)*(Z+1)^4 ≤ ticks) : + let E := MatrixCallbacks.program ps frob label + let raw := H.binary ps ++ runtime es + (UniversalMachine.paths E ticks (UniversalMachine.initial E raw) : ZMod p.val) = + (M.withCanonicalPresentation (D)).functional (∏ j, M.labels j^(es j).val) ∧ + ∀ time (bits : Fin time → Bool) (i : Fin (time+1)), StateFits + (2240*(Fintype.card ports+1)*(H.envelope ps+Z+1)^4) (EvaluatorTail.history E time (UniversalMachine.initial E raw) bits i) := by + have h := H.resources_and_value ps hps hall es ticks hticks + exact ⟨h.2.1, h.2.2.2⟩ + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorEvaluatorWidths.lean b/lean/OAI/Computability/VPVNP/CompressorEvaluatorWidths.lean new file mode 100644 index 0000000000..e1576613aa --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorEvaluatorWidths.lean @@ -0,0 +1,96 @@ +import OAI.Computability.VPVNP.CompressorEvaluatorAdvice +import OAI.Computability.VPVNP.CompressorLabelReadback +import OAI.Computability.VPVNP.EvaluatorCanonicalLiteral + +/-! +# Uniform field widths and the canonical compressor presentation + +The physical slice-field representation, including the Frobenius divisor and +Fermat-inversion workspace, uses a width bounded before choosing the advised +prime or the exponent array. The indexed matrices come from the same joint +grammar and compressor equations used by the algebraic descent. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open LabelEvaluator EvaluatorAdviceSerialization SliceArithmetic MvPolynomial +open JointLabelSystem RadicalCertificate.MonomialIndex + +local instance fieldWidthPrime (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩ +/-- Finite enumeration of the slice ground field used when bounding its physical +representation. -/ +noncomputable local instance fieldWidthFintype (p : Nat.Primes) (t d : ℕ) : Fintype (Ground p t d) := Fintype.ofFinite _ +/-- Decidable equality of elements of the slice ground field used in the width calculation. -/ +noncomputable local instance fieldWidthDecidableEq (p : Nat.Primes) (t d : ℕ) : DecidableEq (Ground p t d) := Classical.decEq _ +/-- Algebra structure induced on the ambient field by the slice embedding for the given column +bound. -/ +noncomputable local instance fieldWidthAmbientAlgebra (p : Nat.Primes) (t d : ℕ) : Algebra (Ground p t d) (Ambient p) := + (SliceField.embed p.val (columnCountBound t d) (Ambient p)).toRingHom.toAlgebra + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Width for field limbs and their Fermat-inversion counters. -/ +noncomputable def fieldWordBound (q c n : ℕ) := + 2*(1+Nat.clog 2 (columnCountBound (B.compressorLabelCount c n) (B.compressorDegree n))+ + B.compressorHeaderWidth q c n)+1 + +theorem fieldWordBound_polynomial (q c : ℕ) : PolynomiallyBounded (B.fieldWordBound q c) := by + have hc := columnCountBound_clog (B.compressorLabelCount_polynomial c) B.compressorDegree_polynomial.clog + have hh := B.compressorHeaderWidth_polynomial q c + exact (((PolynomiallyBounded.const 2).mul (((PolynomiallyBounded.const 1).add hc).add hh)).add (.const 1)) + +/-- Choose the actual bit array for the field-cardinality divisor with one +extra bit so a cardinality which is a power of two is encoded literally. -/ +noncomputable def cardinalBits (p : Nat.Primes) (t d : ℕ) : List Bool := + let N := Fintype.card (Ground p t d) + BurstRAM.wordBits (⟨N, (Nat.le_pow_clog (by decide : 1 < 2) N).trans_lt + (Nat.pow_lt_pow_right (by decide) (Nat.lt_succ_self _))⟩ : BurstRAM.Word (Nat.clog 2 N+1)) + +@[simp] theorem value_cardinalBits (p : Nat.Primes) (t d : ℕ) : + TapeWord.value (cardinalBits p t d) = Fintype.card (Ground p t d) := TapeWord.value_wordBits _ + +@[simp] theorem length_cardinalBits (p : Nat.Primes) (t d : ℕ) : + (cardinalBits p t d).length = Nat.clog 2 (Nat.card (Ground p t d))+1 := by + rw [Nat.card_eq_fintype_card]; exact BurstRAM.length_wordBits _ + +/-- Every allowed characteristic uses the same length bounds for the input +divisor, extension degree and required field working width. -/ +theorem field_parameters_le (q c n : ℕ) (p : Nat.Primes) (hp : q ≠ 0 → p.val = q) + (hz : q = 0 → p.val ≤ 2 ^ B.compressorPrimeBits c n) : + let t := B.compressorLabelCount c n + let d := B.compressorDegree n + let e := degree p.val t d + (cardinalBits p t d).length ≤ B.fieldWordBound q c n ∧ e ≤ B.fieldWordBound q c n ∧ + max (Word.workingWidth p.val) (e*Nat.clog 2 p.val+1) ≤ B.fieldWordBound q c n := by + intro t d e + have hprime := (B.prime_fits_compressorHeader p hp hz).le + have hlog := Nat.clog_le_of_le_pow hprime + have hcard := ground_card_clog_le p t d _ hprime + have hlimb := elementWidth_le p t d _ hprime + have he := extensionDegree_le_width p t d + change e * Nat.clog 2 p.val ≤ _ at hlimb + change e ≤ e*Nat.clog 2 p.val at he + rw [length_cardinalBits] + unfold fieldWordBound Word.workingWidth + dsimp only [t,d] at hcard hlimb ⊢ + exact ⟨by omega, by omega, max_le (by omega) (by omega)⟩ + +/-- The canonical monomial listing for the actual two-block compressor model. +Its integer reader addresses word equations first, followed by the two fixed +templates' equations. -/ +noncomputable def compressorCanonical {p : Nat.Primes} {n : ℕ} (hn : 2 ≤ n) (c : ℕ) + (M : Model p (B.compressorDegree n) (B.compressorEquations hn c)) : + (M.queryData (B.compressorCoeff hn c)).Canonical (E := Ambient p) + (sliceIdeal p (B.compressorDegree n) (B.compressorEquations hn c) M.pins M.values) := + M.canonicalPresentation (FixedRows.rowIndex B.EquationIndex n) (B.compressorCoeff hn c) + (le_max_left ..) (B.compressorEquation_degree hn c) (B.compressorCoeff_eq hn c) + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorExecutionCalendar.lean b/lean/OAI/Computability/VPVNP/CompressorExecutionCalendar.lean new file mode 100644 index 0000000000..aa7943c2e1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorExecutionCalendar.lean @@ -0,0 +1,137 @@ +import OAI.Computability.VPVNP.CompressorExecutionLevels + +/-! # The block calendar of the actual mathematical compression execution + +The initial cursor network undergoes shrinking at indices zero through +the last shrinking index, followed by one refresh, on every completed block. +Dependent bind and the intermediate degree casts preserve the chronological +order. The schedule also identifies the active pass before choosing a term, +which matters when that selector has no admitted term. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ExecutionCalendar +open Compression +open private bindOrigins ProcedureOrigins idOrigins ProcedureOrigins.seq ProcedureOrigins.reindex + shrinkOrigins refreshOrigins prefixOrigins blockOrigins repeatOrigins from OAI.Computability.VPVNP.CompressorExecutionLevels + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + +/-- Calendar label for an indexed shrinking pass or the subsequent degree refresh. -/ +inductive Phase where + | shrink (index : ℕ) + | refresh + deriving DecidableEq + +/-- Read the calendar label from the origin of a concrete state pass. -/ +def kind {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} : PassOrigin B f hf p → Phase + | .shrink i _ _ => .shrink i.val + | .refresh _ => .refresh + +/-- Follow the prescribed schedule on every choice, including the next +row's phase on branches for which no later full path exists. -/ +def Follows {a g b n : ℕ} {X : State a g} : + (E : StateExecution R b n X) → PassOrigins B f hf E → List Phase → Prop + | .done _, _, phases => phases = [] + | .more _ _, _, [] => False + | .more _ tail, origin, s::ss => kind origin.1 = s ∧ ∀ i, Follows (tail i) (origin.2 i) ss + +private theorem bind {a g b n b' n' : ℕ} {X : State a g} (E : StateExecution R b n X) + (tail : (z : E.Choices) → StateExecution R b' n' (E.finalState z)) + (o : PassOrigins B f hf E) (ot : ∀ z, PassOrigins B f hf (tail z)) + (ss ts : List Phase) (first : Follows E o ss) (rest : ∀ z, Follows (tail z) (ot z) ts) : + Follows (E.bind tail) (bindOrigins B f hf E tail o ot) (ss++ts) := by + induction E generalizing ss with + | done => + change ss = [] at first + subst ss + exact rest () + | more p next ih => + cases ss with + | nil => exact first.elim + | cons s ss => exact ⟨first.1,fun i => ih i _ (o.2 i) _ ss (first.2 i) (fun z => rest ⟨i,z⟩)⟩ + +variable {a b l d : ℕ} {μ : ℝ} + +private abbrev ProcedureFollows {P : Procedure R a b l d μ} + (o : ProcedureOrigins B f hf P) (ss : List Phase) : Prop := + ∀ g n h X, Follows (P.run g n h X) (o g n h X) ss + +private theorem seq {c l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} {Q : Procedure R b c l' d' ν} + {p : ProcedureOrigins B f hf P} {q : ProcedureOrigins B f hf Q} {ss ts : List Phase} + (first : ProcedureFollows p ss) (next : ProcedureFollows q ts) : + ProcedureFollows (ProcedureOrigins.seq B f hf p q) (ss++ts) := by + intro g n h X + exact bind _ _ _ _ _ _ (first _ _ _ X) (fun z => next _ _ _ _) + +private theorem reindex {a' b' l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} {o : ProcedureOrigins B f hf P} + {ha : a = a'} {hb : b = b'} {hl : l = l'} {hd : d = d'} {hμ : μ = ν} + {ss : List Phase} (h : ProcedureFollows o ss) : + ProcedureFollows (ProcedureOrigins.reindex B f hf o (ha := ha) (hb := hb) (hl := hl) (hd := hd) (hμ := hμ)) ss := by + subst a' b' l' d' ν + exact h + +private theorem id (a : ℕ) : ProcedureFollows (idOrigins B f hf a) [] := by + intro g n h X + have hn : n = g := h.trans (Nat.zero_add g) + subst g + rfl + +private theorem shrinking (i : Fin S.steps) : ProcedureFollows (shrinkOrigins B f hf i) [.shrink i.val] := by + intro g n h X + subst n + exact ⟨rfl,fun _ => rfl⟩ + +private theorem refreshing : ProcedureFollows (refreshOrigins B f hf) [.refresh] := by + intro g n h X + subst n + exact ⟨rfl,fun _ => rfl⟩ + +private theorem prefix_order (j : ℕ) (hj : j ≤ S.steps) : + ProcedureFollows (prefixOrigins B f hf j hj) ((List.range j).map Phase.shrink) := by + induction j with + | zero => + simp only [prefixOrigins,BlockSchedule.shrinkPrefix,List.range_zero,List.map_nil] + exact reindex (id _) + | succ j ih => + simp only [prefixOrigins,BlockSchedule.shrinkPrefix,List.range_succ,List.map_append,List.map_singleton] + exact reindex (seq (ih (Nat.le_of_succ_le hj)) (reindex (shrinking ⟨j,hj⟩))) + +/-- Chronological pass labels of one compressor block, with each shrink in order followed by +refresh. -/ +def oneBlock (steps : ℕ) := (List.range steps).map Phase.shrink ++ [.refresh] + +private theorem block : ProcedureFollows (blockOrigins B f hf) (oneBlock S.steps) := by + unfold blockOrigins oneBlock + exact reindex (seq (reindex (prefix_order S.steps le_rfl)) refreshing) + +/-- Calendar obtained by concatenating the pass lists of the requested number of complete +blocks. -/ +def blocks (steps t : ℕ) := (List.replicate t (oneBlock steps)).flatten + +private theorem repeats (g T n : ℕ) (h : n = T * S.laneBits + g) (X : State (S.degreeExponent 0) n) : + Follows ((B.procedure f hf).repeatExecution g T n h X) (repeatOrigins B f hf g T n h X) (blocks S.steps T) := by + induction T generalizing n with + | zero => + have hn : n = g := by simpa using h + subst g + rfl + | succ t ih => + let E := (B.procedure f hf).run (t*S.laneBits+g) n (by rw [h,Nat.succ_mul]; omega) X + exact bind E _ _ _ (oneBlock S.steps) (blocks S.steps t) (block _ _ _ X) (fun z => ih _ rfl (E.finalState z)) + +/-- The selected compressor's mathematical tree follows precisely the +finite block program's repeating shrinking and refresh schedule. -/ +theorem execute_follows (T : ℕ) {n : ℕ} (h : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) : + Follows (B.execute f hf T h X) (executeOrigins B f hf T h X) (blocks S.steps T) := + repeats _ _ _ _ _ + +end CompressorRecords.ExecutionCalendar + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorExecutionLevels.lean b/lean/OAI/Computability/VPVNP/CompressorExecutionLevels.lean new file mode 100644 index 0000000000..5f46c3c132 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorExecutionLevels.lean @@ -0,0 +1,189 @@ +import OAI.Computability.VPVNP.CursorDescriptorUnits + +/-! +# Selected compressor levels for the descriptor passes + +The labels in this file distinguish the scheduled six-party shrinking kernels +from the expander refresh kernel. Each label indexes the actual state pass of +the selected execution. Thus a native descriptor implementation may recover +the original input state and term index by cases on the label, including after +dependent sequencing and iteration. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords + +open Compression +open PairSimulation.LocalHistory + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) + +/-- Origin of a pass in the executable compression block. -/ +inductive PassOrigin : {a g b n : ℕ} → {X : State a g} → StatePass R X b n → Type 1 + | shrink (i : Fin S.steps) {g n : ℕ} + (h : n = packingLaneBits (S.degreeExponent i.castSucc) g) + (X : State (S.degreeExponent i.castSucc) n) : PassOrigin (B.shrinkPassAt f hf i h X) + | refresh {g : ℕ} (X : State S.portExponent (S.portExponent + g)) : + PassOrigin (Refresh.dyadicRefreshPass X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2 + (f ∘ Sum.inr) ((B.solution_iff f).mp hf).2) + +/-- Keep the origin of every elementary step, including on branch-dependent tails. -/ +def PassOrigins {a g b n : ℕ} {X : State a g} : StateExecution R b n X → Type 1 + | .done _ => PUnit + | .more p tail => PassOrigin B f hf p × ((i : p.step.Choice) → PassOrigins (tail i)) + +private def bindOrigins {a g b n b' n' : ℕ} {X : State a g} (E : StateExecution R b n X) + (next : (z : E.Choices) → StateExecution R b' n' (E.finalState z)) + (first : PassOrigins B f hf E) (rest : ∀ z, PassOrigins B f hf (next z)) : + PassOrigins B f hf (E.bind next) := by + induction E with + | done => exact rest () + | more _ _ ih => exact ⟨first.1, fun i ↦ ih i _ (first.2 i) (fun z ↦ rest ⟨i,z⟩)⟩ + +variable {a b l d : ℕ} {μ : ℝ} + +private abbrev ProcedureOrigins (P : Procedure R a b l d μ) := + ∀ g n h X, PassOrigins B f hf (P.run g n h X) + +private def idOrigins (a : ℕ) : ProcedureOrigins B f hf (Procedure.id R a) := by + intro g n h X + have hn : n = g := h.trans (Nat.zero_add g) + subst g + exact PUnit.unit + +private def passOriginsOfPass {C : ℝ} (hd : 0 < d) (hμ : 0 ≤ μ) (hC : 0 ≤ C) + (p : ∀ g (X : State a (l+g)), StatePass R X b g) + (hc : ∀ g X (i : (p g X).step.Choice), X.positions = d * ((p g X).next i).positions) + (he : ∀ g X (i : (p g X).step.Choice), + ((p g X).next i).energy ≤ μ * X.energy + C * (X.positions : ℝ)^2) + (o : ∀ g X, PassOrigin B f hf (p g X)) : ProcedureOrigins B f hf (Procedure.ofPass hd hμ hC p hc he) := by + intro g n h X + subst n + exact ⟨o g X, fun _ ↦ PUnit.unit⟩ + +private def ProcedureOrigins.seq {c l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} + {Q : Procedure R b c l' d' ν} (p : ProcedureOrigins B f hf P) (q : ProcedureOrigins B f hf Q) : + ProcedureOrigins B f hf (P.seq Q) := + fun g n h X ↦ + let E := P.run (l'+g) n (h.trans (Nat.add_assoc l l' g)) X + bindOrigins B f hf E _ (p _ _ _ X) (fun z ↦ q _ _ _ (E.finalState z)) + +private def ProcedureOrigins.reindex {a' b' l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} + (o : ProcedureOrigins B f hf P) {ha : a = a'} {hb : b = b'} {hl : l = l'} {hd : d = d'} + {hμ : μ = ν} : ProcedureOrigins B f hf (P.reindex ha hb hl hd hμ) := by + subst a' b' l' d' ν + exact o + +private noncomputable def shrinkOrigins (i : Fin S.steps) : ProcedureOrigins B f hf (B.shrinkProcedure f hf i) := + passOriginsOfPass B f hf _ _ _ _ _ _ (fun g X ↦ .shrink i (packingLaneBits_add _ g) X) + +private noncomputable def refreshOrigins : ProcedureOrigins B f hf (B.refreshProcedure f hf) := by + intro g n h X + subst n + exact ⟨.refresh X, fun _ ↦ PUnit.unit⟩ + +private noncomputable def prefixOrigins (j : ℕ) (hj : j ≤ S.steps) : + ProcedureOrigins B f hf (S.shrinkPrefix (B.shrinkProcedure f hf) j hj) := + match j with + | 0 => by + rw [BlockSchedule.shrinkPrefix] + exact ProcedureOrigins.reindex B f hf (idOrigins B f hf _) + | j + 1 => by + rw [BlockSchedule.shrinkPrefix] + exact ProcedureOrigins.reindex B f hf (ProcedureOrigins.seq B f hf (prefixOrigins j (by omega)) + (ProcedureOrigins.reindex B f hf (shrinkOrigins B f hf ⟨j,hj⟩))) + +private noncomputable def blockOrigins : ProcedureOrigins B f hf (B.procedure f hf) := by + unfold BlockSchedule.Templates.procedure BlockSchedule.assembleBlock + exact ProcedureOrigins.reindex B f hf (ProcedureOrigins.seq B f hf + (ProcedureOrigins.reindex B f hf (prefixOrigins B f hf S.steps le_rfl)) (refreshOrigins B f hf)) + +private noncomputable def repeatOrigins (g : ℕ) : (T n : ℕ) → (h : n = T*S.laneBits+g) → + (X : State (S.degreeExponent 0) n) → + PassOrigins B f hf ((B.procedure f hf).repeatExecution g T n h X) + | 0, n, h, X => idOrigins B f hf _ g n (by simpa using h) X + | t+1, n, h, X => + let E := (B.procedure f hf).run (t*S.laneBits+g) n (by rw [h, Nat.succ_mul]; omega) X + bindOrigins B f hf E _ (blockOrigins B f hf _ _ _ X) (fun z ↦ repeatOrigins g t _ rfl (E.finalState z)) + +/-- Identify the actual kernel at every substep of the selected compression tree. -/ +noncomputable def executeOrigins {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) : + PassOrigins B f hf (B.execute f hf T h X) := + repeatOrigins B f hf _ T n (Nat.add_sub_of_le h).symm X + +/-- One concrete level with its input graph, selected term and selector encoding. -/ +structure SelectedLevel where + /-- Base-two exponent of the graph degree entering this selected pass. -/ + inputExponent : ℕ + /-- Number of binary lane coordinates in the input state of the selected pass. -/ + inputLanes : ℕ + /-- Base-two exponent of the graph degree produced by the selected pass. -/ + outputExponent : ℕ + /-- Number of binary lane coordinates remaining in the output state of this pass. -/ + outputLanes : ℕ + /-- Compression state on which the selected pass operates. -/ + input : State inputExponent inputLanes + /-- State transition with the specified input state and output degree and lane dimensions. -/ + pass : StatePass R input outputExponent outputLanes + /-- Witness identifying the pass as a particular scheduled shrink or refresh. -/ + origin : PassOrigin B f hf pass + /-- Local kernel choice taken by this execution of the pass. -/ + term : pass.step.Choice + /-- Boolean selector encoding of the chosen term for the native descriptor workers. -/ + selector : List Bool + +namespace SelectedLevel + +variable {B f hf} + +/-- Charge counting one unit per input position and input slot, together with the selector +bits. -/ +def units (v : SelectedLevel B f hf) : ℕ := + v.input.positions * (2 ^ v.inputExponent + 1) + v.selector.length + +end SelectedLevel + +private noncomputable def collectLevels {a g b n : ℕ} {X : State a g} : + (E : StateExecution R b n X) → (W : E.MapWitnesses f) → ExecutionReaders E W → + PassOrigins B f hf E → E.Choices → List (SelectedLevel B f hf) + | .done _, _, _, _, _ => [] + | @StateExecution.more _ _ _ _ a g b' n' X p tail, W, r, o, z => + ⟨a,g,b',n',X,p,o.1,z.1,r.1.select.encode z.1⟩ :: collectLevels (tail z.1) (W.2 z.1) (r.2 z.1) (o.2 z.1) z.2 + +private theorem collectLevels_sum_units {a g b n : ℕ} {X : State a g} + (E : StateExecution R b n X) (W : E.MapWitnesses f) (r : ExecutionReaders E W) + (o : PassOrigins B f hf E) (z : E.Choices) : + ((collectLevels B f hf E W r o z).map SelectedLevel.units).sum = scanUnits E W r z := by + induction E with + | done => rfl + | more p tail ih => + simp only [collectLevels, List.map_cons, List.sum_cons, scanUnits, SelectedLevel.units, + ih z.1 (W.2 z.1) (r.2 z.1) (o.2 z.1) z.2] + +/-- Chronological list of the actual passes, input states, and selected terms along the given +block execution. -/ +noncomputable def executeLevels {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) + (z : (B.execute f hf T h X).Choices) : List (SelectedLevel B f hf) := + collectLevels B f hf (B.execute f hf T h X) _ + (repeatReaders (blockReaders B f hf) _ T n (Nat.add_sub_of_le h).symm X) (executeOrigins B f hf T h X) z + +theorem executeLevels_sum_units {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) + (X : State (S.degreeExponent 0) n) (z : (B.execute f hf T h X).Choices) : + ((executeLevels B f hf T h X z).map SelectedLevel.units).sum = + CursorNetwork.descriptorUnits B f hf T h X z := + collectLevels_sum_units B f hf _ _ _ _ _ + +end CompressorRecords + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorExecutionTrace.lean b/lean/OAI/Computability/VPVNP/CompressorExecutionTrace.lean new file mode 100644 index 0000000000..69d1058a66 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorExecutionTrace.lean @@ -0,0 +1,95 @@ +import OAI.Computability.VPVNP.CompressorOnlineBranchCut +import OAI.Computability.VPVNP.CompressionState + +/-! # Complete descriptor paths indexed by the mathematical compression tree + +An internal node has the native cut for its single compression pass. Its +children begin in the memory and control state returned for the selected term. +At a leaf the last deterministic native segment halts. Recursion gives an +exact bijection with complete accepting streams of the one fixed table, +retaining its actual reports, final memory and optional resource predicate. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BranchSegments +open BurstRAM Compression + +variable {w cap : ℕ} {Q : Type*} {P : BurstRAM.Program w Q} +variable {st : Option (Word w)} {m : Memory w} +variable {R : Type*} [CommSemiring R] {a g b n : ℕ} {X : State a g} + +/-- One local pass on the native machine and recursive executions on its +actual outputs. The only terminal case is a forced native halting segment. -/ +inductive ExecutionTrace (P : BurstRAM.Program w Q) (cap : ℕ) : + {a g b n : ℕ} → {X : State a g} → StateExecution R b n X → Option (Word w) → Memory w → Type _ where + | done {b n : ℕ} {X : State b n} {st m} (s : Segment P cap st m) (calls : ℕ) + (quiet : s.bits = List.replicate calls []) (halt : s.state = none) : ExecutionTrace P cap (.done X) st m + | more {a g a' g' b n : ℕ} {X : State a g} {p : StatePass R X a' g'} + {tail : ∀ i, StateExecution R b n (p.next i)} {st m} + (pass : Cut P cap st m p.step.Choice) + (next : ∀ i, ExecutionTrace P cap (tail i) (pass.part i).state (pass.part i).memory) : + ExecutionTrace P cap (.more p tail) st m + +namespace ExecutionTrace + +variable {E : StateExecution R b n X} + +/-- The native prefix is the concatenation of the chosen passes and the +terminating segment on that very branch. -/ +def cut {a g b n : ℕ} {X : State a g} {E : StateExecution R b n X} {st m} (t : ExecutionTrace P cap E st m) : Cut P cap st m E.Choices := + match t with + | .done s calls quiet _ => Cut.deterministic s calls quiet + | .more pass next => pass.bind fun i => cut (next i) + +theorem stopped (t : ExecutionTrace P cap E st m) (z : E.Choices) : (t.cut.part z).state = none := by + induction t with + | done s calls quiet halt => exact halt + | more pass next ih => exact ((pass.part z.1).append_state ((next z.1).cut.part z.2)).trans (ih z.1 z.2) + +private theorem stopped_empty {bits rs} (run : runSegment P cap none m bits = some rs) : bits = [] ∧ rs = [] := by + cases bits with + | nil => exact ⟨rfl,(Option.some.inj run).symm⟩ + | cons b bs => contradiction + +/-- Complete accepted paths with a report predicate are exactly the terms +whose actual descriptor execution meets that predicate. -/ +noncomputable def acceptedEquiv (t : ExecutionTrace P cap E st m) (allow : List (Report w) → Prop) : + {z : E.Choices // allow (t.cut.part z).logs} ≃ LiveProgram.PathsFrom P cap st m allow := by + classical + let emit (z : {z : E.Choices // allow (t.cut.part z).logs}) : LiveProgram.PathsFrom P cap st m allow := + ⟨(t.cut.part z.val).bits,_,(t.cut.part z.val).run,t.stopped z.val,z.property⟩ + apply Equiv.ofBijective emit + constructor + · intro a b h + apply Subtype.ext + apply t.cut.separate a.val b.val [] [] + simpa only [List.append_nil] using congrArg Subtype.val h + · rintro ⟨bs,rs,run,halt,good⟩ + obtain ⟨i,rest,more,hb,hl,hr,_⟩ := t.cut.split run halt + rw [t.stopped i] at hr + obtain ⟨rfl,rfl⟩ := stopped_empty hr + rw [List.append_nil] at hl hb + exact ⟨⟨i,hl ▸ good⟩,Subtype.ext hb.symm⟩ + +@[simp] theorem acceptedEquiv_bits (t : ExecutionTrace P cap E st m) (allow : List (Report w) → Prop) + (z : {z : E.Choices // allow (t.cut.part z).logs}) : + ((t.acceptedEquiv allow) z).val = (t.cut.part z.val).bits := rfl + +/-- Every mathematical branch meets the allotted resource predicate. -/ +noncomputable def allEquiv (t : ExecutionTrace P cap E st m) (allow : List (Report w) → Prop) + (allowed : ∀ z, allow (t.cut.part z).logs) : E.Choices ≃ LiveProgram.PathsFrom P cap st m allow := + (Equiv.subtypeUnivEquiv allowed).symm.trans (t.acceptedEquiv allow) + +@[simp] theorem allEquiv_bits (t : ExecutionTrace P cap E st m) (allow : List (Report w) → Prop) + (allowed : ∀ z, allow (t.cut.part z).logs) (z : E.Choices) : + (t.allEquiv allow allowed z).val = (t.cut.part z).bits := rfl + +end ExecutionTrace +end CompressorRecords.BranchSegments + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorFlatRowOperands.lean b/lean/OAI/Computability/VPVNP/CompressorFlatRowOperands.lean new file mode 100644 index 0000000000..4622d45949 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorFlatRowOperands.lean @@ -0,0 +1,200 @@ +import OAI.Computability.VPVNP.PrimedStackRAMCode +import OAI.Computability.VPVNP.LiveStageLinkPaths +import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner + +/-! +# Loading local worker operands in a whole-level scan + +For each parameter and for the local cursor, the prologue computes +`base + globalRow * stride`, optionally reads the word there, and adds a +fixed offset. The source-worker registers remain zero until its body starts. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.FlatRows + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +open private update_left update_right from OAI.Computability.VPVNP.CompressorRecordFrame +open private probe_append bits_append from OAI.Computability.VPVNP.LiveStageLinkPaths + +variable {w r k : ℕ} + +/-- Register count for a flattened row worker, including the original registers, operand cache, +and three temporaries. -/ +abbrev Registers (r k : ℕ) := r + ((k+1)+3) +/-- Number of public words needed for three address fields per local operand, including the +local cursor. -/ +abbrev Params (k : ℕ) := (k+1)*3 +/-- Public operand bank indexed by the address-field positions of a flattened row worker. -/ +abbrev Public (k w : ℕ) := Fin (Params k) → Word w + +/-- Flatten an operand number and its base, stride, or offset field into one public-word index. -/ +def field (j : Fin (k+1)) (d : Fin 3) := finProdFinEquiv (j,d) + +/-- Embed an original worker register into the leading register bank of the flattened worker. -/ +def ordinary (k : ℕ) (j : Fin r) : Fin (Registers r k) := j.castAdd _ +/-- Register holding one cached local operand or the local cursor after the prologue. -/ +def slot (r : ℕ) (j : Fin (k+1)) : Fin (Registers r k) := (j.castAdd 3).natAdd r +/-- Select one of the three temporary registers following the operand cache. -/ +def scratch (r k : ℕ) (j : Fin 3) : Fin (Registers r k) := (j.natAdd (k+1)).natAdd r + +/-- Row-dependent address computed from an operand's public base and stride. -/ +def addr (p : Public k w) (s : Word w) (j : Fin (k+1)) := p (field j 0)+s*p (field j 1) +/-- Operand supplied to the body after optionally loading from its row address and adding the +public offset. -/ +def value (load : Fin (k+1) → Bool) (p : Public k w) (s : Word w) (m : Memory w) (j : Fin (k+1)) := + (if load j then m (addr p s j).val else addr p s j)+p (field j 2) + +/-- One affine parameter takes seven lines, with the fifth line a single +read for indirect operands and a register copy for direct operands. -/ +def operand (r : ℕ) (load : Fin (k+1) → Bool) (j : Fin (k+1)) : List (Op (Registers r k) (Params k)) := + let tmp := scratch r k 1 + let dst := slot r j + [.publicWord tmp (field j 1), .binary .mul dst (scratch r k 0) tmp, + .publicWord tmp (field j 0), .binary .add dst tmp dst, + if load j then .read dst dst else .copy dst dst, + .publicWord tmp (field j 2), .binary .add dst dst tmp] + +/-- Seven prologue events for one operand, including an external read precisely when its load +flag is set. -/ +def operandEvents (load : Fin (k+1) → Bool) (p : Public k w) (s : Word w) (m : Memory w) (j : Fin (k+1)) : + List (Event w) := + [.tick,.tick,.tick,.tick,if load j then .read (addr p s j) (m (addr p s j).val) else .tick,.tick,.tick] + +/-- Combine the body registers, cached operands, and three temporaries into a single register +bank. -/ +def registers (core : Fin r → Word w) (cached : Fin (k+1) → Word w) (temps : Fin 3 → Word w) : + Fin (Registers r k) → Word w := Fin.append core (Fin.append cached temps) + +@[simp] theorem registers_ordinary (core : Fin r → Word w) (cache : Fin (k+1) → Word w) (temps : Fin 3 → Word w) + (j : Fin r) : registers core cache temps (ordinary k j) = core j := Fin.append_left .. +@[simp] theorem registers_slot (core : Fin r → Word w) (cache : Fin (k+1) → Word w) (temps : Fin 3 → Word w) + (j : Fin (k+1)) : registers core cache temps (slot r j) = cache j := by + simp [registers,slot] +@[simp] theorem registers_scratch (core : Fin r → Word w) (cache : Fin (k+1) → Word w) (temps : Fin 3 → Word w) + (j : Fin 3) : registers core cache temps (scratch r k j) = temps j := by simp [registers,scratch] + +theorem update_ordinary (core : Fin r → Word w) (cache : Fin (k+1) → Word w) (temps : Fin 3 → Word w) + (j : Fin r) (v : Word w) : + Function.update (registers core cache temps) (ordinary k j) v = registers (Function.update core j v) cache temps := by + exact update_left .. + +theorem update_slot (core : Fin r → Word w) (cache : Fin (k+1) → Word w) (temps : Fin 3 → Word w) + (j : Fin (k+1)) (v : Word w) : + Function.update (registers core cache temps) (slot r j) v = registers core (Function.update cache j v) temps := by + simp only [registers,slot,update_right,update_left] + +theorem update_scratch (core : Fin r → Word w) (cache : Fin (k+1) → Word w) (temps : Fin 3 → Word w) + (j : Fin 3) (v : Word w) : + Function.update (registers core cache temps) (scratch r k j) v = registers core cache (Function.update temps j v) := by + simp only [registers,scratch,update_right] + +variable (load : Fin (k+1) → Bool) (p : Public k w) (s : Word w) (m : Memory w) + +private theorem operand_trace (j : Fin (k+1)) (core : Fin r → Word w) (cache : Fin (k+1) → Word w) + (temps : Fin 3 → Word w) (hs : temps 0 = s) : + trace p s (operand r load j) (registers core cache temps) m = + some (operandEvents load p s m j, + registers core (Function.update cache j (value load p s m j)) + (Function.update temps 1 (p (field j 2))),m) := by + cases hl : load j <;> + simp (config := {decide := true}) [operand,operandEvents,value,hl,trace,Op.effect,BinaryOp.eval,addr, + update_slot,update_scratch,Function.update_idem,hs] + +private def loadList (is : List (Fin (k+1))) (cache : Fin (k+1) → Word w) := + fun j => if j ∈ is then value load p s m j else cache j + +private theorem trace_list (is : List (Fin (k+1))) (core : Fin r → Word w) (cache : Fin (k+1) → Word w) + (temps : Fin 3 → Word w) (hs : temps 0 = s) : + ∃ tmp, trace p s (is.flatMap (operand r load)) (registers core cache temps) m = + some (is.flatMap (operandEvents load p s m), + registers core (loadList load p s m is cache) (Function.update temps 1 tmp),m) := by + induction is generalizing cache temps with + | nil => + have h : loadList load p s m [] cache = cache := by funext j; simp [loadList] + exact ⟨temps 1,by simp [trace,h]⟩ + | cons j is ih => + let v := value load p s m + let temps' := Function.update temps 1 (p (field j 2)) + obtain ⟨tmp,hr⟩ := ih (Function.update cache j (v j)) temps' (by simpa [temps'] using hs) + have h : loadList load p s m is (Function.update cache j (v j)) = + loadList load p s m (j::is) cache := by + funext t + by_cases ht : t ∈ is <;> by_cases he : t = j <;> simp [loadList,Function.update,ht,he,v] + refine ⟨tmp,?_⟩ + simp only [List.flatMap_cons,trace_append,operand_trace load p s m j core cache temps hs,Option.bind_some] + change (trace p s (is.flatMap (operand r load)) (registers core (Function.update cache j (v j)) temps') m).map _ = _ + rw [hr]; simp [h,temps',Function.update_idem] + +/-- Instructions that cache all operands for the current global row and calculate the successor +row cursor. -/ +def prologue (r : ℕ) (load : Fin (k+1) → Bool) : List (Op (Registers r k) (Params k)) := + [.stateWord (scratch r k 0)] ++ (List.finRange (k+1)).flatMap (operand r load) ++ + [.constant (scratch r k 1) 1,.binary .add (scratch r k 2) (scratch r k 0) (scratch r k 1)] + +/-- Complete prologue event list for a global row, including the operand reads and cursor +arithmetic. -/ +def events := [.tick] ++ (List.finRange (k+1)).flatMap (operandEvents load p s m) ++ [.tick,.tick] + +theorem prologue_trace : + trace p s (prologue r load) (fun _ => 0) m = + some (events load p s m,registers (fun _ : Fin r => 0) (value load p s m) ![s,1,s+1],m) := by + let zero : Fin 3 → Word w := fun _ => 0 + let z : Fin (k+1) → Word w := fun _ => 0 + let core : Fin r → Word w := fun _ => 0 + let tmp := Function.update zero 0 s + have hz : (fun _ => (0 : Word w)) = registers core z zero := by + funext i; cases i using Fin.addCases with + | left j => simp [registers,core] + | right j => cases j using Fin.addCases <;> simp [registers,z,zero] + obtain ⟨v,hr⟩ := trace_list load p s m (List.finRange _) core z tmp (by simp [tmp]) + have full : loadList load p s m (List.finRange (k+1)) z = value load p s m := by funext j; simp [loadList] + rw [full] at hr + have hlast : Function.update (Function.update tmp 1 (1 : Word w)) 2 (s+1) = ![s,1,s+1] := by + funext j; fin_cases j <;> simp [tmp,Function.update] + rw [hz] + simp only [prologue,trace_append,trace,Op.effect,update_scratch,Option.bind_some,pure,bind] + change ((trace p s ((List.finRange (k+1)).flatMap (operand r load)) (registers core z tmp) m).map _).bind _ = _ + rw [hr] + simp only [Option.map_some,Option.bind_some,update_scratch,registers_scratch,BinaryOp.eval,Function.update_idem] + simp [events,core,tmp,Function.update] + exact congrArg (registers core (value load p s m)) hlast + +theorem prologue_length : (prologue r load).length = 3+7*(k+1) := by + have h (is : List (Fin (k+1))) : (is.flatMap (operand r load)).length = 7*is.length := by + induction is with + | nil => simp + | cons j is ih => simp [operand,ih,Nat.mul_succ] + simp [prologue,h]; omega + +theorem events_cost : + (events load p s m).length = 3+7*(k+1) ∧ + countProbes (events load p s m) ≤ k+1 ∧ after m (events load p s m) = m ∧ + choiceBits (events load p s m) = [] := by + have h (is : List (Fin (k+1))) : + (is.flatMap (operandEvents load p s m)).length = 7*is.length ∧ + countProbes (is.flatMap (operandEvents load p s m)) ≤ is.length ∧ + after m (is.flatMap (operandEvents load p s m)) = m ∧ + choiceBits (is.flatMap (operandEvents load p s m)) = [] := by + induction is with + | nil => exact ⟨rfl,le_rfl,rfl,rfl⟩ + | cons j js ih => + obtain ⟨hlen,hprobe,hmem,hbits⟩ := ih + change (List.flatMap (operandEvents load p s m) js).foldl BurstRAM.update m = m at hmem + cases hj : load j <;> + simp [operandEvents,hj,countProbes,choiceBits,after,BurstRAM.update,Nat.mul_succ,hlen,hbits,hmem] <;> omega + obtain ⟨hl,hp,hm,hb⟩ := h (List.finRange (k+1)) + simp only [List.length_finRange] at hl hp + simp only [events,List.length_append,List.length_cons,List.length_nil,probe_append,bits_append, + countProbes,choiceBits,after,List.foldl_append,List.foldl_cons,List.foldl_nil,BurstRAM.update,hl,hb] at * + exact ⟨by omega,by omega,hm,rfl⟩ + +end CompressorRecords.FlatRows + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorFlatRowScan.lean b/lean/OAI/Computability/VPVNP/CompressorFlatRowScan.lean new file mode 100644 index 0000000000..c6bf12a6c1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorFlatRowScan.lean @@ -0,0 +1,97 @@ +import OAI.Computability.VPVNP.CompressorFlatRowWorker +import OAI.Computability.VPVNP.CompressorSourceWalk + +/-! +# Visiting every bundle in one online calendar stage + +The persistent cursor of a calendar visit is the bundle ordinal. Its report +updates that bundle's bank and advances the cursor. A finite stage list may +therefore transpose the fixed per-bundle operations while retaining the +input columns and every previously completed bank. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.FlatRows + +open BurstRAM + +variable {w R : ℕ} {C J : Type*} + +theorem scan (P : BurstRAM.Program w C) (fuel : ℕ) (R : ℕ) + (shared : Memory w → Prop) (bank : Fin R → ℕ → Prop) + (apart : ∀ {i j : Fin R}, i ≠ j → ∀ x, bank i x → ¬ bank j x) + (before done : Fin R → Memory w → Prop) + (keepBefore : ∀ i m out, before i m → (∀ x, bank i x → out x = m x) → before i out) + (keepDone : ∀ i m out, done i m → (∀ x, bank i x → out x = m x) → done i out) + (one : ∀ i : Fin R, ∀ m, shared m → before i m → + ∃ r, execute P fuel (P.start (Fin.ofNat _ i.val)) m [] = some r ∧ + r.result = some (Fin.ofNat _ (i.val+1)) ∧ shared (after m r.events) ∧ done i (after m r.events) ∧ + ∀ x, ¬ bank i x → after m r.events x = m x) + (m : Memory w) (hshared : shared m) (ready : ∀ i, before i m) : + ∃ rs, runSegment P fuel (some 0) m (List.replicate R []) = some rs ∧ + endState (some 0) rs = some (Fin.ofNat _ R) ∧ rs.length = R ∧ + shared (after m (eventLog rs)) ∧ (∀ i, done i (after m (eventLog rs))) ∧ + ∀ x, (∀ i, ¬ bank i x) → after m (eventLog rs) x = m x := by + have sweep (k len : ℕ) (room : k+len ≤ R) (mem : Memory w) + (hs : shared mem) (rows : ∀ i : Fin R, (if i.val < k then done i mem else before i mem)) : + ∃ rs, runSegment P fuel (some (Fin.ofNat _ k)) mem (List.replicate len []) = some rs ∧ + endState (some (Fin.ofNat _ k)) rs = some (Fin.ofNat _ (k+len)) ∧ rs.length = len ∧ + shared (after mem (eventLog rs)) ∧ + (∀ i : Fin R, if i.val < k+len then done i (after mem (eventLog rs)) else before i (after mem (eventLog rs))) ∧ + ∀ x, (∀ i, ¬ bank i x) → after mem (eventLog rs) x = mem x := by + induction len generalizing k mem with + | zero => exact ⟨[],rfl,rfl,rfl,hs,rows,fun _ _ => rfl⟩ + | succ len ih => + let i : Fin R := ⟨k,by omega⟩ + obtain ⟨r,exec,ret,shared',row,frame⟩ := one i mem hs (by simpa [i] using rows i) + let post := after mem r.events + have status (j : Fin R) : if j.val < k+1 then done j post else before j post := by + by_cases eq : j = i + · subst j; simpa [i,post] using row + · have hv : j.val ≠ k := fun e => eq (Fin.ext e) + have preserve (x) (hx : bank j x) : post x = mem x := frame x (apart eq x hx) + by_cases lt : j.val < k + · rw [ite_eq_left (by omega)] + exact keepDone _ _ _ (by simpa only [ite_eq_left lt] using rows j) preserve + · rw [ite_eq_right (by omega)] + exact keepBefore _ _ _ (by simpa only [ite_eq_right lt] using rows j) preserve + obtain ⟨tail,run,end',size,hs',rows',outside⟩ := ih (k+1) (by omega) post shared' status + have replay : after mem (eventLog (r::tail)) = after post (eventLog tail) := by + change List.foldl update mem (r.events ++ eventLog tail) = _ + rw [List.foldl_append]; rfl + refine ⟨r::tail,?_,?_,by simp [size],replay ▸ hs',?_,?_⟩ + · rw [List.replicate_succ,runSegment,exec] + simp only [ret,i,run,Option.map_some,post] at * + · change endState r.result tail = _ + rw [ret,end',show k+1+len = k+(len+1) by omega] + · intro j; rw [replay,show k+(len+1) = k+1+len by omega]; exact rows' j + · intro x hx; exact (congrFun replay x).trans ((outside x hx).trans (frame x (hx i))) + obtain ⟨rs,run,hend,hlen,hs,rows,frame⟩ := sweep 0 R (by omega) m hshared (by simpa using ready) + exact ⟨rs,run,by simpa using hend,hlen,hs,fun i => by simpa using rows i,frame⟩ + +/-- Compose the calendar visits in their actual list order, retaining the +post-memory for all stages. -/ +theorem walk {source : J → Memory w → List (Report w) → Prop} + (js : List J) (inv : ℕ → Memory w → Prop) (start : ℕ) (m : Memory w) (hm : inv start m) + (step : ∀ i : Fin js.length, ∀ m, inv (start+i.val) m → + ∃ rs, source js[i.val] m rs ∧ inv (start+i.val+1) (after m (eventLog rs))) : + ∃ rs, SourceWalk source js m rs ∧ inv (start+js.length) (after m (eventLog rs)) := by + induction js generalizing m start with + | nil => exact ⟨[],.done _,hm⟩ + | cons j js ih => + obtain ⟨head,hh,hn⟩ := step 0 m (by simpa using hm) + obtain ⟨tail,ht,hf⟩ := ih (start+1) _ hn (fun i m h => by + simpa only [List.getElem_cons_succ,Fin.val_succ,show start+(i.val+1) = start+1+i.val by omega] using + step i.succ m (by simpa only [Fin.val_succ,show start+(i.val+1) = start+1+i.val by omega] using h)) + refine ⟨head++tail,.next hh ht,?_⟩ + rw [SourceWalk.after_append,List.length_cons,show start+(js.length+1) = start+1+js.length by omega] + exact hf + +end CompressorRecords.FlatRows + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorFlatRowWorker.lean b/lean/OAI/Computability/VPVNP/CompressorFlatRowWorker.lean new file mode 100644 index 0000000000..5414006c22 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorFlatRowWorker.lean @@ -0,0 +1,183 @@ +import OAI.Computability.VPVNP.CompressorFlatRowOperands + +/-! +# A fixed whole-level worker for repeated local descriptor calls + +The original worker runs with the computed public operands and local cursor. +A successful return advances the global row cursor, while choice streams, +external effects and rejection agree with the original body. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.FlatRows + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open private contains_indexed from OAI.Computability.VPVNP.PrimedStackRAMCode + +variable {w p r k : ℕ} (T : Template p r k) (load : Fin (k+1) → Bool) + +/-- Number of program counters for the prologue, original body, and final return instruction. -/ +abbrev PCs (p r : ℕ) (load : Fin (k+1) → Bool) := (prologue r load).length+p+1 + +/-- Relocate an original body program counter past the operand-loading prologue. -/ +def bodyPC (i : Fin p) : Fin (PCs p r load) := + ⟨(prologue r load).length+i.val,by unfold PCs; have := i.isLt; omega⟩ + +/-- Map a prologue counter into the flattened program, transferring to the original entry when +the prologue finishes. -/ +def prePC (j : Fin ((prologue r load).length+1)) : Fin (PCs p r load) := + if h : j.val < (prologue r load).length then ⟨j.val,by unfold PCs; omega⟩ else bodyPC (r := r) load T.entry + +private def badPC : Fin (PCs p r load) := Fin.last ((prologue r load).length+p) + +private def liftOp : Instr w p r k → Instr w (PCs p r load) (Registers r k) (Params k) + | .constant a x t => .constant (ordinary k a) x (bodyPC load t) + | .publicWord a j t => .copy (ordinary k a) (slot r j.castSucc) (bodyPC load t) + | .stateWord a t => .copy (ordinary k a) (slot r (Fin.last k)) (bodyPC load t) + | .copy a b t => .copy (ordinary k a) (ordinary k b) (bodyPC load t) + | .binary op a b c t => .binary op (ordinary k a) (ordinary k b) (ordinary k c) (bodyPC load t) + | .loadPrivate a b t => .loadPrivate (ordinary k a) (ordinary k b) (bodyPC load t) + | .storePrivate a b t => .storePrivate (ordinary k a) (ordinary k b) (bodyPC load t) + | .jumpEq a b y n => .jumpEq (ordinary k a) (ordinary k b) (bodyPC load y) (bodyPC load n) + | .jumpLt a b y n => .jumpLt (ordinary k a) (ordinary k b) (bodyPC load y) (bodyPC load n) + | .choose y n => .choose (bodyPC load y) (bodyPC load n) + | .readExternal a b t => .readExternal (ordinary k a) (ordinary k b) (bodyPC load t) + | .writeExternal a b t => .writeExternal (ordinary k a) (ordinary k b) (bodyPC load t) + | .returnState _ => .returnState (scratch r k 2) + | .accept => .accept + | .reject => .reject + +/-- The whole-level template. The operand array is indexed by (local public +parameter or local cursor, base/stride/bias). -/ +def compile : Template (PCs p r load) (Registers r k) (Params k) where + literalWidth := max 2 T.literalWidth + entry := prePC T load 0 + code i := + let ops := prologue r load + if hp : i.val < ops.length then + ((ops[i.val]).emit (prePC T load ⟨i.val+1,by change i.val < (prologue r load).length at hp; omega⟩) (badPC load)).resize _ + else if hb : i.val-ops.length < p then + liftOp load ((T.code ⟨i.val-ops.length,hb⟩).resize _) + else .reject + +private theorem resize_twice {b f : ℕ} (op : Instr b p r k) (h : b ≤ f) : + (op.resize f).resize w = op.resize w := by + cases op with + | constant reg v t => + have hlt : v.val < 2^f := v.isLt.trans_le (Nat.pow_le_pow_right (by decide) h) + simp [Instr.resize,Nat.mod_eq_of_lt hlt] + | _ => rfl + +private theorem body_code (pub : Public k w) (i : Fin p) : + ((compile T load).instantiate w pub).code (bodyPC (r := r) load i) = liftOp load ((T.code i).resize w) := by + let n := (prologue r load).length + have hlt : ¬ n+i.val < n := by omega + have hb : n+i.val-n < p := by rw [Nat.add_sub_cancel_left]; exact i.isLt + change ((compile T load).code (bodyPC load i)).resize w = _ + simp only [compile,bodyPC] + change ((if hp : n+i.val < n then _ else if h : n+i.val-n < p then _ else _ : Instr (max 2 T.literalWidth) (PCs p r load) (Registers r k) (Params k))).resize w = _ + rw [dite_eq_right hlt,dite_eq_left hb] + have he : (⟨n+i.val-n,hb⟩ : Fin p) = i := Fin.ext (Nat.add_sub_cancel_left ..) + rw [he] + have h (op : Instr T.literalWidth p r k) : + (liftOp load (op.resize (max 2 T.literalWidth))).resize w = liftOp load (op.resize w) := by + have hw := resize_twice (w := w) op (le_max_right 2 T.literalWidth) + rw [← hw] + generalize op.resize (max 2 T.literalWidth) = op' + cases op' <;> rfl + exact h _ + +private theorem pre_contains (pub : Public k w) : + Contains ((compile T load).instantiate w pub) (badPC load) + (prePC T load 0) (prologue r load) (bodyPC load T.entry) := by + have last : prePC T load (Fin.last (prologue r load).length) = bodyPC load T.entry := by simp [prePC] + rw [← last] + apply contains_indexed _ _ _ (prePC T load) + intro i + have hpre : (prePC T load i.castSucc).val = i.val := by simp [prePC,i.isLt] + change ((compile T load).code (prePC T load i.castSucc)).resize w = _ + simp only [compile,hpre,dite_eq_left i.isLt] + exact resize_twice _ (le_max_left 2 T.literalWidth) + +private theorem bad_code (pub : Public k w) : + ((compile T load).instantiate w pub).code (badPC load) = .reject := by + let n := (prologue r load).length + change ((compile T load).code (badPC load)).resize w = _ + simp only [compile,badPC,Fin.val_last] + change ((if hp : n+p < n then _ else if h : n+p-n < p then _ else _ : Instr (max 2 T.literalWidth) (PCs p r load) (Registers r k) (Params k))).resize w = _ + rw [dite_eq_right (by omega),dite_eq_right (by omega)]; rfl + +private def liftConfig (global : Word w) (operands : Fin k → Word w) (c : Config w p r) : + Config w (PCs p r load) (Registers r k) := + ⟨bodyPC load c.pc,global,registers c.reg (Fin.snoc operands c.persistent) ![global,1,global+1],c.privateMem⟩ + +/-- Preserve the body's events and rejection, and replace a successful return by the next +global row cursor. -/ +def result (s : Word w) (rep : Report w) : Report w := ⟨rep.events,rep.result.map (fun _ => s+1)⟩ + +private def mapAction {C D : Type*} (s : Word w) (f : C → D) : CallAction w C → CallAction w D + | .localStep c => .localStep (f c) + | .branch g => .branch (f ∘ g) + | .read a g => .read a (f ∘ g) + | .write a v c => .write a v (f c) + | .finish v => .finish (v.map (fun _ => s+1)) + | .reject => .reject + +private theorem body_step (pub : Public k w) (s : Word w) (v : Fin k → Word w) (c : Config w p r) : + ((compile T load).instantiate w pub).program.step (liftConfig load s v c) = + mapAction s (liftConfig load s v) ((T.instantiate w v).program.step c) := by + change (((compile T load).instantiate w pub).code (bodyPC load c.pc)).run _ _ = mapAction _ _ (((T.code c.pc).resize w).run v c) + rw [body_code] + generalize (T.code c.pc).resize w = op + cases op <;> simp only [liftOp,Instr.run,liftConfig,mapAction,Config.put,Config.store, + registers_ordinary,registers_slot,registers_scratch,Fin.snoc_castSucc,Fin.snoc_last,update_ordinary,Function.comp_def] + all_goals first | rfl | (split <;> rfl) | (congr 1; funext b; cases b <;> rfl) + +private theorem body_run (pub : Public k w) (s : Word w) (v : Fin k → Word w) (f : ℕ) + (c : Config w p r) (m : Memory w) (bs : List Bool) : + execute ((compile T load).instantiate w pub).program f (liftConfig load s v c) m bs = + (execute (T.instantiate w v).program f c m bs).map (result s) := by + induction f generalizing c m bs with + | zero => rfl + | succ f ih => + rw [execute,body_step,execute] + cases h : (T.instantiate w v).program.step c <;> simp only [mapAction,Function.comp_apply] + all_goals first + | rfl + | (split <;> rfl) + | (rw [ih]; simp [Option.map_map,result,Report.prepend,Function.comp_def]) + | (cases bs <;> simp [ih,Option.map_map,result,Report.prepend,Function.comp_def]) + +/-- A successful local call contributes exactly its original events after the +operand prologue. Rejection and its accepted branch stream are preserved. -/ +theorem execute_flat (pub : Public k w) (s : Word w) (m : Memory w) (bs : List Bool) (f : ℕ) : + let vals := value load pub s m + let src := (T.instantiate w (fun j => vals j.castSucc)).program + let flat := ((compile T load).instantiate w pub).program + execute flat (f+(3+7*(k+1))) (flat.start s) m bs = + (execute src f (src.start (vals (Fin.last k))) m bs).map (fun rep => + ⟨events load pub s m ++ rep.events,rep.result.map (fun _ => s+1)⟩) := by + intro vals src flat + have init : flat.start s = ⟨prePC T load 0,s,fun _ => 0,fun _ => 0⟩ := rfl + rw [init,← prologue_length (r := r) load, + (pre_contains T load pub).execute (bad_code T load pub),run_eq_trace,prologue_trace] + simp only [Option.bind_some] + have full : Fin.snoc (fun j : Fin k => vals j.castSucc) (vals (Fin.last k)) = vals := by + funext j; cases j using Fin.lastCases <;> simp + have exactConfig : (⟨bodyPC load T.entry,s,registers (fun _ => 0) vals ![s,1,s+1],fun _ => 0⟩ : + Config w (PCs p r load) (Registers r k)) = + liftConfig load s (fun j => vals j.castSucc) (src.start (vals (Fin.last k))) := by + simp only [liftConfig,src,Machine.program,Template.instantiate,full] + change ((execute _ f (⟨bodyPC load T.entry,s,registers (fun _ => 0) vals ![s,1,s+1],fun _ => 0⟩ : Config w (PCs p r load) (Registers r k)) m bs).map _) = _ + rw [exactConfig,body_run] + simp [Option.map_map,result,Function.comp_def] + rfl + +end CompressorRecords.FlatRows + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorFlowFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorFlowFootprint.lean new file mode 100644 index 0000000000..0bc1445e01 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorFlowFootprint.lean @@ -0,0 +1,87 @@ +import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete +import OAI.Computability.VPVNP.RAMRecords +import OAI.Computability.VPVNP.RAMChoicePrefix +import OAI.Computability.VPVNP.CompressorSourceTransport + +/-! +# Event support of the private compressor computations + +An accepting flow with an empty choice tape fixes its entire event list. +A flow containing only register operations and control transfers accesses +no external cells, including when its finite execution takes loop branches. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.FlowFootprint + +open BurstRAM PrimedInputRAM PrimedStackRAM SourceTransport + +variable {w r k : ℕ} + +theorem events_eq {f : Flow r k} {pub : Fin k → Word w} {s : Word w} {rs r₁ r₂ : Regs w r} + {m m₁ m₂ : Memory w} {es fs : List (Event w)} + (first : Flow.Exec pub s f rs m es r₁ m₁) (empty : choiceBits es = []) + (second : Flow.Exec pub s f rs m fs r₂ m₂) : es = fs := by + let left : Report w := ⟨es,none⟩ + let right : Report w := ⟨fs,none⟩ + have a := (Flow.template_execute_iff f none pub s (fun _ => 0) rs m (es.length+1) [] left).mpr + ⟨r₁,m₁,first,rfl,Nat.lt_succ_self _,empty⟩ + have b := (Flow.template_execute_iff f none pub s (fun _ => 0) rs m (fs.length+1) ([] ++ choiceBits fs) right).mpr + ⟨r₂,m₂,second,rfl,Nat.lt_succ_self _,rfl⟩ + exact congrArg Report.events (execute_prefix_unique a b).2 + +/-- Test whether an instruction avoids external memory reads and writes. -/ +def privateOp : Op r k → Bool + | .read .. | .write .. => false + | _ => true + +/-- Recursively check that every instruction in a flow avoids external memory reads and writes. -/ +def privateOnly : Flow r k → Bool + | .line op => privateOp op + | .seq a b | .ifEq _ _ a b | .ifLt _ _ a b | .branch a b => privateOnly a && privateOnly b + | .whileLt _ _ a => privateOnly a + +private theorem private_tick {op : Op r k} {pub : Fin k → Word w} {s : Word w} + {rs out : Regs w r} {m post : Memory w} {e : Event w} + (code : privateOp op = true) (run : op.effect pub s rs m = some (e,out,post)) : e = .tick := by + cases op <;> simp only [privateOp,Bool.false_eq_true] at code + all_goals simp only [Op.effect,Option.some.injEq,Prod.mk.injEq] at run + all_goals first | exact run.1.symm | split at run <;> simp_all + +theorem noProbes {f : Flow r k} {pub : Fin k → Word w} {s rs m es out post} + (code : privateOnly f = true) (run : Flow.Exec pub s f rs m es out post) : + countProbes es = 0 := by + have add (es fs : List (Event w)) : countProbes (es ++ fs) = countProbes es + countProbes fs := by + induction es with + | nil => simp [countProbes] + | cons e es ih => cases e <;> simp [countProbes,ih,Nat.add_assoc] + induction run with + | line h => rw [private_tick code h]; rfl + | seq _ _ ih ih' => + have both := Bool.and_eq_true_iff.mp code + rw [add,ih both.1,ih' both.2] + | ifEqYes _ _ ih | ifLtYes _ _ ih | branchYes _ ih => exact ih (Bool.and_eq_true_iff.mp code).1 + | ifEqNo _ _ ih | ifLtNo _ _ ih | branchNo _ ih => exact ih (Bool.and_eq_true_iff.mp code).2 + | whileDone => rfl + | whileStep _ _ _ ih ih' => simp only [countProbes,add,ih code,ih' code,Nat.add_zero] + +theorem bounds_of_noProbes {es : List (Event w)} (readable writable : ℕ → Prop) (h : countProbes es = 0) : + Reads readable es ∧ Writes writable es := by + induction es with + | nil => exact ⟨fun _ _ hn => (List.not_mem_nil hn).elim,fun _ _ hn => (List.not_mem_nil hn).elim⟩ + | cons e es ih => + cases e with + | read | write => simp [countProbes] at h + | tick | choice => + obtain ⟨rd,wr⟩ := ih h + exact ⟨fun a v hn => rd a v (List.mem_cons.mp hn |>.resolve_left (by simp)), + fun a v hn => wr a v (List.mem_cons.mp hn |>.resolve_left (by simp))⟩ + +end CompressorRecords.FlowFootprint + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorFlowRebase.lean b/lean/OAI/Computability/VPVNP/CompressorFlowRebase.lean new file mode 100644 index 0000000000..3bb6e5b2c9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorFlowRebase.lean @@ -0,0 +1,150 @@ +import OAI.Computability.VPVNP.PrimedCounterRenameRun + +/-! +# Calling a native flow with a register as its persistent argument + +The enclosing call keeps its own persistent word. Each persistent-word load in +a component becomes a copy from a register outside its ordinary operand bank. +The component therefore observes one fixed input throughout loops and branches. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Rebased + +open BurstRAM PrimedStackRAM PrimedInputRAM PrimedCounter + +variable {w r k R K : ℕ} + +/-- Relabel an instruction's operands, replacing a persistent-state load by a copy from the +designated argument register. -/ +def opAt (reg : Fin r → Fin R) (pub : Fin k → Fin K) (arg : Fin R) : Op r k → Op R K + | .stateWord dst => .copy (reg dst) arg + | op => renameOp reg pub op + +private theorem effect (reg : Fin r ↪ Fin R) (pub : Fin k → Fin K) (arg : Fin R) (op : Op r k) + (data : Fin K → Word w) (state : Word w) (rs : Regs w R) (mem : Memory w) : + ((opAt reg pub arg op).effect data state rs mem).map (fun (e,r',m') => (e,r' ∘ reg,m')) = + op.effect (data ∘ pub) (rs arg) (rs ∘ reg) mem := by + have upd (dst : Fin r) (v : Word w) : + Function.update rs (reg dst) v ∘ reg = Function.update (rs ∘ reg) dst v := by + funext j + by_cases h : j = dst <;> simp [h,Function.comp_apply] + cases op <;> simp [opAt,renameOp,Op.effect,upd,Function.comp_apply] + +/-- Rebase a whole flow on an argument register while relabeling registers, public operands, +and branch conditions. -/ +def code (reg : Fin r → Fin R) (pub : Fin k → Fin K) (arg : Fin R) : Flow r k → Flow R K + | .line op => .line (opAt reg pub arg op) + | .seq a b => .seq (code reg pub arg a) (code reg pub arg b) + | .ifEq x y a b => .ifEq (reg x) (reg y) (code reg pub arg a) (code reg pub arg b) + | .ifLt x y a b => .ifLt (reg x) (reg y) (code reg pub arg a) (code reg pub arg b) + | .branch a b => .branch (code reg pub arg a) (code reg pub arg b) + | .whileLt x y a => .whileLt (reg x) (reg y) (code reg pub arg a) + +/-- One relocated opcode can only write an embedded register. -/ +private theorem line_outside (reg : Fin r ↪ Fin R) (pub : Fin k → Fin K) (arg : Fin R) (op : Op r k) + (data : Fin K → Word w) (state : Word w) (rs : Regs w R) (mem : Memory w) + {e out m'} (he : (opAt reg pub arg op).effect data state rs mem = some (e,out,m')) + (j : Fin R) (hj : j ∉ Set.range reg) : out j = rs j := by + have hn (i : Fin r) : j ≠ reg i := fun hh => hj ⟨i, hh.symm⟩ + cases op <;> simp only [opAt, renameOp, Op.effect] at he + all_goals first | split at he | skip + all_goals first | contradiction | (cases Option.some.inj he; simp [Function.update_of_ne (hn _)]) + +/-- Lift a finite small-register computation to the enclosing register space. +All unrelated enclosing registers retain their prior values. -/ +theorem liftExec (reg : Fin r ↪ Fin R) (pub : Fin k → Fin K) (arg : Fin R) (outside : arg ∉ Set.range reg) (data : Fin K → Word w) + {state argument : Word w} {a : Flow r k} {small m es out m'} + (he : Flow.Exec (data ∘ pub) argument a small m es out m') + (rs : Regs w R) (hr : rs ∘ reg = small) (harg : rs arg = argument) : + ∃ rs', Flow.Exec data state (code reg pub arg a) rs m es rs' m' ∧ + rs' ∘ reg = out ∧ ∀ j, j ∉ Set.range reg → rs' j = rs j := by + induction he generalizing rs with + | @line op small m e small' m' h => + subst small + have hx := (effect reg pub arg op data state rs m).trans (harg ▸ h) + obtain ⟨⟨ev, rs', m''⟩, hh, heq⟩ := Option.map_eq_some_iff.mp hx + obtain ⟨rfl, heq, rfl⟩ := Prod.mk.inj heq + exact ⟨rs', .line hh, rfl, line_outside reg pub arg op data state rs m hh⟩ + | seq _ _ ih₁ ih₂ => + obtain ⟨mid, hm, he, ho⟩ := ih₁ rs hr harg + obtain ⟨out, hrun, he', ho'⟩ := ih₂ mid he ((ho arg outside).trans harg) + exact ⟨out, .seq hm hrun, he', fun j hj => (ho' j hj).trans (ho j hj)⟩ + | ifEqYes ht _ ih | ifEqNo ht _ ih | ifLtYes ht _ ih | ifLtNo ht _ ih => + obtain ⟨out, ho, he, hh⟩ := ih rs hr harg + subst_vars + first | exact ⟨out, .ifEqYes ht ho, rfl, hh⟩ | exact ⟨out, .ifEqNo ht ho, rfl, hh⟩ + | exact ⟨out, .ifLtYes ht ho, rfl, hh⟩ | exact ⟨out, .ifLtNo ht ho, rfl, hh⟩ + | branchYes _ ih => + obtain ⟨out, ho, he, hh⟩ := ih rs hr harg + exact ⟨out, .branchYes ho, he, hh⟩ + | branchNo _ ih => + obtain ⟨out, ho, he, hh⟩ := ih rs hr harg + exact ⟨out, .branchNo ho, he, hh⟩ + | whileDone ht => + subst_vars + exact ⟨rs, .whileDone ht, rfl, fun _ _ => rfl⟩ + | whileStep ht _ _ ih₁ ih₂ => + obtain ⟨mid, hb, he, ho⟩ := ih₁ rs hr harg + obtain ⟨out, hrun, he', ho'⟩ := ih₂ mid he ((ho arg outside).trans harg) + rw [← hr] at ht + exact ⟨out, .whileStep ht hb hrun, he', fun j hj => (ho' j hj).trans (ho j hj)⟩ + +/-- Conversely, every successful enclosing execution restricts to a genuine +execution of the original program. Both directions include the exact event log. -/ +theorem restrictExec (reg : Fin r ↪ Fin R) (pub : Fin k → Fin K) (arg : Fin R) (outside : arg ∉ Set.range reg) (data : Fin K → Word w) + {state : Word w} (a : Flow r k) {rs m es out m'} + (he : Flow.Exec data state (code reg pub arg a) rs m es out m') : + Flow.Exec (data ∘ pub) (rs arg) a (rs ∘ reg) m es (out ∘ reg) m' ∧ + ∀ j, j ∉ Set.range reg → out j = rs j := by + generalize hcmd : code reg pub arg a = cmd at he + induction he generalizing a with + | @line op rs m e out m' h => + cases a <;> simp only [code, reduceCtorEq, Flow.line.injEq] at hcmd + subst op + constructor + · apply Flow.Exec.line + rw [← effect reg pub arg _ data state rs m, h] + rfl + · exact line_outside reg pub arg _ data state rs m h + | seq _ _ ih₁ ih₂ => + cases a <;> simp only [code, reduceCtorEq, Flow.seq.injEq] at hcmd + obtain ⟨ha, hb⟩ := hcmd + obtain ⟨h₁, o₁⟩ := ih₁ _ ha + obtain ⟨h₂, o₂⟩ := ih₂ _ hb + rw [o₁ arg outside] at h₂ + exact ⟨.seq h₁ h₂, fun j hj => (o₂ j hj).trans (o₁ j hj)⟩ + | ifEqYes ht _ ih | ifEqNo ht _ ih | ifLtYes ht _ ih | ifLtNo ht _ ih => + cases a <;> simp only [code, reduceCtorEq, Flow.ifEq.injEq, Flow.ifLt.injEq] at hcmd + obtain ⟨rfl, rfl, ha, hb⟩ := hcmd + first + | obtain ⟨h, ho⟩ := ih _ ha; exact ⟨.ifEqYes ht h, ho⟩ + | obtain ⟨h, ho⟩ := ih _ hb; exact ⟨.ifEqNo ht h, ho⟩ + | obtain ⟨h, ho⟩ := ih _ ha; exact ⟨.ifLtYes ht h, ho⟩ + | obtain ⟨h, ho⟩ := ih _ hb; exact ⟨.ifLtNo ht h, ho⟩ + | branchYes _ ih | branchNo _ ih => + cases a <;> simp only [code, reduceCtorEq, Flow.branch.injEq] at hcmd + obtain ⟨ha, hb⟩ := hcmd + first + | obtain ⟨h, ho⟩ := ih _ ha; exact ⟨.branchYes h, ho⟩ + | obtain ⟨h, ho⟩ := ih _ hb; exact ⟨.branchNo h, ho⟩ + | whileDone ht => + cases a <;> simp only [code, reduceCtorEq, Flow.whileLt.injEq] at hcmd + obtain ⟨rfl, rfl, _⟩ := hcmd + exact ⟨.whileDone ht, fun _ _ => rfl⟩ + | whileStep ht _ _ ih₁ ih₂ => + cases a <;> simp only [code, reduceCtorEq, Flow.whileLt.injEq] at hcmd + obtain ⟨rfl, rfl, rfl⟩ := hcmd + obtain ⟨h₁, o₁⟩ := ih₁ _ rfl + obtain ⟨h₂, o₂⟩ := ih₂ (.whileLt _ _ _) rfl + rw [o₁ arg outside] at h₂ + exact ⟨.whileStep ht h₁ h₂, fun j hj => (o₂ j hj).trans (o₁ j hj)⟩ + +end CompressorRecords.Rebased + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorFormulaFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorFormulaFootprint.lean new file mode 100644 index 0000000000..10c1de5e60 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorFormulaFootprint.lean @@ -0,0 +1,176 @@ +import OAI.Computability.VPVNP.CompressorFormulaRow +import OAI.Computability.VPVNP.CompressorFlowFootprint + +/-! +# External addresses accessed by a compiled formula row + +A load first evaluates its address in entry memory. The compiler's scratch +register then contains exactly that address when the read executes. After +the destination and field expressions finish, the row writer stores one +word at each consecutive machine address. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PhaseRecipe + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM RowRecipe SourceTransport +open scoped Fin.CommRing +open private run compile_value Phase.formulas Phase.scratch Phase.slot Phase.emit room slot_val from + OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +open private storeLog eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe +open private FormulaRow.carrier FormulaRow.paramIndex from OAI.Computability.VPVNP.CompressorFormulaRow + +variable {w r k g : ℕ} + +/-- Every external address read while evaluating an expression belongs to +the specified region, including reads needed to compute another address. -/ +def Expr.ReadsFrom (data : ℕ → Prop) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : Expr → Prop + | .lit _ | .publicWord _ | .state => True + | .load e => e.ReadsFrom data pub s m ∧ data (e.eval pub s m).val + | .binary _ a b => a.ReadsFrom data pub s m ∧ b.ReadsFrom data pub s m + +private theorem log_append (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (as bs : List (Assign r k)) (rs : Regs w r) : + (evaluate pub s m (as++bs) rs).1 = + (evaluate pub s m as rs).1 ++ (evaluate pub s m bs (evaluate pub s m as rs).2).1 := by + induction as generalizing rs with + | nil => rfl + | cons a as ih => + simp only [List.cons_append,evaluate,ih] + +private theorem reads_append {data : ℕ → Prop} {es fs : List (Event w)} + (h : Reads data es) (h' : Reads data fs) : Reads data (es++fs) := + fun a v ha => (List.mem_append.mp ha).elim (h a v) (h' a v) + +private theorem compile_safe (data : ℕ → Prop) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (e : Expr) (h : e.ReadsFrom data pub s m) (slot : ℕ → Fin r) (cap start : ℕ) + (enough : start+e.slots ≤ cap) (inj : ∀ i < cap, ∀ j < cap, slot i = slot j → i = j) + (rs : Regs w r) : Reads data (evaluate pub s m (e.compile slot start) rs).1 := by + induction e generalizing start rs with + | lit n => + apply (FlowFootprint.bounds_of_noProbes data data _).1 + rw [(eval_cost ..).2, Expr.compile_reads]; rfl + | state | publicWord _ => + simp [Expr.compile,evaluate,RHS.event,Reads] + | load a ih => + rw [Expr.compile,log_append] + apply reads_append (ih h.1 start enough rs) + intro addr v ha + have atSlot := compile_value pub s m a slot cap start rs enough inj + simp only [evaluate,RHS.event,List.mem_singleton,Event.read.injEq] at ha + change addr = run pub s m (a.compile slot start) rs (slot start) ∧ _ at ha + rw [ha.1,atSlot] + exact h.2 + | binary op a b ha hb => + have bounds : start+max a.slots (1+b.slots) ≤ cap := enough + rw [Expr.compile,log_append,log_append] + apply reads_append (reads_append (ha h.1 start (by omega) rs) (hb h.2 (start+1) (by omega) _)) + simp [evaluate,RHS.event,Reads] + +private theorem emitted_safe (data : ℕ → Prop) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (P : Phase g) (js : List (Fin (g+4))) (ok : ∀ j ∈ js, (Phase.formulas P j).ReadsFrom data pub s m) + (rs : Regs w P.registerCount) : + Reads data (evaluate pub s m (js.flatMap (Phase.emit P)) rs).1 := by + induction js generalizing rs with + | nil => simp [evaluate,Reads] + | cons j js ih => + rw [List.flatMap_cons,log_append] + apply reads_append _ (ih (fun i hi => ok i (List.mem_cons_of_mem _ hi)) _) + rw [Phase.emit,log_append] + refine reads_append ?_ ?_ + · apply compile_safe data pub s m _ (ok j (List.mem_cons_self)) (Phase.slot P) (Phase.scratch P) 0 + (by simpa only [Nat.zero_add] using room P j) + intro i hi j hj he + have eqn := congrArg Fin.val he + rw [slot_val P hi,slot_val P hj] at eqn + omega + · simp [evaluate,RHS.event,Reads] + +private theorem store_no_reads (data : ℕ → Prop) (dest : Word w) (vs : List (Word w)) : + Reads data (storeLog dest vs) := by + induction vs generalizing dest with + | nil => simp [storeLog,Reads] + | cons v vs ih => + intro a x hx + apply ih (dest+1) a x + simpa [storeLog] using hx + +private theorem eval_no_writes (data : ℕ → Prop) (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (ls : List (Assign r k)) (rs : Regs w r) : Writes data (evaluate pub s m ls rs).1 := by + induction ls generalizing rs with + | nil => simp [evaluate,Writes] + | cons a ls ih => + intro addr v hv + obtain ⟨dst,rhs⟩ := a + apply ih (Function.update rs dst (rhs.value pub s m rs)) addr v + cases rhs <;> simpa [evaluate,RHS.event] using hv + +private theorem store_writes (data : ℕ → Prop) (dest : Word w) (vs : List (Word w)) + (cells : ∀ i : Fin vs.length, data (dest+(i.val : Word w)).val) : Writes data (storeLog dest vs) := by + induction vs generalizing dest with + | nil => simp [storeLog,Writes] + | cons v vs ih => + intro a x hx + simp only [storeLog,List.mem_cons,Event.write.injEq,reduceCtorEq,false_or] at hx + rcases hx with ⟨rfl,rfl⟩ | hx + · simpa only [Fin.val_zero,Nat.cast_zero,add_zero] using cells 0 + · apply ih (dest+1) _ a x hx + intro i + simpa only [Fin.val_succ,Nat.cast_add,Nat.cast_one,add_assoc,add_comm (1 : Word w)] using cells i.succ + +namespace FormulaRow + +variable (R : FormulaRow g) (data : ℕ → Prop) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + +/-- Every external read of the actual formula-row report is justified by +a load in the destination expression or in one of the field expressions. -/ +theorem report_reads (dest : R.dest.ReadsFrom data pub s m) + (fields : ∀ i, (R.fields i).ReadsFrom data pub s m) : + Reads data (R.recipe.report pub s m).events := by + have safe : Reads data (evaluate pub s m R.recipe.lines (fun _ => 0)).1 := by + apply emitted_safe data pub s m (FormulaRow.carrier R) + intro j hj + obtain ⟨i,_,rfl⟩ := List.mem_map.mp hj + simp only [FormulaRow.carrier,Phase.formulas,FormulaRow.paramIndex,Fin.cons_succ] + cases i using Fin.cases with + | zero => exact dest + | succ i => exact fields i + intro a v h + simp only [Recipe.report,List.mem_append,List.mem_cons,List.not_mem_nil,reduceCtorEq, + or_false] at h + exact h.elim (safe a v) (store_no_reads data _ _ a v) + +/-- Stores use machine-word addition, even when a row wraps at the end of +the address space. -/ +theorem report_writes (cells : ∀ i : Fin (g+3), data (R.dest.eval pub s m + (i.val : Word w)).val) : + Writes data (R.recipe.report pub s m).events := by + have safe : Writes data (storeLog (R.recipe.address pub s m) (R.recipe.words pub s m)) := by + rw [recipe_address,recipe_words] + apply store_writes + intro i + exact cells ⟨i.val,by simpa only [List.length_ofFn] using i.isLt⟩ + intro a v h + simp only [Recipe.report,List.mem_append,List.mem_cons,List.not_mem_nil,reduceCtorEq, + or_false] at h + exact h.elim (eval_no_writes data pub s m _ _ a v) (safe a v) + +/-- A physically allocated row uses ordinary natural offsets for all stores. -/ +theorem report_writes_nat (fit : (R.dest.eval pub s m).val + (g+3) ≤ 2^w) + (cells : ∀ i : Fin (g+3), data ((R.dest.eval pub s m).val+i.val)) : + Writes data (R.recipe.report pub s m).events := by + apply R.report_writes + intro i + have hi := i.isLt + rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (show i.val < 2^w by omega), + Nat.mod_eq_of_lt (show (R.dest.eval pub s m).val+i.val < 2^w by omega)] + exact cells i + +end FormulaRow +end CompressorRecords.PhaseRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorFormulaRow.lean b/lean/OAI/Computability/VPVNP/CompressorFormulaRow.lean new file mode 100644 index 0000000000..45209be832 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorFormulaRow.lean @@ -0,0 +1,108 @@ +import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +import OAI.Computability.VPVNP.CompressorRecordsCursorInit + +/-! +# Native publication of a consecutive row of computed descriptor fields + +The finite program evaluates the destination and all field expressions against +entry memory before performing any store. The program works at every word width +and its instruction and probe counts depend only on the expressions. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PhaseRecipe + +open BurstRAM BurstRAM.PrivateRAM RowRecipe +open private Phase.emit Phase.out Phase.formulas emit_list run from + OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +open private stores_at from OAI.Computability.VPVNP.CompressorRecordsCursorInit + +/-- A computed starting address and the consecutive words installed there. -/ +structure FormulaRow (g : ℕ) where + /-- Expression computing the destination address of the first word of the published row. -/ + dest : Expr + /-- Expressions for the consecutive row words, evaluated against the entry memory before + publication. -/ + fields : Fin (g+3) → Expr + +namespace FormulaRow + +variable {g w : ℕ} (R : FormulaRow g) + +/-- Use the phase compiler's scratch allocation for exactly the requested +expressions. The extra phase prefix is omitted from the emitted assignments. -/ +private def carrier : Phase (g+4) := ⟨0, .lit 0, .lit 0, Fin.cons R.dest R.fields⟩ + +private def paramIndex (j : Fin (g+4)) : Fin ((g+4)+4) := j.succ.succ.succ.succ + +/-- Compile the row's destination and fields into a recipe that publishes the tag, interval, +and parameters. -/ +def recipe : Recipe R.carrier.registerCount 5 g where + lines := ((List.finRange (g+4)).map paramIndex).flatMap (Phase.emit R.carrier) + dest := Phase.out R.carrier (paramIndex 0) + tag := Phase.out R.carrier (paramIndex (0 : Fin (g+3)).succ) + start := Phase.out R.carrier (paramIndex (0 : Fin (g+2)).succ.succ) + stop := Phase.out R.carrier (paramIndex (0 : Fin (g+1)).succ.succ.succ) + params i := Phase.out R.carrier (paramIndex i.succ.succ.succ.succ) + +private theorem eval_param (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) (j : Fin (g+4)) : + R.recipe.values pub s m (Phase.out R.carrier (paramIndex j)) = + Expr.eval pub s m (Fin.cons (α := fun _ ↦ Expr) R.dest R.fields j) := by + change run pub s m (((List.finRange (g+4)).map paramIndex).flatMap (Phase.emit R.carrier)) _ _ = _ + rw [emit_list] + have h : paramIndex j ∈ (List.finRange (g+4)).map paramIndex := + List.mem_map.mpr ⟨j, List.mem_finRange j, rfl⟩ + rw [ite_eq_left h] + simp only [paramIndex, Phase.formulas, Fin.cons_succ, carrier] + +theorem recipe_address (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + R.recipe.address pub s m = R.dest.eval pub s m := by + exact R.eval_param pub s m 0 + +theorem recipe_words (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + R.recipe.words pub s m = List.ofFn (fun j ↦ (R.fields j).eval pub s m) := by + rw [Recipe.words, Recipe.fields] + simp only [List.map_cons, List.map_ofFn] + conv_rhs => rw [List.ofFn_succ, List.ofFn_succ, List.ofFn_succ] + change R.recipe.values pub s m (Phase.out R.carrier (paramIndex (0 : Fin (g+3)).succ)) :: + R.recipe.values pub s m (Phase.out R.carrier (paramIndex (0 : Fin (g+2)).succ.succ)) :: + R.recipe.values pub s m (Phase.out R.carrier (paramIndex (0 : Fin (g+1)).succ.succ.succ)) :: + List.ofFn (fun j : Fin g ↦ R.recipe.values pub s m + (Phase.out R.carrier (paramIndex j.succ.succ.succ.succ))) = _ + simp only [eval_param, Fin.cons_succ] + +/-- Normal entry executes one burst, returns the next state, installs each +field at its natural address and preserves all words outside the row. -/ +theorem execute (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (fit : (R.dest.eval pub s m).val + (g+3) ≤ 2^w) : + let M := R.recipe.table.instantiate w pub + let rep := R.recipe.report pub s m + let dest := (R.dest.eval pub s m).val + BurstRAM.execute M.program (R.recipe.code.length+1) (M.program.start s) m [] = some rep ∧ + rep.result = some (s+1) ∧ + (∀ j : Fin (g+3), after m rep.events (dest+j.val) = (R.fields j).eval pub s m) ∧ + (∀ a, a < dest ∨ dest + (g+3) ≤ a → after m rep.events a = m a) ∧ + rep.events.length = R.recipe.code.length ∧ rep.probes = R.recipe.reads+(g+3) ∧ + choiceBits rep.events = [] := by + intro M rep dest + have hf : (R.recipe.address pub s m).val + (g+3) ≤ 2^w := R.recipe_address pub s m ▸ fit + have hs := row_stores R.recipe pub s m hf + rw [recipe_address, recipe_words] at hs + obtain ⟨he,hp,hc⟩ := report_cost R.recipe pub s m + refine ⟨execute_row R.recipe pub s m [] _ (by omega), rfl, ?_, ?_, he.trans (code_length _).symm, hp, hc⟩ + · intro j + have hj : j.val < (List.ofFn (fun i ↦ (R.fields i).eval pub s m)).length := by simpa only [List.length_ofFn] using j.isLt + exact (stores_at _ _ hs (by simpa using fit) hj).trans (List.getElem_ofFn hj) + · intro a ha + exact row_outside R.recipe pub s m hf a (R.recipe_address pub s m ▸ ha) + +end FormulaRow + +end CompressorRecords.PhaseRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyLevelPlan.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyLevelPlan.lean new file mode 100644 index 0000000000..bc7a35a7bd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyLevelPlan.lean @@ -0,0 +1,260 @@ +import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedyLayout +import OAI.Computability.VPVNP.CompressorGreedyRelocated +import OAI.Computability.VPVNP.CompressorRecordsShrinkTagColumn + +/-! +# Planning the ordered greedy scans for a shrinking level + +The initializer receives the current level's base mate pointers in its public +frame. The color and tag labels occupy separate arenas, each immediately +followed by its fixed-stride records. A read starts at the first record and +stops at the address just past the last record. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyLevelPlan + +open BurstRAM BurstRAM.PrivateRAM Compression PhaseRecipe BlockPlanner Greedy +open scoped Fin.CommRing + +private def firstRecord (step : ℕ) (labels : Expr) := labels.add (LevelFields.vertices step) +private def recordsEnd (step width : ℕ) (labels : Expr) := + (firstRecord step labels).add ((LevelFields.vertices step).mul (.lit (2 + width))) + +/-- Starting address of the tag-label arena, immediately following the color labels and +records. -/ +def offsetBase (step a : ℕ) (origin : Expr) := recordsEnd step (2 * 2 ^ a) origin +/-- Starting address of the extracted shifts, immediately following the tag labels and records. -/ +def shiftBase (step a : ℕ) (origin : Expr) := + recordsEnd step (4 * WalkLayout.tagCount (2 ^ a)) (offsetBase step a origin) +/-- Address of the shared zero word following all per-port shifts. -/ +def zeroAddress (step a : ℕ) (origin : Expr) := + (shiftBase step a origin).add ((LevelFields.vertices step).mul (LevelFields.degree step)) +/-- Exclusive end of the greedy scratch region, one word past the shared zero cell. -/ +def greedyStop (step a : ℕ) (origin : Expr) := (zeroAddress step a origin).add (.lit 1) + +private def controls (shape : DescriptorSpace.Shape) (step width : ℕ) + (displacements labels zero : Expr) : Fin 8 → Expr := + ![LevelFields.degree step, LevelFields.incidence shape step 0, LevelFields.incidence shape step 1, + displacements, labels, zero, firstRecord step labels, .lit (2 + width)] + +private def prepare {d : ℕ} (shape : DescriptorSpace.Shape) (step width : ℕ) + (rows : OperandRows d) (displacements labels zero : Expr) : Visit := + ⟨Relocated.preparePass rows, .lit 0, LevelFields.vertices step, + Fin.addCases (fun i ↦ .lit i.val) (controls shape step width displacements labels zero)⟩ + +private def read (step arity tests width : ℕ) (labels : Expr) : Visit := + ops (visitCode arity tests) 4 (firstRecord step labels) (recordsEnd step width labels) Fin.elim0 + +/-- Calendar visit that prepares the color-test operand records for every base vertex. -/ +def colorPrepare (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : Visit := + prepare shape step (2 * 2 ^ a) (colorOperandRows (2 ^ a)) (LevelFields.incidence shape step 2) + origin (zeroAddress step a origin) + +/-- Calendar visit that scans the prepared color records to assign the greedy color labels. -/ +def colorRead (step a : ℕ) (origin : Expr) : Visit := read step 1 (2 * 2 ^ a) (2 * 2 ^ a) origin + +/-- Calendar visit that prepares the four-operand tag tests from the extracted shifts and label +tables. -/ +def tagPrepare (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : Visit := + prepare shape step (4 * WalkLayout.tagCount (2 ^ a)) (tagOperandRows (2 ^ a)) + (shiftBase step a origin) (offsetBase step a origin) (zeroAddress step a origin) + +/-- Calendar visit that scans the prepared tag records to assign the greedy tag labels. -/ +def tagRead (step a : ℕ) (origin : Expr) : Visit := + read step 4 (WalkLayout.tagCount (2 ^ a)) (4 * WalkLayout.tagCount (2 ^ a)) (offsetBase step a origin) + +/-- The four greedy walk visits in order, preparing and scanning colors before preparing and +scanning tags. -/ +def walkVisits (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : List Visit := + [colorPrepare shape step a origin, colorRead step a origin, + tagPrepare shape step a origin, tagRead step a origin] + +private def projectionParams (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : Fin 5 → Expr := + ![LevelFields.incidence shape step 2, shiftBase step a origin, zeroAddress step a origin, + LevelFields.residualLanes step, .lit (2 ^ Shrink.J a)] + +/-- Calendar visit that projects the old incidence shifts into the scratch shift column, one +row per base port. -/ +def extractShifts (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : Visit := + ⟨ShrinkTagColumn.extractPass, .lit 0, (LevelFields.vertices step).mul (LevelFields.degree step), + projectionParams shape step a origin⟩ + +/-- Single-row visit that initializes the shared zero cell used by the greedy walks. -/ +def publishZero (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : Visit := + ⟨ShrinkTagColumn.zeroPass, .lit 0, .lit 1, projectionParams shape step a origin⟩ + +/-- Project the displacement and install the zero operand before preparing either directory. -/ +def visits (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : List Visit := + extractShifts shape step a origin :: publishZero shape step a origin :: walkVisits shape step a origin + +@[simp] theorem visits_length (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : + (visits shape step a origin).length = 6 := rfl + +theorem operand_counts (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : + (visits shape step a origin).map (fun v ↦ v.worker.params) = + [5, 5, (2 ^ a + 1) + 8, 0, (2 ^ a + 1) + 8, 0] := rfl + +variable {w : ℕ} {pub : Fin 5 → Word w} {state : Word w} {m : Memory w} +variable {shape : DescriptorSpace.Shape} {step a n g start : ℕ} {origin : Expr} {T : IncidenceDirectory w} + +/-- Values supplied by the physical level header and the chosen scratch origin. -/ +structure Reads (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) + (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) (n g start : ℕ) (T : IncidenceDirectory w) : Prop where + vertices : (LevelFields.vertices step).eval pub state m = (n : Word w) + degree : (LevelFields.degree step).eval pub state m = ((2 ^ a : ℕ) : Word w) + residual : (LevelFields.residualLanes step).eval pub state m = ((2 ^ g : ℕ) : Word w) + incidence : ∀ c, (LevelFields.incidence shape step c).eval pub state m = T.column c + origin : origin.eval pub state m = (start : Word w) + +theorem Reads.of_published {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} + {B : S.Templates} {f : B.Entry → R} {hf : B.IsSolution f} (v : SelectedLevel B f hf) + {layout : DescriptorSpace.Layout} {first expander : ℕ} (e : LevelFields.Entry layout first pub state m) + (h : LevelFields.Published layout (first + step) v expander m) + (heads : ∀ c, (DescriptorSpace.incidenceHead layout (first + step) c) < 2 ^ w ∧ + m (DescriptorSpace.incidenceHead layout (first + step) c) = T.column c) + (address : origin.eval pub state m = (start : Word w)) : + Reads layout.shape step v.inputExponent origin pub state m (Fintype.card v.input.Base) v.outputLanes start T := by + have room := h.room + exact ⟨(LevelFields.eval_scalar e step 0 (by omega)).trans h.vertices, + (LevelFields.eval_scalar e step 1 (by omega)).trans h.degree, + (LevelFields.eval_scalar e step 3 (by omega)).trans h.residual, + fun c ↦ (LevelFields.eval_incidence e step c (heads c).1).trans (heads c).2, address⟩ + +variable (h : Reads shape step a origin pub state m n g start T) + +include h + +private theorem eval_firstRecord (labels : Expr) (z : ℕ) (hl : labels.eval pub state m = (z : Word w)) : + (firstRecord step labels).eval pub state m = ((z + n : ℕ) : Word w) := by + change labels.eval pub state m + (LevelFields.vertices step).eval pub state m = _ + rw [hl, h.vertices, Nat.cast_add] + +private theorem eval_recordsEnd (labels : Expr) (width z : ℕ) (hl : labels.eval pub state m = (z : Word w)) : + (recordsEnd step width labels).eval pub state m = ((z + n + n * (2 + width) : ℕ) : Word w) := by + change (firstRecord step labels).eval pub state m + (LevelFields.vertices step).eval pub state m * + ((2 + width : ℕ) : Word w) = _ + simp only [eval_firstRecord h _ _ hl, h.vertices, Nat.cast_add, Nat.cast_mul] + +theorem eval_offsetBase : (offsetBase step a origin).eval pub state m = (GreedyArena.offsetBase start n a : Word w) := + eval_recordsEnd h _ _ _ h.origin + +theorem eval_shiftBase : (shiftBase step a origin).eval pub state m = (GreedyArena.shiftBase start n a : Word w) := + eval_recordsEnd h _ _ _ (eval_offsetBase h) + +theorem eval_zeroAddress : (zeroAddress step a origin).eval pub state m = (GreedyArena.zeroCell start n a : Word w) := by + change (shiftBase step a origin).eval pub state m + + (LevelFields.vertices step).eval pub state m * (LevelFields.degree step).eval pub state m = _ + rw [eval_shiftBase h, h.vertices, h.degree, GreedyArena.zeroCell, Nat.cast_add, Nat.cast_mul] + +theorem eval_greedyStop : (greedyStop step a origin).eval pub state m = (GreedyArena.greedyStop start n a : Word w) := by + change (zeroAddress step a origin).eval pub state m + (1 : ℕ) = _ + rw [eval_zeroAddress h, GreedyArena.greedyStop, Nat.cast_add] + +private theorem prepare_values {width : ℕ} (rows : OperandRows (2 ^ a)) (disps labels zero : Expr) + (L : WalkLayout w n width) (hl : labels.eval pub state m = (L.origin : Word w)) : + let v := prepare shape step width rows disps labels zero + let bank := GreedyArena.tables T a (L.origin : Word w) (zero.eval pub state m) (disps.eval pub state m) + v.initial.eval pub state m = 0 ∧ v.stop.eval pub state m = (n : Word w) ∧ + (fun j ↦ (v.params j).eval pub state m) = Relocated.publicWords (2 ^ a) L bank := by + refine ⟨rfl, h.vertices, funext fun j ↦ ?_⟩ + cases j using Fin.addCases with + | left i => simp [prepare, Relocated.publicWords, slotNumbers, Expr.eval] + | right i => + simp only [prepare, Relocated.publicWords, Fin.addCases_right] + fin_cases i + · exact h.degree + · exact h.incidence 0 + · exact h.incidence 1 + · rfl + · exact hl + · rfl + · change (firstRecord step labels).eval pub state m = L.base 0 + rw [eval_firstRecord h _ _ hl, WalkLayout.base, Nat.zero_mul, Nat.add_zero] + rfl + · rfl + +private theorem read_values {width : ℕ} (arity tests : ℕ) (labels : Expr) + (L : WalkLayout w n width) (hl : labels.eval pub state m = (L.origin : Word w)) : + let v := read step arity tests width labels + v.initial.eval pub state m = L.base 0 ∧ v.stop.eval pub state m = L.base n ∧ + (fun j ↦ (v.params j).eval pub state m) = Fin.elim0 := by + exact ⟨by + change (firstRecord step labels).eval pub state m = L.base 0 + rw [eval_firstRecord h _ _ hl, WalkLayout.base, Nat.zero_mul, Nat.add_zero] + rfl, + eval_recordsEnd h _ _ _ hl, funext fun j ↦ Fin.elim0 j⟩ + +private theorem projection_values : + (fun j ↦ (projectionParams shape step a origin j).eval pub state m) = + ShrinkTagColumn.params T a g (GreedyArena.shiftBase start n a : Word w) (GreedyArena.zeroCell start n a : Word w) := by + funext j + fin_cases j + · exact h.incidence 2 + · exact eval_shiftBase h + · exact eval_zeroAddress h + · exact h.residual + · rfl + +theorem extractShifts_values : + let v := extractShifts shape step a origin + v.initial.eval pub state m = 0 ∧ v.stop.eval pub state m = ((n * 2 ^ a : ℕ) : Word w) ∧ + (fun j ↦ (v.params j).eval pub state m) = + ShrinkTagColumn.params T a g (GreedyArena.shiftBase start n a : Word w) (GreedyArena.zeroCell start n a : Word w) := by + refine ⟨rfl, ?_, projection_values h⟩ + change (LevelFields.vertices step).eval pub state m * (LevelFields.degree step).eval pub state m = _ + rw [h.vertices, h.degree, Nat.cast_mul] + +theorem publishZero_values : + let v := publishZero shape step a origin + v.initial.eval pub state m = 0 ∧ v.stop.eval pub state m = 1 ∧ + (fun j ↦ (v.params j).eval pub state m) = + ShrinkTagColumn.params T a g (GreedyArena.shiftBase start n a : Word w) (GreedyArena.zeroCell start n a : Word w) := + ⟨rfl, rfl, projection_values h⟩ + +variable (room : GreedyArena.greedyStop start n a < 2 ^ w) + +theorem colorPrepare_values : + let L := GreedyArena.colorLayout w start n a room + let bank := GreedyArena.tables T a (start : Word w) (GreedyArena.zeroCell start n a : Word w) T.shift + let v := colorPrepare shape step a origin + v.initial.eval pub state m = 0 ∧ v.stop.eval pub state m = (n : Word w) ∧ + (fun j ↦ (v.params j).eval pub state m) = Relocated.publicWords (2 ^ a) L bank := by + have shift : (LevelFields.incidence shape step 2).eval pub state m = T.shift := h.incidence 2 + simpa only [colorPrepare, GreedyArena.colorLayout, GreedyArena.colorBase, eval_zeroAddress h, shift] using prepare_values h (colorOperandRows (2 ^ a)) + (LevelFields.incidence shape step 2) origin (zeroAddress step a origin) (GreedyArena.colorLayout w start n a room) h.origin + +theorem colorRead_values : + let L := GreedyArena.colorLayout w start n a room + let v := colorRead step a origin + v.initial.eval pub state m = L.base 0 ∧ v.stop.eval pub state m = L.base n ∧ + (fun j ↦ (v.params j).eval pub state m) = Fin.elim0 := + read_values h _ _ origin _ h.origin + +theorem tagPrepare_values : + let L := GreedyArena.tagLayout w start n a room + let bank := GreedyArena.tables T a (GreedyArena.offsetBase start n a : Word w) + (GreedyArena.zeroCell start n a : Word w) (GreedyArena.shiftBase start n a : Word w) + let v := tagPrepare shape step a origin + v.initial.eval pub state m = 0 ∧ v.stop.eval pub state m = (n : Word w) ∧ + (fun j ↦ (v.params j).eval pub state m) = Relocated.publicWords (2 ^ a) L bank := by + simpa only [tagPrepare, GreedyArena.tagLayout, eval_zeroAddress h, eval_shiftBase h] using prepare_values h (tagOperandRows (2 ^ a)) + (shiftBase step a origin) (offsetBase step a origin) (zeroAddress step a origin) + (GreedyArena.tagLayout w start n a room) (eval_offsetBase h) + +theorem tagRead_values : + let L := GreedyArena.tagLayout w start n a room + let v := tagRead step a origin + v.initial.eval pub state m = L.base 0 ∧ v.stop.eval pub state m = L.base n ∧ + (fun j ↦ (v.params j).eval pub state m) = Fin.elim0 := + read_values h _ _ (offsetBase step a origin) _ (eval_offsetBase h) + +end CompressorRecords.GreedyLevelPlan + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyPacketFootprints.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyPacketFootprints.lean new file mode 100644 index 0000000000..ef4b2d883d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyPacketFootprints.lean @@ -0,0 +1,113 @@ +import OAI.Computability.VPVNP.CompressorGreedyPrepareScanAccess +import OAI.Computability.VPVNP.CompressorGreedyProjectionAccess +import OAI.Computability.VPVNP.CompressorGreedyReaderAccess +import OAI.Computability.VPVNP.CompressorGreedyVisitWalk + +/-! +# Physical memory bounds for the six greedy packets + +The color and offset initializers read the old forward and inverse mate +columns and write their own directories. Together with tag projection, +zero publication and the two readers, each stage reads from the level +data and writes only into the fresh greedy allocation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM Compression Greedy GreedyArena +open scoped Fin.CommRing + +variable {w a g origin : ℕ} {X : ShrinkingState a g} {T : IncidenceDirectory w} + {m : Memory w} (r : GreedyArena.Run X T origin m) + +local notation "N" => Fintype.card X.Base +local notation "limit" => greedyStop origin N a + +namespace GreedyArena.Run + +include r in +private theorem mate_cells (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) + (e : X.Base × Fin (2^a)) (b : Word w) (hb : b ∈ [T.baseOut, T.baseIn]) : + PrepareAccess.Interval lo limit (b + portNumber X.baseIndex e).val := by + have col (c : Fin 6) : PrepareAccess.Interval lo limit (T.column c + portNumber X.baseIndex e).val := by + have idx : (portNumber (w := w) X.baseIndex e).val < N * 2^a := by + change (IncidenceDirectory.basePort (w := w) X e).val < _ + rw [IncidenceDirectory.basePort_number] + exact (Nat.mod_le _ _).trans_lt (IncidenceDirectory.baseOrder X e).isLt + have bound := r.old c + have mul := Nat.mul_le_mul_right (2^a) (Nat.le_mul_of_pos_right N (Nat.two_pow_pos (packingLaneBits a g))) + have room := r.room + have h := bounds origin N a + change origin+N ≤ _ ∧ _ at h + rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)] + exact ⟨(low c).trans (Nat.le_add_right ..), by omega⟩ + rcases List.mem_cons.mp hb with rfl | hb + · exact col 0 + · obtain rfl := List.mem_singleton.mp hb + exact col 1 + +/-- The relocated color initializer reads old mates and writes only its fresh +color labels, headers and operand pointers. -/ +theorem color_prepare_access (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) : + LogAccess (PrepareAccess.Interval lo limit) (PrepareAccess.Interval origin limit) r.color.prep := by + let L := colorLayout w origin N a r.room + let U := colorTables T origin N a + have h := bounds origin N a + change origin+N ≤ _ ∧ _ at h + have room := r.room + have src := PrepareAccess.scan L U X.slots.base X.baseIndex (colorOperandRows (2^a)) + (projectedMemory X T origin m) rfl r.color_tables + (by change offsetBase origin N a < 2^w; omega) (r.old.graphOutside L le_rfl _ _ _) + (fun _ ↦ rowWords_color_length _ _ _ _) (PrepareAccess.Interval lo limit) (mate_cells r lo low) _ r.color.prepRun + exact src.mono (fun _ hz ↦ hz) (fun x ⟨h₁,h₂⟩ ↦ by + change origin ≤ x at h₁ + change x < offsetBase origin N a at h₂ + exact ⟨h₁, by omega⟩) + +/-- The offset initializer follows the same old mate columns and writes its +disjoint offset directory. -/ +theorem tag_prepare_access (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) : + LogAccess (PrepareAccess.Interval lo limit) (PrepareAccess.Interval origin limit) r.offsets.prep := by + let L := tagLayout w origin N a r.room + let U := tagTables T origin N a + have h := bounds origin N a + change origin+N ≤ _ ∧ _ at h + have room := r.room + have src := PrepareAccess.scan L U X.slots.base X.baseIndex (tagOperandRows (2^a)) + r.color.post rfl r.offset_tables + (by change shiftBase origin N a < 2^w; omega) + (r.old.graphOutside L (by change origin ≤ offsetBase origin N a; omega) _ _ _) + (fun _ ↦ by rw [rowWords_tag_length, tagTests_length, Nat.mul_comm]) (PrepareAccess.Interval lo limit) + (mate_cells r lo low) _ r.offsets.prepRun + exact src.mono (fun _ hz ↦ hz) (fun x ⟨h₁,h₂⟩ ↦ by + change offsetBase origin N a ≤ x at h₁ + change x < shiftBase origin N a at h₂ + exact ⟨by omega, by omega⟩) + +end GreedyArena.Run + +namespace GreedyVisit + +/-- Per-packet memory bounds in native execution order. The lower read bound +may be any common lower bound for the six old incidence columns. -/ +theorem packet_access (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) (j : Stage) : + LogAccess (PrepareAccess.Interval lo limit) (PrepareAccess.Interval origin limit) (packetReports r j) := by + cases j with + | extract => exact r.projection_access lo low + | zero => exact r.zero_access lo + | colorPrepare => exact r.color_prepare_access lo low + | colorRead => exact r.color_read_access lo low + | tagPrepare => exact r.tag_prepare_access lo low + | tagRead => exact r.tag_read_access lo low + +end GreedyVisit + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyPacketWalk.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyPacketWalk.lean new file mode 100644 index 0000000000..d29e1f4c99 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyPacketWalk.lean @@ -0,0 +1,88 @@ +import OAI.Computability.VPVNP.CompressorGreedyPlannerFootprint + +/-! # Evaluating each greedy packet in its own source memory + +The old level scalars, incidence heads and table pointer are below the +greedy workspace. The six native workers preserve that prefix. Their +dynamic launch expressions consequently read the same inputs at each +stage, even after earlier workers have written the two directories. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyVisit + +open BurstRAM Compression DescriptorSpace PhaseRecipe SourceTransport +open scoped Fin.CommRing + +variable {w a g z : ℕ} {X : GreedyArena.ShrinkingState a g} {T : IncidenceDirectory w} + {m : Memory w} + +private theorem transfer {D : ℕ → Prop} {pub : Fin 5 → Word w} {s : Word w} {input : Memory w} + (e : Expr) (same : ∀ x < z, input x = m x) + (low : e.ReadsFrom (· < z) pub s m) (reads : e.ReadsFrom D pub s m) : + e.eval pub s input = e.eval pub s m ∧ e.ReadsFrom D pub s input := by + induction e with + | lit | publicWord | state => exact ⟨rfl,trivial⟩ + | load e ih => + obtain ⟨addr,hr⟩ := ih low.1 reads.1 + exact ⟨(congrArg (fun x : Word w => input x.val) addr).trans (same _ low.2),hr,addr ▸ reads.2⟩ + | binary op e f he hf => + obtain ⟨er,es⟩ := he low.1 reads.1 + obtain ⟨fr,fs⟩ := hf low.2 reads.2 + exact ⟨congrArg₂ op.eval er fr,es,fs⟩ + +/-- Uniform fuel bound obtained by summing the fuel budgets of all greedy stages. -/ +def maxFuel (a : ℕ) := (stages.map (fuel a)).sum + +theorem fuel_le (j : Stage) : fuel a j ≤ maxFuel a := by + apply List.single_le_sum + · exact fun _ _ => Nat.zero_le _ + exact List.mem_map.mpr ⟨j,by cases j <;> decide,rfl⟩ + +/-- Turn the six actual native kernels into header-relative source packets. +The only memory facts used about their traces are the two access bounds. -/ +theorem packet_walk (r : GreedyArena.Run X T z m) (L : Layout) (shape : Shape) (step : ℕ) + (origin : Expr) (pub : Fin 5 → Word w) (s : Word w) (D : ℕ → Prop) + (initial : GreedyLevelPlan.Reads shape step a origin pub s m (Fintype.card X.Base) g z T) + (low : ∀ j, HeaderOperands.Supported (· < z) pub s m (visit shape step a origin j)) + (supported : ∀ j, HeaderOperands.Supported D pub s m (visit shape step a origin j)) + (floor : levelStart L 0 ≤ z) + (reads : ∀ j, Reads (levelStart L 0 ≤ ·) (eventLog (packetReports r j))) + (writes : ∀ j, Writes (z ≤ ·) (eventLog (packetReports r j))) (bound : ℕ) (budget : maxFuel a ≤ bound) : + SourceWalk (fun v input rs => ∃ f bits, f ≤ bound ∧ HeaderPacket.Run L pub s v input rs f bits ∧ + HeaderOperands.Supported D pub s input v) + (GreedyLevelPlan.visits shape step a origin) m r.reports := by + let P := fun j input rs => input = packetInput r j ∧ rs = packetReports r j ∧ Source r shape step origin j input rs + have lift {js : List Stage} {input : Memory w} {rs : List (Report w)} (walk : SourceWalk P js input rs) + (same : ∀ x < z, input x=m x) : + SourceWalk (fun v input rs => ∃ f bits, f ≤ bound ∧ HeaderPacket.Run L pub s v input rs f bits ∧ + HeaderOperands.Supported D pub s input v) + (js.map (visit shape step a origin)) input rs := by + induction walk with + | done => exact .done _ + | @next j js cur head tail stage _ ih => + obtain ⟨_,rfl,hsrc⟩ := stage + obtain ⟨ha,hb,hc⟩ := values r initial j + have hi := transfer _ same (low j).initial (supported j).initial + have hs := transfer _ same (low j).stop (supported j).stop + have hp k := transfer _ same ((low j).params k) ((supported j).params k) + have hargs : (fun k => ((visit shape step a origin j).params k).eval pub s cur) = + params r shape step origin j := (funext fun k => (hp k).1).trans hc + have srun : HeaderPacket.Run L pub s (visit shape step a origin j) cur (packetReports r j) (fuel a j) (choices X j) := by + refine ⟨fuel_pos _,?_,?_,reads j,fun x v hx => floor.trans (writes j x v hx)⟩ + · dsimp only + rw [hargs,hi.1,ha]; exact hsrc.native + · rw [hi.1,ha,hs.1,hb]; exact hsrc.progress + exact .next ⟨_,_,(fuel_le j).trans budget,srun,⟨hi.2,hs.2,fun k => (hp k).2⟩⟩ + (ih (fun x hx => (after_outside cur (writes j) (Nat.not_le_of_lt hx)).trans (same x hx))) + rw [← visits_eq] + exact lift (indexed_walk r shape step origin) (fun _ _ => rfl) + +end CompressorRecords.GreedyVisit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyPlannerFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyPlannerFootprint.lean new file mode 100644 index 0000000000..cf7782078d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyPlannerFootprint.lean @@ -0,0 +1,76 @@ +import OAI.Computability.VPVNP.CompressorGreedyVisitWalk +import OAI.Computability.VPVNP.CompressorHeaderOperands + +/-! # Reads of the six greedy launch recipes + +The recipes use the pitch word, three scalar fields, three old incidence +heads, and the selected table head. The locations are computed relative to +the first level of the block at the actual visit. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyVisit + +open BurstRAM PhaseRecipe BlockPlanner DescriptorSpace Greedy +open scoped Fin.CommRing +open private firstRecord recordsEnd controls prepare read projectionParams from + OAI.Computability.VPVNP.CompressorGreedyLevelPlan + +variable {w : ℕ} + +theorem planner_reads (D : ℕ → Prop) (pub : Fin 5 → Word w) (s : Word w) (mem : Memory w) + (F : Shape) (step a : ℕ) (origin : Expr) + (vert : (LevelFields.vertices step).ReadsFrom D pub s mem) + (degree : (LevelFields.degree step).ReadsFrom D pub s mem) + (resid : (LevelFields.residualLanes step).ReadsFrom D pub s mem) + (inc : ∀ j : Fin 6, (LevelFields.incidence F step j).ReadsFrom D pub s mem) + (base : origin.ReadsFrom D pub s mem) (j : Stage) : + HeaderOperands.Supported D pub s mem (visit F step a origin j) := by + have first (l : Expr) (hl : l.ReadsFrom D pub s mem) : (firstRecord step l).ReadsFrom D pub s mem := ⟨hl,vert⟩ + have ending (width : ℕ) (l : Expr) (hl : l.ReadsFrom D pub s mem) : + (recordsEnd step width l).ReadsFrom D pub s mem := ⟨first l hl,vert,trivial⟩ + have off : (GreedyLevelPlan.offsetBase step a origin).ReadsFrom D pub s mem := ending _ _ base + have shift : (GreedyLevelPlan.shiftBase step a origin).ReadsFrom D pub s mem := ending _ _ off + have zero : (GreedyLevelPlan.zeroAddress step a origin).ReadsFrom D pub s mem := ⟨shift,vert,degree⟩ + have proj (k : Fin 5) : (projectionParams F step a origin k).ReadsFrom D pub s mem := by + fin_cases k <;> first | exact inc 2 | exact shift | exact zero | exact resid | trivial + have init {d : ℕ} (width : ℕ) (rows : OperandRows d) (disps labels z : Expr) + (hd : disps.ReadsFrom D pub s mem) (hl : labels.ReadsFrom D pub s mem) (hz : z.ReadsFrom D pub s mem) : + HeaderOperands.Supported D pub s mem (prepare F step width rows disps labels z) := by + refine ⟨trivial,vert,?_⟩ + intro k + cases k using Fin.addCases with + | left i => simp only [prepare, Fin.addCases_left]; trivial + | right i => + simp only [prepare,Fin.addCases_right] + fin_cases i <;> first | exact degree | exact inc 0 | exact inc 1 | exact hd | exact hl | exact hz | exact first _ hl | trivial + have reader (k n width : ℕ) (labels : Expr) (hl : labels.ReadsFrom D pub s mem) : + HeaderOperands.Supported D pub s mem (read step k n width labels) := + ⟨first _ hl,ending _ _ hl,fun i => Fin.elim0 i⟩ + cases j with + | extract => exact ⟨trivial,⟨vert,degree⟩,proj⟩ + | zero => exact ⟨trivial,trivial,proj⟩ + | colorPrepare => exact init _ _ _ _ _ (inc 2) base zero + | colorRead => exact reader _ _ _ _ base + | tagPrepare => exact init _ _ _ _ _ shift off zero + | tagRead => exact reader _ _ _ _ off + +/-- When the launch state addresses the correct block, each loaded scalar +is in the data region, and the sole address load below it is the pitch. -/ +theorem scalar_support (D : ℕ → Prop) {pub : Fin 5 → Word w} {s : Word w} {mem : Memory w} + (L : Layout) (first step offset : ℕ) (entry : LevelFields.Entry L first pub s mem) + (pitch : D (pub 1-1).val) (allowed : D (levelStart L (first+step)+offset)) + (fit : levelStart L (first+step)+offset < 2^w) : + (LevelFields.scalar step offset).ReadsFrom D pub s mem := by + refine ⟨⟨⟨trivial,trivial,⟨trivial,trivial⟩,pitch⟩,trivial⟩,?_⟩ + rw [LevelFields.eval_address entry,Fin.val_natCast,Nat.mod_eq_of_lt fit] + exact allowed + +end CompressorRecords.GreedyVisit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareHeaderAccess.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareHeaderAccess.lean new file mode 100644 index 0000000000..75aaa1c600 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareHeaderAccess.lean @@ -0,0 +1,65 @@ +import OAI.Computability.VPVNP.CompressorGreedyRelocated +import OAI.Computability.VPVNP.CompressorLogAccess +import OAI.Computability.VPVNP.CompressorFlowFootprint + +/-! # Addresses touched by the relocated greedy initializer + +The control-word prefix runs entirely in registers. The next block clears +one label and writes the two words at the beginning of the vertex record. +The final block increments the private cursor. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy.PrepareAccess + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport Compression +open scoped Fin.CommRing +open private putHeader index_add base_index base_next base_bounds nextVertex + from OAI.Computability.VPVNP.CompressorRecordGreedyPrepare + +variable {w N width d : ℕ} {V : Type*} + +/-- Membership in the half-open interval of physical addresses from `lo` to `hi`. -/ +def Interval (lo hi x : ℕ) := lo ≤ x ∧ x < hi + +theorem head (L : WalkLayout w N width) (T : PortTables w) (m : Memory w) (i : Fin N) + (rs : Regs w 13) (labels : T.labels = Fin.ofNat _ L.origin) + (input : RowInput T (Fin.ofNat _ i.val) 0 rs) (unit : rs 11 = 1) + (first : rs 8 = L.base 0) (stride : rs 9 = Fin.ofNat _ (2+width)) + {es : List (Event w)} {out : Regs w 13} {mem : Memory w} + (run : trace (slotNumbers w d) (Fin.ofNat _ i.val) (putHeader d) rs m = some (es,out,mem)) : + Reads (fun _ ↦ False) es ∧ Writes (Interval L.origin L.limit) es := by + have lab : T.labels+Fin.ofNat _ i.val = L.label i := by rw [labels,index_add]; rfl + have x : es = [.tick,.tick,.tick,.tick,.write (L.label i) 0,.write (L.base i.val) (L.label i), + .tick,.tick,.write (L.base i.val+1) (L.base (i.val+1)),.tick] := by + have h := congrArg (fun v ↦ v.map Prod.fst) run + simpa (config := {decide := true}) [-Fin.ofNat_eq_cast,putHeader,trace,Op.effect, + BinaryOp.eval,Function.update,input.vertex,input.labels,unit,first,stride,base_index,base_next,lab] using h.symm + rw [x] + obtain ⟨hb,fit⟩ := base_bounds L i + have hl : Interval L.origin L.limit (L.label i).val := by + rw [Interval,L.label_val]; unfold WalkLayout.limit; have := i.isLt; omega + have hf : L.limit ≤ 2^w := L.fits + have one : (L.base i.val+1).val = (L.base i.val).val+1 := by + rw [Fin.val_add,Fin.val_one',Nat.mod_eq_of_lt (by omega : 1 < 2^w),Nat.mod_eq_of_lt (by omega)] + constructor <;> intro a v h + · simp at h + · simp only [List.mem_cons,List.not_mem_nil,or_false,false_or,reduceCtorEq,Event.write.injEq] at h + rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ + · exact hl + · exact ⟨by omega,by omega⟩ + · rw [Interval,one]; exact ⟨by omega,by omega⟩ + +theorem append {rd wr : ℕ → Prop} {es fs : List (Event w)} (p : Reads rd es ∧ Writes wr es) + (q : Reads rd fs ∧ Writes wr fs) : Reads rd (es++fs) ∧ Writes wr (es++fs) := + ⟨fun a v h ↦ (List.mem_append.mp h).elim (p.1 a v) (q.1 a v), + fun a v h ↦ (List.mem_append.mp h).elim (p.2 a v) (q.2 a v)⟩ + +end CompressorRecords.Greedy.PrepareAccess + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareProgress.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareProgress.lean new file mode 100644 index 0000000000..f2a2719b74 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareProgress.lean @@ -0,0 +1,119 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy +import OAI.Computability.VPVNP.CompressorSourceOnline + +/-! +# Cursor progress of the native greedy preparation scans + +Each call starts at the index of its vertex and returns the following index. +The memory before that call contains the prepared prefix of the directory. +This gives the exclusive stop guard for both the color and offset scans. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyArena + +open BurstRAM Compression Greedy SourceOnline +open scoped Fin.CommRing + +namespace Assignment + +variable {w N width d arity n : ℕ} {V A : Type*} +variable {L : WalkLayout w N width} {T : PortTables w} {G : SlotGraph V d} {order : V ≃ Fin N} + {rows : OperandRows d} {m : Memory w} {encode : A → Word w} {label : V → A} + +/-- In a native preparation scan, every reported return advances to the next +vertex and the final cursor reaches the exclusive vertex count. -/ +theorem prep_progress (r : Assignment L T G order rows arity n m encode label) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (space : L.limit < 2 ^ w) (outside : GraphOutside (d := d) L T order) + (size : ∀ i : Fin N, (rowWords T G order (order.symm i) rows).length = width) : + Progress (N : Word w) 0 r.prep := by + let ptrs := fun i : Fin N ↦ rowWords T G order (order.symm i) rows + let mem := L.prefixMemory ptrs m + let P := ((Relocated.preparePass rows).table.instantiate w (Relocated.publicWords d L T)).program + let fuel := 1 + (Relocated.prepareCode rows).length + have fit : N < 2 ^ w := by unfold WalkLayout.limit at space; omega + have loop (left k : ℕ) (stop : k + left = N) (rs : List (Report w)) + (run : runSegment P fuel (some (Fin.ofNat _ k)) (mem k) (List.replicate left []) = some rs) : + Progress (N : Word w) (Fin.ofNat _ k) rs := by + induction left generalizing k rs with + | zero => + have empty : [] = rs := Option.some.inj run + subst rs + simp only [Nat.add_zero] at stop + subst k + exact .done le_rfl + | succ left ih => + let i : Fin N := ⟨k, by omega⟩ + obtain ⟨es, he, hm, _, _⟩ := Relocated.prepare_one L T G order rows (mem k) i labels + (L.prefixMemory_tables ptrs m i.isLt.le rep outside) space outside (size i) + have next : after (mem k) es = mem (k+1) := hm.trans (L.write_prefixMemory ptrs m size i) + rw [List.replicate_succ, runSegment, he] at run + change (runSegment P fuel (some (Fin.ofNat _ (k+1))) (after (mem k) es) + (List.replicate left [])).map _ = some rs at run + rw [next] at run + obtain ⟨tail, ht, rfl⟩ := Option.map_eq_some_iff.mp run + refine .next (next := Fin.ofNat _ (k+1)) ?_ rfl (ih _ (by omega) _ ht) + change k % (2 ^ w) < N % (2 ^ w) + rw [Nat.mod_eq_of_lt (by omega : k < 2 ^ w), Nat.mod_eq_of_lt fit] + omega + have zero : Fin.ofNat _ 0 = (0 : Word w) := Fin.ext (Nat.zero_mod _) + rw [← zero] + apply loop N 0 (Nat.zero_add N) + rw [show mem 0 = m from L.prefixMemory_zero ptrs m, zero] + exact r.prepRun + +end Assignment + +namespace Run + +variable {w a g origin : ℕ} {X : ShrinkingState a g} {T : IncidenceDirectory w} + {m : Memory w} (r : Run X T origin m) + +open private projection_frame from OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy + +include r in +private theorem projected_below (z : ℕ) (hz : z < origin) : projectedMemory X T origin m z = m z := by + have hb := bounds origin (Fintype.card X.Base) a + change origin + _ ≤ _ ∧ _ at hb + exact projection_frame X T origin m r.room r.projection z (by omega) + +/-- Progress for the color initializer on the memory left by tag projection. -/ +theorem color_prepare_progress : Progress ((Fintype.card X.Base : ℕ) : Word w) 0 r.color.prep := by + let n := Fintype.card X.Base + have hb := bounds origin n a + change origin + n ≤ _ ∧ _ at hb + have room : greedyStop origin n a < 2 ^ w := r.room + have colorFit := colorFits origin n a w Fintype.card_pos room + have baseFit := r.old.baseFits.trans (by omega : origin ≤ 2 ^ w) + have preRep := r.old.preserve r.input (projected_below r) + exact r.color.prep_progress rfl (tables_rep preRep _ _ _ (by omega) baseFit) + (by change offsetBase origin n a < 2 ^ w; omega) + (r.old.graphOutside _ le_rfl _ _ _) (fun i ↦ rowWords_color_length _ _ _ _) + +/-- Progress for the offset initializer on the memory left by the color reader. -/ +theorem tag_prepare_progress : Progress ((Fintype.card X.Base : ℕ) : Word w) 0 r.offsets.prep := by + let n := Fintype.card X.Base + have hb := bounds origin n a + change origin + n ≤ _ ∧ _ at hb + have room : greedyStop origin n a < 2 ^ w := r.room + have colorFit := colorFits origin n a w Fintype.card_pos room + have baseFit := r.old.baseFits.trans (by omega : origin ≤ 2 ^ w) + have colorBelow (z : ℕ) (hz : z < origin) : r.color.post z = m z := + (r.color.frame z (.inl hz)).trans (projected_below r z hz) + have colorRep := r.old.preserve r.input colorBelow + exact r.offsets.prep_progress rfl (tables_rep colorRep _ _ _ (by omega) baseFit) + (by change shiftBase origin n a < 2 ^ w; omega) + (r.old.graphOutside _ (by change origin ≤ offsetBase origin n a; omega) _ _ _) + (fun i ↦ by rw [rowWords_tag_length, tagTests_length, Nat.mul_comm]) + +end Run + +end CompressorRecords.GreedyArena + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareRowsAccess.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareRowsAccess.lean new file mode 100644 index 0000000000..1d198ee21f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareRowsAccess.lean @@ -0,0 +1,164 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedyInit +import OAI.Computability.VPVNP.CompressorSourceTransport + +/-! +# External addresses of greedy row preparation + +Each row reads the chosen incidence's mate and then writes the operand +addresses in order. The addresses written into the row may name shifts or +labels. The preparer itself only accesses the two mate arrays and its own +consecutive destination cells. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy.PrepareAccess + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression SourceTransport + +open private valueCode packed_eq mate_trace emit_trace emit_list regValue next_val from + OAI.Computability.VPVNP.CompressorRecordGreedyInit + +variable {V : Type*} {N w d : ℕ} + +private theorem split_trace {r k : ℕ} {pub : Fin k → Word w} {s : Word w} {left right : List (Op r k)} + {rs mid last : Regs w r} {m midMem finalMem : Memory w} {es logs : List (Event w)} + (h₁ : trace pub s left rs m = some (es,mid,midMem)) + (h : trace pub s (left++right) rs m = some (logs,last,finalMem)) : + ∃ fs, trace pub s right mid midMem = some (fs,last,finalMem) ∧ logs = es++fs := by + rw [trace_append,h₁] at h + simp only [Option.bind_some, Option.map_eq_some_iff] at h + obtain ⟨⟨fs,last',final'⟩,ht,he⟩ := h + obtain ⟨rfl, rfl, rfl⟩ := Prod.mk.inj he + exact ⟨fs,ht,rfl⟩ + +private theorem operand (s : Word w) (m : Memory w) (rs : Regs w 13) (a : Operand d) + (rd : ℕ → Prop) {es out m'} (run : trace (slotNumbers w d) s (emitOperand a) rs m = some (es,out,m')) : + Reads rd es ∧ Writes (fun z ↦ z = (rs 1).val) es := by + have ht := congrArg (Option.map Prod.fst) run + cases a + case' increment remote i => cases remote + all_goals simp (config := {decide := true}) [trace, Op.effect, valueCode, emitOperand, + BinaryOp.eval, Function.update] at ht + all_goals rw [← ht] + all_goals simp [Reads, Writes, List.mem_cons, Event.write.injEq] + +private theorem operands (s : Word w) (m : Memory w) (rs : Regs w 13) (one : rs 11 = 1) + (args : List (Operand d)) (rd : ℕ → Prop) (fit : (rs 1).val+args.length < 2^w) + {es out m'} (run : trace (slotNumbers w d) s (args.flatMap emitOperand) rs m = some (es,out,m')) : + Reads rd es ∧ Writes (fun z ↦ (rs 1).val ≤ z ∧ z < (rs 1).val+args.length) es := by + induction args generalizing m rs es out m' with + | nil => + have h : es = [] := (Prod.mk.inj (Option.some.inj run)).1.symm + simp [h, Reads, Writes] + | cons a args ih => + obtain ⟨head,mid,hh,_,_,hd,keep⟩ := emit_trace s m rs one a + obtain ⟨tail,ht,rfl⟩ := split_trace hh run + have hv : (mid 1).val = (rs 1).val+1 := hd ▸ next_val (rs 1) (by simp at fit; omega) + have h₁ := operand s m rs a rd hh + have h₂ := ih _ mid ((keep 11 (by decide) (by decide) (by decide)).trans one) + (by simp only [List.length_cons] at fit; omega) ht + constructor + · intro x v h + exact (List.mem_append.mp h).elim (h₁.1 x v) (h₂.1 x v) + · intro x v h + simp only [List.length_cons] + rcases List.mem_append.mp h with hx | hx + · have := h₁.2 x v hx + omega + · have := h₂.2 x v hx + omega + +private theorem mate (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (s : Word w) (x : V) (t : Bool × Fin d) (m : Memory w) (dest : Word w) (rs : Regs w 13) + (h : RowInput T (vertexNumber order x) dest rs) (rep : T.Represents G order m) + (rd wr : ℕ → Prop) + (cells : ∀ e : V × Fin d, ∀ b ∈ [T.outgoing,T.incoming], rd (b+portNumber order e).val) + {es out m'} (run : trace (slotNumbers w d) s (loadMate t.1 t.2) rs m = some (es,out,m')) : + Reads rd es ∧ Writes wr es := by + have ht := congrArg (Option.map Prod.fst) run + obtain ⟨b,i⟩ := t + have packed := packed_eq rep x i + cases b + all_goals simp (config := {decide := true}) [loadMate, trace, Op.effect, BinaryOp.eval, + Function.update, h.vertex, h.degree, h.outgoing, h.incoming, packed] at ht + all_goals rw [← ht] + all_goals constructor + all_goals intro a v ha + all_goals simp only [List.mem_cons, List.not_mem_nil, Event.read.injEq, reduceCtorEq, + false_or, or_false] at ha + all_goals first + | exact ha.elim + | obtain ⟨ha,_⟩ := ha; subst a; exact cells (x,i) _ (by simp) + +private theorem row (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) (s : Word w) + (x : V) (t : Bool × Fin d) (args : List (Operand d)) (m : Memory w) (dest : Word w) (rs : Regs w 13) + (h : RowInput T (vertexNumber order x) dest rs) (rep : T.Represents G order m) + (fit : dest.val+args.length < 2^w) (rd : ℕ → Prop) + (cells : ∀ e : V × Fin d, ∀ b ∈ [T.outgoing,T.incoming], rd (b+portNumber order e).val) + {es out m'} (run : trace (slotNumbers w d) s (initRow t args) rs m = some (es,out,m')) : + Reads rd es ∧ Writes (fun z ↦ dest.val ≤ z ∧ z < dest.val+args.length) es := by + obtain ⟨head,mid,hh,_,_,hi,h₁,_⟩ := mate_trace T G order m rep s dest rs x t h + obtain ⟨tail,ht,rfl⟩ := split_trace hh run + let wr := fun z ↦ dest.val ≤ z ∧ z < dest.val+args.length + have hhead := mate T G order s x t m dest rs h rep rd wr cells hh + have htail := operands s m mid h₁ args rd (hi.dest ▸ fit) ht + rw [hi.dest] at htail + exact ⟨fun a v ha ↦ (List.mem_append.mp ha).elim (hhead.1 a v) (htail.1 a v), + fun a v ha ↦ (List.mem_append.mp ha).elim (hhead.2 a v) (htail.2 a v)⟩ + +/-- The complete initializer reads only at directed mate cells and writes +only in the half-open interval of the actual row words. -/ +theorem rows (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) (s : Word w) + (x : V) (rows : OperandRows d) (m : Memory w) (dest : Word w) (rs : Regs w 13) + (h : RowInput T (vertexNumber order x) dest rs) (rep : T.Represents G order m) + (fit : dest.val+(rowWords T G order x rows).length < 2^w) + (free : T.Free (d := d) order dest.val (rowWords T G order x rows).length) + (rd : ℕ → Prop) (cells : ∀ e : V × Fin d, ∀ b ∈ [T.outgoing,T.incoming], rd (b+portNumber order e).val) + {es out m'} (run : trace (slotNumbers w d) s (initRows rows) rs m = some (es,out,m')) : + Reads rd es ∧ Writes (fun z ↦ dest.val ≤ z ∧ z < dest.val+(rowWords T G order x rows).length) es := by + induction rows generalizing m dest rs es out m' with + | nil => + have hnil : es = [] := (Prod.mk.inj (Option.some.inj run)).1.symm + simp [hnil, Reads, Writes] + | cons one tail ih => + obtain ⟨t,args⟩ := one + let words := args.map (operandAddress T G order x t) + let rest := rowWords T G order x tail + have hwords : (rowWords T G order x ((t,args)::tail)).length = words.length+rest.length := + List.length_append + rw [hwords] at fit free ⊢ + have len : words.length = args.length := List.length_map _ + have hd : (advance dest words.length).val = dest.val+words.length := advance_val _ _ (by omega) + have left : T.Free (d := d) order dest.val words.length := by + intro e b hb + have := free e b hb + omega + have right : T.Free (d := d) order (advance dest words.length).val rest.length := by + intro e b hb + have := free e b hb + omega + obtain ⟨head,mid,hh,_,_,hmid⟩ := initRow_trace T G order m rep s dest rs x t h args + obtain ⟨next,ht,rfl⟩ := split_trace hh run + have hhead := row T G order s x t args m dest rs h rep (by omega) rd cells hh + have htail := ih (writeRow m dest words) (advance dest words.length) mid (len ▸ hmid) + (keep_tables T G order m dest words (by omega) rep left) + (by change (advance dest words.length).val+rest.length < _; omega) right ht + constructor + · intro a v ha + exact (List.mem_append.mp ha).elim (hhead.1 a v) (htail.1 a v) + · intro a v ha + rcases List.mem_append.mp ha with h₁ | h₂ + · have := hhead.2 a v h₁ + omega + · have hv := htail.2 a v h₂ + change (advance dest words.length).val ≤ a.val ∧ a.val < (advance dest words.length).val+rest.length at hv + omega + +end CompressorRecords.Greedy.PrepareAccess + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareScanAccess.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareScanAccess.lean new file mode 100644 index 0000000000..d42f7f19f7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareScanAccess.lean @@ -0,0 +1,53 @@ +import OAI.Computability.VPVNP.CompressorGreedyPrepareVisitAccess +import OAI.Computability.VPVNP.RAMChoicePrefix + +/-! # External accesses of the complete greedy preparation sweep + +Each row writer leaves the old mate tables readable for the next row. +The external address bounds therefore hold throughout the native scan. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy.PrepareAccess + +open BurstRAM SourceTransport Compression +open scoped Fin.CommRing + +variable {w N width d : ℕ} {V : Type*} + +theorem scan (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows' : OperandRows d) (m : Memory w) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (space : L.limit < 2^w) (free : GraphOutside (d := d) L T order) + (size : ∀ i : Fin N, (rowWords T G order (order.symm i) rows').length = width) + (rd : ℕ → Prop) (cells : ∀ e : V × Fin d, ∀ b ∈ [T.outgoing,T.incoming], rd (b+portNumber order e).val) + (rs : List (Report w)) + (run : runSegment ((Relocated.preparePass rows').table.instantiate w (Relocated.publicWords d L T)).program + (1+(Relocated.prepareCode rows').length) (some 0) m (List.replicate N []) = some rs) : + LogAccess rd (Interval L.origin L.limit) rs := by + let P := ((Relocated.preparePass rows').table.instantiate w (Relocated.publicWords d L T)).program + let fuel := 1+(Relocated.prepareCode rows').length + apply OrdinalRun.footprint P fuel (Fin.ofNat (2^w)) N (fun _ ↦ T.Represents G order) rd + (Interval L.origin L.limit) _ 0 _ m rs (by simp) rep run + intro j hj mem hRep bits row executed + let i : Fin N := ⟨j,hj⟩ + obtain ⟨es,he,read,write⟩ := one L T G order rows' mem i labels hRep space free (size i) rd cells + have eq := (execute_prefix_unique he (show execute P fuel (P.start (Fin.ofNat _ j)) mem ([]++bits) = + some row from executed)).2 + subst row + have keep (e : V × Fin d) (b : Word w) (hb : b ∈ [T.outgoing,T.incoming]) : + after mem es (b+portNumber order e).val = mem (b+portNumber order e).val := by + apply SourceTransport.after_outside mem write + have := free e b hb + rintro ⟨x,y⟩; omega + exact ⟨rfl,⟨hRep.degree,hRep.fits,hRep.vertices,fun e ↦ (keep e _ (by simp)).trans (hRep.outgoing e), + fun e ↦ (keep e _ (by simp)).trans (hRep.incoming e)⟩,read,write⟩ + +end CompressorRecords.Greedy.PrepareAccess + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareVisitAccess.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareVisitAccess.lean new file mode 100644 index 0000000000..f53ccf98f2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyPrepareVisitAccess.lean @@ -0,0 +1,101 @@ +import OAI.Computability.VPVNP.CompressorGreedyPrepareHeaderAccess +import OAI.Computability.VPVNP.CompressorGreedyPrepareRowsAccess + +/-! # Memory accesses of one relocated greedy record writer + +The public control-word loader and the final cursor increment have no +external probes. The header and operand writers stay inside the current +walk layout, and the only external reads are the two mate tables. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy.PrepareAccess + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport Compression +open scoped Fin.CommRing +open private header_written base_bounds nextVertex putHeader from OAI.Computability.VPVNP.CompressorRecordGreedyPrepare +open private split_trace from OAI.Computability.VPVNP.CompressorGreedyPrepareRowsAccess +open private loaded loadControls trace_slots from OAI.Computability.VPVNP.CompressorGreedyRelocated + +variable {w N width d : ℕ} {V : Type*} + +private theorem body (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows' : OperandRows d) (m : Memory w) (i : Fin N) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (space : L.limit < 2^w) (free : GraphOutside (d := d) L T order) + (size : (rowWords T G order (order.symm i) rows').length = width) + (rd : ℕ → Prop) (cells : ∀ e : V × Fin d, ∀ b ∈ [T.outgoing,T.incoming], rd (b+portNumber order e).val) + (rs : Regs w 13) (input : RowInput T (Fin.ofNat _ i.val) 0 rs) (unit : rs 11 = 1) + (first : rs 8 = L.base 0) (stride : rs 9 = Fin.ofNat _ (2+width)) + {es out last} (run : trace (slotNumbers w d) (Fin.ofNat _ i.val) (prepareBody rows') rs m = + some (es,out,last)) : Reads rd es ∧ Writes (Interval L.origin L.limit) es := by + let s := Fin.ofNat (2^w) i.val + let b := L.base i.val + let dest := b+1+1 + let mid := writeRow (writeMemory m (L.label i) 0) b [L.label i,L.base (i.val+1)] + obtain ⟨bs,bend⟩ := base_bounds L i + change b.val = _ at bs + change b.val+(2+width) ≤ L.limit at bend + have hd : dest.val = b.val+2 := advance_val b 2 (by omega) + obtain ⟨hs,hregs,hRun,_,_,hstate⟩ := header_written L T m i d rs labels input unit first stride + change trace (slotNumbers w d) s (putHeader d) rs m = some (hs,hregs,mid) at hRun + have hacc := head L T m i rs labels input unit first stride hRun + have table (e : V × Fin d) (x : Word w) (hx : x ∈ [T.outgoing,T.incoming]) : + mid (x+portNumber order e).val = m (x+portNumber order e).val := by + rw [← trace_after hRun] + apply SourceTransport.after_outside m hacc.2 + have := free e x hx + rintro ⟨ha,hb⟩; omega + have rep' : T.Represents G order mid := + ⟨rep.degree,rep.fits,rep.vertices,fun e ↦ (table e _ (by simp)).trans (rep.outgoing e), + fun e ↦ (table e _ (by simp)).trans (rep.incoming e)⟩ + have hin : RowInput T (vertexNumber order (order.symm i)) dest hregs := by + simpa only [vertexNumber,Equiv.apply_symm_apply] using hstate + have wordsFit : dest.val+(rowWords T G order (order.symm i) rows').length < 2^w := by rw [size]; omega + have wordsFree := free.free dest.val (rowWords T G order (order.symm i) rows').length (by omega) (by rw [size]; omega) + obtain ⟨ms,mregs,mRun,_,_,_⟩ := initRows_trace T G order s (order.symm i) rows' mid dest hregs hin rep' wordsFit wordsFree + have macc := rows T G order s (order.symm i) rows' mid dest hregs hin rep' wordsFit wordsFree rd cells mRun + change trace _ s ((putHeader d ++ initRows rows') ++ nextVertex d) rs m = _ at run + rw [List.append_assoc] at run + obtain ⟨ts,tRun,rfl⟩ := split_trace hRun run + obtain ⟨ns,nRun,rfl⟩ := split_trace mRun tRun + have no : countProbes ns = 0 := by + have h := congrArg (fun z ↦ z.map (countProbes ∘ Prod.fst)) nRun + simpa (config := {decide := true}) [nextVertex,trace,Op.effect,BinaryOp.eval,Function.update,countProbes] using h.symm + apply append ⟨fun a v h ↦ (hacc.1 a v h).elim,hacc.2⟩ + apply append _ (FlowFootprint.bounds_of_noProbes rd (Interval L.origin L.limit) no) + refine ⟨macc.1,fun a v h ↦ ?_⟩ + obtain ⟨h₁,h₂⟩ := macc.2 a v h + rw [size] at h₂ + exact ⟨by omega,by omega⟩ + +/-- Native single vertex visit and the complete bounds on its external addresses. -/ +theorem one (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows' : OperandRows d) (m : Memory w) (i : Fin N) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (space : L.limit < 2^w) (free : GraphOutside (d := d) L T order) + (size : (rowWords T G order (order.symm i) rows').length = width) + (rd : ℕ → Prop) (cells : ∀ e : V × Fin d, ∀ b ∈ [T.outgoing,T.incoming], rd (b+portNumber order e).val) : + let P := ((Relocated.preparePass rows').table.instantiate w (Relocated.publicWords d L T)).program + ∃ es, execute P (1+(Relocated.prepareCode rows').length) (P.start (Fin.ofNat _ i.val)) m [] = + some ⟨es,some (Fin.ofNat _ (i.val+1))⟩ ∧ Reads rd es ∧ Writes (Interval L.origin L.limit) es := by + let s := Fin.ofNat (2^w) i.val + obtain ⟨a,r,ha,_,hpa,hr,hu,hfirst,hstride⟩ := loaded L T m s d + obtain ⟨b,last,hb,hresult,_,_⟩ := prepareBody_trace L T G order rows' m i labels rep space free size r hr hu hfirst hstride + have acc := append (FlowFootprint.bounds_of_noProbes rd (Interval L.origin L.limit) hpa) + (body L T G order rows' m i labels rep space free size rd cells r hr hu hfirst hstride hb) + refine ⟨a++b,?_,acc⟩ + let M := (template (Relocated.prepareCode rows') 0).instantiate w (Relocated.publicWords d L T) + change execute M.program (1+(Relocated.prepareCode rows').length) ⟨M.entry,s,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + dsimp only [M] + rw [execute_template,run_eq_trace,Relocated.prepareCode,trace_append,ha] + simp only [Option.bind_some,trace_slots,s,hb,Option.map_some,hresult,List.append_nil] + +end CompressorRecords.Greedy.PrepareAccess + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyProjectionAccess.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyProjectionAccess.lean new file mode 100644 index 0000000000..ba99689d58 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyProjectionAccess.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy +import OAI.Computability.VPVNP.CompressorLogAccess + +/-! # Memory used to prepare the shrinking tag operands + +The first pass reads the old displacement column and writes the projected +tags. The second pass publishes their zero operand. Both label computations +can still read the old directed incidence tables afterward. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyArena.Run + +open BurstRAM Compression Greedy +open scoped Fin.CommRing +open private projection_frame from OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy + +variable {w a g origin : ℕ} {X : ShrinkingState a g} {T : IncidenceDirectory w} {m : Memory w} +variable (r : Run X T origin m) +local notation "N" => Fintype.card X.Base +local notation "D" => (2:ℕ)^a +local notation "limit" => greedyStop origin (Fintype.card X.Base) a +local notation "project" => projectionWords T origin (Fintype.card X.Base) a g + +include r in +theorem projection_access (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) : + LogAccess (fun z ↦ lo ≤ z ∧ z < limit) (fun z ↦ origin ≤ z ∧ z < limit) + (ShrinkTagColumn.scan project 0 (N*D) m) := by + obtain ⟨h₁,h₂,h₃⟩ := bounds origin N a + change origin+N ≤ _ at h₁ + have fit := r.room + have old : T.shift.val+N*D ≤ origin := (Nat.add_le_add_left (Nat.mul_le_mul_right D + (Nat.le_mul_of_pos_right N (Nat.two_pow_pos (packingLaneBits a g)))) _).trans (r.old 2) + have dst : (project 1).val = shiftBase origin N a := Nat.mod_eq_of_lt (by omega) + apply LogAccess.mono (ShrinkTagColumn.scan_footprints project (N*D) m) + · rintro z ⟨i,hi,rfl⟩ + change lo ≤ (T.shift + (i : Word w)).val ∧ (T.shift + (i : Word w)).val < _ + rw [Fin.val_add,Fin.val_natCast,Nat.add_mod_mod,Nat.mod_eq_of_lt (by omega)] + exact ⟨(low 2).trans (Nat.le_add_right ..),by omega⟩ + · rintro z ⟨i,hi,rfl⟩ + change origin ≤ (project 1+(i : Word w)).val ∧ (project 1+(i : Word w)).val < _ + rw [Fin.val_add,Fin.val_natCast,Nat.add_mod_mod,dst,Nat.mod_eq_of_lt (by omega)]; omega + +include r in +theorem zero_access (lo : ℕ) : + LogAccess (fun z ↦ lo ≤ z ∧ z < limit) (fun z ↦ origin ≤ z ∧ z < limit) + [ShrinkTagColumn.zeroRow project] := by + have h := bounds origin N a + change origin+N ≤ _ ∧ _ at h + have fit := r.room + have zero : (project 2).val = zeroCell origin N a := Nat.mod_eq_of_lt (Nat.lt_of_succ_lt fit) + apply LogAccess.mono (ShrinkTagColumn.zero_footprints project) + · exact fun _ hf ↦ hf.elim + · rintro z rfl; rw [zero]; change origin ≤ shiftBase origin N a+N*D ∧ shiftBase origin N a+N*D < limit; omega + +include r in +private theorem degreeFits : D < 2^w := by + have h := bounds origin N a + change origin+N ≤ _ ∧ _ at h + have nd := r.old.baseFits + have fit := r.room + exact (Nat.le_mul_of_pos_left _ (Fintype.card_pos : 0 Fintype.card X.Base + +/-- Cursor guards for the native color reader in the shrinking run. -/ +theorem color_read_progress : + let L := colorLayout w origin N a r.room + Progress (L.base N) (L.base 0) r.color.reads := by + have hb := bounds origin N a + have room := r.room + exact r.color.read_progress (fun _ ↦ rowWords_color_length _ _ _ _) + (by rw [color_limit]; omega) (colorFits origin N a w Fintype.card_pos room) + +/-- Cursor guards for the native offset reader in the shrinking run. -/ +theorem tag_read_progress : + let L := tagLayout w origin N a r.room + Progress (L.base N) (L.base 0) r.offsets.reads := by + have hb := bounds origin N a + have room := r.room + have fit := (packingTagBits_sufficient (2 ^ a)).trans_le (Nat.pow_le_pow_right (by decide) r.tagFit) + exact r.offsets.read_progress (fun _ ↦ by rw [rowWords_tag_length, tagTests_length, Nat.mul_comm]) + (by rw [tag_limit]; omega) fit + +end Run + +end CompressorRecords.GreedyArena + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyReaderAccess.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyReaderAccess.lean new file mode 100644 index 0000000000..734eccee3b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyReaderAccess.lean @@ -0,0 +1,164 @@ +import OAI.Computability.VPVNP.CompressorGreedyWalkValid +import OAI.Computability.VPVNP.CompressorGreedyVisitAccess +import OAI.Computability.VPVNP.CompressorLogAccess +import OAI.Computability.VPVNP.CompressorGreedyRecordRanges + +/-! +# External memory touched by the greedy readers + +As the cursor advances through the directory, only the labels can change. +The immutable row fields determine both the direct field reads and the +addresses of the indirect operand reads. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyArena + +open BurstRAM Compression Greedy SourceTransport +open scoped Fin.CommRing + +namespace Assignment + +variable {w N width d arity n : ℕ} {V A : Type*} +variable {L : WalkLayout w N width} {T : PortTables w} {G : SlotGraph V d} {order : V ≃ Fin N} + {rows : OperandRows d} {m : Memory w} {encode : A → Word w} {label : V → A} + +open private has_visit from OAI.Computability.VPVNP.CompressorGreedyWalkValid +open private base_bounds from OAI.Computability.VPVNP.CompressorRecordGreedyPrepare +open private stores_iff_fields from OAI.Computability.VPVNP.CompressorRecordGreedyDirectory + +/-- Reads in each prepared row are direct header or pointer reads, or indirect +reads at one of the row's operand addresses. Writes affect only label cells. -/ +theorem read_access (r : Assignment L T G order rows arity n m encode label) + (size : ∀ i : Fin N, (rowWords T G order (order.symm i) rows).length = width) + (used : arity*n = width) (fit : n < 2^w) (space : L.limit < 2^w) + (rd wr : ℕ → Prop) + (dir : ∀ z, L.origin ≤ z → z < L.limit → rd z) + (ptr : ∀ i : Fin N, ∀ p ∈ rowWords T G order (order.symm i) rows, rd p.val) + (labels : ∀ i : Fin N, wr (L.label i).val) : + LogAccess rd wr r.reads := by + let ptrs := fun i : Fin N ↦ rowWords T G order (order.symm i) rows + let initial := L.initialMemory ptrs m + let fixed (mem : Memory w) := ∀ z, z < L.origin ∨ L.origin+N ≤ z → mem z = initial z + let P := (visitMachine w arity n).program + let fuel := 1+(visitCode arity n).length + have scan (left k : ℕ) (stop : k+left = N) (mem : Memory w) (keep : fixed mem) + (rs : List (Report w)) (run : runSegment P fuel (some (L.base k)) mem (List.replicate left []) = some rs) : + LogAccess rd wr rs := by + induction left generalizing k mem rs with + | zero => + have empty : [] = rs := Option.some.inj run + subst rs + exact ⟨fun _ _ h ↦ False.elim (List.not_mem_nil h), fun _ _ h ↦ False.elim (List.not_mem_nil h)⟩ + | succ left ih => + let i : Fin N := ⟨k, by omega⟩ + let b := L.base k + have repr : L.Represents initial mem id (Equiv.refl (Fin N)) (fun j ↦ mem (L.label j).val) := + ⟨fun _ ↦ rfl,keep⟩ + obtain ⟨dst, next, stored⟩ := repr.record L size i + obtain ⟨bs, bound⟩ := base_bounds L i + change b.val = _ at bs + change b.val+(2+width) ≤ L.limit at bound + have b1 : (b+1).val = b.val+1 := advance_val b 1 (by omega) + have b2 : (b+1+1).val = b.val+2 := advance_val b 2 (by omega) + have values := (stores_iff_fields mem (b+1+1) (ptrs i) (by rw [b2,size i]; omega)).mp stored + have args (j : ℕ) (hj : j < arity*n) : + rd (advance (b+1+1) j).val ∧ rd (mem (advance (b+1+1) j).val).val := by + have pos : j < width := used ▸ hj + have addr : (advance (b+1+1) j).val = (b+1+1).val+j := advance_val _ _ (by omega) + rw [addr] + refine ⟨dir _ (by omega) (by omega), ?_⟩ + have idx : j < (ptrs i).length := (size i).symm ▸ pos + rw [values ⟨j,idx⟩] + exact ptr i _ (List.getElem_mem idx) + obtain ⟨v, es, he, hm, _⟩ := has_visit mem b arity n fit + have access := Greedy.visit_access mem b arity n rd wr (dir _ (by omega) (by omega)) + (dir _ (by omega) (by omega)) args (dst ▸ labels i) _ he + rw [show mem b.val = L.label i from dst] at hm + rw [show mem (b+1).val = L.base (k+1) from next] at he + rw [List.replicate_succ,runSegment,he] at run + obtain ⟨tail, ht, rfl⟩ := Option.map_eq_some_iff.mp run + have nextKeep : fixed (after mem es) := by + intro z hz + rw [hm] + have away : z ≠ (L.label i).val := by rw [WalkLayout.label_val]; have := i.isLt; omega + exact (ite_eq_right away).trans (keep z hz) + obtain ⟨tr, tw⟩ := ih _ (by omega) _ nextKeep _ ht + exact ⟨fun a v ha ↦ (List.mem_append.mp ha).elim (access.1 a v) (tr a v), + fun a v ha ↦ (List.mem_append.mp ha).elim (access.2 a v) (tw a v)⟩ + apply scan N 0 (Nat.zero_add _) initial (fun _ _ ↦ rfl) + simpa only [r.prepMemory] using r.readRun + +end Assignment + +namespace Run + +variable {w a g origin : ℕ} {X : ShrinkingState a g} {T : IncidenceDirectory w} + {m : Memory w} (r : Run X T origin m) +local notation "n" => Fintype.card X.Base + +/-- Both direct record reads and indirect color-label reads are above the +old-column lower bound. Every write is to the fresh greedy allocation. -/ +theorem color_read_access (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) : + LogAccess (fun z ↦ lo ≤ z ∧ z < greedyStop origin n a) + (fun z ↦ origin ≤ z ∧ z < greedyStop origin n a) r.color.reads := by + have ho := r.old 0 + have hl := low 0 + have hb := bounds origin n a + change origin+n ≤ _ ∧ _ at hb + have room := r.room + apply r.color.read_access (fun i ↦ rowWords_color_length _ _ _ _) (Nat.one_mul _) + (colorFits origin n a w Fintype.card_pos r.room) + (by change offsetBase origin n a < 2^w; omega) + · intro z hz hz' + change origin ≤ z at hz + change z < offsetBase origin n a at hz' + exact ⟨by omega, by omega⟩ + · intro i p hp + have range := r.color_pointer_range _ _ hp + exact ⟨by omega, by omega⟩ + · intro i + rw [WalkLayout.label_val] + change origin ≤ origin+i.val ∧ origin+i.val < greedyStop origin n a + have := i.isLt + exact ⟨by omega, by omega⟩ + +/-- The offset reader dereferences only offset labels, projected displacement +words and the shared zero, and writes within the fresh allocation. -/ +theorem tag_read_access (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) : + LogAccess (fun z ↦ lo ≤ z ∧ z < greedyStop origin n a) + (fun z ↦ origin ≤ z ∧ z < greedyStop origin n a) r.offsets.reads := by + have ho := r.old 0 + have hl := low 0 + have hb := bounds origin n a + change origin+n ≤ _ ∧ _ at hb + have room := r.room + have big := Nat.le_mul_of_pos_left (2+4*WalkLayout.tagCount (2^a)) (Fintype.card_pos (α := X.Base)) + have fit : WalkLayout.tagCount (2^a) < 2^w := by + unfold shiftBase at hb + omega + apply r.offsets.read_access (fun i ↦ by rw [rowWords_tag_length,tagTests_length,Nat.mul_comm]) rfl fit + (by change shiftBase origin n a < 2^w; omega) + · intro z hz hz' + change offsetBase origin n a ≤ z at hz + change z < shiftBase origin n a at hz' + exact ⟨by omega, by omega⟩ + · intro i p hp + have range := r.tag_pointer_range _ _ hp + exact ⟨by omega, range.2⟩ + · intro i + rw [WalkLayout.label_val] + change origin ≤ offsetBase origin n a+i.val ∧ offsetBase origin n a+i.val < greedyStop origin n a + have := i.isLt + exact ⟨by omega, by omega⟩ + +end Run + +end CompressorRecords.GreedyArena + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyRecordRanges.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyRecordRanges.lean new file mode 100644 index 0000000000..04a65a7d89 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyRecordRanges.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy + +/-! +# Addresses stored in the color and offset operand records + +The color records point to labels in their own arena. The offset records +point to offset labels, projected displacements or the common zero cell. +All of these lie in the newly allocated greedy region. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyArena + +open BurstRAM Compression Greedy +open scoped Fin.CommRing + +private theorem tagPointers_range {V : Type*} {w d : ℕ} (rd : ℕ → Prop) (G : SlotGraph V d) + (A : TagAddresses V d w) (x : V) (t : SlotGraph.TagTests d) + (zero : rd A.zero.val) (disp : ∀ e, rd (A.displacement e).val) (label : ∀ x, rd (A.label x).val) : + ∀ u ∈ tagPointers G A x t, rd u.val := by + have incr (y : V) (i : Option (Fin d)) : rd (A.increment y i).val := by + cases i with + | none => exact zero + | some i => exact disp (y,i) + obtain ⟨⟨b,i⟩,j | ⟨j,k⟩⟩ := t <;> cases b + all_goals + intro u hu + simp only [tagPointers,List.mem_cons,List.not_mem_nil,or_false] at hu + rcases hu with rfl|rfl|rfl|rfl <;> first | exact zero | exact disp _ | exact incr _ _ | exact label _ + +namespace Run + +variable {w a g origin : ℕ} {X : ShrinkingState a g} {T : IncidenceDirectory w} + {m : Memory w} (r : Run X T origin m) +local notation "n" => Fintype.card X.Base +local notation "L" => colorLayout w origin n a r.room +local notation "K" => tagLayout w origin n a r.room + +open private assignment_addresses from OAI.Computability.VPVNP.CompressorRecordGreedyPass +open private shifted_port from OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy +include r + +/-- Every color operand is the address of a label in the fresh color array. -/ +theorem color_pointer_range (x : X.Base) (u : Word w) + (hu : u ∈ rowWords (colorTables T origin n a) X.slots.base X.baseIndex x (colorOperandRows (2^a))) : + origin ≤ u.val ∧ u.val < origin+n := by + rw [rowWords_color, assignment_addresses (d := 2^a) L _ _ rfl] at hu + obtain ⟨z, hz, huz⟩ := List.mem_flatten.mp hu + obtain ⟨t, _, rfl⟩ := List.mem_map.mp hz + obtain rfl := List.mem_singleton.mp huz + change origin ≤ ((L).label _).val ∧ ((L).label _).val < origin+n + rw [WalkLayout.label_val] + exact ⟨Nat.le_add_right .., Nat.add_lt_add_left (X.baseIndex _).isLt _⟩ + +/-- Every offset operand points to an offset label, a projected displacement +word or the common zero word, all within the same fresh allocation. -/ +theorem tag_pointer_range (x : X.Base) (u : Word w) + (hu : u ∈ rowWords (tagTables T origin n a) X.slots.base X.baseIndex x (tagOperandRows (2^a))) : + origin ≤ u.val ∧ u.val < greedyStop origin n a := by + rw [rowWords_tag] at hu + obtain ⟨z, hz, huz⟩ := List.mem_flatten.mp hu + obtain ⟨t, _, rfl⟩ := List.mem_map.mp hz + have hb := bounds origin n a + change origin+n ≤ _ ∧ _ at hb + have room := r.room + apply tagPointers_range (fun v ↦ origin ≤ v ∧ v < greedyStop origin n a) _ _ _ _ _ _ _ _ huz + · change origin ≤ zeroCell origin n a % (2^w) ∧ zeroCell origin n a % (2^w) < greedyStop origin n a + rw [Nat.mod_eq_of_lt (Nat.lt_of_succ_lt room)] + change origin ≤ shiftBase origin n a+n*2^a ∧ shiftBase origin n a+n*2^a < greedyStop origin n a + omega + · intro e + change origin ≤ (CursorRAM.encode w (shiftBase origin n a) + IncidenceDirectory.basePort X e).val ∧ + (CursorRAM.encode w (shiftBase origin n a) + IncidenceDirectory.basePort X e).val < greedyStop origin n a + rw [shifted_port X origin room e] + have he := (IncidenceDirectory.baseOrder X e).isLt + change _ < n*2^a at he + omega + · intro y + rw [assignment_addresses (d := 2^a) K _ _ rfl] + simp only [Function.comp_apply, WalkLayout.label_val] + have hy := (X.baseIndex y).isLt + change origin ≤ offsetBase origin n a + (X.baseIndex y).val ∧ offsetBase origin n a + (X.baseIndex y).val < greedyStop origin n a + omega + +end Run + +end CompressorRecords.GreedyArena + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyRelocated.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyRelocated.lean new file mode 100644 index 0000000000..b538971fda --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyRelocated.lean @@ -0,0 +1,207 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedyDirectory +import OAI.Computability.VPVNP.CompressorRecordsSchedule +import OAI.Computability.VPVNP.PrimedCounterRename + +/-! +# Greedy preparation from an active scheduler frame + +The worker receives the slot numbers followed by eight current-level controls. +It loads those controls into registers and runs the shared native record writer. +Both color and tag directories use the same placement of public operands. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy.Relocated + +open BurstRAM BurstRAM.PrivateRAM Compression PrimedStackRAM + +variable {w N width d : ℕ} {V : Type*} + +/-- Control indices are those of the original greedy preparation block. -/ +def controls (L : WalkLayout w N width) (T : PortTables w) (j : Fin 8) : Word w := + (controlWords L T).get j + +/-- Public operand bank consisting of the slot numbers followed by the eight relocated walk +controls. -/ +def publicWords (d : ℕ) (L : WalkLayout w N width) (T : PortTables w) : + Fin ((d+1)+8) → Word w := + Fin.addCases (slotNumbers w d) (controls L T) + +private def loadControls (d : ℕ) : List (Op 13 ((d+1)+8)) := + [.stateWord 0, .constant 11 1, + .publicWord 2 ((0 : Fin 8).natAdd (d+1)), .publicWord 3 ((1 : Fin 8).natAdd (d+1)), + .publicWord 4 ((2 : Fin 8).natAdd (d+1)), .publicWord 5 ((3 : Fin 8).natAdd (d+1)), + .publicWord 6 ((4 : Fin 8).natAdd (d+1)), .publicWord 7 ((5 : Fin 8).natAdd (d+1)), + .publicWord 8 ((6 : Fin 8).natAdd (d+1)), .publicWord 9 ((7 : Fin 8).natAdd (d+1))] + +/-- Preparation instructions that load the relocated controls before running the greedy record +builder. -/ +def prepareCode (rows : OperandRows d) : List (Op 13 ((d+1)+8)) := + loadControls d ++ (prepareBody rows).map (PrimedCounter.renameOp id (Fin.castAdd 8)) + +/-- Schedulable pass that builds the relocated greedy records and returns its cursor in +register zero. -/ +abbrev preparePass (rows : OperandRows d) : Schedule.Pass := ⟨_,_,_,template (prepareCode rows) 0⟩ + +private theorem loaded (L : WalkLayout w N width) (T : PortTables w) (m : Memory w) + (s : Word w) (d : ℕ) : + ∃ es rs, trace (publicWords d L T) s (loadControls d) (fun _ ↦ 0) m = some (es,rs,m) ∧ + es.length = 10 ∧ countProbes es = 0 ∧ RowInput T s 0 rs ∧ rs 11 = 1 ∧ + rs 8 = L.base 0 ∧ rs 9 = Fin.ofNat _ (2+width) := by + simp (config := {decide := true}) [loadControls,trace,Op.effect,countProbes,Function.update, + publicWords,Fin.addCases_right] + exact ⟨⟨rfl,rfl,rfl,rfl,rfl,rfl,rfl,rfl⟩,rfl,rfl,rfl⟩ + +private theorem trace_slots {r : ℕ} (L : WalkLayout w N width) (T : PortTables w) + (s : Word w) (ops : List (Op r (d+1))) (rs : Regs w r) (m : Memory w) : + trace (publicWords d L T) s (ops.map (PrimedCounter.renameOp id (Fin.castAdd 8))) rs m = + trace (slotNumbers w d) s ops rs m := by + induction ops generalizing rs m with + | nil => rfl + | cons op ops ih => + have effect : (PrimedCounter.renameOp id (Fin.castAdd 8) op).effect (publicWords d L T) s rs m = + op.effect (slotNumbers w d) s rs m := by + cases op <;> first | rfl | simp [PrimedCounter.renameOp,Op.effect,publicWords] + simp only [List.map_cons,trace,effect,ih] + +/-- A frame-based preparation call writes the same label and record as the +original greedy initializer, including the pointer to the next record. -/ +theorem prepare_one (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows : OperandRows d) (m : Memory w) (i : Fin N) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (space : L.limit < 2^w) (outside : GraphOutside (d := d) L T order) + (size : (rowWords T G order (order.symm i) rows).length = width) : + let P := ((preparePass rows).table.instantiate w (publicWords d L T)).program + let ptrs := fun k : Fin N ↦ rowWords T G order (order.symm k) rows + ∃ es, execute P (1+(prepareCode rows).length) (P.start (Fin.ofNat _ i.val)) m [] = + some ⟨es,some (Fin.ofNat _ (i.val+1))⟩ ∧ + after m es = writeRow (writeMemory m (L.label i) 0) (L.base i.val) (L.record ptrs i) ∧ + es.length ≤ 22+8*rows.length+6*width ∧ countProbes es = 3+rows.length+width := by + let s : Word w := Fin.ofNat _ i.val + obtain ⟨a,r,ha,hla,hpa,hr,hu,hfirst,hstride⟩ := loaded L T m s d + obtain ⟨b,last,hb,hresult,hlen,hprobes⟩ := + prepareBody_trace L T G order rows m i labels rep space outside size r hr hu hfirst hstride + have he : trace (publicWords d L T) s (prepareCode rows) (fun _ ↦ 0) m = + some (a++b,last,writeRow (writeMemory m (L.label i) 0) (L.base i.val) + (L.record (fun k ↦ rowWords T G order (order.symm k) rows) i)) := by + rw [prepareCode,trace_append,ha] + simp only [Option.bind_some,trace_slots] + rw [hb]; rfl + refine ⟨a++b,?_,trace_after he,?_,?_⟩ + · let M := (template (prepareCode rows) 0).instantiate w (publicWords d L T) + change execute M.program (1+(prepareCode rows).length) ⟨M.entry,s,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + dsimp only [M] + rw [execute_template,run_eq_trace,he] + simp [hresult] + · rw [List.length_append,hla]; omega + · rw [probes_append,hpa,hprobes,Nat.zero_add] + +/-- The completed native scan installs the directory from arbitrary initial +memory. All external probes go to the mate arrays, labels and records. -/ +theorem prepare_directory (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows : OperandRows d) (m : Memory w) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (space : L.limit < 2^w) (outside : GraphOutside (d := d) L T order) + (size : ∀ i : Fin N, (rowWords T G order (order.symm i) rows).length = width) : + let P := ((preparePass rows).table.instantiate w (publicWords d L T)).program + let ptrs := fun i : Fin N ↦ rowWords T G order (order.symm i) rows + ∃ rs, runSegment P (1+(prepareCode rows).length) (some 0) m (List.replicate N []) = some rs ∧ + endState (some 0) rs = some (Fin.ofNat _ N) ∧ after m (eventLog rs) = L.initialMemory ptrs m ∧ + rs.length = N ∧ RAMBuckets.cost Report.probes rs = N*(4+rows.length+width) ∧ + ∀ r ∈ rs, r.events.length ≤ 22+8*rows.length+6*width ∧ r.probes = 3+rows.length+width := by + let ptrs := fun i : Fin N ↦ rowWords T G order (order.symm i) rows + let P := ((preparePass rows).table.instantiate w (publicWords d L T)).program + have call (i : Fin N) := prepare_one L T G order rows (L.prefixMemory ptrs m i.val) i labels + (L.prefixMemory_tables ptrs m i.isLt.le rep outside) space outside (size i) + have whole := WalkLayout.prepare_segment (N := N) P (1+(prepareCode rows).length) + (3+rows.length+width) (22+8*rows.length+6*width) (L.prefixMemory ptrs m) (fun i ↦ by + obtain ⟨es,he,hm,hs,hp⟩ := call i + exact ⟨es,he,hm.trans (L.write_prefixMemory ptrs m size i),hs,hp⟩) 0 N (by omega) + have zero : Fin.ofNat _ 0 = (0 : Word w) := Fin.ext (Nat.zero_mod _) + have cost : 1+(3+rows.length+width) = 4+rows.length+width := by omega + have charge : (fun r : Report w ↦ countProbes r.events) = Report.probes := rfl + rw [charge] at whole + simp only [WalkLayout.prefixMemory_zero,Nat.zero_add,WalkLayout.prefixMemory_full,zero,cost] at whole + obtain ⟨rs,hr,hs,hm,hn,hp,hw⟩ := whole + exact ⟨rs,hr,hs,hm,hn,hp,hw⟩ + +open scoped Fin.CommRing + +private theorem valid_segment {q : ℕ} {A : Type*} (C : Schedule.Catalog q) (worker : Fin q) + (ports : Schedule.Ports w) (pub : Fin (C worker).params → Word w) + (P : Program w A) (fuel N : ℕ) (mem : ℕ → Memory w) (fit : N < 2^w) + (ready : ∀ k, k ≤ N → Schedule.Ready C worker ports pub (N : Word w) (mem k)) + (step : ∀ i : Fin N, ∃ es, execute P fuel (P.start (Fin.ofNat _ i.val)) (mem i.val) [] = + some ⟨es,some (Fin.ofNat _ (i.val+1))⟩ ∧ after (mem i.val) es = mem (i.val+1)) + (k n : ℕ) (stop : k+n=N) (rs : List (Report w)) + (run : runSegment P fuel (some (Fin.ofNat _ k)) (mem k) (List.replicate n []) = some rs) : + Schedule.ValidTrace C worker ports pub (N : Word w) (Fin.ofNat _ k) (mem k) rs := by + induction n generalizing k rs with + | zero => + have h : rs = [] := (Option.some.inj run).symm + subst rs + simp only [Nat.add_zero] at stop + subst k + exact ⟨ready N le_rfl,le_rfl⟩ + | succ n ih => + have hk : k < N := by omega + obtain ⟨es,he,hm⟩ := step ⟨k,hk⟩ + rw [List.replicate_succ,runSegment,he] at run + change (runSegment P fuel (some (Fin.ofNat _ (k+1))) (after (mem k) es) + (List.replicate n [])).map _ = some rs at run + rw [hm] at run + obtain ⟨tail,ht,rfl⟩ := Option.map_eq_some_iff.mp run + refine ⟨ready k hk.le,?_,Fin.ofNat _ (k+1),rfl,?_⟩ + · change k % (2^w) < N % (2^w) + rwa [Nat.mod_eq_of_lt (hk.trans fit),Nat.mod_eq_of_lt fit] + · change Schedule.ValidTrace C worker ports pub _ _ (after (mem k) es) tail + rw [hm] + exact ih _ (by omega) _ ht + +/-- The preparation reports meet the linked worker's exclusive guard. Each +prefix writes only the walk allocation, so the stop, parameters and tag can +be read from the same external frame at every call. -/ +theorem prepare_valid {q : ℕ} (C : Schedule.Catalog q) (worker : Fin q) (ports : Schedule.Ports w) + (pub : Fin (C worker).params → Word w) (L : WalkLayout w N width) (T : PortTables w) + (G : SlotGraph V d) (order : V ≃ Fin N) (rows : OperandRows d) (m : Memory w) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (space : L.limit < 2^w) (outside : GraphOutside (d := d) L T order) + (size : ∀ i : Fin N, (rowWords T G order (order.symm i) rows).length = width) + (ready : Schedule.Ready C worker ports pub (N : Word w) m) + (tag : ports.tag.val < L.origin ∨ L.limit ≤ ports.tag.val) + (frame : ∀ j : Fin ((C worker).params+1), (ports.activeFrame+(j.val : Word w)).val < L.origin ∨ + L.limit ≤ (ports.activeFrame+(j.val : Word w)).val) + (rs : List (Report w)) + (native : let P := ((preparePass rows).table.instantiate w (publicWords d L T)).program + runSegment P (1+(prepareCode rows).length) (some 0) m (List.replicate N []) = some rs) : + Schedule.ValidTrace C worker ports pub (N : Word w) 0 m rs := by + let ptrs := fun i : Fin N ↦ rowWords T G order (order.symm i) rows + let mem := L.prefixMemory ptrs m + let P := ((preparePass rows).table.instantiate w (publicWords d L T)).program + have fresh (k : ℕ) (hk : k ≤ N) : Schedule.Ready C worker ports pub (N : Word w) (mem k) := by + have keep {z : ℕ} (hz : z < L.origin ∨ L.limit ≤ z) : mem k z = m z := + L.prefixMemory_outside ptrs m hk hz + refine ⟨(keep tag).trans ready.1,?_,?_⟩ + · exact (keep (by simpa using frame 0)).trans ready.2.1 + · funext i + exact (keep (frame i.succ)).trans (congrFun ready.2.2 i) + have one (i : Fin N) := prepare_one L T G order rows (mem i.val) i labels + (L.prefixMemory_tables ptrs m i.isLt.le rep outside) space outside (size i) + have zero : Fin.ofNat _ 0 = (0 : Word w) := Fin.ext (Nat.zero_mod _) + have start : mem 0 = m := L.prefixMemory_zero ptrs m + rw [← start,← zero] + refine valid_segment C worker ports pub P (1+(prepareCode rows).length) N mem + (by unfold WalkLayout.limit at space; omega) fresh ?_ 0 N (Nat.zero_add N) rs ?_ + · intro i + obtain ⟨es,he,hm,_,_⟩ := one i + exact ⟨es,he,hm.trans (L.write_prefixMemory ptrs m size i)⟩ + · rwa [start,zero] + +end CompressorRecords.Greedy.Relocated + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyVisitAccess.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyVisitAccess.lean new file mode 100644 index 0000000000..92c85edf95 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyVisitAccess.lean @@ -0,0 +1,186 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedyInit +import OAI.Computability.VPVNP.CompressorFlowFootprint + +/-! +# Addresses accessed by the greedy record reader + +Every forbidden operand is fetched in two reads, first from the pointer row +and then from the addressed cell. The search repeats those reads from the +same first pointer. At the end it reads the two header words and writes the +chosen value to the destination named in the header. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport + +open private fetchOne fetch compareWord compare_run scan pass passes visitHead visitTail from + OAI.Computability.VPVNP.CompressorRecordGreedy +open private advance_add from OAI.Computability.VPVNP.CompressorRecordGreedyInit + +variable {w : ℕ} + +private abbrev PointerReads (m : Memory w) (rd : ℕ → Prop) (ptr : Word w) (n : ℕ) := + ∀ j < n, rd (advance ptr j).val ∧ rd (m (advance ptr j).val).val + +private def AccessRun (s : Word w) (m : Memory w) (rd wr : ℕ → Prop) + (ops : List (Op 8 0)) (regs out : Regs w 8) : Prop := + ∃ es, trace Fin.elim0 s ops regs m = some (es, out, m) ∧ Reads rd es ∧ Writes wr es + +private theorem AccessRun.append {s : Word w} {m : Memory w} {rd wr : ℕ → Prop} + {ops more : List (Op 8 0)} {regs mid out : Regs w 8} + (left : AccessRun s m rd wr ops regs mid) (right : AccessRun s m rd wr more mid out) : + AccessRun s m rd wr (ops ++ more) regs out := by + obtain ⟨es, he, rd₁, wr₁⟩ := left + obtain ⟨fs, hf, rd₂, wr₂⟩ := right + exact ⟨es ++ fs, by simp [trace_append, he, hf], + fun a v h ↦ (List.mem_append.mp h).elim (rd₁ a v) (rd₂ a v), + fun a v h ↦ (List.mem_append.mp h).elim (wr₁ a v) (wr₂ a v)⟩ + +private theorem AccessRun.quiet {s : Word w} {m : Memory w} {rd wr : ℕ → Prop} + {ops : List (Op 8 0)} {regs out : Regs w 8} {es : List (Event w)} + (run : trace Fin.elim0 s ops regs m = some (es,out,m)) (quiet : countProbes es = 0) : + AccessRun s m rd wr ops regs out := ⟨es, run, FlowFootprint.bounds_of_noProbes rd wr quiet⟩ + +private theorem fetch_access (s : Word w) (m : Memory w) (rd wr : ℕ → Prop) (n : ℕ) + (regs : Regs w 8) (one : regs 1 = 1) (pointers : PointerReads m rd (regs 3) n) : + ∃ out, AccessRun s m rd wr (fetch n) regs out ∧ out 0 = regs 0 ∧ out 1 = 1 ∧ + out 3 = advance (regs 3) n := by + induction n generalizing regs with + | zero => exact ⟨regs, .quiet (es := []) rfl rfl, rfl, one, rfl⟩ + | succ n ih => + let ptr := regs 3 + let addr := m ptr.val + let val := m addr.val + let xor := BinaryOp.bitXor.eval (regs 4) val + let mid := Function.update (Function.update (Function.update regs (7 : Fin 8) val) 4 xor) 3 (ptr + 1) + have head : AccessRun s m rd wr fetchOne regs mid := by + refine ⟨[.read ptr addr, .read addr val, .tick, .tick], ?_, ?_, ?_⟩ + · simp (config := {decide := true}) [fetchOne, trace, Op.effect, BinaryOp.eval, one, + mid, ptr, addr, val, xor, Function.update] + · intro a v h + simp only [List.mem_cons, List.not_mem_nil, Event.read.injEq, reduceCtorEq, or_false] at h + rcases h with ⟨rfl, _⟩ | ⟨rfl, _⟩ + exacts [(pointers 0 (by omega)).1, (pointers 0 (by omega)).2] + · intro a v h; simp at h + have rest : PointerReads m rd (mid 3) n := by + intro j hj + simpa only [mid, Function.update_self, ptr, advance] using pointers (j+1) (by omega) + obtain ⟨out, run, h₀, h₁, h₃⟩ := ih mid (by simpa [mid] using one) rest + exact ⟨out, head.append run, by simpa [mid] using h₀, h₁, by simpa [mid, ptr, advance] using h₃⟩ + +private theorem scan_access (s : Word w) (m : Memory w) (rd wr : ℕ → Prop) (arity n : ℕ) + (regs : Regs w 8) (one : regs 1 = 1) (pointers : PointerReads m rd (regs 3) (arity*n)) : + ∃ out, AccessRun s m rd wr (scan arity n) regs out ∧ out 0 = regs 0 ∧ out 1 = 1 := by + induction n generalizing regs with + | zero => exact ⟨regs, .quiet (es := []) rfl rfl, rfl, one⟩ + | succ n ih => + let reset := Function.update regs (4 : Fin 8) 0 + have head : AccessRun s m rd wr [.constant 4 0] regs reset := .quiet (es := [.tick]) rfl rfl + have row : PointerReads m rd (reset 3) arity := by + intro j hj + simpa [reset] using pointers j (by rw [Nat.mul_succ]; omega) + obtain ⟨f, fetchRun, f₀, f₁, f₃⟩ := fetch_access s m rd wr arity reset (by simpa [reset] using one) row + obtain ⟨c, ⟨es, he, _, noProbes⟩, _, keeps⟩ := compare_run s m f + have compareRun : AccessRun s m rd wr compareWord f c := .quiet he noProbes + have next : c 3 = advance (regs 3) arity := by + simpa [reset] using (keeps 3 (by decide) (by decide)).trans f₃ + have remaining : PointerReads m rd (c 3) (arity*n) := by + intro j hj + rw [next, ← advance_add] + exact pointers _ (by rw [Nat.mul_succ]; omega) + obtain ⟨out, tail, c₀, c₁⟩ := ih c ((keeps 1 (by decide) (by decide)).trans f₁) remaining + exact ⟨out, ((head.append fetchRun).append compareRun).append tail, + by simpa [reset] using c₀.trans ((keeps 0 (by decide) (by decide)).trans f₀), c₁⟩ + +private theorem pass_access (s : Word w) (m : Memory w) (rd wr : ℕ → Prop) (arity n : ℕ) + (regs : Regs w 8) (one : regs 1 = 1) (pointers : PointerReads m rd (regs 0) (arity*n)) : + ∃ out, AccessRun s m rd wr (pass arity n) regs out ∧ out 0 = regs 0 ∧ out 1 = 1 := by + let reset := Function.update (Function.update regs (3 : Fin 8) (regs 0)) 6 (regs 1) + have head : AccessRun s m rd wr [.copy 3 0, .copy 6 1] regs reset := by + apply AccessRun.quiet (es := [.tick, .tick]) _ rfl + simp [reset, trace, Op.effect] + obtain ⟨c, scanRun, c₀, c₁⟩ := scan_access s m rd wr arity n reset + (by simpa [reset] using one) (by simpa [reset] using pointers) + let diff := c 1 - c 6 + let out := Function.update (Function.update c (6 : Fin 8) diff) 2 (c 2 + diff) + have tail : AccessRun s m rd wr [.binary .sub 6 1 6, .binary .add 2 2 6] c out := by + apply AccessRun.quiet (es := [.tick, .tick]) _ rfl + simp [trace, Op.effect, BinaryOp.eval, diff, out] + exact ⟨out, (head.append scanRun).append tail, by simpa [out, reset] using c₀, + by simpa [out] using c₁⟩ + +private theorem passes_access (s : Word w) (m : Memory w) (rd wr : ℕ → Prop) (arity n j : ℕ) + (regs : Regs w 8) (one : regs 1 = 1) (pointers : PointerReads m rd (regs 0) (arity*n)) : + ∃ out, AccessRun s m rd wr (passes arity n j) regs out := by + induction j generalizing regs with + | zero => exact ⟨regs, .quiet (es := []) rfl rfl⟩ + | succ j ih => + obtain ⟨mid, head, m₀, m₁⟩ := pass_access s m rd wr arity n regs one pointers + obtain ⟨out, tail⟩ := ih mid m₁ (m₀ ▸ pointers) + exact ⟨out, head.append tail⟩ + +/-- Read and write support of the native visitor, including the indirect +operand reads of every search pass. Addresses advance in word arithmetic. -/ +theorem visit_access (m : Memory w) (base : Word w) (arity n : ℕ) (rd wr : ℕ → Prop) + (header : rd base.val) (next : rd (base+1).val) + (words : ∀ j < arity*n, rd (advance (base+1+1) j).val ∧ rd (m (advance (base+1+1) j).val).val) + (dest : wr (m base.val).val) (r : Report w) + (native : execute (visitMachine w arity n).program (1 + (visitCode arity n).length) + ((visitMachine w arity n).program.start base) m [] = some r) : + Reads rd r.events ∧ Writes wr r.events := by + let reset := Function.update (Function.update (Function.update (fun _ : Fin 8 => (0 : Word w)) 0 base) 1 1) + 0 (base+1+1) + have head : AccessRun base m rd wr visitHead (fun _ ↦ 0) reset := by + apply AccessRun.quiet (es := [.tick,.tick,.tick,.tick]) _ rfl + simp (config := {decide := true}) [visitHead, trace, Op.effect, BinaryOp.eval, reset, Function.update] + rfl + let start := Function.update (Function.update reset (1 : Fin 8) 1) 2 0 + have init : AccessRun base m rd wr [.constant 1 1,.constant 2 0] reset start := + .quiet (es := [.tick,.tick]) rfl rfl + obtain ⟨c, passesRun⟩ := passes_access base m rd wr arity n n start (by simp [start]) + (by simpa [start, reset] using words) + obtain ⟨es, he, esRead, esWrite⟩ := head.append (init.append passesRun) + let addr := m base.val + let resume := m (base+1).val + let out := Function.update (Function.update (Function.update (Function.update + (Function.update c (7 : Fin 8) base) 5 addr) 1 1) 7 (base+1)) 4 resume + let tail : List (Event w) := [.tick, .read base addr, .tick, .tick, .read (base+1) resume, .write addr (c 2)] + have ht : trace Fin.elim0 base visitTail c m = some (tail, out, writeMemory m addr (c 2)) := by + simp (config := {decide := true}) [visitTail, trace, Op.effect, BinaryOp.eval, addr, resume, out, + tail, Function.update] + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have full : trace Fin.elim0 base (visitCode arity n) (fun _ ↦ 0) m = + some (es ++ tail, out, writeMemory m addr (c 2)) := by + change trace Fin.elim0 base (visitHead ++ choose arity n) (fun _ ↦ 0) m = _ at he + simp only [visitCode, trace_append, he, ht, Option.bind_some, Option.map_some] + let M := visitMachine w arity n + change execute M.program (1 + (visitCode arity n).length) ⟨M.entry, base, fun _ ↦ 0, fun _ ↦ 0⟩ m [] = _ at native + dsimp only [M, visitMachine] at native + rw [execute_template, run_eq_trace, full] at native + have events : es ++ tail = r.events := by simpa using congrArg Report.events (Option.some.inj native) + rw [← events] + constructor + · intro a v h + rcases List.mem_append.mp h with h | h + · exact esRead a v h + · simp only [tail, List.mem_cons, List.not_mem_nil, Event.read.injEq, reduceCtorEq, + or_false, false_or] at h + rcases h with ⟨rfl, _⟩ | ⟨rfl, _⟩ + exacts [header, next] + · intro a v h + rcases List.mem_append.mp h with h | h + · exact esWrite a v h + · simp only [tail, List.mem_cons, List.not_mem_nil, Event.write.injEq, reduceCtorEq, + or_false, false_or] at h + exact h.1 ▸ dest + +end CompressorRecords.Greedy + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyVisitWalk.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyVisitWalk.lean new file mode 100644 index 0000000000..2a5b0f0797 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyVisitWalk.lean @@ -0,0 +1,212 @@ +import OAI.Computability.VPVNP.CompressorGreedyPrepareProgress +import OAI.Computability.VPVNP.CompressorGreedyReadProgress +import OAI.Computability.VPVNP.CompressorGreedyLevelPlan +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy +import OAI.Computability.VPVNP.CompressorSourceOnline +import OAI.Computability.VPVNP.CompressorSourceWalk + +/-! +# Six consecutive native visits that compute the shrinking directory + +The tag projection and zero publication precede the color directory. Both +offset visits begin in the post-memory of the color reader. Each packet keeps +its exact native program, public parameters, cursor interval and choice tapes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyVisit + +open BurstRAM PrivateRAM Compression BlockPlanner PhaseRecipe Greedy GreedyArena +open scoped Fin.CommRing + +/-- The six native stages used to build the shrinking level's greedy color and tag directories. -/ +inductive Stage | extract | zero | colorPrepare | colorRead | tagPrepare | tagRead + deriving DecidableEq + +/-- Execution order of the greedy stages, beginning with shift extraction and ending with the +tag scan. -/ +def stages : List Stage := [.extract,.zero,.colorPrepare,.colorRead,.tagPrepare,.tagRead] + +instance : Fintype Stage := ⟨stages.toFinset, by intro j; cases j <;> decide⟩ + +/-- Planner visit implementing a greedy stage at the specified level and scratch origin. -/ +def visit (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : Stage → BlockPlanner.Visit + | .extract => GreedyLevelPlan.extractShifts shape step a origin + | .zero => GreedyLevelPlan.publishZero shape step a origin + | .colorPrepare => GreedyLevelPlan.colorPrepare shape step a origin + | .colorRead => GreedyLevelPlan.colorRead step a origin + | .tagPrepare => GreedyLevelPlan.tagPrepare shape step a origin + | .tagRead => GreedyLevelPlan.tagRead step a origin + +theorem visits_eq (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : + stages.map (visit shape step a origin) = GreedyLevelPlan.visits shape step a origin := rfl + +variable {w a g z : ℕ} {X : GreedyArena.ShrinkingState a g} {T : IncidenceDirectory w} + {m : Memory w} (r : GreedyArena.Run X T z m) + +private abbrev n := Fintype.card X.Base +private abbrev project := projectionWords T z (n (X := X)) a g +private abbrev L := colorLayout w z (n (X := X)) a r.room +private abbrev K := tagLayout w z (n (X := X)) a r.room + +/-- Initial cursor for a greedy stage. Record readers start at their first record address and +the other stages start at zero. -/ +def start : Stage → Word w + | .colorRead => (L r).base 0 + | .tagRead => (K r).base 0 + | _ => 0 + +/-- Exclusive cursor bound for the stage, expressed as a row count or the address past the +final walk record. -/ +def stop : Stage → Word w + | .extract => ((n (X := X) * 2^a : ℕ) : Word w) + | .zero => 1 + | .colorPrepare | .tagPrepare => (n (X := X) : Word w) + | .colorRead => (L r).base (n (X := X)) + | .tagRead => (K r).base (n (X := X)) + +/-- Private instruction budget for one worker call of the given greedy stage and degree +exponent. -/ +def fuel (a : ℕ) : Stage → ℕ + | .extract => 14 + | .zero => 5 + | .colorPrepare => 1 + (Relocated.prepareCode (colorOperandRows (2^a))).length + | .tagPrepare => 1 + (Relocated.prepareCode (tagOperandRows (2^a))).length + | .colorRead => 1 + (visitCode 1 (2*2^a)).length + | .tagRead => 1 + (visitCode 4 (WalkLayout.tagCount (2^a))).length + +theorem fuel_pos (j : Stage) : 0 < fuel a j := by cases j <;> simp [fuel] + +/-- Empty choice tapes for the deterministic greedy calls, with one tape per row visited by the +stage. -/ +def choices (X : GreedyArena.ShrinkingState a g) : Stage → List (List Bool) + | .extract => List.replicate (Fintype.card X.Base * 2^a) [] + | .zero => [[]] + | _ => List.replicate (Fintype.card X.Base) [] + +/-- Concrete public operands of the installed worker, obtained from the greedy arena and its +incidence tables. -/ +def params (shape : DescriptorSpace.Shape) (step : ℕ) (origin : Expr) (j : Stage) : + Fin (visit shape step a origin j).worker.params → Word w := + match j with + | .extract | .zero => project (X := X) (T := T) (z := z) + | .colorPrepare => Relocated.publicWords (2^a) (L r) (colorTables T z (n (X := X)) a) + | .colorRead | .tagRead => Fin.elim0 + | .tagPrepare => Relocated.publicWords (2^a) (K r) (tagTables T z (n (X := X)) a) + +/-- These equalities identify the worker ABI at any memory in which the +descriptor parameters have their specified values. -/ +theorem values {shape : DescriptorSpace.Shape} {step : ℕ} {origin : Expr} {pub : Fin 5 → Word w} + {state : Word w} {input : Memory w} + (h : GreedyLevelPlan.Reads shape step a origin pub state input (n (X := X)) g z T) (j : Stage) : + let v := visit shape step a origin j + v.initial.eval pub state input = start r j ∧ v.stop.eval pub state input = stop r j ∧ + (fun i => (v.params i).eval pub state input) = params r shape step origin j := by + cases j with + | extract => exact GreedyLevelPlan.extractShifts_values h + | zero => exact GreedyLevelPlan.publishZero_values h + | colorPrepare => exact GreedyLevelPlan.colorPrepare_values h r.room + | colorRead => exact GreedyLevelPlan.colorRead_values h r.room + | tagPrepare => exact GreedyLevelPlan.tagPrepare_values h r.room + | tagRead => exact GreedyLevelPlan.tagRead_values h r.room + +/-- Evidence that the native stage produces the stated reports from its input memory and +advances to its prescribed stop cursor. -/ +structure Source (shape : DescriptorSpace.Shape) (step : ℕ) (origin : Expr) (j : Stage) + (input : Memory w) (reports : List (Report w)) : Prop where + native : runSegment (((visit shape step a origin j).worker.table.instantiate w (params r shape step origin j)).program) + (fuel a j) (some (start r j)) input (choices X j) = some reports + progress : SourceOnline.Progress (stop r j) (start r j) reports + +private theorem projection_progress (p : Fin 5 → Word w) (i len : ℕ) (input : Memory w) (fit : i+len < 2^w) : + SourceOnline.Progress ((i+len : ℕ) : Word w) (i : Word w) (ShrinkTagColumn.scan p i len input) := by + induction len generalizing i input with + | zero => exact .done le_rfl + | succ len ih => + have hnext := ih (i+1) (after input (ShrinkTagColumn.row p (i : Word w) input).events) (by omega) + rw [show i+1+len = i+(len+1) by omega] at hnext + refine .next (next := ((i+1 : ℕ) : Word w)) ?_ ?_ hnext + · change i%(2^w) < (i+(len+1))%(2^w) + rw [Nat.mod_eq_of_lt (by omega : i < 2^w),Nat.mod_eq_of_lt fit]; omega + · simp [ShrinkTagColumn.row] + +/-- Chronological reports emitted by the chosen stage of the greedy shrinking pass. -/ +def packetReports : Stage → List (Report w) + | .extract => ShrinkTagColumn.scan (project (X := X) (T := T) (z := z)) 0 ((n (X := X))*2^a) m + | .zero => [ShrinkTagColumn.zeroRow (project (X := X) (T := T) (z := z))] + | .colorPrepare => r.color.prep + | .colorRead => r.color.reads + | .tagPrepare => r.offsets.prep + | .tagRead => r.offsets.reads + +/-- Input memory for the given stage after applying the reports of its predecessors in the +greedy walk. -/ +def packetInput : Stage → Memory w + | .extract => m + | .zero => after m (eventLog (packetReports r .extract)) + | .colorPrepare => projectedMemory X T z m + | .colorRead => after (projectedMemory X T z m) (eventLog r.color.prep) + | .tagPrepare => r.color.post + | .tagRead => after r.color.post (eventLog r.offsets.prep) + +private theorem zeroOutput : + after (packetInput r .zero) (eventLog (packetReports r .zero)) = packetInput r .colorPrepare := + (SourceWalk.after_append m (packetReports r .extract) (packetReports r .zero)).symm + +theorem source_at (shape : DescriptorSpace.Shape) (step : ℕ) (origin : Expr) (j : Stage) : + Source r shape step origin j (packetInput r j) (packetReports r j) := by + cases j with + | extract => + refine ⟨r.projection.extractRun,?_⟩ + have room := r.room + change GreedyArena.shiftBase z (n (X := X)) a + (n (X := X))*2^a + 1 < 2^w at room + simpa [stop,start,packetReports] using projection_progress (project (X := X) (T := T) (z := z)) + 0 ((n (X := X))*2^a) m (by omega) + | zero => + have hpos : 1 < 2^w := by + have room := r.room + change GreedyArena.shiftBase z (n (X := X)) a + (n (X := X))*2^a + 1 < 2^w at room + omega + refine ⟨r.projection.zeroRun,.next (next := 1) ?_ rfl (.done le_rfl)⟩ + change 0%(2^w) < 1%(2^w); rw [Nat.zero_mod,Nat.mod_eq_of_lt hpos]; decide + | colorPrepare => exact ⟨r.color.prepRun,r.color_prepare_progress⟩ + | colorRead => exact ⟨r.color.readRun,r.color_read_progress⟩ + | tagPrepare => exact ⟨r.offsets.prepRun,r.tag_prepare_progress⟩ + | tagRead => exact ⟨r.offsets.readRun,r.tag_read_progress⟩ + +/-- Each stage names its own input memory and report slice in the walk. -/ +theorem indexed_walk (shape : DescriptorSpace.Shape) (step : ℕ) (origin : Expr) : + SourceWalk (fun j input rs => input = packetInput r j ∧ rs = packetReports r j ∧ + Source r shape step origin j input rs) stages m r.reports := by + let P := fun j input rs => input = packetInput r j ∧ rs = packetReports r j ∧ Source r shape step origin j input rs + have row (j : Stage) : P j (packetInput r j) (packetReports r j) := ⟨rfl,rfl,source_at r shape step origin j⟩ + have rest : SourceWalk P [.colorPrepare,.colorRead,.tagPrepare,.tagRead] (packetInput r .colorPrepare) + (r.color.prep ++ (r.color.reads ++ (r.offsets.prep ++ r.offsets.reads))) := + SourceWalk.next (row .colorPrepare) (SourceWalk.next (row .colorRead) + (SourceWalk.next (row .tagPrepare) (SourceWalk.singleton (row .tagRead)))) + rw [← zeroOutput r] at rest + have whole := SourceWalk.next (row .extract) (SourceWalk.next (row .zero) rest) + change SourceWalk P stages m (((((packetReports r .extract ++ packetReports r .zero) ++ + r.color.prep) ++ r.color.reads) ++ r.offsets.prep) ++ r.offsets.reads) + simp only [List.append_assoc] + exact whole + +/-- Six actual native segments, including the guard proof for every call. -/ +theorem walk (shape : DescriptorSpace.Shape) (step : ℕ) (origin : Expr) : + SourceWalk (Source r shape step origin) stages m r.reports := by + have forget {js input rs} (h : SourceWalk (fun j input rs => input = packetInput r j ∧ + rs = packetReports r j ∧ Source r shape step origin j input rs) js input rs) : + SourceWalk (Source r shape step origin) js input rs := by + induction h with + | done => exact .done _ + | next head _ tail => exact .next head.2.2 tail + exact forget (indexed_walk r shape step origin) + +end CompressorRecords.GreedyVisit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGreedyWalkValid.lean b/lean/OAI/Computability/VPVNP/CompressorGreedyWalkValid.lean new file mode 100644 index 0000000000..24d89cd3e6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGreedyWalkValid.lean @@ -0,0 +1,143 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedyPhases + +/-! +# Dispatcher guards for the greedy record readers + +Every call writes its vertex's label, reads the next cursor from the immutable +record header and leaves the active dispatcher frame intact. Consequently +the guard continues through all records and stops at the first address past +the directory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy.WalkLayout + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {w N width q : ℕ} + +private theorem base_lt_stop (L : WalkLayout w N width) (space : L.limit < 2 ^ w) (i : Fin N) : + L.base i.val < L.base N := by + have h : L.origin + N + i.val * (2 + width) < L.limit := + Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_right i.isLt (by omega)) _ + change (L.origin + N + i.val * (2 + width)) % (2 ^ w) < L.limit % (2 ^ w) + rwa [Nat.mod_eq_of_lt (h.trans space), Nat.mod_eq_of_lt space] + +private theorem has_visit (m : Memory w) (base : Word w) (arity n : ℕ) (fit : n < 2 ^ w) : + ∃ value, Visit m base arity n value := by + obtain ⟨_, regs, _, _, _, h⟩ := choose_trace base m arity n (fun _ ↦ base + 1 + 1) fit + exact ⟨regs 2, visit_native m base _ arity n fit h.symm⟩ + +private def fixedOutsideLabels (L : WalkLayout w N width) (initial m : Memory w) : Prop := + ∀ z, z < L.origin ∨ L.origin + N ≤ z → m z = initial z + +/-- Induction along the actual reader reports. At each boundary the immutable +directory still supplies the next cursor and the memory outside the labels is +unchanged from the prepared input. -/ +private theorem read_induction (L : WalkLayout w N width) + (ptrs : Fin N → List (Word w)) (outside : Memory w) (arity n : ℕ) + (size : ∀ i, (ptrs i).length = width) (space : L.limit < 2 ^ w) (fit : n < 2 ^ w) + (Q : Word w → Memory w → List (Report w) → Prop) + (done : ∀ m, fixedOutsideLabels L (L.initialMemory ptrs outside) m → Q (L.base N) m []) + (step : ∀ (i : Fin N) m (r : Report w) rs, + fixedOutsideLabels L (L.initialMemory ptrs outside) m → L.base i.val < L.base N → + r.result = some (L.base (i.val + 1)) → Q (L.base (i.val + 1)) (after m r.events) rs → + Q (L.base i.val) m (r :: rs)) + (rs : List (Report w)) (native : runSegment (visitMachine w arity n).program + (1 + (visitCode arity n).length) (some (L.base 0)) (L.initialMemory ptrs outside) + (List.replicate N []) = some rs) : + Q (L.base 0) (L.initialMemory ptrs outside) rs := by + let initial := L.initialMemory ptrs outside + let fixed := fixedOutsideLabels L initial + let M := (visitMachine w arity n).program + let fuel := 1 + (visitCode arity n).length + have loop (left k : ℕ) (stop : k + left = N) (m : Memory w) (keep : fixed m) + (reports : List (Report w)) + (run : runSegment M fuel (some (L.base k)) m (List.replicate left []) = some reports) : + Q (L.base k) m reports := by + induction left generalizing k m reports with + | zero => + have empty : [] = reports := Option.some.inj run + subst reports + simp only [Nat.add_zero] at stop + subst k + exact done m keep + | succ left ih => + let i : Fin N := ⟨k, by omega⟩ + let labels (j : Fin N) := m (L.label j).val + have rep : L.Represents initial m id (Equiv.refl (Fin N)) labels := ⟨fun _ ↦ rfl, keep⟩ + obtain ⟨dest, next, _⟩ := rep.record L size i + obtain ⟨v, es, he, hm, _⟩ := has_visit m (L.base k) arity n fit + rw [show m (L.base k).val = L.label i from dest] at hm + rw [show m (L.base k + 1).val = L.base (k + 1) from next] at he + have nextKeep : fixed (after m es) := by + intro z hz + rw [hm] + have away : z ≠ (L.label i).val := by rw [L.label_val]; have := i.isLt; omega + exact (ite_eq_right away).trans (keep z hz) + rw [List.replicate_succ, runSegment, he] at run + obtain ⟨tail, ht, rfl⟩ := Option.map_eq_some_iff.mp run + exact step i m _ tail keep (base_lt_stop L space i) rfl (ih (k+1) (by omega) _ nextKeep _ ht) + exact loop N 0 (Nat.zero_add _) initial (fun _ _ ↦ rfl) rs native + +/-- Guard validity for any native reader trace on a prepared operand directory. +Only the mutable labels must be disjoint from the active scheduler fields. -/ +theorem read_valid (C : Schedule.Catalog q) (worker : Fin q) (ports : Schedule.Ports w) + (pub : Fin (C worker).params → Word w) (L : WalkLayout w N width) + (ptrs : Fin N → List (Word w)) (outside : Memory w) (arity n : ℕ) + (size : ∀ i, (ptrs i).length = width) (space : L.limit < 2 ^ w) (fit : n < 2 ^ w) + (tag : ports.tag.val < L.origin ∨ L.origin + N ≤ ports.tag.val) + (frame : ∀ j : Fin ((C worker).params + 1), (ports.activeFrame + (j.val : Word w)).val < L.origin ∨ + L.origin + N ≤ (ports.activeFrame + (j.val : Word w)).val) + (ready : Schedule.Ready C worker ports pub (L.base N) (L.initialMemory ptrs outside)) + (rs : List (Report w)) (native : runSegment (visitMachine w arity n).program + (1 + (visitCode arity n).length) (some (L.base 0)) (L.initialMemory ptrs outside) + (List.replicate N []) = some rs) : + Schedule.ValidTrace C worker ports pub (L.base N) (L.base 0) (L.initialMemory ptrs outside) rs := by + let initial := L.initialMemory ptrs outside + let fixed := fixedOutsideLabels L initial + have live {m : Memory w} (keep : fixed m) : Schedule.Ready C worker ports pub (L.base N) m := by + refine ⟨(keep _ tag).trans ready.1, ?_, ?_⟩ + · exact (keep _ (by simpa using frame 0)).trans ready.2.1 + · exact funext fun i ↦ (keep _ (frame i.succ)).trans (congrFun ready.2.2 i) + exact read_induction L ptrs outside arity n size space fit + (Schedule.ValidTrace C worker ports pub (L.base N)) (fun _ keep ↦ ⟨live keep, le_rfl⟩) + (fun i _ _ _ keep active ret tail ↦ ⟨live keep, active, L.base (i.val + 1), ret, tail⟩) + rs native + +end CompressorRecords.Greedy.WalkLayout + +namespace CompressorRecords.GreedyArena.Assignment + +open BurstRAM Compression Greedy +open scoped Fin.CommRing + +variable {w N width q d arity n : ℕ} {V A : Type*} +variable {L : WalkLayout w N width} {T : PortTables w} {G : SlotGraph V d} {order : V ≃ Fin N} + {rows : OperandRows d} {m : Memory w} {encode : A → Word w} {label : V → A} + +/-- The reports of the actual assignment reader can be lifted into the linked +dispatcher under the same guard as the source reader. -/ +theorem read_valid (P : Assignment L T G order rows arity n m encode label) + (C : Schedule.Catalog q) (worker : Fin q) (ports : Schedule.Ports w) + (pub : Fin (C worker).params → Word w) + (size : ∀ i : Fin N, (rowWords T G order (order.symm i) rows).length = width) + (space : L.limit < 2 ^ w) (fit : n < 2 ^ w) + (tag : ports.tag.val < L.origin ∨ L.origin + N ≤ ports.tag.val) + (frame : ∀ j : Fin ((C worker).params + 1), (ports.activeFrame + (j.val : Word w)).val < L.origin ∨ + L.origin + N ≤ (ports.activeFrame + (j.val : Word w)).val) + (ready : Schedule.Ready C worker ports pub (L.base N) (after m (eventLog P.prep))) : + Schedule.ValidTrace C worker ports pub (L.base N) (L.base 0) (after m (eventLog P.prep)) P.reads := by + have native := P.readRun + rw [P.prepMemory] at native ready ⊢ + exact WalkLayout.read_valid C worker ports pub L _ _ arity n size space fit tag frame ready _ native + +end CompressorRecords.GreedyArena.Assignment + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGroupBoundary.lean b/lean/OAI/Computability/VPVNP/CompressorGroupBoundary.lean new file mode 100644 index 0000000000..af955d7ac7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGroupBoundary.lean @@ -0,0 +1,59 @@ +import OAI.Computability.VPVNP.CompressorDeterministicGroup +import OAI.Computability.VPVNP.CompressorScheduledTraceData + +/-! # Transferring selected source records through a deterministic group + +The output agrees with the source's actual post-memory throughout the +data arena. The directory guard, ordinal, stride and protected bank are +read from the same native endpoint, so the following pass can start in +that memory with the chosen mathematical history. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM BlockPlanner DescriptorSpace Schedule SourceTransport Compression +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + {w small cap ordinal total : ℕ} {L : Layout} {pub : Fin 11 → Word w} {raw m : Memory w} + {resident : Resident B f hf w} {a g : ℕ} {X : State a g} {past : List (SelectedLevel B f hf)} +local notation "A" => BlockProgram.script B +set_option quotPrecheck false in +local notation "pt" => Workspace.ports (arity (BlockProgram.script B).catalog) (pub 2) +set_option quotPrecheck false in +local notation "tag" => LiveStageLink.tagWord w (Online.calendarIndex (BlockProgram.script B).size (BlockProgram.script B).size) + +/-- A completed source-group derivation supplies all scheduler fields of a +pass boundary and the true cost of the small-clock reports. Only the +application's data-region preservation law is required for its resident +mathematical state. -/ +theorem boundary_of_group {ps : List (SourceOnline.Packet (A) w)} + (group : SourceOnline.Group (A) L (pub 2) small ordinal total raw ps) + (quiet : ∀ p ∈ ps, p.stage.choices = List.replicate p.stage.choices.length []) + (clock : small ≤ cap) (bounds : Online.Run.ControlBounds (A).plan small (w := w)) + (arityEq : arity (A).catalog = L.shape.arity) (baseEq : (pub 2).val = L.base) + (fit : levelStart L 0 < 2^w) (count : ordinal+ps.length ≤ total) (room : total ≤ directoryRows L) + (agree : Agree (levelStart L 0 ≤ ·) raw m) + (bank : Workspace.Installed (arity (A).catalog) (pub 2) m) (htag : m (pt).tag.val = tag) + (ord : (m (pt).ordinal.val).val = ordinal) (rows : (m (pt).rows.val).val = total) + (stride : m ((pt).directory-1).val = (levelWords L : Word w)) + (stored : resident past X (SourceOnline.post raw ps)) + (transfer : ∀ u v, Agree (levelStart L 0 ≤ ·) u v → resident past X u → resident past X v) : + ∃ out : QuietInterval (A) pub cap small (some 0) m, + Boundary resident pub (levelWords L : Word w) total (ordinal+ps.length) past X out.segment.memory ∧ + Agree (levelStart L 0 ≤ ·) (SourceOnline.post raw ps) out.segment.memory ∧ + RAMBuckets.cost Report.probes out.source.logs ≤ groupCost (A) ps := by + obtain ⟨out,agreement,bank',tag',ordinal',total',stride',cost⟩ := + deterministicGroup group quiet clock bounds arityEq baseEq fit count room agree bank htag ord rows stride + exact ⟨out,⟨bank',tag',ordinal',total',stride',transfer _ _ agreement stored⟩,agreement,cost⟩ + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorGroupCost.lean b/lean/OAI/Computability/VPVNP/CompressorGroupCost.lean new file mode 100644 index 0000000000..4216982efb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorGroupCost.lean @@ -0,0 +1,37 @@ +import OAI.Computability.VPVNP.CompressorDeterministicGroup + +/-! # Communication charges across a source-group split + +Each source report and each descriptor row is charged once. A bound on the +full native pass therefore covers its two deterministic intervals and its +selected row at the same rate. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM BlockPlanner + +variable {w : ℕ} + +/-- Concatenating source groups adds their report and descriptor charges. -/ +theorem groupCost_append (A : Script) (xs ys : List (SourceOnline.Packet A w)) : + groupCost A (xs++ys) = groupCost A xs + groupCost A ys := by + simp only [groupCost,List.flatMap_append,RAMBuckets.cost_append,List.length_append,Nat.add_mul] + ac_rfl + +/-- Exact charge of a selector together with its forced prefix and suffix. -/ +theorem groupCost_split_selector (A : Script) (before : List (SourceOnline.Packet A w)) + (selected : SourceOnline.Packet A w) (tail : List (SourceOnline.Packet A w)) : + groupCost A (before++selected::tail) = groupCost A before + groupCost A [selected] + groupCost A tail := by + change groupCost A (before++([selected]++tail)) = _ + rw [groupCost_append,groupCost_append,Nat.add_assoc] + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorHeaderOperands.lean b/lean/OAI/Computability/VPVNP/CompressorHeaderOperands.lean new file mode 100644 index 0000000000..dc3a50d892 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorHeaderOperands.lean @@ -0,0 +1,115 @@ +import OAI.Computability.VPVNP.CompressorBlockInitialPackets + +/-! +# Planner reads for the initial and substep header visits + +The first-header formula reads the row count. Level offsets read the pitch. +Only the cursor planner loads additional words, namely its six scalar inputs +in the permanent first-level frame. These facts apply to each reference +memory at which the corresponding visit is prepared. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.HeaderOperands + +open BurstRAM PhaseRecipe BlockPlanner BlockHeaderRun DescriptorSpace +open scoped Fin.CommRing +open private fit_fields address_val from OAI.Computability.VPVNP.CompressorBlockHeaderRun + +variable {w : ℕ} (D : ℕ → Prop) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + +/-- The start, stop, and parameter expressions of a visit read only addresses allowed by the +specified region. -/ +structure Supported (v : Visit) : Prop where + initial : v.initial.ReadsFrom D pub s m + stop : v.stop.ReadsFrom D pub s m + params : ∀ j, (v.params j).ReadsFrom D pub s m + +private theorem first (rows : D (pub 3).val) : BlockHeaderPlan.firstHeader.ReadsFrom D pub s m := + ⟨trivial,⟨⟨⟨trivial,trivial⟩,trivial⟩,trivial,rows⟩⟩ + +private theorem atLevel (pitch : D (pub 1-1).val) (i : ℕ) : (LevelFields.atLevel i).ReadsFrom D pub s m := + ⟨trivial,trivial,⟨trivial,trivial⟩,pitch⟩ + +private theorem formula {g : ℕ} (r : FormulaRow g) (src dest : Expr) (hs : src.ReadsFrom D pub s m) + (hd : dest.ReadsFrom D pub s m) : Supported D pub s m (BlockHeaderPlan.formula r src dest) := by + refine ⟨hs,⟨hs,trivial⟩,?_⟩ + intro i + fin_cases i <;> first | exact hd | trivial + +private theorem heads (F : Shape) (dest : Expr) (hd : dest.ReadsFrom D pub s m) + (rows : D (pub 3).val) : Supported D pub s m (BlockHeaderPlan.heads F dest) := by + refine ⟨trivial,trivial,?_⟩ + intro i + fin_cases i <;> first | exact hd | exact first D pub s m rows | trivial + +private theorem cursor (L : Layout) (nonempty : 0 < L.levels) (fields : 14 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (rows : D (pub 3).val) (data : ∀ x, levelStart L 0 ≤ x → D x) + (hFirst : BlockHeaderPlan.firstHeader.eval pub s m = header w L 0) : + Supported D pub s m (BlockPlanner.cursor BlockHeaderPlan.persistentFrame) := by + let frame := BlockHeaderPlan.persistentFrame + let read := fun i : ℕ ↦ Expr.load (frame.add (.lit i)) + have hf : frame.eval pub s m = header w L 0+6 := by + change BlockHeaderPlan.firstHeader.eval pub s m + ((6 : ℕ) : Word w) = _ + rw [hFirst,Nat.cast_ofNat] + have hdr : frame.ReadsFrom D pub s m := ⟨first D pub s m rows,trivial⟩ + have ok (i : ℕ) (hi : i < 8) : (read i).ReadsFrom D pub s m := by + refine ⟨⟨hdr,trivial⟩,?_⟩ + change D (frame.eval pub s m+(i : Word w)).val + rw [hf,show header w L 0+6+(i : Word w) = header w L 0+((6+i : ℕ) : Word w) by simp [add_assoc]] + have bound := fit_fields L ⟨0,nonempty⟩ fit + change levelStart L 0+L.shape.scalarFields < 2^w at bound + rw [address_val L 0 _ (by omega)] + exact data _ (Nat.le_add_right ..) + let cnt := (((read 3).mul (read 4)).mul (read 5)).mul (read 2) + have hc : cnt.ReadsFrom D pub s m := ⟨⟨⟨ok 3 (by decide),ok 4 (by decide)⟩,ok 5 (by decide)⟩,ok 2 (by decide)⟩ + refine ⟨trivial,hc,?_⟩ + change ∀ j : Fin (5+6), ((Fin.append (fun j : Fin 5 ↦ read (j.val+2)) + (fun c : Fin 6 ↦ (read 7).add ((Expr.lit c.val).mul cnt))) j).ReadsFrom D pub s m + apply Fin.addCases + · intro i + rw [Fin.append_left] + exact ok _ (by have := i.isLt; omega) + · intro i + rw [Fin.append_right] + exact ⟨ok 7 (by decide),trivial,hc⟩ + +/-- Covers the concrete four visits in their true order, including the +level-zero role word at offset 27. -/ +theorem initial (L : Layout) (a : ℕ) (nonempty : 0 < L.levels) (fields : 14 ≤ L.shape.scalarFields) + (fit : endAddress L < 2^w) (rows : D (pub 3).val) (pitch : D (pub 1-1).val) + (data : ∀ x, levelStart L 0 ≤ x → D x) (hFirst : BlockHeaderPlan.firstHeader.eval pub s m = header w L 0) + (v : Visit) (hv : v ∈ BlockInitialPackets.order L a) : Supported D pub s m v := by + rcases List.mem_cons.mp hv with rfl|hv + · exact formula D pub s m _ _ _ ⟨first D pub s m rows,trivial⟩ (first D pub s m rows) + rcases List.mem_cons.mp hv with rfl|hv + · exact heads D pub s m _ _ (first D pub s m rows) rows + rcases List.mem_cons.mp hv with rfl|hv + · exact cursor D pub s m L nonempty fields fit rows data hFirst + obtain rfl := List.mem_singleton.mp hv + refine ⟨trivial,trivial,?_⟩ + intro i + fin_cases i + · exact ⟨atLevel D pub s m pitch 0,trivial⟩ + · trivial + +/-- At any substep the two scalar publishers need only the runtime pitch. +The pointer publisher also reads the row count to locate the first level. -/ +theorem substep (F : Shape) {a b : ℕ} (step : ℕ) (p : Scalars.Pass a b) (rows : D (pub 3).val) + (pitch : D (pub 1-1).val) (v : Visit) (hv : v ∈ BlockHeaderPlan.substep F step p) : + Supported D pub s m v := by + rcases List.mem_cons.mp hv with rfl|hv + · exact formula D pub s m _ _ _ (atLevel D pub s m pitch step) (atLevel D pub s m pitch step) + rcases List.mem_cons.mp hv with rfl|hv + · exact formula D pub s m _ _ _ (atLevel D pub s m pitch step) (atLevel D pub s m pitch (step+1)) + obtain rfl := List.mem_singleton.mp hv + exact heads D pub s m _ _ (atLevel D pub s m pitch (step+1)) rows + +end CompressorRecords.HeaderOperands + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorHistoryArenaBase.lean b/lean/OAI/Computability/VPVNP/CompressorHistoryArenaBase.lean new file mode 100644 index 0000000000..d8d3f1baf9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorHistoryArenaBase.lean @@ -0,0 +1,201 @@ +import OAI.Computability.VPVNP.CompressorDescriptorParameters +import OAI.Computability.VPVNP.CompressorDescriptorStride + +/-! +# Installing the initial history arena and traversal bounds + +After the stride pass, the row count and level stride suffice to compute +the exclusive end of the tight descriptor allocation. The pair-ABI program +writes that end to scalar 14 of the first level, the level count to scalar +28, and the live input length to scalar 29. All source expressions run +before any of the three external stores. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.HistoryArenaBase + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PhaseRecipe RowRecipe +open DescriptorSpace DescriptorParameters +open scoped Fin.CommRing +open private low ptr one Assign.code lines_trace zeros eval_cost from + OAI.Computability.VPVNP.CompressorRecordsRowRecipe + +variable {r w : ℕ} + +private def stores (R : Recipe r 5 2) : List (Op (r+2) 5) := + [.write (low R.dest) (low R.tag), .write (low R.start) (low R.stop), + .write (low (R.params 0)) (low (R.params 1)), .stateWord (ptr r), + .constant (one r) 1, .binary .add (ptr r) (ptr r) (one r)] + +private def ops (R : Recipe r 5 2) := R.lines.map Assign.code ++ stores R + +private def changes (R : Recipe r 5 2) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) := + let v := R.values pub s m + writeMemory (writeMemory (writeMemory m (v R.dest) (v R.tag)) (v R.start) (v R.stop)) + (v (R.params 0)) (v (R.params 1)) + +private def scanReport (R : Recipe r 5 2) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : Report w := + let v := R.values pub s m + ⟨(evaluate pub s m R.lines (fun _ ↦ 0)).1 ++ + [.write (v R.dest) (v R.tag), .write (v R.start) (v R.stop), .write (v (R.params 0)) (v (R.params 1)), + .tick,.tick,.tick],some (s+1)⟩ + +private theorem trace_stores (R : Recipe r 5 2) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + ∃ out, trace pub s (ops R) (fun _ ↦ 0) m = some ((scanReport R pub s m).events,out,changes R pub s m) ∧ + out (ptr r) = s+1 := by + rw [ops,zeros,trace_append,lines_trace] + simp [stores,trace,Op.effect,low,ptr,one,scanReport,changes,Recipe.values, + BinaryOp.eval,Function.update,Fin.append_left] + +private theorem native_stores (R : Recipe r 5 2) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + let M := (template (ops R) (ptr r)).instantiate w pub + let rep := scanReport R pub s m + execute M.program (1+(ops R).length) (M.program.start s) m [] = some rep ∧ + after m rep.events = changes R pub s m ∧ rep.events.length = (ops R).length ∧ + rep.probes = R.reads+3 ∧ choiceBits rep.events = [] := by + intro M rep + obtain ⟨out,ht,hr⟩ := trace_stores R pub s m + have run : execute M.program (1+(ops R).length) (M.program.start s) m [] = some rep := by + change execute ((template (ops R) (ptr r)).instantiate w pub).program _ + ⟨((template (ops R) (ptr r)).instantiate w pub).entry,s,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + rw [execute_template,run_eq_trace,ht]; simp [hr,rep,scanReport] + have cost := eval_cost pub s m R.lines (fun _ ↦ 0) + refine ⟨run,Greedy.trace_after ht,?_,?_,(execute_spec run).2.2⟩ + · simp [rep,scanReport,ops,stores,cost.1] + · simp [rep,scanReport,Report.probes,Greedy.probes_append,countProbes,Recipe.reads,cost.2] + +private def levels (initial phases steps : ℕ) := + (Expr.lit 1).add ((calendarBlocks initial phases).mul (.lit (steps+1))) + +private def stride (F : Shape) := Expr.load ((.publicWord 0 : Expr).add (.lit (10+F.arity))) + +private def calculation (F : Shape) (initial phases steps : ℕ) : FormulaRow 2 := + let head := firstLevel F.arity + let num := levels initial phases steps + ⟨head.add (.lit 14), ![head.add (num.mul (stride F)),head.add (.lit 28),num,head.add (.lit 29),.publicWord 1]⟩ + +/-- One fixed pair-ABI table performs the three separated stores. -/ +def table (F : Shape) (initial phases steps : ℕ) := + let R := (calculation F initial phases steps).recipe + LiveStageLink.widen (template (ops R) (ptr _)) (Function.Embedding.refl _) operand + +/-- Native report publishing the history arena base, allocated level count, and input length in +the first level header. -/ +def report (F : Shape) (initial phases steps : ℕ) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) := + scanReport (calculation F initial phases steps).recipe (pub ∘ operand) s m + +/-- Instruction count for computing and publishing the three initial history fields. -/ +def cost (F : Shape) (initial phases steps : ℕ) := (ops (calculation F initial phases steps).recipe).length + +/-- Number of external probes for history setup, including the three header stores after +evaluating the recipe. -/ +def probes (F : Shape) (initial phases steps : ℕ) := (calculation F initial phases steps).recipe.reads+3 + +/-- The exact three memory updates produced by the stage. -/ +def install (L : Layout) (n : ℕ) (m : Memory w) : Memory w := + let head := levelStart L 0 + writeMemory (writeMemory (writeMemory m ((head+14 : ℕ) : Word w) (endAddress L : Word w)) + ((head+28 : ℕ) : Word w) (L.levels : Word w)) ((head+29 : ℕ) : Word w) (n : Word w) + +/-- Exact native execution after the chronological count and level stride +have been published. All cells outside the three destinations are preserved. -/ +theorem native {L B n initial phases T pub m} (h : Ready (w := w) L B n initial phases T pub m) + (steps : ℕ) (hlevels : L.levels = 1+T*(steps+1)) + (pitch : m (pub 2 + ((10+L.shape.arity : ℕ) : Word w)).val = (levelWords L : Word w)) + (s : Word w) : + let M := (table L.shape initial phases steps).instantiate w pub + let rep := report L.shape initial phases steps pub s m + execute M.program (1+cost L.shape initial phases steps) (M.program.start s) m [] = some rep ∧ + after m rep.events = install L n m ∧ rep.result = some (s+1) ∧ + rep.events.length = cost L.shape initial phases steps ∧ + rep.probes = probes L.shape initial phases steps ∧ choiceBits rep.events = [] := by + intro M rep + let R := calculation L.shape initial phases steps + let p := pub ∘ operand + have hr := native_stores R.recipe p s m + have hv : (levels initial phases steps).eval p s m = (L.levels : Word w) := by + change 1+(calendarBlocks initial phases).eval (pub ∘ operand) s m * ((steps+1 : ℕ) : Word w) = _ + rw [eval_blocks h, hlevels] + push_cast + rfl + have head : (firstLevel L.shape.arity).eval p s m = ((levelStart L 0 : ℕ) : Word w) := eval_level h s + have hs : (stride L.shape).eval p s m = (levelWords L : Word w) := pitch + have hend : levelStart L 0 + L.levels * levelWords L = endAddress L := by + simp [levelStart,endAddress] + have dest : R.recipe.values p s m R.recipe.dest = ((levelStart L 0+14 : ℕ) : Word w) := by + change R.recipe.address p s m = _ + rw [FormulaRow.recipe_address] + change (firstLevel L.shape.arity).eval p s m + 14 = _ + rw [head,Nat.cast_add,Nat.cast_ofNat] + have values : R.recipe.words p s m = + [(endAddress L : Word w),((levelStart L 0+28 : ℕ) : Word w),(L.levels : Word w), + ((levelStart L 0+29 : ℕ) : Word w),(n : Word w)] := by + rw [FormulaRow.recipe_words] + have vals : (fun j ↦ (R.fields j).eval p s m) = ![(endAddress L : Word w), + ((levelStart L 0+28 : ℕ) : Word w),(L.levels : Word w),((levelStart L 0+29 : ℕ) : Word w),(n : Word w)] := by + funext j + fin_cases j + · change (firstLevel L.shape.arity).eval p s m + (levels initial phases steps).eval p s m * (stride L.shape).eval p s m = _ + rw [head,hv,hs,← hend,Nat.cast_add,Nat.cast_mul]; rfl + · change (firstLevel L.shape.arity).eval p s m + 28 = ((levelStart L 0+28 : ℕ) : Word w) + rw [head,Nat.cast_add,Nat.cast_ofNat] + · exact hv + · change (firstLevel L.shape.arity).eval p s m + 29 = ((levelStart L 0+29 : ℕ) : Word w) + rw [head,Nat.cast_add,Nat.cast_ofNat] + · apply Fin.ext + exact h.length.trans (Nat.mod_eq_of_lt (h.length ▸ (pub 6).isLt)).symm + rw [vals] + rfl + have updates : changes R.recipe p s m = install L n m := by + have i (j : Fin 5) := congrArg (fun xs : List (Word w) ↦ xs[j.val]?) values + have v₀ := Option.some.inj (i 0) + have v₁ := Option.some.inj (i 1) + have v₂ := Option.some.inj (i 2) + have v₃ : R.recipe.values p s m (R.recipe.params 0) = ((levelStart L 0+29 : ℕ) : Word w) := Option.some.inj (i 3) + have v₄ : R.recipe.values p s m (R.recipe.params 1) = (n : Word w) := Option.some.inj (i 4) + simp only [changes,install,dest,v₀,v₁,v₂,v₃,v₄] + exact ⟨(LiveStageLink.execute_widen_start ..).trans hr.1,hr.2.1.trans updates,rfl,hr.2.2⟩ + +/-- The first-level scalars hold the full natural numbers for the history +traversal, including the exclusive end of the arena allocation. -/ +theorem stored (L : Layout) (n : ℕ) (m : Memory w) (hn : n < 2^w) + (hl : 0 < L.levels) (hs : 30 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) : + let head := levelStart L 0 + let out := install L n m + (out (head+14)).val = endAddress L ∧ (out (head+28)).val = L.levels ∧ (out (head+29)).val = n ∧ + ∀ j, j ≠ head+14 → j ≠ head+28 → j ≠ head+29 → out j = m j := by + intro head out + have hwords : 30 ≤ levelWords L := by + apply hs.trans + unfold levelWords levelHeaderWords + omega + have hpos : 0 < levelWords L := (by decide : 0 < 30).trans_le hwords + have levelsFit : L.levels < 2^w := (Nat.le_mul_of_pos_right _ hpos).trans_lt + ((Nat.le_add_left .. : L.levels * levelWords L ≤ endAddress L).trans_lt fit) + have hlimit : head+30 ≤ endAddress L := calc + _ ≤ levelStart L 1 := by simpa [head,levelStart] using Nat.add_le_add_left hwords (levelsBase L) + _ ≤ _ := levelStart_mono L hl + have bound (j : ℕ) (hj : j < 30) : ((head+j : ℕ) : Word w).val = head+j := + Nat.mod_eq_of_lt (lt_trans ((Nat.add_lt_add_left hj head).trans_le hlimit) fit) + have outAt (j : ℕ) : out j = if j = head+29 then (n : Word w) else + if j = head+28 then (L.levels : Word w) else if j = head+14 then (endAddress L : Word w) else m j := by + simp only [out,install,writeMemory] + rw [bound 14 (by decide),bound 28 (by decide),bound 29 (by decide)] + refine ⟨?_,?_,?_,?_⟩ + · rw [outAt,ite_eq_right (by omega),ite_eq_right (by omega),ite_eq_left rfl] + exact Nat.mod_eq_of_lt fit + · rw [outAt,ite_eq_right (by omega),ite_eq_left rfl] + exact Nat.mod_eq_of_lt levelsFit + · rw [outAt,ite_eq_left rfl] + exact Nat.mod_eq_of_lt hn + · intro j h₁ h₂ h₃ + simp only [outAt,ite_eq_right h₃,ite_eq_right h₂,ite_eq_right h₁] + +end CompressorRecords.HistoryArenaBase + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialBoundary.lean b/lean/OAI/Computability/VPVNP/CompressorInitialBoundary.lean new file mode 100644 index 0000000000..fc2abfcd6a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialBoundary.lean @@ -0,0 +1,73 @@ +import OAI.Computability.VPVNP.CompressorInitialScheduled +import OAI.Computability.VPVNP.CompressorInitialProbeRate +import OAI.Computability.VPVNP.CompressorCurrentResident + +/-! # The stored cursor state at the first selected compression pass + +The four physical cursor workers publish the degree, site and lane counts, +the six incidence columns, the table heads and the initial DFS base. These +words and the zero cursor role initialize the selected directory history. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace + +open BurstRAM Compression DescriptorSpace Schedule BlockPlanner BlockHeaderRun +open PairSimulation.LocalHistory PairSimulation.TraversalRows PairSimulation.TraversalRoles +open scoped Fin.CommRing + +variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {base positions blocks cap small b l width n : ℕ} {pub : Fin 11 → Word w} {m : Memory w} + {X : State (S.degreeExponent 0) l} + +local notation "L" => BlockProgram.layout B base positions blocks +local notation "a₀" => S.degreeExponent 0 +local notation "A" => BlockProgram.script B + +/-- The persistent cursor frame read by later passes from the first level. -/ +def cursorFrame (alloc : Layout) (a b l width : ℕ) : Fin 8 → Word w := + CursorRAM.ScheduleInit.inputs (CursorRAM.encode w (directoryBase alloc)) (CursorRAM.encode w 1) b l a width (incidenceStart alloc 0) + +variable (init : InitialInterval B base positions blocks cap small b l width pub m) + +theorem InitialInterval.boundary {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) + (cursor : BlockStartupPrefix.Resident L a₀ b l width n (pub 2) m X) + (fit : endAddress L < 2^w) : + Boundary (CurrentResident.resident B f hf ⟨leafLayer (siteOrder X),.cursor⟩ L (endAddress L) n (cursorFrame L a₀ b l width)) + pub (levelWords L : Word w) (directoryRows L) 4 [] X init.interval.segment.memory := by + exact ⟨init.bank,init.tag,init.ordinal,init.total,init.stride, + CurrentResident.initial_live cursor init.agrees (by change 0 < 1+(S.steps+1)*blocks; omega) (by change 14 ≤ 54; decide) fit⟩ + +/-- Coefficient depending only on the fixed script, independent of the +length, memory, row count and group-specific histogram. -/ +def initialRate (B : S.Templates) := + let script := BlockProgram.script B + let a := S.degreeExponent 0 + (7*2^a + InitialProbeRate.fixed (BlockProgram.layout B 0 0 0) a)*(arity script.catalog+3) + + 4*(Online.Run.maxReads script.plan+4*arity script.catalog+26) + +theorem InitialInterval.rate (cursor : BlockStartupPrefix.Resident L a₀ b l width n (pub 2) m X) + : RAMBuckets.cost Report.probes init.interval.source.logs ≤ initialRate B*(positions+1) := by + apply init.cost.trans + have rows : CursorRAM.rowCount b l a₀ = positions*2^a₀ := by + change ((b+l)*2^b*2^l)*2^a₀ = _ + exact congrArg (· * 2^a₀) cursor.positions + unfold initialCost initialRate + rw [(InitialProbeRate.raw L a₀ b l width m).2,rows,InitialProbeRate.fixed_layout] + let g := arity (Script.catalog (BlockProgram.script B))+3 + let h := InitialProbeRate.fixed (BlockProgram.layout B 0 0 0) a₀ + let ov := 4*(Online.Run.maxReads (Script.plan (BlockProgram.script B))+4*arity (Script.catalog (BlockProgram.script B))+26) + change (7*(positions*2^a₀)+h)*g+ov ≤ ((7*2^a₀+h)*g+ov)*(positions+1) + nlinarith only [Nat.zero_le (h*g*positions), Nat.zero_le (ov*positions), Nat.zero_le (7*2^a₀*g)] + +end CompressorRecords.ScheduledTrace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialClocks.lean b/lean/OAI/Computability/VPVNP/CompressorInitialClocks.lean new file mode 100644 index 0000000000..f2cc2b08b6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialClocks.lean @@ -0,0 +1,58 @@ +import OAI.Computability.VPVNP.CompressorBlockClock +import OAI.Computability.VPVNP.LiveCompressedPairHandoff +import OAI.Computability.VPVNP.LiveCompressedPairSourceCaps + +/-! # The block program's source clock within the live pair clock + +The inner source reports run at the fixed block program's polylogarithmic +clock. The workspace frame needs twenty-four ticks per call, and the pair +transfer needs three further ticks on a terminating source report. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM Compression Schedule CursorBounds LiveProgram Filter +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Private clock left after the online dispatch and the twenty-four framing instructions. -/ +def sourceCap {w : ℕ} (pub : Fin 11 → Word w) (clock : ℕ) := + CompressedPair.clockAt pub clock CompressedPair.Stage.online - 24 + +set_option exponentiation.threshold 10000 in +theorem pair_room {G : PairStages.Group} {w n small : ℕ} (pub : Fin 11 → Word w) + (hn : 128 ≤ n) (clock : G.clock = n^10000) (size : small ≤ n^9999) : + small+3 ≤ sourceCap pub (G.clockAt LiveProgram.Stage.pair) ∧ + sourceCap pub (G.clockAt LiveProgram.Stage.pair)+24 = + CompressedPair.clockAt pub (G.clockAt LiveProgram.Stage.pair) CompressedPair.Stage.online := by + have upper := CompressedPair.private_clock_room G hn clock + have disp : (LiveStageLink.dispatchEvents (PairTag.address pub) CompressedPair.Stage.online).length = 20 := rfl + unfold sourceCap CompressedPair.clockAt + rw [disp] + omega + +set_option exponentiation.threshold 10000 in +/-- The same length threshold supplies the real smaller clock and the +three transfer ticks for every group and every eleven-word operand vector. -/ +theorem eventually_clocks (addr : ℕ) (ha : 1 ≤ addr) : + ∀ᶠ n : ℕ in atTop, let small := BlockClock.small B addr n + let script := BlockProgram.script B + InitialScriptPackets.budget script (BlockProgram.layout B 0 0 0) (S.degreeExponent 0) ≤ small ∧ + Online.Run.ControlBounds script.plan small (w := wordBits addr n) ∧ + ∀ (G : PairStages.Group) (pub : Fin 11 → Word (wordBits addr n)), G.clock = n^10000 → + small+3 ≤ sourceCap pub (G.clockAt LiveProgram.Stage.pair) ∧ + sourceCap pub (G.clockAt LiveProgram.Stage.pair)+24 = + CompressedPair.clockAt pub (G.clockAt LiveProgram.Stage.pair) CompressedPair.Stage.online := by + filter_upwards [BlockClock.eventually_room B addr ha 0,eventually_ge_atTop 128] with n room hn + intro small script + exact ⟨(BlockClock.start B addr n 0 0 0).1,room.2 _ le_rfl,fun G pub clock => + pair_room pub hn clock ((by simpa using room.1 : small ≤ n).trans (Nat.le_self_pow (by decide) _))⟩ + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialConverse.lean b/lean/OAI/Computability/VPVNP/CompressorInitialConverse.lean new file mode 100644 index 0000000000..85d2875fae --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialConverse.lean @@ -0,0 +1,133 @@ +import OAI.Computability.VPVNP.CompressorBlockInitialPackets +import OAI.Computability.VPVNP.CompressorWorkspaceBranchCut +import OAI.Computability.VPVNP.CompressorSourceBankFrame + +/-! +# Forced physical execution of the initial cursor visits + +All four data workers consume only empty choice strings. Calendar, planner, +launcher and closing calls also consume empty strings. Any accepted framed +run therefore has exactly the native initial reports and memory before the +next compressor phase. With four directory rows the next calendar call is +the final accepting call. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.InitialConverse + +open BurstRAM BlockPlanner DescriptorSpace BranchSegments Schedule +open scoped Fin.CommRing + +variable {w : ℕ} (A : Script) (pub : Fin 11 → Word w) +local notation "pt" => Workspace.ports (arity A.catalog) (pub 2) +local notation "tag" => LiveStageLink.tagWord w (Online.calendarIndex A.size A.size) +local notation "P" => OnlineWorkspace.program A.plan pub + +private theorem bits_empty (cap : ℕ) (m : Memory w) (steps : List (Online.Run.Step A.size A.size w)) + (run : Online.Run.Interval A.plan pt cap m steps) + (empty : ∀ st ∈ steps, ∀ r ∈ st.row.reports, choiceBits r.events = []) : + ∀ st ∈ steps, st.row.choices = List.replicate st.row.choices.length [] := by + induction steps generalizing m with + | nil => simp + | cons st rest ih => + intro u hu + rcases List.mem_cons.mp hu with rfl|hu + · have paths := ((runSegment_iff ..).mp run.1.source.sourceRun).2.2 + apply List.eq_replicate_length.mpr + intro b hb + rw [← paths] at hb + obtain ⟨r,hr,rfl⟩ := List.mem_map.mp hb + exact empty _ List.mem_cons_self r hr + · exact ih _ run.2 (fun u mem ↦ empty u (List.mem_cons_of_mem _ mem)) u hu + +theorem quiet (L : Layout) (a b l width cap : ℕ) (m : Memory w) (steps : List (Online.Run.Step A.size A.size w)) + (run : Online.Run.Interval A.plan pt cap m steps) + (trace : (steps.map (fun st ↦ st.row.reports)).flatten = BlockInitialPackets.logs L a b l width m) : + Online.Run.intervalBits steps = List.replicate (Online.Run.intervalBits steps).length [] := by + apply Online.Run.quietInterval + apply bits_empty A pub cap m steps run + intro st hs r hr + apply BlockInitialPackets.quiet L a b l width m r + rw [← trace] + exact List.mem_flatten.mpr ⟨st.row.reports,List.mem_map.mpr ⟨st,hs,rfl⟩,hr⟩ + +/-- Each accepting framed tape has the entire verified prefix, also when +the next selected level admits no accepting branches. -/ +def cut (L : Layout) (a b l width cap : ℕ) (m : Memory w) (steps : List (Online.Run.Step A.size A.size w)) + (bounds : Online.Run.ControlBounds A.plan cap (w := w)) (tagged : m (pt).tag.val = tag) + (bank : Workspace.Installed (arity A.catalog) (pub 2) m) + (run : Online.Run.Interval A.plan pt cap m steps) + (stable : SourceBankFrame.Stable ((pub 2).val+6) m (Online.Run.intervalLog A.plan pt m steps)) + (trace : (steps.map (fun st ↦ st.row.reports)).flatten = BlockInitialPackets.logs L a b l width m) : + Cut P (cap+24) (some 0) m Unit := + let inner := Online.Run.intervalSegment A.plan pt (state := 0) bounds tagged steps run + let outer := OnlineWorkspace.framedSegment A.plan pub inner (stable.banks bank) + Cut.deterministic outer (Online.Run.intervalBits steps).length (quiet A pub L a b l width cap m steps run trace) + +private theorem valid_at_end (cap : ℕ) (m : Memory w) (steps : List (Online.Run.Step A.size A.size w)) + (run : Online.Run.Interval A.plan pt cap m steps) + (closed : let endMem := Online.Run.finalMemory (C := A.catalog) pt m steps + endMem (pt).rows.val ≤ endMem (pt).ordinal.val) : + Online.Run.Valid A.plan pt cap m steps := by + induction steps generalizing m with + | nil => exact closed + | cons s rest ih => exact ⟨run.1,ih _ run.2 closed⟩ + +private theorem logs_end (m : Memory w) (steps : List (Online.Run.Step A.size A.size w)) : + Online.Run.reports A.plan pt m steps = Online.Run.intervalLog A.plan pt m steps ++ + [Online.linked pt (Online.calendarIndex A.size A.size) + (LevelCalendar.closedReport (pt).data (Online.Run.finalMemory (C := A.catalog) pt m steps))] := by + induction steps generalizing m with + | nil => rfl + | cons s ss ih => + simp only [Online.Run.reports,Online.Run.intervalLog,Online.Run.finalMemory,ih,List.append_assoc] + +/-- When the four initial rows exhaust the calendar, the fully framed +program has exactly one accepting tape and one report log. -/ +theorem exhausted (L : Layout) (a b l width cap : ℕ) (m : Memory w) (steps : List (Online.Run.Step A.size A.size w)) + (bounds : Online.Run.ControlBounds A.plan cap (w := w)) (tagged : m (pt).tag.val = tag) + (bank : Workspace.Installed (arity A.catalog) (pub 2) m) + (run : Online.Run.Interval A.plan pt cap m steps) + (stable : SourceBankFrame.Stable ((pub 2).val+6) m (Online.Run.intervalLog A.plan pt m steps)) + (trace : (steps.map (fun st ↦ st.row.reports)).flatten = BlockInitialPackets.logs L a b l width m) + (closed : let endMem := Online.Run.finalMemory (C := A.catalog) pt m steps + endMem (pt).rows.val ≤ endMem (pt).ordinal.val) : + let bs := Online.Run.choices steps + let logs := OnlineWorkspace.framed (pub 2) m (Online.Run.reports A.plan pt m steps) + runSegment P (cap+24) (some 0) m bs = some logs ∧ endState (some 0) logs = none ∧ + ∀ other rs, runSegment P (cap+24) (some 0) m other = some rs → endState (some 0) rs = none → + other = bs ∧ rs = logs := by + intro bs logs + have hv := valid_at_end A pub cap m steps run closed + have native := Online.Run.execute A.plan pt steps m 0 cap tagged bounds.tags bounds.calendar bounds.launch hv + have yes := (Online.Run.effect A.plan pt steps m 0 hv).2 + have full : SourceBankFrame.Stable ((pub 2).val+6) m (Online.Run.reports A.plan pt m steps) := by + rw [logs_end A pub m steps] + apply stable.append + have endMemory := Online.Run.interval_memory A.plan pt (state := 0) bounds tagged steps run + change after m (eventLog (Online.Run.intervalLog A.plan pt m steps)) = _ at endMemory + rw [endMemory] + refine ⟨?_,trivial⟩ + intro x _ + exact congrFun (Online.terminal_effect (initial := A.initial.length) (phases := A.block.length) + (d := A.size) pt _).2.1 x + have framed := OnlineWorkspace.run_framed A.plan pub cap (some 0) m bs _ native (full.banks bank) + have halt : endState (some 0) logs = none := (OnlineWorkspace.framed_effect (pub 2) m _ (some 0)).1.trans yes + have empty : bs = List.replicate bs.length [] := by + have q := quiet A pub L a b l width cap m steps run trace + change Online.Run.intervalBits steps ++ [[]] = List.replicate (Online.Run.intervalBits steps ++ [[]]).length [] + rw [List.length_append,List.replicate_add,← q] + rfl + refine ⟨framed,halt,?_⟩ + intro other rs otherRun otherHalt + obtain ⟨unique,exactLogs⟩ := accepted_empty_unique (empty ▸ framed) halt otherRun otherHalt + exact ⟨unique.trans empty.symm,exactLogs⟩ + +end CompressorRecords.InitialConverse + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialLiveBoundary.lean b/lean/OAI/Computability/VPVNP/CompressorInitialLiveBoundary.lean new file mode 100644 index 0000000000..ed6ee79c64 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialLiveBoundary.lean @@ -0,0 +1,112 @@ +import OAI.Computability.VPVNP.CompressorInitialPhysicalBoundary +import OAI.Computability.VPVNP.CompressorInitialClocks + +/-! # The complete live startup and initial descriptor boundary + +Starting with the pair tag prepared by the auxiliary copy, the physical +eleven-word table executes its eight startup calls and four cursor rows +on their actual consecutive memories. The proof uses the same smaller +clock as all selected shrinking and refresh rows. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace + +universe v + +open BurstRAM Compression DescriptorSpace BlockPlanner Schedule CursorBounds CursorNetwork CursorRouting +open LiveProgram LiveProgram.CompressedPair PairSimulation.LocalHistory PairSimulation.TraversalRows PairSimulation.TraversalRoles +open Filter +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} + (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) + +attribute [local irreducible] BlockProgram.script BlockProgram.layout BlockClock.small sourceCap + InitialTransferred.bootstrap CursorBounds.virtualBits CursorBounds.initialWidth CursorBounds.initialPositions + CursorNetwork.cursorState + +/-- The pair startup and four cursor visits, with the typed state at the first selected pass. -/ +def InitialLive (p q addr n base clk : ℕ) (terminal : PairTable) (pub : Fin 11 → Word (wordBits addr n)) + (incoming : Memory (wordBits addr n)) (hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0)) : Prop := + let boot := InitialTransferred.bootstrap B p q + let A := BlockProgram.script B + let T := roundedDown p q n + let l := T*S.laneBits + let b := virtualBits addr n-l + let L := BlockProgram.layout B base (initialPositions addr n) T + let bits : RAMSystem (virtualBits addr n) → ℕ := ramFieldBits (virtualBucket n) (wordBits addr n) + let mem := after incoming (eventLog (cursorStartupLogs boot pub addr n base incoming A.initial.length A.block.length A.size)) + StartupResult boot A.plan terminal pub addr n base incoming clk ∧ + ∃ hD : 1 < b+l, let X := cursorState (cursorCoordinateLabels b l) hD hd bits + ∃ initial : InitialInterval B base (initialPositions addr n) T (sourceCap pub clk) (BlockClock.small B addr n) + b l (initialWidth addr n) pub mem, + Boundary (CurrentResident.resident B f hf ⟨leafLayer (siteOrder X),.cursor⟩ L (endAddress L) n + (cursorFrame L (S.degreeExponent 0) b l (initialWidth addr n))) pub + (levelWords L : Word (wordBits addr n)) (directoryRows L) 4 [] X initial.interval.segment.memory ∧ + RAMBuckets.cost Report.probes initial.interval.source.logs ≤ initialRate B*(initialPositions addr n+1) ∧ + BlockClock.small B addr n+3 ≤ sourceCap pub clk ∧ + sourceCap pub clk+24 = CompressedPair.clockAt pub clk CompressedPair.Stage.online + +attribute [local semireducible] InitialTransferred.bootstrap BlockProgram.script BlockProgram.layout + +set_option exponentiation.threshold 10000 in +theorem eventually_initial_live_uniform (c : Constants) (terminal : PairTable) (p q addr : ℕ) {H : ℕ → ℕ} + (hq : 0 < q) (haddr : 1 ≤ addr) (hθ : (p : ℝ)/q ≤ 1) (lanes : S.laneBits ≤ addr) (hH : PolynomiallyBounded H) : + ∃ hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0), ∀ᶠ n : ℕ in atTop, ∀ {R : Type v} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f), + ∀ (lit : LiteralPrefix) (incoming : Memory (wordBits addr n)) (G : PairStages.Group), + let g := paperGeometry addr H n + let pub := Pieces.word g lit ∘ StageOperands.pair c + let base := (LiveProgram.Layout.pairWorkspace c).eval g + G.clock = n^10000 → incoming (PairTag.address pub).val = 0 → + InitialLive B f hf p q addr n base (G.clockAt LiveProgram.Stage.pair) terminal pub incoming hd := by + let A := BlockProgram.script B + let boot := InitialTransferred.bootstrap B p q + let base n := (LiveProgram.Layout.pairWorkspace c).eval (paperGeometry addr H n) + have hb : PolynomiallyBounded base := startup_workspace_polynomial c haddr hH + obtain ⟨hd,run⟩ := eventually_initial_uniform B p q addr hq haddr hθ lanes hb + have enough : 7 ≤ boot.shape.arity := (by decide : 7 ≤ 11).trans (InitialTransferred.arity B) + obtain ⟨K,start⟩ := eventually_physical_startup c boot A.plan terminal addr haddr hH hq + (InitialTransferred.phases_pos B) hθ lanes rfl enough (by change 30 ≤ 54; decide) + refine ⟨hd,?_⟩ + filter_upwards [run,start,eventually_startup_inputs c haddr hH,eventually_clocks B addr haddr, + eventually_polylog_le K 1,eventually_ge_atTop 128] with n initialized startup data clocks length hn + intro R _ f hf lit incoming G g pub address time tag + let clk := G.clockAt LiveProgram.Stage.pair + have low := CompressedPair.private_clock_room G hn time + have lower : K*(n.log2+1) ≤ clk := + (by simpa only [pow_one] using length : K*(n.log2+1) ≤ n).trans + ((Nat.le_self_pow (by decide : 9999 ≠ 0) n).trans (le_trans (Nat.le_add_right _ _) low)) + have ready := startup lit incoming clk tag lower + obtain ⟨ws,len,addrEq,tagLt⟩ := data lit + obtain ⟨initialBound,control,available⟩ := clocks + obtain ⟨slack,joinedClock⟩ := available G pub time + obtain ⟨hD,initial,boundary,cost⟩ := initialized f hf pub ws len addrEq (tagLt.trans_le ws.le) incoming terminal clk + (sourceCap pub clk) (BlockClock.small B addr n) ready initialBound ((Nat.le_add_right _ _).trans slack) control + exact ⟨ready,hD,initial,boundary,cost,slack,joinedClock⟩ + +set_option exponentiation.threshold 10000 in +/-- The live initialization specialized to fixed coefficients. -/ +theorem eventually_initial_live (c : Constants) (terminal : PairTable) (p q addr : ℕ) {H : ℕ → ℕ} + (hq : 0 < q) (haddr : 1 ≤ addr) (hθ : (p : ℝ)/q ≤ 1) (lanes : S.laneBits ≤ addr) (hH : PolynomiallyBounded H) : + ∃ hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0), ∀ᶠ n : ℕ in atTop, + ∀ (lit : LiteralPrefix) (incoming : Memory (wordBits addr n)) (G : PairStages.Group), + let g := paperGeometry addr H n + let pub := Pieces.word g lit ∘ StageOperands.pair c + let base := (LiveProgram.Layout.pairWorkspace c).eval g + G.clock = n^10000 → incoming (PairTag.address pub).val = 0 → + InitialLive B f hf p q addr n base (G.clockAt LiveProgram.Stage.pair) terminal pub incoming hd := by + obtain ⟨hd,allModels⟩ := eventually_initial_live_uniform B c terminal p q addr hq haddr hθ lanes hH + exact ⟨hd,allModels.mono fun _ run => run f hf⟩ + +end CompressorRecords.ScheduledTrace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialOnline.lean b/lean/OAI/Computability/VPVNP/CompressorInitialOnline.lean new file mode 100644 index 0000000000..dafcacd40c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialOnline.lean @@ -0,0 +1,185 @@ +import OAI.Computability.VPVNP.CompressorInitialScriptPackets +import OAI.Computability.VPVNP.CompressorHeaderOperands +import OAI.Computability.VPVNP.CompressorWindowPrepared +import OAI.Computability.VPVNP.CompressorBlockStartupPrefix + +/-! +# Running the four initial visits inside the online scheduler + +The source packets start from the transferred startup memory. For each +of the four actual phase indices, the runtime calendar locates level zero. +Its recipe reads the row count, pitch, and persistent data and launches +the source with those same operands. The interval retains the source +memory throughout the descriptor suffix. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.InitialOnline + +open BurstRAM DescriptorSpace BlockPlanner SourceTransport Schedule InitialScriptPackets +open scoped Fin.CommRing +open private port_bounds from OAI.Computability.VPVNP.CompressorOnlineFootprint +open private calendar_agree from OAI.Computability.VPVNP.CompressorWindowPrepared + +variable {w : ℕ} (A : Script) (L : Layout) (base : Word w) +local notation "pt" => Workspace.ports (arity A.catalog) base +local notation "H" => levelStart L 0 +local notation "gap" => Fin.val (Ports.directory pt - 1) +local notation "Pkt" => SourceWalk.Packet (SourceOnline.Visit A w) w + +private theorem low_controls (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) (fit : H < 2^w) : + (pt).rows.val < H ∧ gap < H := by + obtain ⟨dir,_,_,_⟩ := port_bounds A L base hg hb fit + have before : directoryBase L ≤ H := by simp [levelStart,levelsBase] + have ahead : L.base + 8 < directoryBase L := by simp only [directoryBase,plannerTag,frameBase]; omega + have rowsFit : base.val+8 < 2^w := hb ▸ (ahead.trans_le before).trans fit + constructor + · change (base.val+(8 : Word w).val)%2^w < H + rw [show (8 : Word w).val = 8 from Nat.mod_eq_of_lt (by omega : 8 < 2^w),Nat.mod_eq_of_lt rowsFit,hb] + exact ahead.trans_le before + · have nz : (pt).directory ≠ 0 := by + intro h + rw [h,Fin.val_zero] at dir + omega + rw [Fin.val_sub_one_of_ne_zero nz,dir] + omega + +private theorem input_before (cap : ℕ) (ps : List Pkt) (m : Memory w) + (chron : SourceWalk.Chronological SourceOnline.Visit.Runs m ps) + (checks : ∀ p ∈ ps, SourceOnline.Checked A L cap p) (x : ℕ) (below : x < H) : + ∀ p ∈ ps, p.input x = m x := by + induction ps generalizing m with + | nil => simp + | cons p ps ih => + obtain ⟨rfl,_,tail⟩ := chron + have keep : p.output x = p.input x := after_outside _ (checks p List.mem_cons_self).write (not_le_of_gt below) + intro q hq + rcases List.mem_cons.mp hq with rfl|mem + · rfl + · exact (ih p.output tail (fun j hj ↦ checks j (List.mem_cons_of_mem _ hj)) q mem).trans keep + +/-- The calendar uses the literal initial ordinal as its phase label and +level zero as its header, including at the fourth role-publication visit. -/ +private theorem phase (i : Fin A.initial.length) : + (Online.calendar A.plan).phase i.val = i.val ∧ (Online.calendar A.plan).level i.val = 0 := by + have eqn : (Online.calendar A.plan).initial.length = A.initial.length := by + simp [Online.calendar,LevelCalendar.recipeCalendar] + have bound : i.val < (Online.calendar A.plan).initial.length := by rw [eqn]; exact i.isLt + simp only [LevelCalendar.Calendar.phase,LevelCalendar.Calendar.level,ite_eq_left bound,and_self] + +theorem prepared (a : ℕ) (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) + (nonempty : 0 < L.levels) (fields : 14 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (order : A.initial = BlockInitialPackets.order L a) (i : Fin A.initial.length) (p : Pkt) + (index : p.stage.phase = i.castAdd A.block.length) + (evaluated : p.stage = HeaderPacket.attach A p.stage.phase (pt).data (BlockHeaderRun.header w L 0) p.input + p.stage.fuel p.stage.choices) + (count : p.input (pt).rows.val = (directoryRows L : Word w)) (pitch : p.input gap = (levelWords L : Word w)) + (room : i.val < directoryRows L) : + SourceOnline.Prepared A L base i.val (directoryRows L) p := by + have firstFit : H < 2^w := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + have baseEq : base = (L.base : Word w) := Fin.ext (by rw [Fin.val_natCast,← hb,Nat.mod_eq_of_lt base.isLt]) + have first : BlockHeaderPlan.firstHeader.eval (pt).data (BlockHeaderRun.header w L 0) p.input = + BlockHeaderRun.header w L 0 := by + rw [hg] + exact BlockHeaderPlan.firstHeader_eval L base p.input _ baseEq count + have member : A.visit p.stage.phase ∈ BlockInitialPackets.order L a := by + rw [index,A.initial_visit,← order] + exact List.getElem_mem .. + let data := Window.operandRegion A L base + have support := HeaderOperands.initial data (pt).data (BlockHeaderRun.header w L 0) p.input L a + nonempty fields fit (.inl rfl) (.inr (.inl rfl)) (fun _ h ↦ .inr (.inr h)) first _ member + intro live ag ordinal total _ livePitch + have active : live (pt).ordinal.val < live (pt).rows.val := Fin.lt_def.mpr (ordinal ▸ total ▸ room) + have liveCount : live (pt).rows.val = (directoryRows L : Word w) := by + apply Fin.ext; rw [Fin.val_natCast,← total,Nat.mod_eq_of_lt (live _).isLt] + obtain ⟨pc,level⟩ := phase A i + refine ⟨pc.trans (congrArg Fin.val index.symm),?_⟩ + have dir := (port_bounds A L base hg hb firstFit).1 + have dirWord : (pt).data 1 = (directoryBase L : Word w) := by + apply Fin.ext; rw [Fin.val_natCast,← dir,Nat.mod_eq_of_lt (pt).directory.isLt]; rfl + have entry := LevelFields.eval_calendar_entry (Online.calendar A.plan) (pt).data live L dirWord + (congrArg (·+3) hg) liveCount livePitch + have head : A.recipeState base live = BlockHeaderRun.header w L 0 := by + have h := entry.pointer + change A.recipeState base live = ((levelStart L (A.levelsPerBlock*(Online.calendar A.plan).level + (live (pt).ordinal.val).val) : ℕ) : Word w) at h + rwa [ordinal,level,Nat.mul_zero] at h + have agree := calendar_agree L base hg hb firstFit p.input live p.stage.phase ag (count.trans liveCount.symm) + (pitch.trans livePitch.symm) + have eqn (e : PhaseRecipe.Expr) (rd : e.ReadsFrom data (pt).data (BlockHeaderRun.header w L 0) p.input) : + A.operand base live p.stage.phase e = e.eval (pt).data (BlockHeaderRun.header w L 0) p.input := by + unfold Script.operand + rw [head] + exact (e.eval_eq_of_reads rd agree).symm + apply SourceOnline.launch_of_evaluation A base L hg hb firstFit live p.stage (ordinal ▸ room) active + · exact (eqn _ support.initial).trans (congrArg SourceOnline.Visit.start evaluated).symm + · exact (eqn _ support.stop).trans (congrArg SourceOnline.Visit.stop evaluated).symm + · intro j + have h : (p.stage.params j) = ((A.visit p.stage.phase).params j).eval (pt).data (BlockHeaderRun.header w L 0) p.input := by + cases p with + | mk v input rs => + cases v + simp only [HeaderPacket.attach,SourceOnline.Visit.mk.injEq,heq_eq_eq,true_and,and_true] at evaluated + exact congrFun evaluated.2.2 j + exact (eqn _ (support.params j)).trans h.symm + +/-- The four catalog phases run online with the same reports and choices as +their raw workers. The next ordinal is four, and every suffix word agrees +with the typed level-zero result. -/ +theorem interval (a b l width cap : ℕ) (hcap : budget A L a ≤ cap) (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) + (nonempty : 0 < L.levels) (fields : 14 ≤ L.shape.scalarFields) (fit : endAddress L < 2^w) + (order : A.initial = BlockInitialPackets.order L a) (m : Memory w) + (walk : SourceWalk (BlockInitialPackets.Source L a (pt).data (BlockHeaderRun.header w L 0)) + (BlockInitialPackets.order L a) m (BlockInitialPackets.logs L a b l width m)) + (live : 4 ≤ directoryRows L) (ord : m (pt).ordinal.val = 0) (total : (m (pt).rows.val).val = directoryRows L) + (tag : m (pt).tag.val = LiveStageLink.tagWord w (Online.calendarIndex A.size A.size)) + (pitch : m gap = (levelWords L : Word w)) : + ∃ steps : List (Online.Run.Step A.size A.size w), + Online.Run.Interval A.plan pt cap m steps ∧ steps.map Online.Run.Step.phase = indices A ∧ + (steps.map (fun step ↦ step.row.reports)).flatten = BlockInitialPackets.logs L a b l width m ∧ + Agree (H ≤ ·) (BlockInitialPackets.post L a b l width m) + (Online.Run.finalMemory (C := A.catalog) pt m steps) ∧ + ((Online.Run.finalMemory (C := A.catalog) pt m steps) (pt).ordinal.val).val = 4 ∧ + (Online.Run.finalMemory (C := A.catalog) pt m steps) (pt).rows.val = m (pt).rows.val ∧ + (Online.Run.finalMemory (C := A.catalog) pt m steps) gap = m gap ∧ + SourceBankFrame.Stable (base.val+6) m (Online.Run.intervalLog A.plan pt m steps) := by + let s := BlockHeaderRun.header w L 0 + have firstFit : H < 2^w := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + obtain ⟨ps,chron,phases,logs,checks⟩ := attach_initial A L a cap (pt).data s m _ order walk + (fun i _ ↦ (budget_bounds A L a i).1.trans hcap) (fun i _ ↦ (budget_bounds A L a i).2.trans hcap) + have hi : A.initial.length = 4 := by rw [order]; rfl + have len : ps.length = A.initial.length := by simpa [indices] using congrArg List.length phases + have native (p : Pkt) (h : p ∈ ps) := (checks p h).1 + have ⟨rowLow,gapLow⟩ := low_controls A L base hg hb firstFit + have cnt : m (pt).rows.val = (directoryRows L : Word w) := by + apply Fin.ext; rw [Fin.val_natCast,← total,Nat.mod_eq_of_lt (m _).isLt] + have prep (i : Fin ps.length) : SourceOnline.Prepared A L base (0+i.val) (directoryRows L) ps[i.val] := by + let j := i.cast len + let p := ps[i.val] + have mem : p ∈ ps := List.getElem_mem .. + have index : p.stage.phase = j.castAdd A.block.length := by + apply Fin.ext + have eqn := congrArg (fun xs : List (Fin A.size) ↦ (xs[i.val]?).map Fin.val) phases + simpa [indices,List.getElem?_eq_getElem,i.isLt,show i.val < A.initial.length by exact j.isLt,j,p] using eqn + have kept (x : ℕ) (below : x < H) : p.input x = m x := input_before A L cap ps m chron native x below p mem + simp only [Nat.zero_add] + exact prepared A L base a hg hb nonempty fields fit order j p index (checks p mem).2 + ((kept _ rowLow).trans cnt) ((kept _ gapLow).trans pitch) (j.isLt.trans_le (hi ▸ live)) + have start : (m (pt).ordinal.val).val = 0 := congrArg Fin.val ord + obtain ⟨steps,actual,phaseEq,reportEq,_,agree,done,rows,unchanged,stable⟩ := + SourceOnline.interval_stable A L base hg hb firstFit cap 0 (directoryRows L) m m ps chron native prep + (by omega) le_rfl (fun _ _ ↦ rfl) start total tag pitch + refine ⟨steps,actual,phaseEq.trans phases,?_,?_,by omega,rows,unchanged,stable⟩ + · rw [reportEq] + exact logs + · rw [logs] at agree + exact agree + +end CompressorRecords.InitialOnline + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialPairInput.lean b/lean/OAI/Computability/VPVNP/CompressorInitialPairInput.lean new file mode 100644 index 0000000000..dc86af5716 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialPairInput.lean @@ -0,0 +1,53 @@ +import OAI.Computability.VPVNP.CompressorInitialLiveBoundary +import OAI.Computability.VPVNP.PaperPairParameters + +/-! # Identifying the physical initial graph with the compression theorem's input + +Both the native cursor scan and the abstract pair input reverse the bits +within their designated base and lane blocks. Transporting the equality +of the total widths through the labels identifies the two states literally. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM Compression LiveProgram CursorNetwork CursorBounds CursorRouting +open scoped Fin.CommRing + +private theorem coordinate_state {d j l a pad : ℕ} {s : Type} [Fintype s] (eqn : d = j+l) + (hD : 1 < d) (sum : 1 < j+l) (degree : 2+pad = 2^a) (bits : s → ℕ) : + cursorState ((finCongr eqn).trans (cursorCoordinateLabels j l)) hD degree bits = + cursorState (cursorCoordinateLabels j l) sum degree bits := by + subst d + rfl + +/-- At the physical split the six-column cursor graph is the very state +used for the pair's compression choices, widths and path contraction. -/ +theorem initial_pairInput {k : Type*} [_root_.Field k] (S : BlockSchedule k) (addr n l : ℕ) + (split : l ≤ virtualBits addr n) (hD : 1 < virtualBits addr n) + (sum : 1 < (virtualBits addr n-l)+l) (hd : 2+(2^(S.degreeExponent 0)-2) = 2^(S.degreeExponent 0)) : + pairInput S (laneLabels (virtualBits addr n) l split) hD = + cursorState (cursorCoordinateLabels (virtualBits addr n-l) l) sum hd + (ramFieldBits (virtualBucket n) (wordBits addr n) : RAMSystem (virtualBits addr n) → ℕ) := + coordinate_state (Nat.sub_add_cancel split).symm hD sum hd _ + +/-- The rational program exponent gives the same number of reserved lanes +as the mathematical schedule, and the reserved lanes fit at every large length. -/ +theorem actual_laneSplit {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + (u : PairExponents B.growthConstant) (addr n : ℕ) (lanes : S.laneBits ≤ addr) (hn : 3 ≤ n) : + let T := roundedDown (blockRatio u).num (blockRatio u).den n + T = blockCount (u.θ : ℝ) n ∧ T*S.laneBits ≤ virtualBits addr n := by + intro T + have h := blockRatio_floor u n + refine ⟨h,?_⟩ + rw [show T = blockCount (u.θ : ℝ) n from h,Nat.mul_comm] + exact laneBudget addr S.laneBits n lanes (by exact_mod_cast (show u.θ ≤ 1 by linarith [u.theta_lt])) hn + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialPhysical.lean b/lean/OAI/Computability/VPVNP/CompressorInitialPhysical.lean new file mode 100644 index 0000000000..eae119ffef --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialPhysical.lean @@ -0,0 +1,99 @@ +import OAI.Computability.VPVNP.CompressorInitialOnline +import OAI.Computability.VPVNP.CompressorInitialConverse + +/-! +# The actual initial cursor prefix of the finite pair-ABI descriptor program + +The startup bank identifies the ready calendar. The four fixed initial +phases run as a deterministic prefix on every accepting Fin11 branch. +At zero blocks the closing calendar call accepts and determines the +whole native choice string and report log. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.InitialPhysical + +open BurstRAM Compression DescriptorSpace BlockPlanner Schedule BranchSegments SourceTransport +open scoped Fin.CommRing + +variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable (base positions blocks cap b l width n : ℕ) (pub : Fin 11 → Word w) (m : Memory w) +local notation "A" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base positions blocks +local notation "a" => S.degreeExponent 0 +local notation "pt" => Workspace.ports (arity (Script.catalog (BlockProgram.script B))) (pub 2) +local notation "P" => OnlineWorkspace.program (Script.plan (BlockProgram.script B)) pub + +private theorem count_lt (fit : endAddress L < 2^w) : directoryRows L < 2^w := by + have head : levelStart L 0 < 2^w := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + have hr : directoryRows L ≤ directoryRows L*((L).shape.arity+3) := + Nat.le_mul_of_pos_right _ (by omega) + change directoryBase L + directoryRows L*((L).shape.arity+3) + 0*levelWords L < 2^w at head + omega + +/-- Every successful run through the native four visits has the source +effects at all data addresses. At zero blocks the same initial segment +followed by the terminal calendar call is the unique accepting run. -/ +theorem run (X : State a l) (fit : endAddress L < 2^w) (workspace : (pub 2).val = base) + (ready : OnlineWorkspace.Ready (A).size (L).shape.arity (pub 2) (directoryRows L) (levelWords L) m) + (cursor : BlockStartupPrefix.Resident L a b l width n (pub 2) m X) + (clock : InitialScriptPackets.budget A (BlockProgram.layout B 0 0 0) a ≤ cap) + (bounds : Online.Run.ControlBounds (A).plan cap (w := w)) : + ∃ cut : Cut P (cap+24) (some 0) m Unit, + (cut.part ()).state = some 0 ∧ + Agree (levelStart L 0 ≤ ·) (BlockInitialPackets.post L a b l width m) (cut.part ()).memory ∧ + ((cut.part ()).memory (pt).ordinal.val).val = 4 ∧ + (cut.part ()).memory (pt).rows.val = m (pt).rows.val ∧ + (cut.part ()).memory ((pt).directory-1).val = m ((pt).directory-1).val ∧ + Workspace.Installed (arity (A).catalog) (pub 2) (cut.part ()).memory ∧ + (blocks = 0 → ∃ bs logs, runSegment P (cap+24) (some 0) m bs = some logs ∧ + endState (some 0) logs = none ∧ ∀ other rs, + runSegment P (cap+24) (some 0) m other = some rs → endState (some 0) rs = none → + other = bs ∧ rs = logs) := by + let script := BlockProgram.script B + let alloc := BlockProgram.layout B base positions blocks + have hg : arity script.catalog = alloc.shape.arity := rfl + have hp : 0 < alloc.levels := by change 0 < 1+(S.steps+1)*blocks; omega + have rows : directoryRows alloc = 4+blocks*script.block.length := + (BlockProgram.directory_rows B base positions blocks).trans (script.calendar_total blocks) + have tagged : m (pt).tag.val = LiveStageLink.tagWord w (Online.calendarIndex script.size script.size) := by + change m (pt).tag.val = ((script.size+1+0 : ℕ) : Word w) + rw [Nat.add_zero] + exact ready.tag + have count : (m (pt).rows.val).val = directoryRows alloc := by + rw [show m (pt).rows.val = (directoryRows alloc : Word w) from ready.count] + exact Nat.mod_eq_of_lt (count_lt B base positions blocks fit) + have capFit : InitialScriptPackets.budget script alloc a ≤ cap := + (InitialScriptPackets.budget_fixed B base positions blocks a) ▸ clock + obtain ⟨steps,actual,_,trace,agree,ordinal,total,pitch,stable⟩ := InitialOnline.interval script alloc (pub 2) + a b l width cap capFit hg workspace hp (by change 14 ≤ 54; decide) fit (InitialScriptPackets.actual_order B base positions blocks) + m cursor.walk (by omega) ready.ordinal count tagged ready.pitch + let inner := Online.Run.intervalSegment script.plan pt (state := 0) bounds tagged steps actual + let c := InitialConverse.cut script pub alloc a b l width cap m steps bounds tagged ready.bank actual stable trace + have state : (c.part ()).state = some 0 := + (OnlineWorkspace.framedSegment_state script.plan pub inner (stable.banks ready.bank)).trans + (Online.Run.interval_state_zero script.plan pt bounds tagged steps actual) + have mem : (c.part ()).memory = Online.Run.finalMemory (C := script.catalog) pt m steps := + (OnlineWorkspace.framedSegment_memory script.plan pub inner (stable.banks ready.bank)).trans + (Online.Run.interval_memory script.plan pt (state := 0) bounds tagged steps actual) + refine ⟨c,state,mem.symm ▸ agree,mem.symm ▸ ordinal,mem.symm ▸ total,mem.symm ▸ pitch,?_,?_⟩ + · have h := stable.installed ready.bank (Online.Run.intervalLog script.plan pt m steps).length + rw [List.take_length] at h + change Workspace.Installed (arity script.catalog) (pub 2) inner.memory at h + exact (OnlineWorkspace.framedSegment_memory script.plan pub inner (stable.banks ready.bank)).symm ▸ h + · intro zero + have closed : let endMem := Online.Run.finalMemory (C := script.catalog) pt m steps + endMem (pt).rows.val ≤ endMem (pt).ordinal.val := by + apply Fin.le_def.mpr + rw [total,count,ordinal,rows,zero,Nat.zero_mul,Nat.add_zero] + exact ⟨_,_,InitialConverse.exhausted script pub alloc a b l width cap m steps bounds tagged ready.bank + actual stable trace closed⟩ + +end CompressorRecords.InitialPhysical + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialPhysicalBoundary.lean b/lean/OAI/Computability/VPVNP/CompressorInitialPhysicalBoundary.lean new file mode 100644 index 0000000000..bc82cfb227 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialPhysicalBoundary.lean @@ -0,0 +1,111 @@ +import OAI.Computability.VPVNP.CompressorInitialBoundary +import OAI.Computability.VPVNP.CompressorInitialTransferred + +/-! # The physical memory entering the selected descriptor timeline + +The eight startup calls run on the actual eleven operands. Their linked +report log fixes the memory on which the four cursor visits run. At every +sufficiently large length these visits establish the first boundary and +retain their true smaller-clock source reports. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace + +universe v + +open BurstRAM Compression DescriptorSpace BlockPlanner Schedule CursorBounds CursorNetwork CursorRouting +open LiveProgram LiveProgram.CompressedPair PairSimulation.LocalHistory PairSimulation.TraversalRows PairSimulation.TraversalRoles +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} + (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) + +private theorem startupRows (p q Baddr n base : ℕ) : + let A := BlockProgram.script B + let boot := InitialTransferred.bootstrap B p q + CalendarRows.rows (bootstrapRows boot A.initial.length A.block.length) n = + directoryRows (BlockProgram.layout B base (initialPositions Baddr n) (roundedDown p q n)) := by + intro A boot + change (BlockProgram.initial B).length + (BlockProgram.block B).length*roundedDown p q n = _ + rw [BlockProgram.layout,LevelFields.tight_rows,Nat.mul_comm] + +/-- The same threshold works for every incoming memory and admissible +literal pair-operand vector. The live clock can exceed the source clock. -/ +theorem eventually_initial_uniform (p q Baddr : ℕ) (hq : 0 < q) (hB : 1 ≤ Baddr) + (hθ : (p : ℝ)/q ≤ 1) (hlanes : S.laneBits ≤ Baddr) {base : ℕ → ℕ} (poly : PolynomiallyBounded base) : + let A := BlockProgram.script B + let boot := InitialTransferred.bootstrap B p q + let a := S.degreeExponent 0 + ∃ hd : 2+(2^a-2) = 2^a, ∀ᶠ n : ℕ in Filter.atTop, ∀ {R : Type v} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f), ∀ (pub : Fin 11 → Word (wordBits Baddr n)), + (pub 2).val = base n → (pub 6).val = n → (pub 7).val = addressBits Baddr n → + (PairTag.address pub).val < base n → ∀ (m : Memory (wordBits Baddr n)) (terminal : PairTable) + (outerCap cap small : ℕ), + StartupResult boot A.plan terminal pub Baddr n (base n) m outerCap → + InitialScriptPackets.budget A (BlockProgram.layout B 0 0 0) a ≤ small → small ≤ cap → + Online.Run.ControlBounds A.plan small (w := wordBits Baddr n) → + let l := roundedDown p q n*S.laneBits + let b := virtualBits Baddr n-l + let L := BlockProgram.layout B (base n) (initialPositions Baddr n) (roundedDown p q n) + let mem := after m (eventLog (cursorStartupLogs boot pub Baddr n (base n) m A.initial.length A.block.length A.size)) + let bits : RAMSystem (virtualBits Baddr n) → ℕ := ramFieldBits (virtualBucket n) (wordBits Baddr n) + ∃ hD : 1 < b+l, let X := cursorState (cursorCoordinateLabels b l) hD hd bits + ∃ init : InitialInterval B (base n) (initialPositions Baddr n) (roundedDown p q n) cap small b l (initialWidth Baddr n) pub mem, + Boundary (CurrentResident.resident B f hf ⟨leafLayer (siteOrder X),.cursor⟩ L (endAddress L) n (cursorFrame L a b l (initialWidth Baddr n))) pub + (levelWords L : Word (wordBits Baddr n)) (directoryRows L) 4 [] X init.interval.segment.memory ∧ + RAMBuckets.cost Report.probes init.interval.source.logs ≤ initialRate B*(initialPositions Baddr n+1) := by + intro A boot a + obtain ⟨hd,prepared⟩ := InitialTransferred.eventually_resident B p q Baddr hq hB hθ hlanes poly + refine ⟨hd,?_⟩ + filter_upwards [prepared] with n resident + intro R _ f hf pub ws len addr lower m terminal outerCap cap small start budget leClock bounds l b L mem bits + obtain ⟨hD,cur⟩ := resident pub ws len addr lower m + let X := cursorState (cursorCoordinateLabels b l) hD hd bits + have eqn := InitialTransferred.allocation B p q Baddr n (base n) + change startupLayout boot A.initial.length A.block.length Baddr n (base n) = L at eqn + have ready := start.ready + rw [eqn,startupRows B p q Baddr n (base n)] at ready + have arena := start.arena + rw [eqn] at arena + have fit : endAddress L < 2^(wordBits Baddr n) := arena.symm.trans_lt (mem _).isLt + obtain ⟨init⟩ := initialInterval B (base n) (initialPositions Baddr n) (roundedDown p q n) cap small b l + (initialWidth Baddr n) n pub mem X fit ws ready cur budget leClock bounds + exact ⟨hD,init,init.boundary f hf cur fit,init.rate cur⟩ + +/-- Specialization to a single scalar solution. -/ +theorem eventually_initial (p q Baddr : ℕ) (hq : 0 < q) (hB : 1 ≤ Baddr) + (hθ : (p : ℝ)/q ≤ 1) (hlanes : S.laneBits ≤ Baddr) {base : ℕ → ℕ} (poly : PolynomiallyBounded base) : + let A := BlockProgram.script B + let boot := InitialTransferred.bootstrap B p q + let a := S.degreeExponent 0 + ∃ hd : 2+(2^a-2) = 2^a, ∀ᶠ n : ℕ in Filter.atTop, ∀ (pub : Fin 11 → Word (wordBits Baddr n)), + (pub 2).val = base n → (pub 6).val = n → (pub 7).val = addressBits Baddr n → + (PairTag.address pub).val < base n → ∀ (m : Memory (wordBits Baddr n)) (terminal : PairTable) + (outerCap cap small : ℕ), + StartupResult boot A.plan terminal pub Baddr n (base n) m outerCap → + InitialScriptPackets.budget A (BlockProgram.layout B 0 0 0) a ≤ small → small ≤ cap → + Online.Run.ControlBounds A.plan small (w := wordBits Baddr n) → + let l := roundedDown p q n*S.laneBits + let b := virtualBits Baddr n-l + let L := BlockProgram.layout B (base n) (initialPositions Baddr n) (roundedDown p q n) + let mem := after m (eventLog (cursorStartupLogs boot pub Baddr n (base n) m A.initial.length A.block.length A.size)) + let bits : RAMSystem (virtualBits Baddr n) → ℕ := ramFieldBits (virtualBucket n) (wordBits Baddr n) + ∃ hD : 1 < b+l, let X := cursorState (cursorCoordinateLabels b l) hD hd bits + ∃ init : InitialInterval B (base n) (initialPositions Baddr n) (roundedDown p q n) cap small b l (initialWidth Baddr n) pub mem, + Boundary (CurrentResident.resident B f hf ⟨leafLayer (siteOrder X),.cursor⟩ L (endAddress L) n (cursorFrame L a b l (initialWidth Baddr n))) pub + (levelWords L : Word (wordBits Baddr n)) (directoryRows L) 4 [] X init.interval.segment.memory ∧ + RAMBuckets.cost Report.probes init.interval.source.logs ≤ initialRate B*(initialPositions Baddr n+1) := by + obtain ⟨hd,allModels⟩ := eventually_initial_uniform B p q Baddr hq hB hθ hlanes poly + exact ⟨hd,allModels.mono fun _ run => run f hf⟩ + +end CompressorRecords.ScheduledTrace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialProbeRate.lean b/lean/OAI/Computability/VPVNP/CompressorInitialProbeRate.lean new file mode 100644 index 0000000000..f7f9b2919a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialProbeRate.lean @@ -0,0 +1,110 @@ +import OAI.Computability.VPVNP.CompressorInitialScriptPackets +import OAI.Computability.VPVNP.CompressorIntervalCost + +/-! +# Initial source and framed descriptor probe costs + +There are three one-call metadata workers and one cursor call per actual +slot. Each cursor call writes six entries. The four scheduled phases also +each execute a calendar, planner, launcher and final stop call. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.InitialProbeRate + +open BurstRAM DescriptorSpace BlockPlanner BlockHeaderRun BlockInitialPackets Schedule +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Position-independent part of the initial probe bound, accounting for scalar and pointer +publication at level zero. -/ +def fixed (L : Layout) (a : ℕ) := + (Scalars.initialRow (.terminal a)).recipe.reads + (DescriptorHeads.publisher L.shape).recipe.reads + + L.shape.tables + 16 + +theorem raw (L : Layout) (a b l width : ℕ) (m : Memory w) : + let N := CursorRAM.rowCount b l a + let rs := logs L a b l width m + rs.length = N+3 ∧ RAMBuckets.cost Report.probes rs = 7*N+fixed L a := by + intro N rs + let base := header w L 0 + let row := Scalars.initialRow (.terminal a) + let mid := initialMemory a L m + have scalar := (RowRecipe.report_cost row.recipe (scalarPorts base) (base+6) m).2.1 + have head := (RowRecipe.report_cost (DescriptorHeads.publisher L.shape).recipe (headPorts base base) 0 mid).2.1 + change (scalarReport row (base+6) base m).probes = row.recipe.reads+6 at scalar + change (headReport L 0 mid).probes = (DescriptorHeads.publisher L.shape).recipe.reads+(L.shape.tables+3+3) at head + have scan : RAMBuckets.cost Report.probes (cursorLogs L w a b l width) = 7*N := CursorRAM.scan_cost .. + have len : (cursorLogs L w a b l width).length = N := CursorRAM.scanReports_length .. + have role : (BlockRoleZero.report w L).probes = 1 := rfl + constructor + · change (headLogs L a m++cursorLogs L w a b l width++[_]).length = _ + simp only [List.length_append,len,headLogs,List.length_cons,List.length_nil]; omega + · change RAMBuckets.cost Report.probes (headLogs L a m++cursorLogs L w a b l width++[_]) = _ + rw [RAMBuckets.cost_append,RAMBuckets.cost_append,scan] + change (1+(scalarReport row (base+6) base m).probes+(1+(headReport L 0 mid).probes+0)) + + 7*N + (1+(BlockRoleZero.report w L).probes+0) = 7*N + fixed L a + rw [head,scalar,role] + change _ = 7*N+(row.recipe.reads + (DescriptorHeads.publisher L.shape).recipe.reads + L.shape.tables + 16) + omega + +private theorem workers_length {d : ℕ} (C : Catalog d) (q : ℕ) (pt : Ports w) (j : Fin d) + (m : Memory w) (rs : List (Report w)) : (Online.workerRows C q pt j m rs).length = rs.length := by + induction rs generalizing m with + | nil => rfl + | cons r rs ih => simp only [Online.workerRows,List.length_cons,ih] + +theorem length (A : Script) (pt : Ports w) (m : Memory w) (steps : List (Online.Run.Step A.size A.size w)) : + (Online.Run.intervalLog A.plan pt m steps).length = + (steps.flatMap (fun st ↦ st.row.reports)).length + 4*steps.length := by + induction steps generalizing m with + | nil => rfl + | cons st rest ih => + simp only [Online.Run.intervalLog,List.length_append,Online.rowLog,Online.preparation, + workers_length,List.flatMap_cons,List.length_cons,List.length_nil,ih] + omega + +/-- Source probes, the inner interval bound, and the exact six additional +frame reads per physical Fin11 call. The constants use only the finite +script and its geometry. -/ +theorem framed (A : Script) (L : Layout) (a b l width cap : ℕ) (base : Word w) (m : Memory w) + (steps : List (Online.Run.Step A.size A.size w)) (phases : steps.length = 4) + (source : (steps.map (fun st ↦ st.row.reports)).flatten = logs L a b l width m) + (run : Online.Run.Interval A.plan (Workspace.ports (arity A.catalog) base) cap m steps) : + let N := CursorRAM.rowCount b l a + let src := Online.Run.sourceCost steps + let es := Online.Run.intervalLog A.plan (Workspace.ports (arity A.catalog) base) m steps + let inner := RAMBuckets.cost Report.probes es + let outer := RAMBuckets.cost Report.probes (OnlineWorkspace.framed base m es) + src = 7*N+fixed L a ∧ es.length = N+19 ∧ + inner ≤ (7*N+fixed L a)*(arity A.catalog+3) + 4*(Online.Run.maxReads A.plan+4*arity A.catalog+26) ∧ + outer = inner+6*(N+19) := by + intro N src es inner outer + have concat : steps.flatMap (fun st ↦ st.row.reports) = logs L a b l width m := source + obtain ⟨hlen,hcost⟩ := raw L a b l width m + have sc : src = 7*N+fixed L a := (Online.Run.sourceCost_eq_flatMap steps).trans ((congrArg (RAMBuckets.cost Report.probes) concat).trans hcost) + have el := length A (Workspace.ports (arity A.catalog) base) m steps + change es.length = _ at el + rw [concat,phases,hlen] at el + have count : es.length = N+19 := by omega + have bound := Online.Run.interval_cost_bound A.plan (Workspace.ports (arity A.catalog) base) steps m run + change inner ≤ src*(arity A.catalog+3)+_ at bound + have extra := (OnlineWorkspace.framed_effect base m es (some 0)).2.2 + change outer = 6*es.length+inner at extra + rw [sc,phases] at bound + exact ⟨sc,count,bound,by rw [extra,count,Nat.add_comm]⟩ + +open Compression in +theorem fixed_layout {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + (base positions blocks a : ℕ) : fixed (BlockProgram.layout B base positions blocks) a = + fixed (BlockProgram.layout B 0 0 0) a := rfl + +end CompressorRecords.InitialProbeRate + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialScheduled.lean b/lean/OAI/Computability/VPVNP/CompressorInitialScheduled.lean new file mode 100644 index 0000000000..1dd96917fd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialScheduled.lean @@ -0,0 +1,102 @@ +import OAI.Computability.VPVNP.CompressorInitialPhysical +import OAI.Computability.VPVNP.CompressorDeterministicGroup + +/-! # The four initial descriptor rows as one scheduled native interval + +The data reports are precisely the initial cursor initialization logs, with +the calendar and planner calls charged at their actual cost. The source runs +at its private clock, and the framed machine can run with a larger clock. +Every prefix, including a successful prefix with no accepting continuation, +preserves the six-pointer bank and all lower addresses. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace + +open BurstRAM Compression DescriptorSpace BlockPlanner Schedule BranchSegments SourceTransport +open scoped Fin.CommRing +open private count_lt from OAI.Computability.VPVNP.CompressorInitialPhysical +open private interval_mono final_tag from OAI.Computability.VPVNP.CompressorDeterministicGroup + +variable {w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable (base positions blocks cap small b l width n : ℕ) (pub : Fin 11 → Word w) (m : Memory w) +local notation "A" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base positions blocks +local notation "a₀" => S.degreeExponent 0 +local notation "pt" => Workspace.ports (arity (Script.catalog (BlockProgram.script B))) (pub 2) + +/-- Native work before the first selected row, including four calendar, +recipe, launch and worker-close calls and the actual source data probes. -/ +def initialCost (script : Script) (data : List (Report w)) := + RAMBuckets.cost Report.probes data * (arity script.catalog+3) + 4*(Online.Run.maxReads script.plan+4*arity script.catalog+26) + +/-- The four deterministic visits, their native cost, and the live memory supplied to ordinal four. -/ +structure InitialInterval where + /-- The actual workspace-framed run of the four visits. -/ + interval : QuietInterval A pub cap small (some 0) m + agrees : Agree (levelStart L 0 ≤ ·) (BlockInitialPackets.post L a₀ b l width m) interval.segment.memory + bank : Workspace.Installed (arity (A).catalog) (pub 2) interval.segment.memory + tag : interval.segment.memory (pt).tag.val = LiveStageLink.tagWord w (Online.calendarIndex (A).size (A).size) + ordinal : (interval.segment.memory (pt).ordinal.val).val = 4 + total : (interval.segment.memory (pt).rows.val).val = directoryRows L + stride : interval.segment.memory ((pt).directory-1).val = (levelWords L : Word w) + cost : RAMBuckets.cost Report.probes interval.source.logs ≤ initialCost A (BlockInitialPackets.logs L a₀ b l width m) + +/-- Run the four cursor visits in the exact incoming RAM memory. The +recovered controller fields are ready for ordinal four. -/ +theorem initialInterval (X : State a₀ l) (fit : endAddress L < 2^w) (workspace : (pub 2).val = base) + (ready : OnlineWorkspace.Ready (A).size (L).shape.arity (pub 2) (directoryRows L) (levelWords L) m) + (cursor : BlockStartupPrefix.Resident L a₀ b l width n (pub 2) m X) + (clock : InitialScriptPackets.budget A (BlockProgram.layout B 0 0 0) a₀ ≤ small) + (leClock : small ≤ cap) (bounds : Online.Run.ControlBounds (A).plan small (w := w)) : + Nonempty (InitialInterval B base positions blocks cap small b l width pub m) := by + let script := BlockProgram.script B + let alloc := BlockProgram.layout B base positions blocks + have arityEq : arity script.catalog = alloc.shape.arity := rfl + have positive : 0 < alloc.levels := by change 0 < 1+(S.steps+1)*blocks; omega + have rows : directoryRows alloc = 4+blocks*script.block.length := + (BlockProgram.directory_rows B base positions blocks).trans (script.calendar_total blocks) + have tag : m (pt).tag.val = LiveStageLink.tagWord w (Online.calendarIndex script.size script.size) := by + change m (pt).tag.val = ((script.size+1+0 : ℕ) : Word w) + rw [Nat.add_zero] + exact ready.tag + have total : (m (pt).rows.val).val = directoryRows alloc := by + rw [show m (pt).rows.val = (directoryRows alloc : Word w) from ready.count] + exact Nat.mod_eq_of_lt (count_lt B base positions blocks fit) + obtain ⟨steps,v,phases,data,agree,ordinal,cnt,pitch,stable⟩ := InitialOnline.interval script alloc (pub 2) + a₀ b l width small ((InitialScriptPackets.budget_fixed B base positions blocks a₀) ▸ clock) arityEq workspace + positive (by change 14 ≤ 54; decide) fit (InitialScriptPackets.actual_order B base positions blocks) + m cursor.walk (by omega) ready.ordinal total tag ready.pitch + have big : Online.Run.ControlBounds script.plan cap (w := w) := + ⟨bounds.tags,bounds.calendar.trans leClock,bounds.launch.trans leClock⟩ + have vBig := interval_mono v leClock + let seg := OnlineWorkspace.intervalSegment script pub big tag steps vBig stable ready.bank + let source : OnlineWorkspace.Core script pub seg small := + ⟨Online.Run.intervalLog script.plan pt m steps,(Online.Run.intervalSegment script.plan pt (state := 0) bounds tag steps v).run,rfl⟩ + let interval : QuietInterval script pub cap small (some 0) m := + ⟨seg,InitialConverse.quiet script pub alloc a₀ b l width small m steps v data, + OnlineWorkspace.intervalSegment_stable ..,OnlineWorkspace.intervalSegment_state ..,source⟩ + have mem : interval.segment.memory = Online.Run.finalMemory (C := script.catalog) pt m steps := + OnlineWorkspace.intervalSegment_memory script pub big tag steps vBig stable ready.bank + have num : steps.length = 4 := by + have len := congrArg List.length phases + simp only [List.length_map, InitialScriptPackets.indices, List.length_ofFn] at len + exact len + refine ⟨⟨interval,mem.symm ▸ agree,OnlineWorkspace.intervalSegment_bank script pub big tag steps vBig stable ready.bank,mem.symm ▸ final_tag tag, + mem.symm ▸ ordinal,mem.symm ▸ (congrArg Fin.val cnt).trans total,mem.symm ▸ pitch.trans ready.pitch,?_⟩⟩ + have actual := Online.Run.interval_cost_bound script.plan pt steps m v + have logs : steps.flatMap (fun s => s.row.reports) = BlockInitialPackets.logs alloc a₀ b l width m := data + rw [Online.Run.sourceCost_eq_flatMap,logs,num] at actual + exact actual + +end CompressorRecords.ScheduledTrace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialScriptPackets.lean b/lean/OAI/Computability/VPVNP/CompressorInitialScriptPackets.lean new file mode 100644 index 0000000000..eec792c9d0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialScriptPackets.lean @@ -0,0 +1,104 @@ +import OAI.Computability.VPVNP.CompressorBlockInitialPackets +import OAI.Computability.VPVNP.CompressorBlockProgram + +/-! # Catalog indices and checked packets for the actual initial script -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.InitialScriptPackets + +open BurstRAM BlockPlanner DescriptorSpace SourceOnline BlockInitialPackets + +variable {w : ℕ} + +/-- The script's initial ordinals precede its repeated block. -/ +def indices (A : Script) := List.ofFn (fun i : Fin A.initial.length ↦ i.castAdd A.block.length) + +theorem visits (A : Script) : (indices A).map A.visit = A.initial := by + rw [indices,List.map_ofFn] + change List.ofFn (fun i : Fin A.initial.length ↦ A.visit (i.castAdd A.block.length)) = _ + simp only [A.initial_visit] + exact List.ofFn_get _ + +/-- The runtime allocation only changes the directory bounds and the catalog +arity. The four workers use the compiled scalar and array dimensions. -/ +theorem actual_order {k : Type*} [_root_.Field k] {S : Compression.BlockSchedule k} (B : S.Templates) + (base positions blocks : ℕ) : (BlockProgram.script B).initial = + order (BlockProgram.layout B base positions blocks) (S.degreeExponent 0) := by rfl + +/-- One finite bound covers all planner code and all four source workers. -/ +def budget (A : Script) (L : Layout) (a : ℕ) := + ∑ i : Fin A.size, max ((A.plan.recipes i).2.code.length+1+2*Schedule.Online.N A.size A.size+5) + (clock L a+3+4*((A.catalog i).params+1)+2*Schedule.Online.N A.size A.size+5) + +theorem budget_bounds (A : Script) (L : Layout) (a : ℕ) (i : Fin A.size) : + (A.plan.recipes i).2.code.length+1+2*Schedule.Online.N A.size A.size+5 ≤ budget A L a ∧ + clock L a+3+4*((A.catalog i).params+1)+2*Schedule.Online.N A.size A.size+5 ≤ budget A L a := by + let cost := fun j : Fin A.size ↦ max ((A.plan.recipes j).2.code.length+1+2*Schedule.Online.N A.size A.size+5) + (clock L a+3+4*((A.catalog j).params+1)+2*Schedule.Online.N A.size A.size+5) + have bound : cost i ≤ budget A L a := + Finset.single_le_sum (fun j _ ↦ Nat.zero_le (cost j)) (Finset.mem_univ i) + exact ⟨(le_max_left ..).trans bound,(le_max_right ..).trans bound⟩ + +theorem budget_fixed {k : Type*} [_root_.Field k] {S : Compression.BlockSchedule k} (B : S.Templates) + (base positions blocks a : ℕ) : + budget (BlockProgram.script B) (BlockProgram.layout B base positions blocks) a = + budget (BlockProgram.script B) (BlockProgram.layout B 0 0 0) a := rfl + +/-- A checked initial packet whose catalog phase, public operands, entry memory, fuel, and +choices agree with its attached header visit. -/ +def Attached (A : Script) (L : Layout) (pub : Fin 5 → Word w) (s : Word w) (cap : ℕ) + (p : SourceWalk.Packet (SourceOnline.Visit A w) w) : Prop := + SourceOnline.Checked A L cap p ∧ + p.stage = HeaderPacket.attach A p.stage.phase pub s p.input p.stage.fuel p.stage.choices + +private theorem labelWalk (A : Script) (L : Layout) (a cap : ℕ) (pub : Fin 5 → Word w) (s : Word w) + (is : List (Fin A.size)) (m : Memory w) (rs : List (Report w)) + (walk : SourceWalk (BlockInitialPackets.Source L a pub s) (is.map A.visit) m rs) + (recipe : ∀ i ∈ is, (A.plan.recipes i).2.code.length+1+2*Schedule.Online.N A.size A.size+5 ≤ cap) + (data : ∀ i ∈ is, clock L a+3+4*((A.catalog i).params+1)+2*Schedule.Online.N A.size A.size+5 ≤ cap) : + ∃ ps : List (SourceWalk.Packet (SourceOnline.Visit A w) w), + SourceWalk.Chronological SourceOnline.Visit.Runs m ps ∧ ps.map (fun p ↦ p.stage.phase) = is ∧ + ps.flatMap SourceWalk.Packet.reports = rs ∧ ∀ p ∈ ps, Attached A L pub s cap p := by + induction is generalizing m rs with + | nil => + cases walk + exact ⟨[],trivial,rfl,rfl,by simp⟩ + | cons i is ih => + cases walk with + | @next _ _ _ head tail src rest => + obtain ⟨fuel,bits,hf,run⟩ := src + let stage := HeaderPacket.attach A i pub s m fuel bits + let p : SourceWalk.Packet (SourceOnline.Visit A w) w := ⟨stage,m,head⟩ + have smaller := data i List.mem_cons_self + have check : Attached A L pub s cap p := ⟨HeaderPacket.attach_checked A i rfl run cap + (recipe i List.mem_cons_self) (by omega),rfl⟩ + obtain ⟨ps,chron,ord,reports,checks⟩ := ih (after m (eventLog head)) tail rest + (fun j hj ↦ recipe j (List.mem_cons_of_mem _ hj)) (fun j hj ↦ data j (List.mem_cons_of_mem _ hj)) + refine ⟨p::ps,⟨rfl,HeaderPacket.attach_runs A i rfl run,chron⟩,?_,?_,?_⟩ + · exact congrArg (i :: ·) ord + · exact congrArg (head ++ ·) reports + · intro q h + rcases List.mem_cons.mp h with rfl|inTail + · exact check + · exact checks q inTail + +/-- The four checked packets use the actual worker labels in the compiled +script and the computed public operands at each successive source memory. -/ +theorem attach_initial (A : Script) (L : Layout) (a cap : ℕ) (pub : Fin 5 → Word w) (s : Word w) + (m : Memory w) (rs : List (Report w)) (shape : A.initial = order L a) + (walk : SourceWalk (BlockInitialPackets.Source L a pub s) (order L a) m rs) + (recipe : ∀ i ∈ indices A, (A.plan.recipes i).2.code.length+1+2*Schedule.Online.N A.size A.size+5 ≤ cap) + (data : ∀ i ∈ indices A, clock L a+3+4*((A.catalog i).params+1)+2*Schedule.Online.N A.size A.size+5 ≤ cap) : + ∃ ps : List (SourceWalk.Packet (SourceOnline.Visit A w) w), + SourceWalk.Chronological SourceOnline.Visit.Runs m ps ∧ ps.map (fun p ↦ p.stage.phase) = indices A ∧ + ps.flatMap SourceWalk.Packet.reports = rs ∧ ∀ p ∈ ps, Attached A L pub s cap p := + labelWalk A L a cap pub s _ m rs (by rw [visits,shape]; exact walk) recipe data + +end CompressorRecords.InitialScriptPackets + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialTraceEquiv.lean b/lean/OAI/Computability/VPVNP/CompressorInitialTraceEquiv.lean new file mode 100644 index 0000000000..0eca929e89 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialTraceEquiv.lean @@ -0,0 +1,90 @@ +import OAI.Computability.VPVNP.CompressorPassIntervalData +import OAI.Computability.VPVNP.CompressorExecutionTrace + +/-! # Prepending the four deterministic cursor rows to selected compressor traces + +The choice of each later pass is retained. The physical path predicate is +evaluated on all reports, including the initial deterministic rows. The +small-clock core report lists and the accepting path's actual bit stream +are preserved by the same concatenation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace.QuietInterval + +open BurstRAM Compression BlockPlanner BranchSegments + +variable {w cap small : ℕ} {script : Script} {pub : Fin 11 → Word w} + {st : Option (Word w)} {m : Memory w} + (initial : QuietInterval script pub cap small st m) + {R : Type*} [CommSemiring R] {a g b n : ℕ} {X : State a g} + {E : StateExecution R b n X} + (t : ExecutionTrace (OnlineWorkspace.program script.plan pub) (cap+24) E initial.segment.state initial.segment.memory) + +/-- The deterministic cursor prefix followed by the selected compression passes. -/ +def withTrace : Cut (OnlineWorkspace.program script.plan pub) (cap+24) st m E.Choices := + Cut.before initial.segment initial.segment.bits.length initial.quiet t.cut + +theorem withTrace_frame (h : t.Framed ((pub 2).val+6)) : + (withTrace initial t).PrefixFrame ((pub 2).val+6) := + Cut.PrefixFrame.before initial.segment initial.segment.bits.length initial.quiet initial.stable h.cut + +theorem withTrace_stopped (z : E.Choices) : ((withTrace initial t).part z).state = none := + (initial.segment.append_state _).trans (t.stopped z) + +theorem withTrace_memory (z : E.Choices) : ((withTrace initial t).part z).memory = (t.cut.part z).memory := + initial.segment.append_memory _ + +/-- The operand-room predicate belongs to the whole run and can depend +on the reports of both the forced prefix and the selected suffix. -/ +def accepted (allow : List (Report w) → Prop) : + {z : E.Choices // allow (initial.segment.logs ++ (t.cut.part z).logs)} ≃ + LiveProgram.PathsFrom (OnlineWorkspace.program script.plan pub) (cap+24) st m allow := + (t.acceptedEquiv fun rs => allow (initial.segment.logs++rs)).trans + (LiveProgram.emptySegmentEquiv (initial.quiet ▸ initial.segment.run) allow) + +/-- Bijection with all selected terms when every branch meets the whole-run predicate. -/ +def allAccepted (allow : List (Report w) → Prop) + (allowed : ∀ z, allow (initial.segment.logs++(t.cut.part z).logs)) : + E.Choices ≃ LiveProgram.PathsFrom (OnlineWorkspace.program script.plan pub) (cap+24) st m allow := + (Equiv.subtypeUnivEquiv allowed).symm.trans (accepted initial t allow) + +theorem allAccepted_bits (allow : List (Report w) → Prop) + (allowed : ∀ z, allow (initial.segment.logs++(t.cut.part z).logs)) (z : E.Choices) : + ((allAccepted initial t allow allowed) z).val = initial.segment.bits++(t.cut.part z).bits := by + change List.replicate initial.segment.bits.length [] ++ (t.cut.part z).bits = _ + rw [← initial.quiet] + +/-- Any finite successful call prefix through these rows and the recursive +timeline retains all six bank words and the preceding live header. -/ +theorem withTrace_stable (frame : t.Framed ((pub 2).val+6)) {bs rs} + (run : runSegment (OnlineWorkspace.program script.plan pub) (cap+24) st m bs = some rs) : + SourceBankFrame.Stable ((pub 2).val+6) m rs := by + rcases Cut.deterministic_prefix initial.segment initial.segment.bits.length initial.quiet initial.stable run with h | ⟨tail,rfl⟩ + · exact h + · rw [PrimedSchedule.runSegment_append,initial.segment.run] at run + change (runSegment _ _ initial.segment.state initial.segment.memory tail).map _ = some rs at run + obtain ⟨xs,done,rfl⟩ := Option.map_eq_some_iff.mp run + exact initial.stable.append (frame.stable done) + +/-- Small-clock inner reports of both the forced cursor interval and the selected tail. -/ +def combinedCore (core : ∀ z, OnlineWorkspace.Core script pub (t.cut.part z) small) (z : E.Choices) : + OnlineWorkspace.Core script pub ((withTrace initial t).part z) small := + initial.source.append (core z) + +theorem combinedCost (core : ∀ z, OnlineWorkspace.Core script pub (t.cut.part z) small) (z : E.Choices) : + RAMBuckets.cost Report.probes (combinedCore initial t core z).logs = + RAMBuckets.cost Report.probes initial.source.logs + RAMBuckets.cost Report.probes (core z).logs := + OnlineWorkspace.Core.cost_append .. + +end CompressorRecords.ScheduledTrace.QuietInterval + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorInitialTransferred.lean b/lean/OAI/Computability/VPVNP/CompressorInitialTransferred.lean new file mode 100644 index 0000000000..63fff00c83 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorInitialTransferred.lean @@ -0,0 +1,131 @@ +import OAI.Computability.VPVNP.CompressorInitialPhysical +import OAI.Computability.VPVNP.LiveCompressedPairStartupRun + +/-! # Exact startup memory of the physical pair at the cursor prefix -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.InitialTransferred + +open BurstRAM Compression DescriptorSpace BlockPlanner CursorBounds LiveProgram.CompressedPair +open scoped Fin.CommRing +open private startupStage from OAI.Computability.VPVNP.LiveCompressedPairCursorStartup + +variable {w : ℕ} + +private theorem after_ofFn {k : ℕ} (entry : Fin (k+1) → Memory w) (rs : Fin k → Report w) + (step : ∀ i, after (entry i.castSucc) (rs i).events = entry i.succ) : + after (entry 0) (eventLog (List.ofFn rs)) = entry (Fin.last k) := by + induction k with + | zero => simp [eventLog,after] + | succ k ih => + have tail := ih (fun j ↦ entry j.succ) (fun i ↦ rs i.succ) (fun i ↦ step i.succ) + rw [List.ofFn_succ] + change after (entry 0) ((rs 0).events ++ eventLog (List.ofFn (fun i : Fin k ↦ rs i.succ))) = _ + have first := step (0 : Fin (k+1)) + change after (entry 0) (rs 0).events = entry (0 : Fin (k+1)).succ at first + rw [show ∀ (m : Memory w) (es fs), after m (es++fs) = after (after m es) fs from fun _ _ _ ↦ List.foldl_append,first] + exact tail + +/-- The emitted outer-linker reports leave exactly the memory used by +the transferred-startup and initial-cursor theorems. -/ +theorem startup_memory (boot : Bootstrap) (pub : Fin 11 → Word w) (B n base : ℕ) (m : Memory w) + (initial phases d : ℕ) : + after m (eventLog (cursorStartupLogs boot pub B n base m initial phases d)) = + BlockHeaderStartup.post (bootstrapRows boot initial phases) d (startupLayout boot initial phases B n base) + B n boot.degreeBits boot.lanesPerBlock boot.steps pub (LiveProgram.PairTag.address pub) m := by + let D := bootstrapRows boot initial phases + let L := startupLayout boot initial phases B n base + let t := startupTrace boot pub B n base m initial phases d + let tag := LiveProgram.PairTag.address pub + change after (t.entry tag m 0) (eventLog (List.ofFn (startupReport boot pub B n base m initial phases d))) = + t.entry tag m (Fin.last 8) + apply after_ofFn + intro i + have step : next (startupStage i.castSucc) = some (startupStage i.succ) := by fin_cases i <;> rfl + have closed := TransferredStartup.source_closed D d L B n boot.degreeBits boot.lanesPerBlock boot.steps + pub tag m i + change (t.source i).result = none at closed + have eff := (report_effect pub (startupStage i.castSucc) (t.source i) (t.entry tag m i.castSucc)).2.2.2 + rw [closed,step] at eff + exact eff.trans (t.transfer tag m i).symm + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Startup parameters for the compiled compressor, including the allocation shape, lane and +degree dimensions, and scale numerator and denominator. -/ +noncomputable def bootstrap (p q : ℕ) : Bootstrap := + ⟨BlockProgram.allocationShape B,S.degreeExponent 0,S.laneBits,S.steps,p,q⟩ + +theorem arity : 11 ≤ (BlockProgram.allocationShape B).arity := by + let A := BlockProgram.script B + let i : Fin A.initial.length := ⟨2,by change 2 < 4; decide⟩ + have hc : A.catalog (i.castAdd A.block.length) = Schedule.cursorPass := by + change (A.visit (i.castAdd A.block.length)).worker = _ + rw [A.initial_visit]; rfl + have h := Schedule.params_le_arity A.catalog (i.castAdd A.block.length) + rw [hc] at h + exact h + +theorem phases_pos : 0 < (BlockProgram.block B).length := by + simp only [BlockProgram.block,BlockProgram.refresh,List.length_append,List.length_cons,List.length_nil] + omega + +/-- The native startup's computed row count selects precisely the concrete +block-program allocation for this input and its actual integer block count. -/ +theorem allocation (p q Baddr n base : ℕ) : + startupLayout (bootstrap B p q) (BlockProgram.initial B).length (BlockProgram.block B).length Baddr n base = + BlockProgram.layout B base (initialPositions Baddr n) (roundedDown p q n) := by + simp only [startupLayout,bootstrap,bootstrapRows,OnlineWorkspace.rowsSpec,CalendarRows.rows,cursorLayout, + BlockProgram.layout,roundedDown_eq,Nat.mul_comm (BlockProgram.block B).length] + +open CursorNetwork CursorRouting in +/-- Uniformly in the initial RAM contents, the post-memory of the eight +literal pair calls supplies the concrete four-visit cursor development. +The allocation and row count are those of the actual block program. -/ +theorem eventually_resident (p q Baddr : ℕ) (hq : 0 < q) (hB : 1 ≤ Baddr) + (hθ : (p : ℝ)/q ≤ 1) (hlanes : S.laneBits ≤ Baddr) {base : ℕ → ℕ} (hb : PolynomiallyBounded base) : + let A := BlockProgram.script B + let boot := bootstrap B p q + let a := S.degreeExponent 0 + let pad := 2^a-2 + ∃ hd : 2+pad = 2^a, ∀ᶠ n : ℕ in Filter.atTop, ∀ (pub : Fin 11 → Word (wordBits Baddr n)), + (pub 2).val = base n → (pub 6).val = n → (pub 7).val = addressBits Baddr n → + (LiveProgram.PairTag.address pub).val < base n → ∀ m, + let T := roundedDown p q n + let l := T*S.laneBits + let b := virtualBits Baddr n-l + let L := BlockProgram.layout B (base n) (initialPositions Baddr n) T + let mem := after m (eventLog (cursorStartupLogs boot pub Baddr n (base n) m A.initial.length A.block.length A.size)) + let bits : RAMSystem (virtualBits Baddr n) → ℕ := ramFieldBits (virtualBucket n) (wordBits Baddr n) + ∃ hD : 1 < b+l, BlockStartupPrefix.Resident L a b l (initialWidth Baddr n) n (pub 2) mem + (cursorState (cursorCoordinateLabels b l) hD hd bits) := by + intro A boot a pad + have hd : 2+pad = 2^a := by + dsimp only [a,pad] + rw [S.initial,pow_succ] + have := Nat.two_pow_pos S.expanderExponent + omega + refine ⟨hd,?_⟩ + let D := bootstrapRows boot A.initial.length A.block.length + have hph : 0 < D.phaseRows := phases_pos B + have ha : 7 ≤ boot.shape.arity := (by decide : 7 ≤ 11).trans (arity B) + have hs : 30 ≤ boot.shape.scalarFields := by change 30 ≤ 54; decide + filter_upwards [BlockStartupPrefix.eventually_resident D A.size boot.shape Baddr a pad S.laneBits S.steps + hd hB hq hph hθ hlanes ha hs hb] with n ready + intro pub workspace len addr lower m T l b L mem bits + have source := ready pub (LiveProgram.PairTag.address pub) workspace len addr lower m + have hL : startupLayout boot A.initial.length A.block.length Baddr n (base n) = L := + allocation B p q Baddr n (base n) + have hm := startup_memory boot pub Baddr n (base n) m A.initial.length A.block.length A.size + change mem = _ at hm + rw [← hL,hm] + exact source + +end CompressorRecords.InitialTransferred + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorIntervalCost.lean b/lean/OAI/Computability/VPVNP/CompressorIntervalCost.lean new file mode 100644 index 0000000000..a0f65a9737 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorIntervalCost.lean @@ -0,0 +1,60 @@ +import OAI.Computability.VPVNP.CompressorOnlineBranchCut + +/-! # Probe costs of online descriptor intervals + +Each row contributes its source worker reports and its share of the +calendar, recipe and launch costs. An interval ends at the boundary +immediately after its last row. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online.Run + +open BurstRAM + +variable {d initial phases w : ℕ} {C : Catalog d} +local notation "q" => initial + phases + +/-- Summing the source workers' costs gives the cost of their concatenated reports. -/ +theorem sourceCost_eq_flatMap (steps : List (Step d q w)) : + sourceCost steps = RAMBuckets.cost Report.probes (steps.flatMap fun s => s.row.reports) := by + induction steps with + | nil => rfl + | cons s rest ih => + rw [List.flatMap_cons, RAMBuckets.cost_append, ← ih] + rfl + +/-- The dispatcher charges a fixed overhead per scheduled row of the interval. -/ +theorem interval_cost_bound (plan : Config C initial phases) (ports : Ports w) + (steps : List (Step d q w)) (m : Memory w) {cap : ℕ} + (valid : Interval plan ports cap m steps) : + RAMBuckets.cost Report.probes (intervalLog plan ports m steps) ≤ + sourceCost steps * (arity C + 3) + steps.length * (maxReads plan + 4 * arity C + 26) := by + induction steps generalizing m with + | nil => simp [intervalLog, RAMBuckets.cost, sourceCost] + | cons s rest ih => + obtain ⟨row, tail⟩ := valid + have tailCost := ih _ tail + have count : s.row.reports.length ≤ RAMBuckets.cost Report.probes s.row.reports := by + rw [RAMBuckets.cost_eq_length_add_probes] + omega + have params := params_le_arity C s.row.worker + have overhead := Nat.mul_le_mul count (Nat.add_le_add_right params 2) + have reads := reads_le plan s.phase + rw [intervalLog, RAMBuckets.cost_append, row_cost plan ports m s.phase s.row row.source] + change _ ≤ (RAMBuckets.cost Report.probes s.row.reports + sourceCost rest) * _ + + (rest.length + 1) * _ + rw [Nat.add_mul, Nat.add_mul, Nat.one_mul] + have workerCost : RAMBuckets.cost Report.probes s.row.reports * (arity C + 3) = + RAMBuckets.cost Report.probes s.row.reports * (arity C + 2) + + RAMBuckets.cost Report.probes s.row.reports := Nat.mul_succ .. + omega + +end CompressorRecords.Schedule.Online.Run + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorLabelEvaluator.lean b/lean/OAI/Computability/VPVNP/CompressorLabelEvaluator.lean new file mode 100644 index 0000000000..b8e5719ef5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorLabelEvaluator.lean @@ -0,0 +1,176 @@ +import OAI.Computability.VPVNP.CompressionTemplates +import OAI.Computability.VPVNP.JointLabelEvaluator +import OAI.Computability.VPVNP.EvaluatorAdviceBounds + +/-! +# A common finite algebra for the grammar and both compressor templates + +At any small-circuit length, the grammar, the six-party block and the port +graph block satisfy their respective equations over the original field. +All three assignments descend together. The number of parties in the two +motifs can differ. The prime and the slice model are chosen before any input +exponent vector for the monomial evaluator. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open MvPolynomial JointLabelSystem LabelEvaluator + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Numbered grammar labels followed, up to a permutation of coordinates, +by the fixed shrinking and degree-refresh map parameters. -/ +noncomputable abbrev compressorLabelCount (c n : ℕ) := Fintype.card (Production n c ⊕ B.Entry) + +/-- The actual simultaneous equations. There is one grammar row per Boolean +input, and the fixed template rows retain their distinct parameter names. -/ +noncomputable def compressorEquations {n : ℕ} (hn : 2 ≤ n) (c : ℕ) : + (Fin n → Bool) ⊕ B.EquationIndex → MvPolynomial (Fin (B.compressorLabelCount c n)) ℤ := + unionEquations (grammarEquation hn c) B.equation + +theorem compressorEquationCount (n : ℕ) : + Fintype.card ((Fin n → Bool) ⊕ B.EquationIndex) = 2 ^ n + Fintype.card B.EquationIndex := by + simp + +theorem compressorLabelCount_polynomial (c : ℕ) : + PolynomiallyBounded (B.compressorLabelCount c) := by + let hw := PolynomiallyBounded.id.pow (c + 5) + apply (((hw.mul (PolynomiallyBounded.id.mul (.const 2))).add + ((PolynomiallyBounded.id.pow 2).mul (hw.pow 3))).add (.const (Fintype.card B.Entry))).of_le + intro n + rw [compressorLabelCount, Fintype.card_sum] + apply Nat.add_le_add_right + simpa only [Fintype.card_fin, Fintype.card_prod, Fintype.card_bool] using + card_grammarLabel_le (Fin n × Bool) (Fin (n ^ (c + 5))) n + +/-- The template contribution to the degree bound is constant across lengths. -/ +noncomputable def compressorDegree (n : ℕ) : ℕ := + max 3 (max (2 * n - 1) (Finset.univ.sup fun i : B.EquationIndex ↦ (B.equation i).totalDegree)) + +/-- A fixed bound for the absolute coefficients of both template families. -/ +noncomputable def compressorHeight : ℕ := + Finset.univ.sup fun i : B.EquationIndex ↦ + (B.equation i).support.sup fun e ↦ ((B.equation i).coeff e).natAbs + +theorem compressorEquation_degree {n : ℕ} (hn : 2 ≤ n) (c : ℕ) (i) : + (B.compressorEquations hn c i).totalDegree ≤ B.compressorDegree n := by + refine unionEquations_totalDegree_le _ _ (fun x ↦ ?_) (fun o ↦ ?_) i + · exact (grammarEquation_totalDegree_le hn c x).trans ((le_max_left ..).trans (le_max_right ..)) + · exact (Finset.le_sup (f := fun z : B.EquationIndex ↦ (B.equation z).totalDegree) + (Finset.mem_univ o)).trans ((le_max_right ..).trans (le_max_right ..)) + +theorem compressorEquation_coeff {n : ℕ} (hn : 2 ≤ n) (c : ℕ) (i e) : + ((B.compressorEquations hn c i).coeff e).natAbs ≤ + 2 ^ (grammarExponent c n + B.compressorHeight) := by + refine unionEquations_coeff_natAbs_le _ _ (fun x b ↦ ?_) (fun o a ↦ ?_) i e + · exact (grammarEquation_coeff_natAbs_le hn c x b).trans + (Nat.pow_le_pow_right (by decide) (Nat.le_add_right ..)) + · by_cases ha : a ∈ (B.equation o).support + · have hh : ((B.equation o).coeff a).natAbs ≤ B.compressorHeight := + (Finset.le_sup (f := fun b ↦ ((B.equation o).coeff b).natAbs) ha).trans + (Finset.le_sup (f := fun i : B.EquationIndex ↦ + (B.equation i).support.sup fun b ↦ ((B.equation i).coeff b).natAbs) (Finset.mem_univ o)) + exact (hh.trans Nat.lt_two_pow_self.le).trans + (Nat.pow_le_pow_right (by decide) (Nat.le_add_left ..)) + · simp [notMem_support_iff.mp ha] + +theorem compressorDegree_polynomial : PolynomiallyBounded B.compressorDegree := + (((PolynomiallyBounded.const 3).add + ((PolynomiallyBounded.const 2).mul PolynomiallyBounded.id)).add + (.const (Finset.univ.sup fun i : B.EquationIndex ↦ (B.equation i).totalDegree))).of_le + fun n ↦ by dsimp [compressorDegree]; omega + +theorem compressorCoeffExponent_polynomial (c : ℕ) : + PolynomiallyBounded (fun n ↦ grammarExponent c n + B.compressorHeight) := by + let h := PolynomiallyBounded.id + let h₂ := (PolynomiallyBounded.const 2).mul h + have hp := (h₂.add ((h.mul (PolynomiallyBounded.const (c + 5))).mul h₂)).add (h₂.mul h) + exact (((hp.add (h.pow clockExponent)).add (.const 1)).add (.const B.compressorHeight)) + +/-- Prime-size exponent in characteristic zero, fixed before the evaluator inputs. -/ +noncomputable def compressorPrimeBits (c n : ℕ) := + let t := B.compressorLabelCount c n + let d := B.compressorDegree n + let a := Nat.clog 2 (multiplierDegree t d + d + 1) * t + 2 * (a + Nat.clog 2 (a + (grammarExponent c n + B.compressorHeight) + 2)) + 1 + +theorem compressorPrimeBits_polynomial (c : ℕ) : PolynomiallyBounded (B.compressorPrimeBits c) := by + have ht := B.compressorLabelCount_polynomial c + have hd := B.compressorDegree_polynomial.clog + have hb := (B.compressorCoeffExponent_polynomial c).clog + exact RadicalCertificate.polynomiallyBounded_good_prime_bits ht + (RadicalCertificate.polynomiallyBounded_clog_paperBound ht hd) hd hb + +/-- Read the original production coefficient equations and both templates +back out of the numbered simultaneous system in an arbitrary ring. -/ +theorem compressorSolution_iff {R : Type*} [CommRing R] {n : ℕ} (hn : 2 ≤ n) (c : ℕ) + (a : Fin (B.compressorLabelCount c n) → R) : + (∀ i, eval₂Hom (Int.castRingHom R) a (B.compressorEquations hn c i) = 0) ↔ + (∀ x : Fin n → Bool, eval₂Hom (Int.castRingHom R) (a ∘ leftIndex (Production n c) B.Entry) + (labelQuery ⟨n - 1, by omega⟩ ⟨0, pow_pos (by omega) _⟩ x) = (acceptingCount x : R)) ∧ + B.IsSolution (a ∘ rightIndex (Production n c) B.Entry) := by + rw [compressorEquations, unionEquations_solution_iff] + simp [grammarEquation, IsSolution, sub_eq_zero] + +/-- Algebraic descent of the full joint system at every satisfiable length. -/ +theorem exists_compressorModel_of_solution (q : ℕ) [CharP k q] {n c : ℕ} + (hn : 2 ≤ n) (a : Fin (B.compressorLabelCount c n) → k) + (ha : ∀ i, eval₂ (Int.castRingHom k) a (B.compressorEquations hn c i) = 0) : + ∃ p : Nat.Primes, (q ≠ 0 → p.val = q) ∧ (q = 0 → p.val ≤ 2 ^ B.compressorPrimeBits c n) ∧ + Nonempty (Model p (B.compressorDegree n) (B.compressorEquations hn c)) := by + have hd : 3 ≤ B.compressorDegree n := le_max_left .. + rcases CharP.char_is_prime_or_zero k q with hp | rfl + · let p : Nat.Primes := ⟨q, hp⟩ + exact ⟨p, fun _ ↦ rfl, fun h ↦ (hp.ne_zero h).elim, exists_model_positive p _ + (B.compressorDegree n) hd (B.compressorEquation_degree hn c) a ha⟩ + · have := CharP.charP_to_charZero k + obtain ⟨p, hp, hm⟩ := exists_model_charZero (B.compressorEquations hn c) _ _ hd + (B.compressorEquation_degree hn c) (B.compressorEquation_coeff hn c) a ha + exact ⟨p, fun h ↦ (h rfl).elim, fun _ ↦ hp, hm⟩ + +/-- A small circuit and the two compressor templates supply one simultaneous +solution to all the formal label equations. -/ +theorem exists_compressorSolution_of_circuit {n c s : ℕ} + (hn : 2 ≤ n) (hc : 1 ≤ c) (hs : s ≤ n ^ c) (circuit : Circuit k (Fin n × Bool) s) + (hpoly : circuit.polynomial = map (Int.castRingHom k) (P n)) : + ∃ a : Fin (B.compressorLabelCount c n) → k, + ∀ i, eval₂ (Int.castRingHom k) a (B.compressorEquations hn c i) = 0 := by + obtain ⟨labels, hlabels⟩ := pathCount_labelEquations hn hc hs circuit hpoly + obtain ⟨κ, hκ⟩ := B.exists_solution + let a := joinAssignment labels κ + have ha := (B.compressorSolution_iff hn c a).mpr (by + simpa only [a, joinAssignment_left, joinAssignment_right] using And.intro hlabels hκ) + exact ⟨a, ha⟩ + +/-- From an actual circuit at the indicated length, obtain one reduced +finite-algebra model for the entire compressor. In positive characteristic +the prime is the given characteristic, and in characteristic zero its bit +length is polynomially bounded. -/ +theorem exists_compressorEvaluator (q : ℕ) [CharP k q] {n c s : ℕ} + (hn : 2 ≤ n) (hc : 1 ≤ c) (hs : s ≤ n ^ c) (circuit : Circuit k (Fin n × Bool) s) + (hpoly : circuit.polynomial = map (Int.castRingHom k) (P n)) : + ∃ p : Nat.Primes, (q ≠ 0 → p.val = q) ∧ (q = 0 → p.val ≤ 2 ^ B.compressorPrimeBits c n) ∧ + Nonempty (Model p (B.compressorDegree n) (B.compressorEquations hn c)) := by + obtain ⟨a,ha⟩ := B.exists_compressorSolution_of_circuit hn hc hs circuit hpoly + exact B.exists_compressorModel_of_solution q hn a ha + +/-- The same model specializes every path-count equation and the two fixed +wire identities. Its functional and all exponent-vector path counts come +from `LabelEvaluator.Model.functional_one` and `Model.branchCount_mod`. -/ +theorem compressorEvaluator_readback {n : ℕ} (hn : 2 ≤ n) (c : ℕ) {p : Nat.Primes} + (M : Model p (B.compressorDegree n) (B.compressorEquations hn c)) : + (∀ x : Fin n → Bool, eval₂Hom (Int.castRingHom M.algebra) + (M.labels ∘ leftIndex (Production n c) B.Entry) + (labelQuery ⟨n - 1, by omega⟩ ⟨0, pow_pos (by omega) _⟩ x) = (acceptingCount x : M.algebra)) ∧ + B.IsSolution (M.labels ∘ rightIndex (Production n c) B.Entry) := + (B.compressorSolution_iff hn c M.labels).mp M.solution + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorLabelReadback.lean b/lean/OAI/Computability/VPVNP/CompressorLabelReadback.lean new file mode 100644 index 0000000000..145ed0542c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorLabelReadback.lean @@ -0,0 +1,57 @@ +import OAI.Computability.VPVNP.CompressorLabelEvaluator +import OAI.Computability.VPVNP.CountedLabelReadback +import OAI.Computability.VPVNP.ParseOracleResources + +/-! +# Coefficient queries for the grammar and the two compressor templates + +The fixed sparse row table contains both the six-party shrink equations and +the port-graph refresh equations. The word-indexed rows use the two counted +Boolean-circuit queries. The integer row result applies to every input word +and every formal exponent vector. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open MvPolynomial JointLabelSystem RadicalCertificate.MonomialIndex + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) {n : ℕ} + +/-- The scalar function in the dense bounded-monomial matrix interface. -/ +noncomputable abbrev compressorCoeff (hn : 2 ≤ n) (c : ℕ) := + FixedRows.countedCoeff B.Entry B.EquationIndex B.equation hn c + +theorem compressorCoeff_eq (hn : 2 ≤ n) (c : ℕ) + (i : Fin (2 ^ n + Fintype.card B.EquationIndex)) (a : Fin (B.compressorLabelCount c n) → ℕ) : + B.compressorCoeff hn c i a = (B.compressorEquations hn c (FixedRows.rowIndex B.EquationIndex n i)).coeff + (exponentVector a) := FixedRows.countedCoeff_eq B.Entry B.EquationIndex B.equation hn c i a + +/-- The label-coordinate order table fits polynomial advice even when the +two template families have different party and label types. -/ +theorem compressorOrderAdvice_polynomial (c : ℕ) : + PolynomiallyBounded (fun n => FixedRows.orderBits B.Entry n c) := + FixedRows.orderBits_polynomiallyBounded B.Entry c + +/-- Polynomial bounds for the circuit advice, stack capacity, and exponent of +the execution time of the dense production histogram lookup. -/ +theorem compressorParseResources_polynomial (c : ℕ) : + PolynomiallyBounded (fun n => ParseOracle.adviceBound c n (FixedRows.productionCount n c) (2*n)) ∧ + PolynomiallyBounded (fun n => ParseOracle.stackBound c n (FixedRows.productionCount n c) (2*n)) ∧ + PolynomiallyBounded (fun n => ParseOracle.timeExponent c n (FixedRows.productionCount n c) (2*n)) := by + have hS : PolynomiallyBounded (fun n => FixedRows.productionCount n c) := + (FixedRows.labelTotal_polynomiallyBounded Unit c).of_le fun n => by + rw [← FixedRows.labelOrder_length] + exact Nat.le_add_right .. + have hw : PolynomiallyBounded (fun n => 2*n) := (PolynomiallyBounded.const 2).mul .id + exact ⟨ParseOracle.adviceBound_polynomial c hS hw, ParseOracle.stackBound_polynomial c hS hw, + ParseOracle.timeExponent_polynomial c hS hw⟩ + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorLevelCounts.lean b/lean/OAI/Computability/VPVNP/CompressorLevelCounts.lean new file mode 100644 index 0000000000..0e90ccce41 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorLevelCounts.lean @@ -0,0 +1,156 @@ +import OAI.Computability.VPVNP.CompressorExecutionLevels + +/-! +# Sizes of the actual arrays scanned at a selected compressor level + +Shrinking indexes motifs by old arcs and refresh indexes motifs by port blocks. +The bounds here follow the chosen term through its original state pass. They +control the base, site, arc, motif and resulting slot scans uniformly along +the execution, as well as the largest input field of every intermediate level. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords + +open Compression PairSimulation.LocalHistory +open private shrinkMotif_count refreshMotif_count castAllRecordsLe from OAI.Computability.VPVNP.PairSimulationSelectorBounds +open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + +namespace PassOrigin + +variable {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} + +/-- Number of physically distinct demand vectors for this pass. -/ +def motifCount (o : PassOrigin B f hf p) : ℕ := match o with + | .shrink _ h X => (shrinkMotifOrder (h ▸ X)).length + | .refresh (g := g) X => Fintype.card X.Base * 2 ^ g + +theorem motifCount_le (o : PassOrigin B f hf p) : o.motifCount ≤ X.positions * 2^a := by + cases o with + | shrink i h X => subst h; exact shrinkMotif_count X + | refresh X => exact (refreshMotif_count X).trans (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _)) + +theorem next_positions_le (o : PassOrigin B f hf p) (c : p.step.Choice) : + (p.next c).positions ≤ X.positions := by + cases o with + | shrink i h X => + exact (Nat.le_mul_of_pos_left _ ((two_lt_packingFactor _).trans' (by decide))).trans_eq + (B.shrinkPassAt_positions f hf i h X c).symm + | refresh X => + exact (Refresh.dyadicRefreshNext_positions X S.graph (Nat.two_pow_pos _) _ B.refresh _ _ c).le + +end PassOrigin + +/-- All degree exponents occur in a single fixed finite schedule. -/ +def slotDegree (S : BlockSchedule k) : ℕ := + max (2 ^ S.portExponent) (Finset.univ.sup (fun i : Fin (S.steps+1) ↦ 2 ^ S.degreeExponent i)) + +namespace SelectedLevel + +variable (v : SelectedLevel B f hf) + +/-- Number of input incidence slots, counting each incident port at every input position. -/ +def oldSlots : ℕ := v.input.positions * 2^v.inputExponent + +/-- Number of positions in the successor state produced by the selected term. -/ +def outputSites : ℕ := (v.pass.next v.term).positions + +/-- Number of successor incidence slots, obtained by multiplying output positions by output +degree. -/ +def outputSlots : ℕ := v.outputSites * 2^v.outputExponent + +theorem oldDegree_le : 2^v.inputExponent ≤ slotDegree S := by + obtain ⟨a,g,b,n,X,p,o,c,sel⟩ := v + cases o with + | shrink i _ _ => exact (Finset.le_sup (f := fun j : Fin (S.steps+1) ↦ 2 ^ S.degreeExponent j) + (Finset.mem_univ i.castSucc)).trans (le_max_right _ _) + | refresh _ => exact le_max_left _ _ + +theorem outputDegree_le : 2^v.outputExponent ≤ slotDegree S := by + obtain ⟨a,g,b,n,X,p,o,c,sel⟩ := v + cases o with + | shrink i _ _ => exact (Finset.le_sup (f := fun j : Fin (S.steps+1) ↦ 2 ^ S.degreeExponent j) + (Finset.mem_univ i.succ)).trans (le_max_right _ _) + | refresh _ => exact (Finset.le_sup (f := fun j : Fin (S.steps+1) ↦ 2 ^ S.degreeExponent j) + (Finset.mem_univ 0)).trans (le_max_right _ _) + +theorem outputSites_le : v.outputSites ≤ v.input.positions := v.origin.next_positions_le v.term + +theorem outputSlots_le : v.outputSlots ≤ v.input.positions * slotDegree S := + Nat.mul_le_mul v.outputSites_le v.outputDegree_le + +theorem oldSlots_le_units : v.oldSlots ≤ v.units := by + dsimp [oldSlots,units]; rw [Nat.mul_add]; omega + +theorem baseSites_le : Fintype.card v.input.Base ≤ v.input.positions := by + rw [State.positions,Fintype.card_prod] + exact Nat.le_mul_of_pos_right _ Fintype.card_pos + +end SelectedLevel + +variable (B f hf) + +private theorem collect_count {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X) + (W : E.MapWitnesses f) (r : ExecutionReaders E W) (o : PassOrigins B f hf E) + (rec : E.Records) (z : E.Choices) : + (collectLevels B f hf E W r o z).length = (E.termChain rec z).length := by + induction E with + | done => rfl + | more p tail ih => + rw [StateExecution.length_more] + exact congrArg Nat.succ (ih z.1 (W.2 z.1) (r.2 z.1) (o.2 z.1) (rec.2 z.1) z.2) + +private theorem collect_limits {a g b n C : ℕ} {X : State a g} (E : StateExecution R b n X) + (W : E.MapWitnesses f) (r : ExecutionReaders E W) (o : PassOrigins B f hf E) + (rec : E.Records) (z : E.Choices) (width : ℕ) (hb : E.Bounded C rec) + (hw : X.maxWireWidth ≤ width) (hr : (E.termChain rec z).AllRecordsLe width) : + ∀ v ∈ collectLevels B f hf E W r o z, v.input.positions ≤ X.positions ∧ v.input.maxWireWidth ≤ width := by + induction E with + | done => simp [collectLevels] + | more p tail ih => + obtain ⟨fields,maps,hrest⟩ := hr + have hnext := o.1.next_positions_le z.1 + have hwidth : (p.next z.1).maxWireWidth ≤ width := by + refine (hb.1 z.1).2.2.trans (Finset.sup_le fun v _ => max_le ?_ ?_) + · exact Finset.sup_le fun j _ => fields v j + · exact Finset.sup_le fun j _ => maps v j + intro v hv + rcases List.mem_cons.mp hv with rfl | htail + · exact ⟨le_rfl,hw⟩ + · obtain ⟨hp,hm⟩ := ih z.1 (W.2 z.1) (r.2 z.1) (o.2 z.1) (rec.2 z.1) z.2 + (hb.2 z.1) hwidth (castAllRecordsLe (p.output_eq z.1).symm _ width hrest) v htail + exact ⟨hp.trans hnext,hm⟩ + +/-- The level directory needs one header for each elementary substep on this branch. -/ +theorem executeLevels_length {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) + (z : (B.execute f hf T h X).Choices) : + (executeLevels B f hf T h X z).length ≤ (S.steps+1)*T := + (collect_count B f hf _ _ _ _ (B.records f hf T h X) z).le.trans + ((Procedure.repeat_recordBounds (B.recordBounds f hf) _ T n (Nat.add_sub_of_le h).symm X).2 z) + +/-- Every site and field in every intermediate input stays within the branch envelope. -/ +theorem executeLevels_limits {n : ℕ} (T : ℕ) (h : T * S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) + (z : (B.execute f hf T h X).Choices) : + ∀ v ∈ executeLevels B f hf T h X z, v.input.positions ≤ X.positions ∧ + v.input.maxWireWidth ≤ B.growthConstant ^ T * (X.maxWireWidth+1) := by + have hb := (Procedure.repeat_recordBounds (B.recordBounds f hf) _ T n (Nat.add_sub_of_le h).symm X).1 + have hw := B.growthConstant_ge_two + exact collect_limits B f hf _ _ _ _ (B.records f hf T h X) z _ hb + ((Nat.le_succ _).trans (Nat.le_mul_of_pos_left _ (Nat.pow_pos (by omega)))) + (B.branch_bounds f hf T h X z).2.2.2.2.1 + +end CompressorRecords + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorLevelOrder.lean b/lean/OAI/Computability/VPVNP/CompressorLevelOrder.lean new file mode 100644 index 0000000000..223a40f821 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorLevelOrder.lean @@ -0,0 +1,127 @@ +import OAI.Computability.VPVNP.CompressorExecutionLevels + +/-! +# Order of the selected compressor levels + +The native calendar repeats a fixed list of pass types. Choices alter the +data of the next level but preserve the scheduled order. The first indices +in a block enumerate shrinking transitions in increasing order, and the +last index is its refresh. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords + +open Compression PairSimulation.LocalHistory +open private bindOrigins ProcedureOrigins idOrigins passOriginsOfPass shrinkOrigins refreshOrigins + prefixOrigins blockOrigins repeatOrigins collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels +open private ProcedureOrigins.seq ProcedureOrigins.reindex from OAI.Computability.VPVNP.CompressorExecutionLevels + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + +/-- Slot of the elementary kernel in one block of the online calendar. -/ +def PassOrigin.ordinal {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} : + PassOrigin B f hf p → ℕ + | .shrink i .. => i.val + | .refresh .. => S.steps + +private def OrderMatches {a g b n : ℕ} {X : State a g} : (E : StateExecution R b n X) → + PassOrigins B f hf E → List ℕ → Prop + | .done _, _, js => js = [] + | .more _ tail, o, js => ∃ rest, js = o.1.ordinal :: rest ∧ ∀ i, OrderMatches (tail i) (o.2 i) rest + +private theorem order_bind {a g b n b' n' : ℕ} {X : State a g} (E : StateExecution R b n X) + (next : (z : E.Choices) → StateExecution R b' n' (E.finalState z)) (o : PassOrigins B f hf E) + (after : ∀ z, PassOrigins B f hf (next z)) {js ks : List ℕ} + (h : OrderMatches E o js) (h' : ∀ z, OrderMatches (next z) (after z) ks) : + OrderMatches (E.bind next) (bindOrigins B f hf E next o after) (js++ks) := by + induction E generalizing js with + | done => change js = [] at h; subst js; exact h' () + | more p tail ih => + obtain ⟨t,rfl,ht⟩ := h + exact ⟨t++ks,rfl,fun i ↦ ih i _ (o.2 i) _ (ht i) (fun z ↦ h' ⟨i,z⟩)⟩ + +variable {a b l d : ℕ} {μ : ℝ} + +private abbrev ProcedureOrder {P : Procedure R a b l d μ} (o : ProcedureOrigins B f hf P) (js : List ℕ) := + ∀ g n h X, OrderMatches (P.run g n h X) (o g n h X) js + +private theorem order_id (a : ℕ) : ProcedureOrder (idOrigins B f hf a) [] := by + intro g n h X + have hn := h.trans (Nat.zero_add g) + subst g; rfl + +private theorem order_seq {c l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} {Q : Procedure R b c l' d' ν} + {o : ProcedureOrigins B f hf P} {p : ProcedureOrigins B f hf Q} {js ks : List ℕ} + (ho : ProcedureOrder o js) (hp : ProcedureOrder p ks) : ProcedureOrder (ProcedureOrigins.seq B f hf o p) (js++ks) := + fun g n h X ↦ + let E := P.run (l'+g) n (h.trans (Nat.add_assoc l l' g)) X + order_bind E _ _ _ (ho _ _ _ X) (fun z ↦ hp _ _ _ (E.finalState z)) + +private theorem order_reindex {a' b' l' d' : ℕ} {ν : ℝ} {P : Procedure R a b l d μ} + {o : ProcedureOrigins B f hf P} {js : List ℕ} (ho : ProcedureOrder o js) + {ha : a=a'} {hb : b=b'} {hl : l=l'} {hd : d=d'} {hμ : μ=ν} : + ProcedureOrder (ProcedureOrigins.reindex B f hf o (ha := ha) (hb := hb) (hl := hl) (hd := hd) (hμ := hμ)) js := by + subst a' b' l' d' ν; exact ho + +variable (B f hf) + +private theorem order_shrink (i : Fin S.steps) : ProcedureOrder (shrinkOrigins B f hf i) [i.val] := by + intro g n h X; subst n + exact ⟨[],rfl,fun _ ↦ rfl⟩ + +private theorem order_refresh : ProcedureOrder (refreshOrigins B f hf) [S.steps] := by + intro g n h X; subst n + exact ⟨[],rfl,fun _ ↦ rfl⟩ + +private theorem order_prefix (j : ℕ) (hj : j ≤ S.steps) : + ProcedureOrder (prefixOrigins B f hf j hj) (List.range j) := by + induction j with + | zero => rw [prefixOrigins]; exact order_reindex (order_id _) + | succ j ih => + rw [prefixOrigins,List.range_succ] + exact order_reindex (order_seq (ih _) (order_reindex (order_shrink B f hf ⟨j,hj⟩))) + +private theorem order_block : ProcedureOrder (blockOrigins B f hf) (List.range (S.steps+1)) := by + rw [List.range_succ] + exact order_reindex (order_seq (order_reindex (order_prefix B f hf S.steps le_rfl)) (order_refresh B f hf)) + +private theorem order_repeat (g T n : ℕ) (h : n=T*S.laneBits+g) (X : State (S.degreeExponent 0) n) : + OrderMatches _ (repeatOrigins B f hf g T n h X) (List.replicate T (List.range (S.steps+1))).flatten := by + induction T generalizing n with + | zero => exact order_id _ _ _ _ _ + | succ t ih => + let E := (B.procedure f hf).run (t*S.laneBits+g) n (by rw [h,Nat.succ_mul]; omega) X + exact order_bind E _ _ _ (order_block B f hf _ _ _ X) (fun z ↦ ih _ rfl (E.finalState z)) + +private theorem collect_ordinals {a g b n : ℕ} {X : State a g} (E : StateExecution R b n X) + (W : E.MapWitnesses f) (r : ExecutionReaders E W) (o : PassOrigins B f hf E) {js : List ℕ} + (ho : OrderMatches E o js) (z : E.Choices) : + (collectLevels B f hf E W r o z).map (fun v ↦ v.origin.ordinal) = js := by + induction E generalizing js with + | done => exact ho.symm + | more p tail ih => + obtain ⟨t,rfl,ht⟩ := ho + exact congrArg (o.1.ordinal :: ·) (ih z.1 (W.2 z.1) (r.2 z.1) (o.2 z.1) (ht z.1) z.2) + +/-- On every branch, the exact chronological kernel sequence is the fixed +calendar block repeated the prescribed number of times. -/ +theorem executeLevels_order {n : ℕ} (T : ℕ) (h : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) + (z : (B.execute f hf T h X).Choices) : + (executeLevels B f hf T h X z).map (fun v ↦ v.origin.ordinal) = + (List.replicate T (List.range (S.steps+1))).flatten := + collect_ordinals B f hf _ _ _ _ (order_repeat B f hf _ T n (Nat.add_sub_of_le h).symm X) z + +end CompressorRecords + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorLogAccess.lean b/lean/OAI/Computability/VPVNP/CompressorLogAccess.lean new file mode 100644 index 0000000000..5f19dd0ad4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorLogAccess.lean @@ -0,0 +1,71 @@ +import OAI.Computability.VPVNP.CompressorRefreshStageFrame + +/-! # Read and write bounds for native report lists + +The bounds compose when report lists are concatenated. A scan that writes +one cell at each ordinal accesses exactly its addressed column. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM SourceTransport +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Bounds on every address actually read or written, including repeated +writes to cells whose eventual values agree with the input. -/ +abbrev LogAccess (rd wr : ℕ → Prop) (rs : List (Report w)) := + Reads rd (eventLog rs) ∧ Writes wr (eventLog rs) + +theorem LogAccess.append {rd wr : ℕ → Prop} {rs ts : List (Report w)} + (r : LogAccess rd wr rs) (t : LogAccess rd wr ts) : LogAccess rd wr (rs++ts) := by + simp only [LogAccess,eventLog,List.flatMap_append] + exact ⟨fun a v ha ↦ (List.mem_append.mp ha).elim (r.1 a v) (t.1 a v), + fun a v ha ↦ (List.mem_append.mp ha).elim (r.2 a v) (t.2 a v)⟩ + +theorem LogAccess.mono {rd wr rd' wr' : ℕ → Prop} {rs : List (Report w)} + (r : LogAccess rd wr rs) (reads : ∀ x, rd x → rd' x) (writes : ∀ x, wr x → wr' x) : + LogAccess rd' wr' rs := ⟨fun a v h ↦ reads _ (r.1 a v h), fun a v h ↦ writes _ (r.2 a v h)⟩ + +/-- Event trace of one direct external write surrounded by specified numbers of tick events. -/ +def directEvents (before ticks : ℕ) (addr v : Word w) : List (Event w) := + List.replicate before .tick ++ [.write addr v] ++ List.replicate ticks .tick + +theorem direct_events (before ticks : ℕ) (a v : Word w) (wr : ℕ → Prop) (ha : wr a.val) : + Reads (fun _ ↦ False) (directEvents before ticks a v) ∧ Writes wr (directEvents before ticks a v) := by + constructor + · intro q z hz; simp [directEvents] at hz + · intro q z hz; simpa [directEvents] using (show wr q.val from by + simp [directEvents] at hz + exact hz.1 ▸ ha) + +private theorem addr_val (base i : ℕ) (fit : base+i < 2^w) : + ((base : Word w)+(i : Word w)).val = base+i := by + rw [← Nat.cast_add] + exact Nat.mod_eq_of_lt fit + +/-- One external write per ordinal, with a fixed number of ticks on each side. -/ +theorem direct_scan {Q : Type*} (P : BurstRAM.Program w Q) (fuel before ticks base n : ℕ) + (value : Word w → Word w) (fit : base+n ≤ 2^w) + (native : ∀ (m : Memory w) (i : Word w), execute P fuel (P.start i) m [] = + some ⟨directEvents before ticks ((base : Word w)+i) (value i),some (i+1)⟩) + (m : Memory w) (rs : List (Report w)) (hr : runSegment P fuel (some 0) m (List.replicate n []) = some rs) : + LogAccess (fun _ ↦ False) (fun x ↦ base ≤ x ∧ x < base+n) rs := by + let ev := fun (_ : Memory w) i ↦ directEvents before ticks ((base : Word w)+i) (value i) + refine (StageFrame.scan P fuel 0 n (fun _ _ ↦ True) ev _ _ (fun _ _ _ m ↦ native m _) ?_ + (Nat.zero_le _) m rs trivial (by simpa only [Nat.sub_zero,Nat.cast_zero] using hr)).2.2 + intro j _ hj _ _ + refine ⟨trivial, direct_events before ticks _ _ _ ?_⟩ + rw [addr_val base j (by omega)] + omega + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorMatrixReader.lean b/lean/OAI/Computability/VPVNP/CompressorMatrixReader.lean new file mode 100644 index 0000000000..c420da8a40 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorMatrixReader.lean @@ -0,0 +1,147 @@ +import OAI.Computability.VPVNP.MacaulayOrdinary +import OAI.Computability.VPVNP.MacaulayFieldReadback +import OAI.Computability.VPVNP.MacaulaySignedRow +import OAI.Computability.VPVNP.MacaulayPinRow +import OAI.Computability.VPVNP.MacaulayAppendedPower +import OAI.Computability.VPVNP.CompressorReaderBudgets + +/-! # The augmented matrix reader for the compressor's actual finite model + +The entry routine is a single finite bit-stack program. On every queried row +and column, including all original grammar and fixed compressor equations, +it returns the encoded scalar in the determinant algorithm's matrix. Its +reusable advice and workspace have a separate stack-height bound, independent +of the exponentially longer clock. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open LabelEvaluator JointLabelSystem MvPolynomial RadicalCertificate.MonomialIndex +open RankQuery.Stack RankQuery.Stack.MacaulayRead RankQuery.Stack.Coordinate.SliceMinors +open RAMTape SliceArithmetic +open scoped Classical + +local instance nativeEntryPrime (p : Nat.Primes) : Fact p.val.Prime := ⟨p.prop⟩ + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) + +set_option maxHeartbeats 2400000 in +set_option maxRecDepth 6000 in +set_option synthInstance.maxSize 3000 in +/-- All coefficients of the actual encoded augmented Macaulay matrix are +computed on the physical scalar-entry ABI required by the rank engine. -/ +theorem compressorMatrixReader (q c : ℕ) {n w v e : ℕ} (hn : 2 ≤ n) {p : Nat.Primes} [NeZero e] + {m : Vector p.val e} [Fact (Irreducible (modulus m))] + (M : Model p (B.compressorDegree n) (B.compressorEquations hn c)) + (φ : AdjoinRoot (modulus m) ≃ₐ[ZMod p.val] Ground p (B.compressorLabelCount c n) (B.compressorDegree n)) + (hp : q ≠ 0 → p.val = q) (hz : q = 0 → p.val ≤ 2^B.compressorPrimeBits c n) + (hw : (B.compressorReaderPlan q c n).wordWidth ≤ w) + (he : e ≤ B.readerDegreeBudget q c n) (hv : v ≤ B.readerLimbBudget q c n) + (working : SliceArithmetic.Word.workingWidth p.val ≤ v) (sp ex : ℕ) + (hspace : SignedLeaf.callSpace B.Entry B.EquationIndex B.equation c hn w v m ≤ sp) + (htime : SignedLeaf.callTime B.Entry B.EquationIndex B.equation c hn w v m ≤ 2^ex) : + let Q := M.queryData (B.compressorCoeff hn c) + let plan := B.compressorReaderPlan q c n + let E := B.readerDegreeBudget q c n + let V := B.readerLimbBudget q c n + let L := JointScalar.Leaf.layout B.Entry B.EquationIndex B.equation c hn w p.val e v + CorrectSpace ordinaryReader (baseMatrix φ Q) w v (plan.readTime E V w sp ex) (plan.armSpace E V w sp) + (BaseAdvice.ready (2^n+Fintype.card B.EquationIndex) Q L m w v M.pins (AffinePin.Query.encode φ ∘ M.values)) := by + intro Q plan E V L + let vals := AffinePin.Query.encode φ ∘ M.values + let aux := Arms.coefficientAdvice L w v M.pins vals + let d := BaseAdvice.inputs Q + let constants := BaseAdvice.scalars m v + let bank := BaseAdvice.leaf Q L m w v M.pins vals + let A := plan.live E V w sp + have cov : plan.Covers Q := (B.compressorReaderCovers q c hn p M hp hz).1 + have hbank : JointScalar.Leaf.bankSize L w (plan.arity*w) ≤ sp := + (le_max_right ..).trans ((Nat.le_add_right ..).trans hspace) + have pre : Arms.Preload (w := w) A d constants aux := + Arms.coefficientAdvice_preload (P := plan) rfl he hv hbank M.pins vals d (fun _ => rfl) constants + (fun b => (Engine.scalar_length v (if b then (1 : Scalar m) else 0)).le) + have rawCap z : (bank z).length ≤ A := by + rcases z with ⟨side,x⟩ | x + · cases x with + | external f => + have hh := PairCall.values_le (d side) (fun _ => []) ([] : List Bool) [] pre.words (pre.arity side) + (by simp) (by simp) (by simp) f + cases f <;> first | exact hh | exact Nat.zero_le _ + | internal | scratch => exact Nat.zero_le _ + · cases x with + | zeroScalar => exact pre.scalars false + | oneScalar => exact pre.scalars true + | temp => exact Nat.zero_le _ + | payload j => exact pre.payload j + have room : max w A + MacaulayRowDispatch.ticks w ≤ plan.armSpace E V w sp := by + rw [max_eq_right pre.words] + have b := plan.leaf_bounds w sp ex he hv (d false) rfl + (cov.degrees.2.1.trans (le_max_right ..)) cov.degrees.2.2 + exact b.2.1.2.2.1 + apply correctSpace_of_arms (M := baseMatrix φ Q) (A := A) (b := plan.addressBits) + (arms := ordinaryArms) (bound := cov.dispatch) (hw := plan.dispatchWidth.1.trans hw) + (hbw := plan.dispatchWidth.2.1.trans hw) (ht := plan.dispatchWidth.2.2.trans hw) + (space := fun s hs z => (show s = bank from hs) ▸ rawCap z) (room := room) + apply armCorrect_of_blocks + · intro rs row o j hrow hsource hcol + obtain ⟨ticks,ht,run⟩ := Arms.signed_row_plan B.Entry B.EquationIndex B.equation c hn φ + Function.Embedding.inl working plan Q rfl (cov.degrees.2.1.trans (le_max_right ..)) cov.degrees.2.2 + he hv sp ex hspace htime hw rs aux pre (Arms.coefficientAdvice_loaded L w v M.pins vals).1 row o j hrow hsource hcol + let a := enumeration plan.arity Q.multiplierDegree o + let b := enumeration plan.arity Q.columnDegree j + let poly := map (Int.castRingHom (Ground p plan.arity (B.compressorDegree n))) + (B.compressorEquations hn c (FixedRows.rowIndex B.EquationIndex n row)) + have hcoef : Q.getCoeff (row.castAdd plan.pins) (fun i => b.val i-a.val i) = poly.coeff (b.val-a.val) := by + let z : Fin plan.arity → ℕ := fun i => b.val i-a.val i + have hx : exponentVector z = b.val-a.val := Finsupp.ext fun _ => rfl + have read : Q.getCoeff (row.castAdd plan.pins) = (fun u => (B.compressorCoeff hn c row u : Ground p plan.arity (B.compressorDegree n))) := + Fin.addCases_left (motive := fun _ => (Fin plan.arity → ℕ) → Ground p plan.arity (B.compressorDegree n)) + (left := fun i u => (B.compressorCoeff hn c i u : Ground p plan.arity (B.compressorDegree n))) + (right := fun i => (M.pinCut i).getCoeff) row + let eq := B.compressorEquations hn c (FixedRows.rowIndex B.EquationIndex n row) + let cast := Int.castRingHom (Ground p plan.arity (B.compressorDegree n)) + have hc : B.compressorCoeff hn c row z = eq.coeff (b.val-a.val) := + (B.compressorCoeff_eq hn c row z).trans (congrArg eq.coeff hx) + exact (congrFun read z).trans ((congrArg cast hc).trans (coeff_map cast eq (b.val-a.val)).symm) + have ident := shifted_matrix_entry φ Q (row.castAdd plan.pins) o j + change _ = (if a.val ≤ b.val then AffinePin.Query.encode φ (Q.getCoeff _ (fun i => b.val i - a.val i)) else 0) at ident + rw [hcoef] at ident + refine ⟨ticks,ht,?_⟩ + exact ident.symm ▸ run + · intro rs row o j hrow hsource hcol + let sys (i) := map (Int.castRingHom (Ground p plan.arity (B.compressorDegree n))) (B.compressorEquations hn c i) + obtain ⟨ticks,ht,run⟩ := Arms.pin_row_plan plan Q cov he hv sp ex hw working φ sys M.pins M.values row L hbank + rs hrow o j hsource hcol + let a := enumeration plan.arity Q.multiplierDegree o + let b := enumeration plan.arity Q.columnDegree j + have hcoef : Q.getCoeff (row.natAdd plan.equations) (fun i => b.val i-a.val i) = + (SliceGeometry.pinnedEquations sys M.pins M.values (.inr row)).coeff (b.val-a.val) := by + let z : Fin plan.arity → ℕ := fun i => b.val i-a.val i + have hx : exponentVector z = b.val-a.val := Finsupp.ext fun _ => rfl + have read : Q.getCoeff (row.natAdd plan.equations) = (M.pinCut row).getCoeff := + Fin.addCases_right (motive := fun _ => (Fin plan.arity → ℕ) → Ground p plan.arity (B.compressorDegree n)) + (left := fun i u => (B.compressorCoeff hn c i u : Ground p plan.arity (B.compressorDegree n))) + (right := fun i => (M.pinCut i).getCoeff) row + have polyEq : (M.pinCut row).polynomial = SliceGeometry.pinnedEquations sys M.pins M.values (.inr row) := + M.pinCut_polynomial row + exact (congrFun read z).trans (((M.pinCut row).getCoeff_eq z).trans (congrArg₂ (fun (f : MvPolynomial (Fin plan.arity) (Ground p plan.arity (B.compressorDegree n))) u => f.coeff u) polyEq hx)) + have ident := shifted_matrix_entry φ Q (row.natAdd plan.equations) o j + change _ = (if a.val ≤ b.val then AffinePin.Query.encode φ (Q.getCoeff _ (fun i => b.val i - a.val i)) else 0) at ident + rw [hcoef] at ident + refine ⟨ticks,ht,?_⟩ + exact ident.symm ▸ run + · intro rs o j hs hj + obtain ⟨ticks,ht,run⟩ := Arms.appended_power_plan plan Q cov he hv sp ex hw rs aux pre o j hs hj + refine ⟨ticks,ht,?_⟩ + rw [show baseMatrix φ Q (appended o) j = _ from power_matrix_entry φ Q o j] + exact run + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorNativeLocatedRuns.lean b/lean/OAI/Computability/VPVNP/CompressorNativeLocatedRuns.lean new file mode 100644 index 0000000000..52ddfe9c87 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorNativeLocatedRuns.lean @@ -0,0 +1,61 @@ +import OAI.Computability.VPVNP.CompressorShrinkEmitter +import OAI.Computability.VPVNP.CompressorRefreshEmitter +import OAI.Computability.VPVNP.CompressorScheduledPassCases + +/-! # The complete two-case descriptor compiler at a common length + +The finite calendar always selects either its specific shrinking worker or +the expander refresh worker. Both act on the actual selected graph and its +previously published records. The shared cost coefficient depends only on +the fixed templates. The threshold precedes the coefficient algebra, +workspace contents, selected graph and term choices. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace + +open Compression BurstRAM DescriptorSpace CursorBounds PairSimulation.TraversalRoles Filter +open scoped Fin.CommRing + +universe u v + +variable {k : Type u} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- A fixed coefficient that covers every shrinking substep and the refresh of one block. -/ +def descriptorRate := commonRawRate (ShrinkScheduledRun.fixedRate B) (RefreshEmit.rawRate B) + +attribute [local irreducible] BlockProgram.script BlockProgram.layout BlockClock.small + +/-- Above one length threshold, the actual selected pass runs in its allocated window over any coefficient ring. -/ +theorem eventually_locatedRuns (factor : ℕ) (hb : 1 ≤ factor) : ∀ᶠ n : ℕ in atTop, + ∀ {R : Type v} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) + (pub : Fin 11 → Word (wordBits factor n)) (blocks cap : ℕ) (initial : TaggedLayer) + (frame : Fin 8 → Word (wordBits factor n)), + let pos := initialPositions factor n + let L := BlockProgram.layout B (pub 2).val pos blocks + let small := BlockClock.small B factor n + let A := BlockProgram.script B + endAddress L < 2^wordBits factor n → small ≤ cap → + Schedule.Online.Run.ControlBounds A.plan small (w := wordBits factor n) → + LocatedRuns (CompiledResident.resident B f hf (pub 2) pos blocks n initial frame) pub (levelWords L) + (directoryRows L) cap small (nativePassRate A (descriptorRate B)*pos) blocks pos n := by + filter_upwards [ShrinkScheduledRun.eventually_emitAt.{u,v} B factor hb,RefreshPass.eventually_emitAt.{u,v} B factor hb] + with n shrink refresh + intro R inst f hf pub blocks cap initial frame pos L small A room clock control + apply locatedRuns_of_passes + · intro i g t X + exact shrink f hf i X pub blocks t cap (RefreshEmit.rawRate B) initial frame room clock control + · intro g t X + exact refresh f hf X pub blocks t cap (ShrinkScheduledRun.fixedRate B) initial frame room clock control + +end CompressorRecords.ScheduledTrace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorNativePassRates.lean b/lean/OAI/Computability/VPVNP/CompressorNativePassRates.lean new file mode 100644 index 0000000000..cc90698477 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorNativePassRates.lean @@ -0,0 +1,93 @@ +import OAI.Computability.VPVNP.CompressorGroupCost +import OAI.Computability.VPVNP.CompressorPassTimeline +import OAI.Computability.VPVNP.CompressorLevelCounts + +/-! # Communication rates of the installed pass program + +All source calls and probes are charged at their actual multiplicity. The +online controller charges a fixed amount per source call and a fixed recipe +overhead per source packet. The latter is bounded by the number of visits +in the single hardwired block. Neither charge uses the private burst clock. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM BlockPlanner Schedule Compression PassTimeline + +/-- Charge per position when the raw source workers use at most `raw` +units per position in the pass. -/ +def nativePassRate (A : Script) (raw : ℕ) : ℕ := + raw*(arity A.catalog+3) + A.block.length*(Online.Run.maxReads A.plan+4*arity A.catalog+26) + +theorem groupCost_nativeRate {w : ℕ} (A : Script) (ps : List (SourceOnline.Packet A w)) + (raw positions : ℕ) (positive : 0 < positions) (visitBound : ps.length ≤ A.block.length) + (work : RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) ≤ raw*positions) : + groupCost A ps ≤ nativePassRate A raw * positions := by + let overhead := Online.Run.maxReads A.plan+4*arity A.catalog+26 + have h := Nat.mul_le_mul_right (arity A.catalog+3) work + have tails : ps.length*overhead ≤ A.block.length*overhead*positions := + (Nat.mul_le_mul_right overhead visitBound).trans (Nat.le_mul_of_pos_right _ positive) + simpa only [groupCost,nativePassRate,Nat.add_mul,Nat.mul_right_comm raw positions] using Nat.add_le_add h tails + +/-- Uniform source-rate bound taking the maximum over all shrink indices and the refresh rate. -/ +def commonRawRate {s : ℕ} (shrinking : Fin s → ℕ) (refresh : ℕ) := + max (Finset.univ.sup shrinking) refresh + +/-- Source rate for a particular scheduled pass, selected from the indexed shrink rates or the +single refresh rate. -/ +def rawPassRate {s : ℕ} (p : PassTimeline.Pass s) (shrinking : Fin s → ℕ) (refresh : ℕ) := + match p with | .shrink i => shrinking i | .refresh => refresh + +theorem rawRate_le {s : ℕ} (p : PassTimeline.Pass s) (shrink : Fin s → ℕ) (refresh : ℕ) : + rawPassRate p shrink refresh ≤ commonRawRate shrink refresh := by + cases p with + | shrink i => exact (Finset.le_sup (f := shrink) (Finset.mem_univ i)).trans (le_max_left ..) + | refresh => exact le_max_right .. + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- The full source cost for a shrinking substep or a refresh yields the +same uniform bound for the three physical parts used in the pass runner. +The absolute ordinal equation gives the number of actual worker visits. -/ +theorem passCharges_le {a g w : ℕ} (X : State a g) (z : Located S.steps) + (shrinking : Fin S.steps → ℕ) (refresh positions : ℕ) (hpos : X.positions ≤ positions) + (pre : List (SourceOnline.Packet (BlockProgram.script B) w)) (selector : SourceOnline.Packet (BlockProgram.script B) w) + (tail : List (SourceOnline.Packet (BlockProgram.script B) w)) + (len : z.first B + pre.length + 1 + tail.length = z.finish B) + (raw : RAMBuckets.cost Report.probes ((pre++selector::tail).flatMap SourceWalk.Packet.reports) ≤ + rawPassRate z.pass shrinking refresh * X.positions) : + groupCost (BlockProgram.script B) pre + groupCost (BlockProgram.script B) [selector] + + groupCost (BlockProgram.script B) tail ≤ nativePassRate (BlockProgram.script B) (commonRawRate shrinking refresh)*positions := by + have window := congrArg List.length (z.window B).block + simp only [List.length_append] at window + have length : (pre++selector::tail).length ≤ (BlockProgram.script B).block.length := by + change z.first B+pre.length+1+tail.length = z.first B+(z.visits B).length at len + simp only [List.length_append,List.length_cons] + omega + rw [← groupCost_split_selector] + exact groupCost_nativeRate _ _ _ _ (X.positions_pos.trans_le hpos) length + (raw.trans (Nat.mul_le_mul (rawRate_le ..) hpos)) + +/-- Total of the uniform per-pass bounds in the actual chronological tree, +followed by the calendar's terminal cost of four. -/ +theorem timeline_rate (T raw positions : ℕ) : + (timeline S.steps T).length * (nativePassRate (BlockProgram.script B) raw * positions) + 4 = + (T*(S.steps+1)) * (nativePassRate (BlockProgram.script B) raw * positions) + 4 := by + have len : (timeline S.steps T).length = T*(S.steps+1) := by + induction T with + | zero => simp [timeline] + | succ t ih => + simp only [timeline,List.range_succ,List.flatMap_append,List.flatMap_singleton,List.length_append] at ih ⊢ + rw [ih,Nat.succ_mul] + simp [oneBlock] + rw [len] + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineBranchCut.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineBranchCut.lean new file mode 100644 index 0000000000..5c1824a00c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineBranchCut.lean @@ -0,0 +1,158 @@ +import OAI.Computability.VPVNP.CompressorBranchSegments + +/-! # Native branch cuts of the fixed online descriptor table + +The data bursts of a term row occur between three empty entering control +calls and one empty returning call. Every valid source tape selects a term, +and all terms use the same number of motifs. These facts distinguish the +terms even in the presence of arbitrary later native calls. The ordinary +descriptor rows are executed from the memory produced by each preceding row. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online.Run + +open BurstRAM BranchSegments + +variable {w d initial phases : ℕ} {C : Catalog d} (plan : Config C initial phases) (ports : Ports w) +local notation "q" => initial + phases +local notation "D" => N d q +local notation "prog" => program plan ports +local notation "tag" => LiveStageLink.tagWord w (calendarIndex d q) + +/-- All non-data instruction bounds are fixed by the finite program. -/ +structure ControlBounds (_plan : Config C initial phases) (cap : ℕ) : Prop where + tags : D ≤ 2^w + calendar : 30+2*q+2*D+5 ≤ cap + launch : 20+6*(arity C+1)+2*D+5 ≤ cap + +variable {cap : ℕ} {m : Memory w} {state : Word w} + +/-- The actual online portion for a single valid source row. -/ +def oneRow (bounds : ControlBounds plan cap (w := w)) (htag : m ports.tag.val = tag) + (s : Step d q w) (h : s.Valid plan ports cap m) : Segment prog cap (some state) m where + bits := rowChoices s.row + logs := rowLog plan ports m s.phase s.row + run := by + have run := row_segment plan ports state m s.phase s.row h.input h.source htag bounds.tags h.active h.phase + bounds.calendar h.recipeCap bounds.launch h.dataCap [] + simpa only [List.append_nil,runSegment,Option.map_some] using run + +theorem oneRow_state (bounds : ControlBounds plan cap (w := w)) (htag : m ports.tag.val = tag) + (s : Step d q w) (h : s.Valid plan ports cap m) : + (oneRow plan ports (state := state) bounds htag s h).state = some 0 := + (row_effect plan ports m s.phase s.row h.input h.source state).2 + +theorem oneRow_memory (bounds : ControlBounds plan cap (w := w)) (htag : m ports.tag.val = tag) + (s : Step d q w) (h : s.Valid plan ports cap m) : + (oneRow plan ports (state := state) bounds htag s h).memory = post C q ports s.row := + (row_effect plan ports m s.phase s.row h.input h.source state).1 + +/-- A finite interval of valid native rows, ending at a calendar boundary. +The ending ordinal may still have further phases to execute. -/ +def Interval (cap : ℕ) : Memory w → List (Step d q w) → Prop + | _, [] => True + | m, s :: rest => s.Valid plan ports cap m ∧ Interval cap (post C q ports s.row) rest + +/-- Concatenate the choice tapes of the successive rows in an online interval. -/ +def intervalBits (steps : List (Step d q w)) := steps.flatMap fun s => rowChoices s.row + +/-- Replay the interval's row reports in chronological order using the memory produced by each +preceding row. -/ +def intervalLog : Memory w → List (Step d q w) → List (Report w) + | _, [] => [] + | m, s :: rest => rowLog plan ports m s.phase s.row ++ intervalLog (post C q ports s.row) rest + +/-- Physical segment witnessing a valid interval of online rows with its original choice tapes +and report log. -/ +def intervalSegment (bounds : ControlBounds plan cap (w := w)) (htag : m ports.tag.val = tag) + (steps : List (Step d q w)) (h : Interval plan ports cap m steps) : Segment prog cap (some state) m where + bits := intervalBits steps + logs := intervalLog plan ports m steps + run := by + induction steps generalizing state m with + | nil => rfl + | cons s rest ih => + change runSegment _ _ _ _ (rowChoices s.row ++ intervalBits rest) = _ + rw [row_segment plan ports state m s.phase s.row h.1.input h.1.source htag bounds.tags h.1.active h.1.phase + bounds.calendar h.1.recipeCap bounds.launch h.1.dataCap] + rw [ih (state := 0) (by simp [post,writeMemory]) h.2] + rfl + +theorem interval_memory (bounds : ControlBounds plan cap (w := w)) (htag : m ports.tag.val = tag) + (steps : List (Step d q w)) (h : Interval plan ports cap m steps) : + (intervalSegment plan ports (state := state) bounds htag steps h).memory = + finalMemory (C := C) ports m steps := by + change after m (eventLog (intervalLog plan ports m steps)) = _ + induction steps generalizing m with + | nil => rfl + | cons s rest ih => + rw [intervalLog,SourceWalk.after_append,(row_effect plan ports m s.phase s.row h.1.input h.1.source state).1] + exact ih (by simp [post,writeMemory]) h.2 + +theorem interval_state_zero (bounds : ControlBounds plan cap (w := w)) (htag : m ports.tag.val = tag) + (steps : List (Step d q w)) (h : Interval plan ports cap m steps) : + (intervalSegment plan ports (state := 0) bounds htag steps h).state = some 0 := by + change endState (some 0) (intervalLog plan ports m steps) = _ + induction steps generalizing m with + | nil => rfl + | cons s rest ih => + rw [intervalLog,endState_append,(row_effect plan ports m s.phase s.row h.1.input h.1.source 0).2] + exact ih (by simp [post,writeMemory]) h.2 + +/-- The entire native interval, including each row's control calls, uses +empty tapes whenever every scheduled source burst does. -/ +theorem quietInterval (steps : List (Step d q w)) + (quiet : ∀ s ∈ steps, s.row.choices = List.replicate s.row.choices.length []) : + intervalBits steps = List.replicate (intervalBits steps).length [] := by + induction steps with + | nil => rfl + | cons s rest ih => + have eq := quiet s List.mem_cons_self + have tail := ih (fun r hr => quiet r (List.mem_cons_of_mem _ hr)) + change rowChoices s.row ++ intervalBits rest = List.replicate (rowChoices s.row ++ intervalBits rest).length [] + rw [List.length_append,List.replicate_add] + have hr : rowChoices s.row = List.replicate (rowChoices s.row).length [] := by + change [] :: [] :: [] :: (s.row.choices ++ [[]]) = _ + simp only [rowChoices,List.length_cons,List.length_append,List.replicate_succ] + rw [List.replicate_add,← eq] + rfl + exact congrArg₂ List.append hr tail + +variable {I : Type*} + +/-- Invert a term row, using its actual one-call worker invariant and the +source selector's completeness on valid recovered rows. -/ +def selectorCut (bounds : ControlBounds plan cap (w := w)) (htag : m ports.tag.val = tag) + (entry : RowStart plan ports cap m) (active : m ports.ordinal.val < m ports.rows.val) + (rows : I → Step d q w) (valid : ∀ i, (rows i).Valid plan ports cap m) + (decode : ∀ s : Step d q w, s.Valid plan ports cap m → s.phase = entry.phase → + s.row.worker = entry.worker → s.row.fuel = entry.fuel → + ∃ i, s.row.choices = (rows i).row.choices) + (count : ℕ) (lengths : ∀ i, (rows i).row.choices.length = count) + (unique : Function.Injective fun i => (rows i).row.choices) : + Cut prog cap (some state) m I where + part i := oneRow plan ports bounds htag (rows i) (valid i) + separate i j a b h := by + change rowChoices (rows i).row ++ a = rowChoices (rows j).row ++ b at h + simp only [rowChoices,List.cons_append,List.cons.injEq,true_and,List.append_assoc] at h + have e := congrArg (List.take count) h + have hi := lengths i + have hj := lengths j + apply unique + rw [← hi,List.take_left,hi,← hj,List.take_left] at e + exact e + cover bs rs run halt := by + obtain ⟨s,tail,more,h,hp,hw,hf,hb,_,_,_⟩ := + recover_row plan ports entry htag bounds.tags active bounds.calendar bounds.launch run halt + obtain ⟨i,selected⟩ := decode s h hp hw hf + exact ⟨i,tail,by simpa only [oneRow,rowChoices,selected] using hb⟩ + +end CompressorRecords.Schedule.Online.Run + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineBudget.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineBudget.lean new file mode 100644 index 0000000000..3cbb9e5b70 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineBudget.lean @@ -0,0 +1,79 @@ +import OAI.Computability.VPVNP.CompressorDirectoryBudget +import OAI.Computability.VPVNP.CompressorRecordsOnlineRun + +/-! +# The selected descriptor branch in the online instruction table + +This adapter executes the actual dispatcher and data workers, and accounts +for every returned report. The finite phase plan and local work bounds +precede all graph and term choices. A valid online directory supplies the +actual memory evolution through the calendar, recipes and workers. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PhaseVisits + +open BurstRAM Compression Schedule CursorNetwork CursorBounds + +private theorem row_valid {d i j w : ℕ} {C : Catalog d} {Q : Online.Config C i j} {p : Ports w} + {cap : ℕ} {steps : List (Online.Run.Step d (i+j) w)} {m : Memory w} + (h : Online.Run.Valid Q p cap m steps) : + ∀ r ∈ steps.map Online.Run.Step.row, r.Valid C p := by + induction steps generalizing m with + | nil => simp + | cons s ss ih => + intro r hr + rcases List.mem_cons.mp hr with rfl | hmem + · exact h.1.source + · exact ih h.2 _ hmem + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} + +/-- The fixed online table, started in calendar state, accepts the selected +tape and stays within the stated local and total communication allowances. -/ +theorem selected_online_budget (B : S.Templates) (u : PairExponents B.growthConstant) (P : Plan S) + (H I q b n : ℕ) (hn : 1 ≤ n) {base lanes : ℕ} + (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) (hD : 1 < virtualBits b n) + (hT : blockCount (u.θ : ℝ) n*S.laneBits ≤ lanes) + {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f) + (z : (B.execute f hf _ hT (pairInput S labels hD)).Choices) + {d w i j : ℕ} {C : Catalog d} (Q : Online.Config C i j) (p : Ports w) + (initial : List (Directory.Row d w)) + (groups : ∀ v : SelectedLevel B f hf, LevelRows (d := d) (w := w) (pairInput S labels hD).positions v) + (hinit : calls initial ≤ I*(pairInput S labels hD).positions) + (steps : List (Online.Run.Step d (i+j) w)) (m : Memory w) (state : Word w) (cap : ℕ) + (valid : Online.Run.Valid Q p cap m steps) + (tag : m p.tag.val = LiveStageLink.tagWord w (Online.calendarIndex d (i+j))) + (fit : Online.N d (i+j) ≤ 2^w) + (cal : 30+2*(i+j)+2*Online.N d (i+j)+5 ≤ cap) + (launch : 20+6*(arity C+1)+2*Online.N d (i+j)+5 ≤ cap) + (clock : cap ≤ H*(n.log2+1)^q) : + let X := pairInput S labels hD + let T := blockCount (u.θ : ℝ) n + let K := (2*(I + (S.steps+1)*max 1 (slotDegree S)*P.levelRate)+1)*H + steps.map Online.Run.Step.row = branchRows P X.positions (executeLevels B f hf T hT X z) initial groups → + let rs := Online.Run.reports Q p m steps + runSegment (Online.program Q p) cap (some state) m (Online.Run.choices steps) = some rs ∧ + after m (eventLog rs) = Online.Run.finalMemory (C := C) p m steps ∧ endState (some state) rs = none ∧ + (∀ r ∈ rs, r.events.length < cap ∧ r.probes < cap) ∧ + RAMBuckets.cost Report.probes rs ≤ K * initialPositions b n * (n.log2+1)^(q+1) := by + intro X T K hs rs + have run := Online.Run.execute Q p steps m state cap tag fit cal launch valid + have eff := Online.Run.effect Q p steps m state valid + have same : Online.Run.choices steps = + (branchRows P X.positions (executeLevels B f hf T hT X z) initial groups).flatMap Online.rowChoices ++ [[]] := by + rw [← hs,Online.Run.choices,List.flatMap_map] + refine ⟨run,eff.1,eff.2,online_run_budget B u P H I q b n hn labels hD hT f hf z C p initial groups hinit + _ state m cap rs ?_ clock (same ▸ run)⟩ + change ∀ r ∈ branchRows P X.positions (executeLevels B f hf T hT X z) initial groups, r.Valid C p + rw [← hs] + exact row_valid valid + +end CompressorRecords.PhaseVisits + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineCursorStartup.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineCursorStartup.lean new file mode 100644 index 0000000000..4a010f6130 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineCursorStartup.lean @@ -0,0 +1,270 @@ +import OAI.Computability.VPVNP.CompressorDescriptorCursorFrame +import OAI.Computability.VPVNP.CompressorDescriptorParameterCapacity +import OAI.Computability.VPVNP.CompressorRecordsOnlineWorkspace + +/-! +# Chronological startup of the online cursor calendar + +The row counter determines the size of the directory before the parameter +publisher computes any level address. The stride and controller setup use the +published cursor parameters and preserve the permanent copy in level zero. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.OnlineCursorStartup + +open BurstRAM BurstRAM.PrivateRAM DescriptorSpace CursorBounds +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- The public pair inputs and integer operands of the first calendar call. -/ +structure Input (D : CalendarRows.Spec) (L : Layout) (B n : ℕ) (pub : Fin 11 → Word w) : Prop where + base : (pub 2).val = L.base + length : (pub 6).val = n + address : (pub 7).val = addressBits B n + denominator_pos : 0 < D.q + phase_pos : 0 < D.phaseRows + phase_fit : D.phaseRows < 2^w + numerator_fit : D.p < 2^w + radix_fit : 2^D.q < 2^w + power_fit : n^D.p < 2^w + rows_fit : CalendarRows.rows D n < 2^w + directory : directoryRows L = CalendarRows.rows D n + +/-- The count writer is the only prerequisite for the raw parameter producer. +Its output memory meets the producer's entry conditions from arbitrary memory. -/ +theorem count_ready (D : CalendarRows.Spec) (L : Layout) (B n : ℕ) + (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) (h : Input D L B n pub) : + let P := ((CalendarRows.table D).instantiate w pub).program + let rep := CalendarRows.report D pub n + let T := roundedDown D.p D.q n + execute P (CalendarRows.ticks D n + 2) (P.start s) m [] = some rep ∧ + DescriptorParameters.Ready L B n D.initialRows D.phaseRows T pub (after m rep.events) := by + refine ⟨CalendarRows.execute_native D pub s m [] n h.denominator_pos h.length h.numerator_fit + h.radix_fit h.power_fit le_rfl, h.base, h.length, h.address, ?_, ?_, h.phase_pos, h.phase_fit⟩ + · rw [CalendarRows.after_report, writeMemory, ite_eq_left rfl, Fin.val_natCast, Nat.mod_eq_of_lt h.rows_fit] + exact Nat.add_left_cancel_iff.mpr (Nat.mul_comm ..) + · rw [h.directory, CalendarRows.rows, Nat.mul_comm] + +/-- Tight allocation puts exactly the computed number of directory rows +before the first level. All integer-fit obligations hold eventually for the +same threshold, regardless of the pair's workspace address. -/ +theorem eventually_input (D : CalendarRows.Spec) (B : ℕ) (hB : 1 ≤ B) + (hq : 0 < D.q) (hph : 0 < D.phaseRows) : + ∀ᶠ n : ℕ in Filter.atTop, ∀ (L : Layout) (pub : Fin 11 → Word (wordBits B n)), + (pub 2).val = L.base → (pub 6).val = n → (pub 7).val = addressBits B n → + Input D (LevelFields.tightDirectory L (CalendarRows.rows D n)) B n pub := by + filter_upwards [CalendarRows.eventually_fits D B hB, + CursorRAM.eventual_word_room B hB (PolynomiallyBounded.const D.phaseRows)] with n h hp + intro L pub base len addr + exact ⟨base, len, addr, hq, hph, hp, h.1, h.2.1, h.2.2.1, h.2.2.2, LevelFields.tight_rows ..⟩ + +/-- All writes of the stride and calendar-arming stages lie below level zero. -/ +private theorem addresses (L : Layout) (base : Word w) (hb : base.val = L.base) + (fit : levelStart L 0 < 2^w) : + (OnlineWorkspace.gap L.shape.arity base).val < levelStart L 0 ∧ + ∀ i : Fin 8, (base + (i.val : Word w)).val < levelStart L 0 := by + have head : L.base+10+L.shape.arity < levelStart L 0 := by + simp only [levelStart, levelsBase, directoryBase, plannerTag, frameBase, Nat.zero_mul, Nat.add_zero] + omega + have atOffset (j : ℕ) (hj : L.base+j < levelStart L 0) : + (base+(j : Word w)).val = L.base+j := by + rw [Fin.val_add, hb, Fin.val_natCast, Nat.mod_eq_of_lt (show j < 2^w by omega), + Nat.mod_eq_of_lt (hj.trans fit)] + constructor + · change (base + ((10+L.shape.arity : ℕ) : Word w)).val < _ + rw [atOffset _ (by omega)]; omega + · intro i + rw [atOffset _ (by have := i.isLt; omega)] + have := i.isLt + omega + +/-- Arming the calendar preserves all persistent descriptor words beginning +at the first level. This includes the cursor operand bank at offsets 6–13. -/ +theorem arm_preserves_levels (d : ℕ) (L : Layout) (pub : Fin 11 → Word w) + (s : Word w) (m : Memory w) (hb : (pub 2).val = L.base) (fit : levelStart L 0 < 2^w) + {row tag : Word w} {b l a W start : ℕ} + (frame : Frame.data (pub 2+9) m = CursorRAM.ScheduleInit.inputs row tag b l a W start) + (positions : (b+l)*2^b*2^l = L.positions) {addr : ℕ} (level : levelStart L 0 ≤ addr) : + let middle := after m (DescriptorStride.report L.shape pub s m).events + OnlineWorkspace.armed d L.shape.arity (pub 2) middle addr = m addr := by + intro middle + obtain ⟨gap,control⟩ := addresses L (pub 2) hb fit + have stride := (DescriptorStride.native L pub s m frame positions).2.2.1 + change middle = writeMemory m (OnlineWorkspace.gap L.shape.arity (pub 2)) _ at stride + rw [OnlineWorkspace.armed, (Workspace.calendar_effect d L.shape.arity ..).1] + have tagBelow : (Workspace.ports L.shape.arity (pub 2)).tag.val < levelStart L 0 := control 6 + rw [writeMemory, ite_eq_right (by omega : addr ≠ (Workspace.ports L.shape.arity (pub 2)).tag.val), + Workspace.init_outside _ _ _ _ (fun i ↦ ne_of_gt ((control i).trans_le level)), stride, writeMemory] + exact ite_eq_right (by omega) + +private theorem closed_call {p r : ℕ} (T : Template p r 11) (pub : Fin 11 → Word w) + (s : Word w) (m : Memory w) (f : ℕ) (rep : Report w) + (native : let P := (T.instantiate w pub).program + execute P f (P.start s) m [] = some rep) : + let P := ((LiveOneShot.oneShot T).instantiate w pub).program + execute P f (P.start s) m [] = some ⟨rep.events,none⟩ := by + dsimp only + rw [LiveOneShot.execute_oneShot] + change (execute _ _ ((T.instantiate w pub).program.start s) m []).map _ = _ + rw [native]; rfl + +/-- The split cursor position count is the position capacity of the native +initial graph, including the boundary case of zero residual base bits. -/ +theorem position_count {B n l : ℕ} (hl : l ≤ virtualBits B n) : + (virtualBits B n-l+l)*2^(virtualBits B n-l)*2^l = initialPositions B n := by + rw [Nat.mul_assoc, ← pow_add, Nat.sub_add_cancel hl, initialPositions, Nat.mul_comm] + +/-- A normal pair-ABI entry of one fixed template at its stated fuel cap. -/ +def Call {pc r : ℕ} (T : Template pc r 11) (pub : Fin 11 → Word w) + (cap : ℕ) (s : Word w) (m : Memory w) (out : Report w) : Prop := + let P := (T.instantiate w pub).program + execute P cap (P.start s) m [] = some out + +/-- Close a startup report by keeping its events and clearing its returned continuation state. -/ +def closed (r : Report w) : Report w := ⟨r.events,none⟩ + +/-- Packing a different number of directory rows changes their addresses +at runtime. The shape-dependent startup instruction tables are fixed. -/ +theorem tight_tables (L : Layout) (rows a initial phases lanes : ℕ) : + let F := (LevelFields.tightDirectory L rows).shape + DescriptorParameters.table F a initial phases lanes = + DescriptorParameters.table L.shape a initial phases lanes ∧ + DescriptorParameters.copyTable F = DescriptorParameters.copyTable L.shape ∧ + OnlineWorkspace.strideTable F = OnlineWorkspace.strideTable L.shape ∧ + Workspace.initTable F.arity = Workspace.initTable L.shape.arity := + ⟨rfl,rfl,rfl,rfl⟩ + +/-- The seven accepting calls that precede the first visit in the online +calendar. The three frame programs use single-call wrappers so the outer +linker can transfer control at their successful exits. -/ +def Runs (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes : ℕ) + (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) : Prop := + let T := roundedDown D.p D.q n + let q := CalendarRows.report D pub n + let counted := after m q.events + let tr := DescriptorParameters.trace L B n a D.initialRows D.phaseRows T lanes pub 0 0 0 counted + let prepared := tr.post counted + let stride := DescriptorStride.report L.shape pub 0 prepared + let pitched := after prepared stride.events + let bank := Workspace.initReport L.shape.arity (pub 2) + let final := OnlineWorkspace.armed d L.shape.arity (pub 2) pitched + Call (CalendarRows.table D) pub (CalendarRows.ticks D n+2) s m q ∧ + Call (LiveOneShot.oneShot (DescriptorParameters.table L.shape a D.initialRows D.phaseRows lanes)) + pub ((DescriptorParameters.raw L.shape a D.initialRows D.phaseRows lanes).recipe.code.length+1) + 0 counted (closed tr.raw) ∧ + Call (LiveOneShot.oneShot DescriptorParameters.loader) pub (VirtualParameters.ticks n+43+4*17) + 0 (tr.postRaw counted) (closed tr.loaded) ∧ + Call (LiveOneShot.oneShot (DescriptorParameters.copyTable L.shape)) pub + ((DescriptorParameters.copy L.shape).recipe.code.length+1) 0 (tr.postLoad counted) (closed tr.copied) ∧ + Call (OnlineWorkspace.strideTable L.shape) pub (1+DescriptorStride.cost L.shape) 0 prepared (closed stride) ∧ + Call (Workspace.initTable L.shape.arity) pub 42 0 pitched bank ∧ + Call (Workspace.calendarStart d) pub 6 0 (after pitched bank.events) (Workspace.calendarReport d (pub 2)) ∧ + OnlineWorkspace.Ready d L.shape.arity (pub 2) (CalendarRows.rows D n) (levelWords L) final ∧ + Frame.data (DescriptorParameters.saved L w) final = DescriptorParameters.outputs L B n a (T*lanes) w + +/-- Starting with arbitrary external memory, compute the row count, produce +both cursor frames, install the stride and leave the online calendar ready +with its level-zero frame intact. -/ +theorem run (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes : ℕ) + (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) (input : Input D L B n pub) + (hw : w = wordBits B n) (hB : 1 ≤ B) + (hL : roundedDown D.p D.q n * lanes ≤ virtualBits B n) + (arity : 7 ≤ L.shape.arity) (scalars : 14 ≤ L.shape.scalarFields) + (positions : initialPositions B n = L.positions) + (capacity : CursorRAM.ParametersInit.Capacity B n a (roundedDown D.p D.q n*lanes) + (directoryBase L) 1 (incidenceStart L 0) (levelStart L 0+6)) : + Runs D d L B n a lanes pub s m := by + unfold Runs + intro T q counted tr prepared stride pitched bank final + obtain ⟨first, ready⟩ := count_ready D L B n pub s m input + obtain ⟨raw, loaded, copied, _, _, _, permanent, active, keep, _⟩ := + DescriptorParameters.run ready hw hB a lanes hL arity scalars capacity 0 0 0 + have savedFit : levelStart L 0+6+8 < 2^w := hw ▸ capacity.frame_end + have headFit : levelStart L 0 < 2^w := by omega + have head : L.base+10+L.shape.arity < levelStart L 0 := by + simp only [levelStart, levelsBase, directoryBase, plannerTag, frameBase, Nat.zero_mul, Nat.add_zero] + omega + have address : (pub 2+8).val = L.base+8 := by + rw [Fin.val_add, input.base, show (8 : Word w).val = 8 from Nat.mod_eq_of_lt (by omega : 8 < 2^w), + Nat.mod_eq_of_lt (by omega)] + have count : prepared (pub 2+8).val = (CalendarRows.rows D n : Word w) := by + change tr.post counted _ = _ + rw [keep _ (Or.inl (by rw [address, frameBase]; omega)) (Or.inl (by rw [address]; omega))] + rw [CalendarRows.after_report, writeMemory, ite_eq_left rfl] + have pos := (position_count hL).trans positions + have ⟨strideExec,initExec,armExec,armed⟩ := + OnlineWorkspace.stride_and_arm d L pub 0 prepared _ active pos (by omega) count + refine ⟨first, closed_call _ _ _ _ _ _ raw, closed_call _ _ _ _ _ _ loaded, + closed_call _ _ _ _ _ _ copied, strideExec, initExec, armExec, armed, ?_⟩ + apply Eq.trans _ permanent + funext j + have hv : (DescriptorParameters.saved L w).val = levelStart L 0+6 := Nat.mod_eq_of_lt (by omega) + have fit : (DescriptorParameters.saved L w).val+8 ≤ 2^w := by omega + rw [Frame.data_at _ _ fit j, Frame.data_at _ _ fit j] + exact arm_preserves_levels d L pub 0 prepared input.base headFit active pos (by rw [hv]; omega) + +/-- External memory passed to the online calendar after the seven calls. -/ +noncomputable def finalMemory (D : CalendarRows.Spec) (d : ℕ) (L : Layout) (B n a lanes : ℕ) + (pub : Fin 11 → Word w) (m : Memory w) : Memory w := + let T := roundedDown D.p D.q n + let counted := after m (CalendarRows.report D pub n).events + let tr := DescriptorParameters.trace L B n a D.initialRows D.phaseRows T lanes pub 0 0 0 counted + let prepared := tr.post counted + let stride := DescriptorStride.report L.shape pub 0 prepared + OnlineWorkspace.armed d L.shape.arity (pub 2) (after prepared stride.events) + +theorem Runs.output {D d L B n a lanes pub s m} (h : Runs (w := w) D d L B n a lanes pub s m) : + let out := finalMemory D d L B n a lanes pub m + OnlineWorkspace.Ready d L.shape.arity (pub 2) (CalendarRows.rows D n) (levelWords L) out ∧ + Frame.data (DescriptorParameters.saved L w) out = + DescriptorParameters.outputs L B n a (roundedDown D.p D.q n*lanes) w := + h.2.2.2.2.2.2.2 + +/-- The first actual dispatch on the pair ABI starts from the memory produced +by the seven calls. Its parameter-frame load and internal tag selection are +included in the reported transcript. -/ +theorem Runs.first_dispatch {D d L B n a lanes pub s m} + (h : Runs (w := w) D d L B n a lanes pub s m) + {C : Schedule.Catalog d} (plan : Schedule.Online.Config C D.initialRows D.phaseRows) + (arity : L.shape.arity = Schedule.arity C) + (nonempty : 0 < (CalendarRows.rows D n : Word w)) (j : Fin (D.initialRows+D.phaseRows)) (hj : j.val = 0) + (fits : Schedule.Online.N d (D.initialRows+D.phaseRows) ≤ 2^w) + {cap : ℕ} (budget : 30+2*(D.initialRows+D.phaseRows)+2*Schedule.Online.N d (D.initialRows+D.phaseRows)+5 ≤ cap) : + let out := finalMemory D d L B n a lanes pub m + let P := Workspace.ports (Schedule.arity C) (pub 2) + let rep := Schedule.Online.linked P (Schedule.Online.calendarIndex d (D.initialRows+D.phaseRows)) + (Schedule.LevelCalendar.dispatchReport (Schedule.Online.calendar plan) P.data out (Schedule.Online.phaseIndex plan j)) + Call (OnlineWorkspace.table plan) pub (cap+24) 0 out (Workspace.report (pub 2) out rep) := by + have ready := h.output.1 + rw [arity] at ready + exact OnlineWorkspace.first_dispatch plan pub 0 _ _ _ ready nonempty j hj fits budget + +/-- At the actual cursor position count, one length threshold establishes +the complete startup for every entry state and memory, for every number of +levels allocated beyond the first header. -/ +theorem eventually_run (D : CalendarRows.Spec) (d : ℕ) (F : Shape) (B a lanes : ℕ) + (hB : 1 ≤ B) (hq : 0 < D.q) (hph : 0 < D.phaseRows) + (hθ : (D.p : ℝ)/D.q ≤ 1) (hlanes : lanes ≤ B) + (arity : 7 ≤ F.arity) (scalars : 14 ≤ F.scalarFields) + {base : ℕ → ℕ} (hb : PolynomiallyBounded base) : + ∀ᶠ n : ℕ in Filter.atTop, ∀ (levels : ℕ) (pub : Fin 11 → Word (wordBits B n)), + (pub 2).val = base n → (pub 6).val = n → (pub 7).val = addressBits B n → + ∀ s m, Runs D d (LevelFields.tightDirectory ⟨F,base n,initialPositions B n,levels⟩ + (CalendarRows.rows D n)) B n a lanes pub s m := by + filter_upwards [eventually_input D B hB hq hph, + DescriptorParameters.eventually_tight_capacity D F B a lanes hB hθ hlanes hb] with n ready cap + intro levels pub base_eq length_eq address_eq s m + obtain ⟨lanes_fit, capacity⟩ := cap (initialPositions B n) levels + exact run D d _ B n a lanes pub s m (ready _ pub base_eq length_eq address_eq) rfl hB + lanes_fit arity scalars rfl capacity + +end CompressorRecords.OnlineCursorStartup + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineFootprint.lean new file mode 100644 index 0000000000..210e52d586 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineFootprint.lean @@ -0,0 +1,196 @@ +import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner +import OAI.Computability.VPVNP.CompressorSourceTransport + +/-! +# Memory agreement across online descriptor calls + +The calendar, row recipe, launcher and closing worker call access the same +memory as the native source scans. Their writes end before the first level +header. In particular, a script can replay a source scan on the prepared +memory and carry its output into the next phase. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.OnlineFootprint + +open BurstRAM DescriptorSpace BlockPlanner Schedule SourceTransport +open scoped Fin.CommRing + +variable {w : ℕ} (A : Script) (L : Layout) (base : Word w) +local notation "g₀" => arity (Script.catalog A) +local notation "P₀" => Workspace.ports (arity (Script.catalog A)) base +local notation "H" => levelStart L 0 + +private theorem first_level : H = directoryBase L + directoryRows L * (L.shape.arity+3) := by + simp only [levelStart, levelsBase, Nat.zero_mul, Nat.add_zero] + +variable (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) (fit : levelStart L 0 < 2^w) + +include hg hb fit in +private theorem port_bounds : + (P₀).directory.val = directoryBase L ∧ (P₀).ordinal.val = L.base+7 ∧ (P₀).tag.val = L.base+6 ∧ + ∀ i : Fin (g₀+1), ((P₀).activeFrame+(i.val : Word w)).val < H := by + have dir : directoryBase L = L.base+(11+g₀) := by + rw [hg] + simp only [directoryBase, plannerTag, frameBase] + omega + have before : directoryBase L ≤ H := (first_level L).symm ▸ Nat.le_add_right .. + have atOffset (j : ℕ) (h : L.base+j ≤ directoryBase L) : + (base+(j : Word w)).val = L.base+j := by + have hj := (h.trans before).trans_lt fit + rw [Fin.val_add,hb,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j < 2^w),Nat.mod_eq_of_lt hj] + refine ⟨(atOffset (11+g₀) dir.symm.le).trans dir.symm, + atOffset 7 (by omega),atOffset 6 (by omega),?_⟩ + intro i + have hi := i.isLt + have ha : L.base+(9+i.val) < directoryBase L := by omega + change (base+9+(i.val : Word w)).val < H + have he : base+9+(i.val : Word w) = base+((9+i.val : ℕ) : Word w) := by + simp only [Nat.cast_add,Nat.cast_ofNat,add_assoc] + rw [he,atOffset _ ha.le] + exact ha.trans_le before + +include hg hb fit in +private theorem tag_before : (P₀).tag.val < H := by + rw [(port_bounds A L base hg hb fit).2.2.1,first_level] + simp only [directoryBase, plannerTag, frameBase] + omega + +include hg hb fit in +/-- The current row's exclusive end is at most the first level address, +including the final allocated row. -/ +theorem row_bound (m : Memory w) (active : (m (P₀).ordinal.val).val < directoryRows L) : + (Controller.rowBase g₀ (P₀).data m).val + (g₀+3) ≤ H := by + have dir := (port_bounds A L base hg hb fit).1 + have end_le : (P₀).directory.val + (m (P₀).ordinal.val).val*(g₀+3) + (g₀+3) ≤ H := by + rw [dir,first_level,← hg, Nat.add_assoc,← Nat.succ_mul] + exact Nat.add_le_add_left (Nat.mul_le_mul_right _ active) _ + have hval := Directory.rowBase_val A.catalog P₀ m (by omega) + change (Directory.rowBase A.catalog P₀ m).val + (g₀+3) ≤ H + rw [hval] + exact end_le + +include hg hb fit in +theorem calendar (m : Memory w) (j : Fin A.size) : + Agree (H ≤ ·) m (after m (Online.calendarReport A.plan P₀ m j).events) := by + rw [(Online.calendar_effect A.plan P₀ m j).2.1] + intro a ha + have hn := ne_of_gt ((tag_before A L base hg hb fit).trans_le ha) + simp [writeMemory,hn] + +include hg hb fit in +theorem recipe (j : Fin A.size) (s : Word w) (m : Memory w) + (active : (m (P₀).ordinal.val).val < directoryRows L) : + Agree (H ≤ ·) m (after m (Online.recipeReport A.plan P₀ j s m).events) := by + let R := (A.phase j).recipe + have bound : (R.address (P₀).data s m).val + (g₀+3) ≤ H := by + rw [PhaseRecipe.recipe_address] + exact row_bound A L base hg hb fit m active + rw [(Online.recipe_effect A.plan P₀ j s m).2.1] + intro a ha + have hn := ne_of_gt ((tag_before A L base hg hb fit).trans_le ha) + change m a = writeMemory (Greedy.writeRow m (R.address (P₀).data s m) (R.words (P₀).data s m)) (P₀).tag 0 a + rw [writeMemory,ite_eq_right hn,← RowRecipe.after_row] + exact (RowRecipe.row_outside R (P₀).data s m (bound.trans fit.le) a (.inr (bound.trans ha))).symm + +include hg hb fit in +theorem launch (m : Memory w) : + Agree (H ≤ ·) m (after m (Online.launchReport A.catalog A.size P₀ m).events) := by + rw [(Online.launch_effect (C := A.catalog) (initial := A.initial.length) + (phases := A.block.length) P₀ m).2.1] + intro a ha + obtain ⟨_,ho,_,hf⟩ := port_bounds A L base hg hb fit + have ord : (P₀).ordinal.val < H := by + rw [ho,first_level] + simp only [directoryBase, plannerTag, frameBase] + omega + exact (Controller.after_row_outside g₀ (P₀).data m a (ne_of_gt (ord.trans_le ha)) + (ne_of_gt ((tag_before A L base hg hb fit).trans_le ha)) (fun i => ne_of_gt ((hf i).trans_le ha))).symm + +include hg hb fit in +theorem worker_close (i : Fin A.size) (m : Memory w) : + Agree (H ≤ ·) m (after m (Online.stopReport A.catalog A.size P₀ i m).events) := by + rw [(Online.stop_effect (C := A.catalog) (initial := A.initial.length) + (phases := A.block.length) P₀ i m).2.1] + intro a ha + have hn := ne_of_gt ((tag_before A L base hg hb fit).trans_le ha) + simp [writeMemory,hn] + +include hg hb fit in +/-- The source worker enters with the same contents at every level address +as at entry to the calendar. -/ +theorem prepared (m : Memory w) (j : Fin A.size) (active : (m (P₀).ordinal.val).val < directoryRows L) : + Agree (H ≤ ·) m (Directory.prepared A.catalog P₀ (Online.rowInput A.plan P₀ m j)) := by + let pre := Online.calendarMemory (d := A.size) P₀ m j + let state := LevelCalendar.header (Online.calendar A.plan) (P₀).data m + let input := Online.rowInput A.plan P₀ m j + obtain ⟨_,ho,ht,_⟩ := port_bounds A L base hg hb fit + have diff : (P₀).ordinal.val ≠ (P₀).tag.val := by omega + have active' : (pre (P₀).ordinal.val).val < directoryRows L := by + simpa only [pre,Online.calendarMemory,writeMemory,diff,↓reduceIte] using active + have hc := calendar A L base hg hb fit m j + rw [(Online.calendar_effect A.plan P₀ m j).2.1] at hc + have hr := recipe A L base hg hb fit j state pre active' + rw [(Online.recipe_effect A.plan P₀ j state pre).2.1] at hr + have hl := launch A L base hg hb fit input + rw [(Online.launch_effect (C := A.catalog) (initial := A.initial.length) + (phases := A.block.length) P₀ input).2.1] at hl + exact fun a ha => (hc a ha).trans ((hr a ha).trans (hl a ha)) + +/-- The three actual linked reports have the prepared memory as their +effect, including the parameter snapshot and the ordinal increment. -/ +theorem preparation_effect (m : Memory w) (j : Fin A.size) : + after m (eventLog (Online.preparation A.plan P₀ m j)) = + Directory.prepared A.catalog P₀ (Online.rowInput A.plan P₀ m j) := by + let pre := Online.calendarMemory (d := A.size) P₀ m j + let state := LevelCalendar.header (Online.calendar A.plan) (P₀).data m + let input := Online.rowInput A.plan P₀ m j + have hc : after m (Online.calendarReport A.plan P₀ m j).events = pre := + (Online.calendar_effect A.plan P₀ m j).2.1 + have hr : after pre (Online.recipeReport A.plan P₀ j state pre).events = input := + (Online.recipe_effect A.plan P₀ j state pre).2.1 + simp only [Online.preparation,eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil, + after,List.foldl_append] + change after (after (after m _) _) (Online.launchReport A.catalog A.size P₀ input).events = _ + rw [hc,hr] + exact (Online.launch_effect (C := A.catalog) (initial := A.initial.length) + (phases := A.block.length) P₀ input).2.1 + +include hg hb fit in +/-- The worker's closing transfer passes its data output to the next calendar. -/ +theorem post (row : Directory.Row A.size w) : + Agree (H ≤ ·) (row.endMemory A.catalog P₀) (Online.post A.catalog A.size P₀ row) := by + have h := worker_close A L base hg hb fit row.worker (row.endMemory A.catalog P₀) + rw [(Online.stop_effect (C := A.catalog) (initial := A.initial.length) + (phases := A.block.length) P₀ row.worker _).2.1] at h + exact h + +include hg hb fit in +/-- A source packet computed on its own input replays on the launched +worker's memory. Its output agrees with the memory of the next calendar. -/ +theorem replay (raw m : Memory w) (j : Fin A.size) (row : Directory.Row A.size w) + (active : (m (P₀).ordinal.val).val < directoryRows L) + (input : row.input = Online.rowInput A.plan P₀ m j) + (agree : Agree (H ≤ ·) raw m) (reads : Reads (H ≤ ·) (eventLog row.reports)) + (run : runSegment ((A.catalog row.worker).table.instantiate w + (Directory.words A.catalog P₀ row.worker row.input)).program row.fuel + (some (Directory.start A.catalog P₀ row.input)) raw row.choices = some row.reports) : + runSegment ((A.catalog row.worker).table.instantiate w + (Directory.words A.catalog P₀ row.worker row.input)).program row.fuel + (some (Directory.start A.catalog P₀ row.input)) (row.dataMemory A.catalog P₀) + row.choices = some row.reports ∧ + Agree (H ≤ ·) (after raw (eventLog row.reports)) (Online.post A.catalog A.size P₀ row) := by + have entry : Agree (H ≤ ·) raw (row.dataMemory A.catalog P₀) := by + rw [Directory.Row.dataMemory,input] + exact fun a ha => (agree a ha).trans (prepared A L base hg hb fit m j active a ha) + obtain ⟨run',out⟩ := SourceTransport.segment run entry reads + exact ⟨run', fun a ha => (out a ha).trans (post A L base hg hb fit row a ha)⟩ + +end CompressorRecords.OnlineFootprint + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineOrdinalForward.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineOrdinalForward.lean new file mode 100644 index 0000000000..266619eb71 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineOrdinalForward.lean @@ -0,0 +1,59 @@ +import OAI.Computability.VPVNP.CompressorOnlineWorkerSegment + +/-! # The directory frame of a complete ordinal worker stream + +Use the same single-call ready and memory invariants as the reverse row +decomposition. The private source fuel is extended to the outer cap +before applying that invariant. The ordinal and number of remaining +bursts determine which dispatcher guard applies. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online + +open BurstRAM + +variable {d w : ℕ} {C : Catalog d} {i : Fin d} {ports : Ports w} + {pub : Fin (C i).params → Word w} {stop : Word w} {fuel cap N : ℕ} + {inv : Word w → Memory w → Prop} +private abbrev source (C : Catalog d) (i : Fin d) (pub : Fin (C i).params → Word w) := + ((C i).table.instantiate w pub).program + +local notation "P" => source C i pub + +theorem ordinalFrame (step : WorkerStep ports i pub stop cap fuel inv) (hfuel : fuel ≤ cap) + (cursor : ℕ → Word w) (active : ∀ j + change some [] = some rs at run + cases Option.some.inj run + have he : j=N := by simpa only [List.length_nil,Nat.add_zero] using hlen + exact ⟨ready,he ▸ closed⟩ + | cons b bs ih => + have hj : j simp [runSegment,h] at run + | some r => + have inc := progress j hj m b r h + have extended := execute_extend h (cap-fuel) + rw [Nat.add_sub_of_le hfuel] at extended + obtain ⟨_,k,ret,ready',hi'⟩ := step (cursor j) m b r ready hi (active j hj) extended + obtain rfl : k = cursor (j+1) := Option.some.inj (ret.symm.trans inc) + simp only [runSegment,h,inc,Option.map_eq_some_iff] at run + obtain ⟨rest,tail,rfl⟩ := run + exact ⟨ready,active j hj,_,inc,ih (j+1) _ rest (by rw [List.length_cons] at hlen; omega) ready' hi' tail⟩ + +end CompressorRecords.Schedule.Online + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineOrdinalInversion.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineOrdinalInversion.lean new file mode 100644 index 0000000000..588bf95994 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineOrdinalInversion.lean @@ -0,0 +1,100 @@ +import OAI.Computability.VPVNP.CompressorOnlineWorkerSegment +import OAI.Computability.VPVNP.CompressorRecordsOrdinalRun + +/-! # Recovering exactly the scheduled number of data-worker calls + +The ordinal invariant determines when the guarded pass can close. Every +accepting online execution therefore runs the required number of source calls, +including when that number is zero. Its final data memory satisfies the last +ordinal invariant and preserves the descriptor control cells. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online + +open BurstRAM OrdinalRun + +variable {d initial phases w : ℕ} {C : Catalog d} (plan : Config C initial phases) +local notation "q₀" => initial+phases + +private theorem exact_length {Q : Type*} (P : BurstRAM.Program w Q) (f : ℕ) (ports : Ports w) (i : Fin d) + (pub : Fin (C i).params → Word w) (bound : Word w) (cursor : ℕ → Word w) (N : ℕ) (I : ℕ → Memory w → Prop) + (active : ∀ j < N, cursor j < bound) (closed : bound ≤ cursor N) + (advance : ∀ j < N, ∀ mem, I j mem → ∀ bits rep, execute P f (P.start (cursor j)) mem bits = some rep → + rep.result = some (cursor (j+1)) ∧ I (j+1) (after mem rep.events)) + (j : ℕ) (hj : j ≤ N) (m : Memory w) (hinv : I j m) (bits : List (List Bool)) (rs : List (Report w)) + (run : runSegment P f (some (cursor j)) m bits = some rs) (valid : ValidTrace C i ports pub bound (cursor j) m rs) : + j+bits.length = N := by + induction bits generalizing j m rs with + | nil => + change some [] = some rs at run + cases Option.some.inj run + obtain ⟨_,stopped⟩ := valid + have : ¬ j (Nat.not_lt.mpr stopped) (active j h) + simp; omega + | cons b bs ih => + cases hs : execute P f (P.start (cursor j)) m b with + | none => simp [runSegment,hs] at run + | some rep => + simp only [runSegment,hs,Option.map_eq_some_iff] at run + obtain ⟨tail,rest,rfl⟩ := run + obtain ⟨_,live,next,returned,hv⟩ := valid + have hlt : j ⟨(advance j hj mem h b rep hs).1,(advance j hj mem h b rep hs).2.1⟩) + 0 (Nat.zero_le _) m initialInv before raw rs vt + obtain ⟨_,good,stable⟩ := OrdinalRun.validTrace C i ports P f pub bound cursor N I active closed advance + 0 before m raw size initialInv ready rs + exact ⟨before,tail,raw,more,by simpa using size,hb,ho,rs,vt,good,stable,remain,ended⟩ + +end CompressorRecords.Schedule.Online + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlinePeel.lean b/lean/OAI/Computability/VPVNP/CompressorOnlinePeel.lean new file mode 100644 index 0000000000..a5d4275e3f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlinePeel.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.CompressorRecordsOnlineRun +import OAI.Computability.VPVNP.LiveDeterministicPaths + +/-! # Recovering online calendar boundaries from arbitrary native branch tapes + +An accepting run must perform the calendar lookup, the selected row recipe +and the launch before it can execute data calls. At the end of the schedule +there is exactly one empty terminal call. These facts apply to arbitrary +supplied choice streams, including streams with extra or missing bits. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online + +open BurstRAM + +variable {d initial phases w : ℕ} {C : Catalog d} (plan : Config C initial phases) (ports : Ports w) +local notation "q₀" => initial+phases +local notation "D₀" => N d q₀ + +/-- The three preparation reports leave the physical memory and persistent +word specified by the dynamically selected directory row. -/ +theorem preparation_effect (state : Word w) (m : Memory w) (j : Fin q₀) : + endState (some state) (preparation plan ports m j) = some (Directory.start C ports (rowInput plan ports m j)) ∧ + after m (eventLog (preparation plan ports m j)) = Directory.prepared C ports (rowInput plan ports m j) := by + let pre := calendarMemory (d := d) ports m j + let s := LevelCalendar.header (calendar plan) ports.data m + have h₁ := (calendar_effect plan ports m j).2.1 + have h₂ := (recipe_effect plan ports j s pre).2.1 + have h₃ := launch_effect (C := C) (initial := initial) (phases := phases) ports (rowInput plan ports m j) + constructor + · exact h₃.1 + · simp only [preparation, eventLog, List.flatMap_cons, List.flatMap_nil, List.append_nil, after, List.foldl_append] + change after (after (after m (calendarReport plan ports m j).events) (recipeReport plan ports j s pre).events) + (launchReport C q₀ ports (rowInput plan ports m j)).events = _ + rw [show after m (calendarReport plan ports m j).events = pre from h₁, + show after pre (recipeReport plan ports j s pre).events = rowInput plan ports m j from h₂] + exact h₃.2.1 + +/-- The entire deterministic prefix is forced even for a malformed candidate +stream. The suffix starts at the physical worker and is itself accepting. -/ +theorem recover_preparation {state : Word w} {m : Memory w} {j : Fin q₀} {cap : ℕ} + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (fits : D₀ ≤ 2^w) + (active : m ports.ordinal.val < m ports.rows.val) (hj : (calendar plan).phase (m ports.ordinal.val).val = j.val) + (activeRow : rowInput plan ports m j ports.ordinal.val < rowInput plan ports m j ports.rows.val) + (calCap : 30+2*q₀+2*D₀+5 ≤ cap) (recipeCap : (plan.recipes j).2.code.length+1+2*D₀+5 ≤ cap) + (launchCap : 20+6*(arity C+1)+2*D₀+5 ≤ cap) + {bits : List (List Bool)} {logs : List (Report w)} + (run : runSegment (program plan ports) cap (some state) m bits = some logs) (halt : endState (some state) logs = none) : + let row := rowInput plan ports m j + ∃ tail reps, bits = [] :: [] :: [] :: tail ∧ logs = preparation plan ports m j ++ reps ∧ + runSegment (program plan ports) cap (some (Directory.start C ports row)) (Directory.prepared C ports row) tail = some reps ∧ + endState (some (Directory.start C ports row)) reps = none := by + intro row + have hp : runSegment (program plan ports) cap (some state) m (List.replicate 3 []) = some (preparation plan ports m j) := by + change runSegment _ _ _ _ ([] :: [] :: [] :: []) = _ + rw [prepare_segment plan ports state m j htag fits active hj activeRow calCap recipeCap launchCap []] + simp [runSegment] + obtain ⟨tail,reps,hbits,rfl,hrest⟩ := LiveProgram.split_empty_segment hp run halt + obtain ⟨hs,hm⟩ := preparation_effect plan ports state m j + rw [hs,hm] at hrest + rw [endState_append,hs] at halt + exact ⟨tail,reps,hbits,rfl,hrest,halt⟩ + +/-- Once the ordinal reaches the exclusive row bound, every accepting native +execution consists solely of the empty-choice calendar halt. -/ +theorem recover_terminal {state : Word w} {m : Memory w} {cap : ℕ} + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (fits : D₀ ≤ 2^w) + (stop : m ports.rows.val ≤ m ports.ordinal.val) (clock : 6+2*D₀+5 ≤ cap) + {bits : List (List Bool)} {logs : List (Report w)} + (run : runSegment (program plan ports) cap (some state) m bits = some logs) (halt : endState (some state) logs = none) : + bits = [[]] ∧ logs = [linked ports (calendarIndex d q₀) (LevelCalendar.closedReport ports.data m)] := by + let r := linked ports (calendarIndex d q₀) (LevelCalendar.closedReport ports.data m) + have hr := calendar_stop plan ports state m htag fits stop clock + have hp : runSegment (program plan ports) cap (some state) m (List.replicate 1 []) = some [r] := by + simp [runSegment, hr, r] + obtain ⟨tail,reps,hbits,hlogs,hrest⟩ := LiveProgram.split_empty_segment hp run halt + have hc : endState (some state) [r] = none := (terminal_effect (initial := initial) (phases := phases) (d := d) ports m).1 + rw [hc] at hrest + cases tail with + | nil => + change some [] = some reps at hrest + cases Option.some.inj hrest + exact ⟨hbits.trans (List.append_nil _), hlogs.trans (List.append_nil _)⟩ + | cons _ _ => contradiction + +end CompressorRecords.Schedule.Online + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineRowInverse.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineRowInverse.lean new file mode 100644 index 0000000000..5d7a21be78 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineRowInverse.lean @@ -0,0 +1,80 @@ +import OAI.Computability.VPVNP.CompressorOnlinePeel +import OAI.Computability.VPVNP.CompressorOnlineWorkerSegment + +/-! # Recovering a physical descriptor row on an accepting run + +The calendar, recipe, launcher, data worker and closing call are inverted on +the same choice stream. Only the worker uses private choice bits. Its local +invariant supplies the valid frame, live cursor, and private clock for every +successful call, including calls reached by arbitrary submitted tapes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online.Run + +open BurstRAM + +variable {d initial phases w : ℕ} {C : Catalog d} (plan : Config C initial phases) (ports : Ports w) +local notation "q₀" => initial+phases +local notation "D₀" => N d q₀ + +/-- All data needed to enter a source row in the current physical memory. +The invariant and its advancement rule concern one data call at a time. -/ +structure RowStart (cap : ℕ) (m : Memory w) where + /-- Calendar phase selected for the current row ordinal at entry to the inverse run. -/ + phase : Fin q₀ + /-- Catalog index of the data worker launched for this row. -/ + worker : Fin d + /-- Private fuel bound available to each data-worker call while recovering the row. -/ + fuel : ℕ + /-- Predicate on the worker cursor and memory used to validate successive calls within the + row. -/ + invariant : Word w → Memory w → Prop + calendarPhase : (calendar plan).phase (m ports.ordinal.val).val = phase.val + liveRow : rowInput plan ports m phase ports.ordinal.val < rowInput plan ports m phase ports.rows.val + positiveFuel : 0 < fuel + recipeCap : (plan.recipes phase).2.code.length+1+2*D₀+5 ≤ cap + dataCap : fuel+3+4*((C worker).params+1)+2*D₀+5 ≤ cap + ready : let entry := rowInput plan ports m phase + Ready C worker ports (Directory.words C ports worker entry) (Directory.bound C ports entry) + (Directory.prepared C ports entry) + initialInv : let entry := rowInput plan ports m phase + invariant (Directory.start C ports entry) (Directory.prepared C ports entry) + dataStep : let entry := rowInput plan ports m phase + WorkerStep ports worker (Directory.words C ports worker entry) (Directory.bound C ports entry) cap fuel invariant + +/-- Separate the complete first row and accepting remainder. The witness is +built from the supplied stream's actual reports, and its data execution is +validated at the row-specific private clock. -/ +theorem recover_row {m : Memory w} {state : Word w} {cap : ℕ} (entry : RowStart plan ports cap m) + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (fits : D₀ ≤ 2^w) + (active : m ports.ordinal.val < m ports.rows.val) + (calCap : 30+2*q₀+2*D₀+5 ≤ cap) (launchCap : 20+6*(arity C+1)+2*D₀+5 ≤ cap) + {bits : List (List Bool)} {logs : List (Report w)} + (run : runSegment (program plan ports) cap (some state) m bits = some logs) (halt : endState (some state) logs = none) : + ∃ (s : Step d q₀ w), ∃ tail more, s.Valid plan ports cap m ∧ s.phase = entry.phase ∧ + s.row.worker = entry.worker ∧ s.row.fuel = entry.fuel ∧ + bits = rowChoices s.row ++ tail ∧ logs = rowLog plan ports m s.phase s.row ++ more ∧ + runSegment (program plan ports) cap (some 0) (post C q₀ ports s.row) tail = some more ∧ + endState (some 0) more = none := by + let x := rowInput plan ports m entry.phase + obtain ⟨rest,reps,hbits,hlogs,run',halt'⟩ := recover_preparation plan ports htag fits active entry.calendarPhase + entry.liveRow calCap entry.recipeCap launchCap run halt + obtain ⟨data,tail,raw,more,hdata,hrep,source,valid,hr,hh⟩ := + recover_worker_segment plan ports entry.worker (Directory.words C ports entry.worker x) (Directory.bound C ports x) + cap entry.fuel entry.invariant entry.dataStep fits _ _ rest reps entry.ready entry.initialInv run' halt' + let s : Step d q₀ w := ⟨entry.phase, ⟨x, entry.worker, entry.fuel, data, raw⟩⟩ + have hv : s.Valid plan ports cap m := ⟨entry.calendarPhase,active,rfl, + ⟨by simp [s, x, rowInput, writeMemory],entry.liveRow,entry.positiveFuel,source,valid⟩,entry.recipeCap,entry.dataCap⟩ + refine ⟨s,tail,more,hv,rfl,rfl,rfl,?_,?_,hr,hh⟩ + · rw [hbits,hdata]; simp [s,rowChoices,List.append_assoc] + · rw [hlogs,hrep]; simp [s,x,rowLog,Directory.Row.endMemory,Directory.Row.dataMemory,List.append_assoc] + +end CompressorRecords.Schedule.Online.Run + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineTraceInverse.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineTraceInverse.lean new file mode 100644 index 0000000000..ca25d8241e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineTraceInverse.lean @@ -0,0 +1,93 @@ +import OAI.Computability.VPVNP.CompressorOnlineRowInverse + +/-! # Completeness of the physical online descriptor trace + +At an active ordinal the fixed calendar must emit the current row, and every +successful data call is governed by its worker's invariant. Each extracted +row consumes the three control calls and its closing call. Induction on the +remaining physical calls therefore recovers all rows from an arbitrary +accepting path, including schedules with no active rows. The equivalence +keeps the path's original list of branch tapes and hence its multiplicity. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online.Run + +open BurstRAM + +variable {d initial phases w : ℕ} {C : Catalog d} (plan : Config C initial phases) (ports : Ports w) +local notation "q₀" => initial+phases +local notation "D₀" => N d q₀ + +/-- At each reachable calendar boundary, supply the physical row's frame +and single-call invariant. On completion of that source row the next memory +again satisfies the boundary invariant. -/ +structure RowInvariant (cap : ℕ) (I : Memory w → Prop) where + /-- Recover the phase, worker, and execution bounds for the next live row from the memory + invariant. -/ + next : ∀ m, I m → m ports.ordinal.val < m ports.rows.val → RowStart plan ports cap m + advance : ∀ m (h : I m) (live : m ports.ordinal.val < m ports.rows.val) (s : Step d q₀ w), + s.Valid plan ports cap m → s.phase = (next m h live).phase → s.row.worker = (next m h live).worker → + s.row.fuel = (next m h live).fuel → I (post C q₀ ports s.row) + +/-- Recover every chronological source row and its exact native reports. +Induction on the supplied stream length does not require a bound on the +number of selector choices available to a worker. -/ +theorem recover_trace {cap : ℕ} {I : Memory w → Prop} (inv : RowInvariant plan ports cap I) + (fits : D₀ ≤ 2^w) (calCap : 30+2*q₀+2*D₀+5 ≤ cap) (launchCap : 20+6*(arity C+1)+2*D₀+5 ≤ cap) + (bits : List (List Bool)) (m : Memory w) (state : Word w) (hm : I m) + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (logs : List (Report w)) + (run : runSegment (program plan ports) cap (some state) m bits = some logs) (halt : endState (some state) logs = none) : + ∃ stages, Valid plan ports cap m stages ∧ choices stages = bits ∧ reports plan ports m stages = logs ∧ + I (finalMemory (C := C) ports m stages) := by + induction bits using (measure List.length).wf.induction generalizing m state logs with + | h bits ih => + by_cases live : m ports.ordinal.val < m ports.rows.val + · let entry := inv.next m hm live + obtain ⟨s,tail,more,valid,hp,hw,hf,hbits,hlogs,rs,hend⟩ := recover_row plan ports entry htag fits live + calCap launchCap run halt + have shorter : (measure List.length).rel tail bits := by + change tail.length < bits.length + rw [hbits,List.length_append] + simp [rowChoices] + have nextInv := inv.advance m hm live s valid hp hw hf + have nextTag : post C q₀ ports s.row ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀) := by + simp [post,writeMemory] + obtain ⟨rest,hv,hb,hl,hI⟩ := ih tail shorter _ 0 nextInv nextTag more rs hend + refine ⟨s::rest,⟨valid,hv⟩,?_,?_,hI⟩ + · rw [hbits,← hb]; simp only [choices, List.flatMap_cons, List.append_assoc] + · rw [hlogs,← hl]; rfl + · have hs := le_of_not_gt live + obtain ⟨hb,hl⟩ := recover_terminal plan ports htag fits hs (by omega) run halt + exact ⟨[],hs,hb.symm,hl.symm,hm⟩ + +/-- A tape list and its resource predicate can be checked on the actual +chronological rows. Different proofs of row invariants carry no path weight. -/ +abbrev RowTapes (cap : ℕ) (m : Memory w) (allow : List (Report w) → Prop) := + {bs : List (List Bool) // ∃ stages : List (Step d q₀ w), Valid plan ports cap m stages ∧ + choices stages = bs ∧ allow (reports plan ports m stages)} + +/-- Bijection between accepting online program paths and valid row tapes satisfying the same +report filter. -/ +def acceptedEquiv {cap : ℕ} {I : Memory w → Prop} (inv : RowInvariant plan ports cap I) + (fits : D₀ ≤ 2^w) (calCap : 30+2*q₀+2*D₀+5 ≤ cap) (launchCap : 20+6*(arity C+1)+2*D₀+5 ≤ cap) + (m : Memory w) (state : Word w) (hm : I m) (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) + (allow : List (Report w) → Prop) : + LiveProgram.PathsFrom (program plan ports) cap (some state) m allow ≃ RowTapes plan ports cap m allow := + Equiv.subtypeEquivRight fun bs => by + constructor + · rintro ⟨logs,run,halt,allowed⟩ + obtain ⟨stages,hv,hb,hl,_⟩ := recover_trace plan ports inv fits calCap launchCap bs m state hm htag logs run halt + exact ⟨stages,hv,hb,hl ▸ allowed⟩ + · rintro ⟨stages,hv,rfl,allowed⟩ + exact ⟨_, execute plan ports stages m state cap htag fits calCap launchCap hv, + (effect plan ports stages m state hv).2,allowed⟩ + +end CompressorRecords.Schedule.Online.Run + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineWorkerInversion.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineWorkerInversion.lean new file mode 100644 index 0000000000..44dd245147 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineWorkerInversion.lean @@ -0,0 +1,120 @@ +import OAI.Computability.VPVNP.CompressorRecordsOnline +import OAI.Computability.VPVNP.LiveHeaderProtectedCore + +/-! # Recovering a scheduled worker call on its actual choice stream + +A successful active call executes the source pass on precisely the same +choice bits. Its report includes the observed frame reads, active guard and +stage link. The closing call has a unique empty choice string and transfers +back to the calendar. These statements allow arbitrary instruction caps. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace BurstRAM + +variable {w : ℕ} {C : Type*} + +/-- The trace itself determines the number of instructions required for +a successful call, including the final return instruction. -/ +theorem Guessed.at_cap {P : Program w C} {f : ℕ} {c : C} {es : List (Event w)} {out : Option (Word w)} + (h : Guessed P f c es out) {cap : ℕ} (hl : es.length < cap) : Guessed P cap c es out := by + induction h generalizing cap with + | done hs => + cases cap with | zero => simp at hl | succ _ => exact .done hs + | step hs _ ih => + cases cap with | zero => simp at hl | succ _ => exact .step hs (ih (by simpa using hl)) + | branch hs _ ih => + cases cap with | zero => simp at hl | succ _ => exact .branch hs (ih (by simpa using hl)) + | read hs _ ih => + cases cap with | zero => simp at hl | succ _ => exact .read hs (ih (by simpa using hl)) + | write hs _ ih => + cases cap with | zero => simp at hl | succ _ => exact .write hs (ih (by simpa using hl)) + +theorem execute_at_cap {P : Program w C} {f cap : ℕ} {c : C} {m : Memory w} {bits : List Bool} {out : Report w} + (h : execute P f c m bits = some out) (hl : out.events.length < cap) : execute P cap c m bits = some out := by + obtain ⟨run,valid,tape⟩ := execute_spec h + exact execute_iff.mpr ⟨run.at_cap hl,valid,tape⟩ + +end BurstRAM + +namespace CompressorRecords.Schedule.Online + +open BurstRAM BurstRAM.PrivateRAM + +variable {d initial phases w : ℕ} {C : Catalog d} (plan : Config C initial phases) +local notation "q₀" => initial+phases +local notation "D₀" => N d q₀ + +/-- Recover a successful source stage at an arbitrary padded cap. Padding +only reconstructs the existing report and retains the original choice bits. -/ +theorem recover_slot (ports : Ports w) (s : Fin D₀) (state : Word w) (m : Memory w) (bits : List Bool) + (htag : m ports.tag.val = LiveStageLink.tagWord w s) (fits : D₀ ≤ 2^w) {cap : ℕ} {out : Report w} + (physical : execute (program plan ports) cap ((program plan ports).start state) m bits = some out) + (pad : ℕ) : + let slot := slots plan s + let P := (slot.table.instantiate w (ports.data ∘ slot.publicIndex)).program + ∃ source, execute P (cap+pad) (P.start state) m bits = some source ∧ out = linked ports s source := by + intro slot P + have extra := execute_extend physical (pad+(LiveStageLink.dispatchEvents ports.tag s).length) + rw [← Nat.add_assoc] at extra + have exec := LiveStageLink.execute_linked (tables plan) (handoff d q₀) ports.data ports.tag s fits + state (cap+pad) m htag bits + simp only [program] at extra + dsimp only at exec + rw [exec] at extra + obtain ⟨exit,hit,eq⟩ := Option.map_eq_some_iff.mp extra + obtain ⟨source,hsource,hout⟩ := Option.bind_eq_some_iff.mp hit + refine ⟨source,?_,?_⟩ + · rw [tables, LiveStageLink.execute_widen_start] at hsource + exact hsource + · dsimp only [LiveStageLink.boundedExit] at hout + split at hout + · exact eq.symm.trans (congrArg (LiveStageLink.prependLog (LiveStageLink.dispatchEvents ports.tag s)) + (Option.some.inj hout).symm) + · contradiction + +theorem worker_active_iff (ports : Ports w) (i : Fin d) (state : Word w) (m : Memory w) (bits : List Bool) + (htag : m ports.tag.val = LiveStageLink.tagWord w i.succ) (fits : D₀ ≤ 2^w) + (guard : state < stopWord ports.activeFrame m) (cap : ℕ) (out : Report w) : + execute (program plan ports) cap ((program plan ports).start state) m bits = some out ↔ + let S := ((C i).table.instantiate w (parameters ports.activeFrame m)).program + out.events.length < cap ∧ ∃ rep, execute S cap (S.start state) m bits = some rep ∧ + out = linked ports (workerIndex q₀ i) (workerReport (C i) ports.activeFrame m rep) := by + dsimp only + constructor + · intro physical + obtain ⟨wrapped,hw,hout⟩ := recover_slot plan ports (workerIndex q₀ i) state m bits htag fits physical + (3+4*((C i).params+1)) + have hslot : slots plan (workerIndex q₀ i) = (⟨worker (C i),fun _ => 0⟩ : Slot) := by + simp only [slots,workerIndex,Fin.addCases_left,Fin.cons_succ] + rfl + rw [hslot] at hw + change execute (((worker (C i)).table.instantiate w (fun _ => ports.activeFrame)).program) _ + (((worker (C i)).table.instantiate w (fun _ => ports.activeFrame)).program.start state) m bits = _ at hw + rw [← Nat.add_assoc,execute_worker _ _ _ _ _ guard, Option.map_eq_some_iff] at hw + obtain ⟨rep,run,heq⟩ := hw + exact ⟨(execute_spec physical).1.length_lt, rep, run, heq.symm ▸ hout⟩ + · rintro ⟨hl,rep,hr,rfl⟩ + have call := worker_active plan ports i state m bits htag fits guard (le_refl _) rep hr + exact execute_at_cap call hl + +theorem worker_stop_iff (ports : Ports w) (i : Fin d) (state : Word w) (m : Memory w) (bits : List Bool) + (htag : m ports.tag.val = LiveStageLink.tagWord w i.succ) (fits : D₀ ≤ 2^w) + (guard : stopWord ports.activeFrame m ≤ state) (cap : ℕ) (out : Report w) : + execute (program plan ports) cap ((program plan ports).start state) m bits = some out ↔ + out.events.length < cap ∧ bits=[] ∧ out=stopReport C q₀ ports i m := by + have closed := worker_stop plan ports i state m htag fits guard (le_refl _) + constructor + · intro physical + exact ⟨(execute_spec physical).1.length_lt,execute_empty_forces_anyFuel closed physical⟩ + · rintro ⟨hl,rfl,rfl⟩ + exact execute_at_cap closed hl + +end CompressorRecords.Schedule.Online + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOnlineWorkerSegment.lean b/lean/OAI/Computability/VPVNP/CompressorOnlineWorkerSegment.lean new file mode 100644 index 0000000000..6ac64fba32 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOnlineWorkerSegment.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.CompressorOnlineWorkerInversion + +/-! # Extracting the source pass from an arbitrary accepting online run + +Each active worker call contributes its original choice tape and complete +source report. After its closing guard, the remaining native calls run from +the calendar with precisely the memory produced by the recovered pass. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online + +open BurstRAM BurstRAM.PrivateRAM + +variable {d initial phases w : ℕ} {C : Catalog d} (plan : Config C initial phases) +local notation "q₀" => initial+phases +local notation "D₀" => N d q₀ + +/-- The source pass preserves its public frame and returns a live cursor on +each active step. A caller may keep a stronger data-memory invariant and a +smaller source cap. No restriction is placed on the choice list. -/ +def WorkerStep (ports : Ports w) (i : Fin d) (pub : Fin (C i).params → Word w) (bound : Word w) + (cap f : ℕ) (inv : Word w → Memory w → Prop) : Prop := + let P := ((C i).table.instantiate w pub).program + ∀ st m bits rep, Ready C i ports pub bound m → inv st m → st < bound → + execute P cap (P.start st) m bits = some rep → rep.events.length < f ∧ + ∃ next, rep.result = some next ∧ Ready C i ports pub bound (after m rep.events) ∧ + inv next (after m rep.events) + +/-- Recover one whole pass and the actual suffix, including the empty closing +call. A zero-length pass still consumes exactly that closing call. -/ +theorem recover_worker_segment (ports : Ports w) (i : Fin d) (pub : Fin (C i).params → Word w) + (bound : Word w) (cap f : ℕ) (inv : Word w → Memory w → Prop) + (step : WorkerStep ports i pub bound cap f inv) (fits : D₀ ≤ 2^w) + (st : Word w) (m : Memory w) (bits : List (List Bool)) (out : List (Report w)) + (ready : Ready C i ports pub bound m) (hInv : inv st m) + (run : runSegment (program plan ports) cap (some st) m bits = some out) (halted : endState (some st) out = none) : + let P := ((C i).table.instantiate w pub).program + ∃ before tail raw more, + let finalMem := after m (eventLog raw) + bits = before ++ []::tail ∧ out = workerRows C q₀ ports i m raw ++ stopReport C q₀ ports i finalMem :: more ∧ + runSegment P f (some st) m before = some raw ∧ ValidTrace C i ports pub bound st m raw ∧ + runSegment (program plan ports) cap (some 0) + (writeMemory finalMem ports.tag (LiveStageLink.tagWord w (calendarIndex d q₀))) tail = some more ∧ + endState (some 0) more = none := by + intro P + induction bits generalizing st m out with + | nil => + change some [] = some out at run + obtain rfl := Option.some.inj run + contradiction + | cons b bs ih => + cases first : execute (program plan ports) cap ((program plan ports).start st) m b with + | none => simp [runSegment,first] at run + | some actual => + simp only [runSegment,first,Option.map_eq_some_iff] at run + obtain ⟨remaining,suffix,rfl⟩ := run + change endState actual.result remaining = none at halted + by_cases active : st < bound + · have guard : st < stopWord ports.activeFrame m := ready.2.1.symm ▸ active + obtain ⟨_,rep,source,linkedEq⟩ := + (worker_active_iff plan ports i st m b ready.1 fits guard cap actual).mp first + rw [ready.2.2] at source + obtain ⟨small,next,returned,valid',inv'⟩ := step st m b rep ready hInv active source + have source' := execute_at_cap source small + have eq : actual = activeReport C q₀ ports i m rep := linkedEq + obtain ⟨res,mem,_⟩ := active_effect (initial := initial) (phases := phases) (C := C) ports i m rep returned + rw [eq,res,mem] at suffix + rw [eq,res] at halted + obtain ⟨before,tail,raw,more,hb,hr,rs,vt,rest,stop⟩ := + ih next (after m rep.events) remaining valid' inv' suffix halted + have finalEq : after m (eventLog (rep::raw)) = after (after m rep.events) (eventLog raw) := by + simp only [eventLog,List.flatMap_cons,after,List.foldl_append] + refine ⟨b::before,tail,rep::raw,more,congrArg (List.cons b) hb,?_,?_,?_,?_,stop⟩ + · simp only [workerRows,List.cons_append,finalEq,eq,hr] + · change execute P f (P.start st) m b = some rep at source' + simp only [runSegment,source',returned,rs,Option.map_some] + · exact ⟨ready,active,next,returned,vt⟩ + · exact finalEq.symm ▸ rest + · have closed : stopWord ports.activeFrame m ≤ st := ready.2.1.symm ▸ Nat.le_of_not_gt active + obtain ⟨_,rfl,eq⟩ := (worker_stop_iff plan ports i st m b ready.1 fits closed cap actual).mp first + obtain ⟨res,mem,_⟩ := stop_effect (initial := initial) (phases := phases) (C := C) ports i m + rw [eq,res,mem] at suffix + rw [eq,res] at halted + exact ⟨[],bs,[],remaining,rfl,congrArg (· :: remaining) eq,rfl,⟨ready,Nat.le_of_not_gt active⟩,suffix,halted⟩ + +end CompressorRecords.Schedule.Online + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorOrdinalProgress.lean b/lean/OAI/Computability/VPVNP/CompressorOrdinalProgress.lean new file mode 100644 index 0000000000..796b31731b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorOrdinalProgress.lean @@ -0,0 +1,58 @@ +import OAI.Computability.VPVNP.CompressorSourceOnline +import OAI.Computability.VPVNP.RAMFinite + +/-! +# Guard progress and work of a native packet + +An ordered list of successful cursor returns determines the guard +progress needed to replay that packet in the online dispatcher. The +same report list also determines its calls-plus-probes charge. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SourceOnline + +open BurstRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +theorem Progress.ofOrdinals (stop start count : ℕ) (fits : stop < 2^w) (endAt : start+count = stop) + (rs : List (Report w)) + (returns : rs.map Report.result = (List.range' (start+1) count).map (fun j : ℕ => some (j : Word w))) : + Progress (stop : Word w) (start : Word w) rs := by + induction count generalizing start rs with + | zero => + have hz : rs = [] := List.map_eq_nil_iff.mp returns + rw [hz] + apply Progress.done + rw [show start = stop by omega] + | succ n ih => + cases rs with + | nil => simp [List.range'_succ] at returns + | cons r rs => + simp only [List.map_cons,List.range'_succ,List.cons.injEq] at returns + have hs : start < stop := by omega + refine Progress.next ?_ returns.1 (ih (start+1) (by omega) rs returns.2) + change start % (2^w) < stop % (2^w) + rwa [Nat.mod_eq_of_lt (hs.trans fits),Nat.mod_eq_of_lt fits] + +theorem packet_cost (rs : List (Report w)) : + RAMBuckets.cost Report.probes rs = rs.length+countProbes (eventLog rs) := by + rw [RAMBuckets.cost_eq_length_add_probes] + congr 1 + induction rs with + | nil => rfl + | cons r rs ih => + change r.probes + RAMBuckets.probeCount Report.probes rs = countProbes (r.events ++ eventLog rs) + rw [ih] + rw [Greedy.probes_append]; rfl + +end CompressorRecords.SourceOnline + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPacketPassRun.lean b/lean/OAI/Computability/VPVNP/CompressorPacketPassRun.lean new file mode 100644 index 0000000000..161e899d95 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPacketPassRun.lean @@ -0,0 +1,120 @@ +import OAI.Computability.VPVNP.CompressorPassRunIntervals +import OAI.Computability.VPVNP.CompressorGroupBoundary +import OAI.Computability.VPVNP.CompressorSelectorGroupPost +import OAI.Computability.VPVNP.CompressorSelectorSitePacket +import OAI.Computability.VPVNP.CompressorDefaultSelection + +/-! # Realizing one mathematical pass from its actual packet groups + +The prefix group runs independently of the existence of an admitted term. +At its actual output memory, the selector site installs the finite motif +worker. Each term's singleton source packet then identifies the exact live +post-memory from which its own deterministic suffix executes. The selected +history and current graph are transported from the raw source into that +specific final memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM Compression BlockPlanner DescriptorSpace Schedule SourceTransport PassTimeline PairSimulation.LocalHistory +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {R : Type*} [CommRing R] + {f : B.Entry → R} {hf : B.IsSolution f} {w small cap total rate : ℕ} {pub : Fin 11 → Word w} + {L : Layout} {resident : Resident B f hf w} {loc : Located S.steps} + {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} {o : PassOrigin B f hf p} + {encode : p.step.Choice → List Bool} {past : List (SelectedLevel B f hf)} {raw m : Memory w} +local notation "A" => BlockProgram.script B +set_option quotPrecheck false in +local notation "pt" => Workspace.ports (arity (BlockProgram.script B).catalog) (pub 2) +set_option quotPrecheck false in +local notation "tag" => LiveStageLink.tagWord w (Online.calendarIndex (BlockProgram.script B).size (BlockProgram.script B).size) + +/-- When the prefix already provides the descriptor's static operands, the +caller can mount the real selector directly in the reached live memory. -/ +theorem PassRun.ofInstalledPacketGroups (pre : List (SourceOnline.Packet (A) w)) (term : p.step.Choice → SourceOnline.Packet (A) w) + (tail : p.step.Choice → List (SourceOnline.Packet (A) w)) + (first : SourceOnline.Group (A) L (pub 2) small (loc.first B) total raw pre) + (middle : ∀ i, SourceOnline.Group (A) L (pub 2) small (loc.first B+pre.length) total + (SourceOnline.post raw pre) [term i]) + (last : ∀ i, SourceOnline.Group (A) L (pub 2) small (loc.first B+pre.length+1) total (term i).output (tail i)) + (emptyPre : ∀ e ∈ pre, e.stage.choices = List.replicate e.stage.choices.length []) + (emptyTail : ∀ i, ∀ e ∈ tail i, e.stage.choices = List.replicate e.stage.choices.length []) + (termBits : ∀ i, (term i).stage.choices = List.ofFn (workerTapes o w i)) + (clock : small ≤ cap) (big : Online.Run.ControlBounds (A).plan cap (w := w)) + (bounds : Online.Run.ControlBounds (A).plan small (w := w)) + (arityEq : arity (A).catalog = L.shape.arity) (baseEq : (pub 2).val = L.base) (fit : levelStart L 0 < 2^w) + (preFits : loc.first B+pre.length < total) (endFits : loc.finish B ≤ total) + (lengths : ∀ i, loc.first B+pre.length+1+(tail i).length = loc.finish B) + (room : total ≤ directoryRows L) (agree : Agree (levelStart L 0 ≤ ·) raw m) + (ready : Boundary resident pub (levelWords L : Word w) total (loc.first B) past X m) + (install : ∀ mid : Memory w, Agree (levelStart L 0 ≤ ·) (SourceOnline.post raw pre) mid → + Workspace.Installed (arity (A).catalog) (pub 2) mid → mid (pt).tag.val = tag → + (mid (pt).ordinal.val).val = loc.first B+pre.length → (mid (pt).rows.val).val = total → + mid ((pt).directory-1).val = (levelWords L : Word w) → Nonempty (SelectorSite o L pub cap small mid)) + (stored : ∀ i, resident (past++[level o encode i]) (p.next i) (SourceOnline.post (term i).output (tail i))) + (transfer : ∀ i u v, Agree (levelStart L 0 ≤ ·) u v → + resident (past++[level o encode i]) (p.next i) u → resident (past++[level o encode i]) (p.next i) v) + (charges : ∀ i, groupCost (A) pre + groupCost (A) [term i] + groupCost (A) (tail i) ≤ rate) : + Nonempty (PassRun resident pub (levelWords L : Word w) total cap small rate loc o encode past m) := by + classical + obtain ⟨before,agree',bank,tag',ord,rows,stride,charge₀⟩ := deterministicGroup first emptyPre clock bounds + arityEq baseEq fit preFits.le room agree ready.bank ready.tag ready.ordinalValue ready.totalValue ready.stride + let site := (install before.segment.memory agree' bank tag' ord rows stride).some + have live : before.segment.memory (pt).ordinal.val < before.segment.memory (pt).rows.val := + Fin.lt_def.mpr (by rw [ord,rows]; exact preFits) + have inside : (before.segment.memory (pt).ordinal.val).val < directoryRows L := ord ▸ preFits.trans_le room + let selected := site.interval big bounds arityEq baseEq fit bank tag' live inside + have mid i := selectorGroupPost selected i (term i) (middle i) + (by rw [termBits]; exact site.interval_bits big bounds arityEq baseEq fit bank tag' live inside i) + bounds arityEq baseEq fit preFits room agree' bank tag' ord rows stride + have doneTail (i : p.step.Choice) : ∃ out : QuietInterval (A) pub cap small (some 0) (selected.cut.part i).memory, + Boundary resident pub (levelWords L : Word w) total (loc.finish B) (past++[level o encode i]) + (p.next i) out.segment.memory ∧ RAMBuckets.cost Report.probes out.source.logs ≤ groupCost (A) (tail i) := by + obtain ⟨data,inst,tag₂,ord₂,total₂,stride₂,_⟩ := mid i + obtain ⟨out,next,_,charge⟩ := boundary_of_group (last i) (emptyTail i) clock bounds arityEq baseEq fit + ((lengths i).le.trans endFits) room data inst tag₂ ord₂ total₂ stride₂ (stored i) (transfer i) + exact ⟨out,lengths i ▸ next,charge⟩ + choose after next charge₂ using doneTail + refine ⟨PassRun.ofIntervals before selected after (fun i => ?_) next⟩ + have charge₁ := (mid i).2.2.2.2.2.2 + exact (Nat.add_le_add (Nat.add_le_add charge₀ charge₁) (charge₂ i)).trans (charges i) + +/-- The genuine source worker on the default admitted term suffices to +install that same physical selector for every reached prefix memory. -/ +theorem PassRun.ofPacketGroups (pre : List (SourceOnline.Packet (A) w)) (term : p.step.Choice → SourceOnline.Packet (A) w) + (tail : p.step.Choice → List (SourceOnline.Packet (A) w)) + (first : SourceOnline.Group (A) L (pub 2) small (loc.first B) total raw pre) + (middle : ∀ i, SourceOnline.Group (A) L (pub 2) small (loc.first B+pre.length) total + (SourceOnline.post raw pre) [term i]) + (last : ∀ i, SourceOnline.Group (A) L (pub 2) small (loc.first B+pre.length+1) total (term i).output (tail i)) + (emptyPre : ∀ e ∈ pre, e.stage.choices = List.replicate e.stage.choices.length []) + (emptyTail : ∀ i, ∀ e ∈ tail i, e.stage.choices = List.replicate e.stage.choices.length []) + (termBits : ∀ i, (term i).stage.choices = List.ofFn (workerTapes o w i)) + (clock : small ≤ cap) (big : Online.Run.ControlBounds (A).plan cap (w := w)) + (bounds : Online.Run.ControlBounds (A).plan small (w := w)) + (arityEq : arity (A).catalog = L.shape.arity) (baseEq : (pub 2).val = L.base) (fit : levelStart L 0 < 2^w) + (preFits : loc.first B+pre.length < total) (endFits : loc.finish B ≤ total) + (lengths : ∀ i, loc.first B+pre.length+1+(tail i).length = loc.finish B) + (room : total ≤ directoryRows L) (agree : Agree (levelStart L 0 ≤ ·) raw m) + (ready : Boundary resident pub (levelWords L : Word w) total (loc.first B) past X m) + (worker : WorkerInput o w) (operands : SelectorSite.SourceWorker worker L (term (defaultSelection o))) + (stored : ∀ i, resident (past++[level o encode i]) (p.next i) (SourceOnline.post (term i).output (tail i))) + (transfer : ∀ i u v, Agree (levelStart L 0 ≤ ·) u v → + resident (past++[level o encode i]) (p.next i) u → resident (past++[level o encode i]) (p.next i) v) + (charges : ∀ i, groupCost (A) pre + groupCost (A) [term i] + groupCost (A) (tail i) ≤ rate) : + Nonempty (PassRun resident pub (levelWords L : Word w) total cap small rate loc o encode past m) := by + apply PassRun.ofInstalledPacketGroups pre term tail first middle last emptyPre emptyTail termBits + clock big bounds arityEq baseEq fit preFits endFits lengths room agree ready _ stored transfer charges + exact SelectorSite.install_from_packet worker (term (defaultSelection o)) operands (middle (defaultSelection o)) + clock arityEq baseEq fit preFits room + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPassIntervalData.lean b/lean/OAI/Computability/VPVNP/CompressorPassIntervalData.lean new file mode 100644 index 0000000000..4589c4d29c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPassIntervalData.lean @@ -0,0 +1,46 @@ +import OAI.Computability.VPVNP.CompressorPrefixFrames +import OAI.Computability.VPVNP.CompressorWorkspaceCore + +/-! # Deterministic and selecting intervals on the physical block program -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM BranchSegments SourceBankFrame BlockPlanner + +variable {w : ℕ} + +/-- A forced interval of actual workspace-framed calls, with the original +inner reports at their computational clock. -/ +structure QuietInterval (A : Script) (pub : Fin 11 → Word w) (cap small : ℕ) + (st : Option (Word w)) (m : Memory w) where + /-- Executed workspace-framed segment for an interval whose source calls have empty choice + tapes. -/ + segment : Segment (OnlineWorkspace.program A.plan pub) (cap+24) st m + quiet : segment.bits = List.replicate segment.bits.length [] + stable : Stable ((pub 2).val+6) m segment.logs + state : segment.state = some 0 + /-- Inner source execution at the smaller clock underlying the deterministic workspace-framed + interval. -/ + source : OnlineWorkspace.Core A pub segment small + +/-- One physical selector row, indexed by the mathematical term. -/ +structure SelectorInterval (A : Script) (pub : Fin 11 → Word w) (cap small : ℕ) + (st : Option (Word w)) (m : Memory w) (I : Type*) where + /-- Branch cut whose indexed segments represent the alternatives of the native selector + interval. -/ + cut : Cut (OnlineWorkspace.program A.plan pub) (cap+24) st m I + frame : cut.PrefixFrame ((pub 2).val+6) + state : ∀ i, (cut.part i).state = some 0 + /-- Inner source execution for each branch of the selector cut at the prescribed source + clock. -/ + source : ∀ i, OnlineWorkspace.Core A pub (cut.part i) small + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPassRunIntervals.lean b/lean/OAI/Computability/VPVNP/CompressorPassRunIntervals.lean new file mode 100644 index 0000000000..23e6af437b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPassRunIntervals.lean @@ -0,0 +1,100 @@ +import OAI.Computability.VPVNP.CompressorPassIntervalData +import OAI.Computability.VPVNP.CompressorScheduledTraceData + +/-! # Joining the physical intervals of one shrinking or refresh pass + +The deterministic preparation and completion can each contain many data +workers. Between them the native selecting row chooses the mathematical +term. The three actual inner report lists concatenate, at the same small +clock, and the final state and resident records belong to the selected +successor. Every partial physical run preserves the low-address frame. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace + +open BurstRAM BranchSegments SourceBankFrame BlockPlanner Compression PassTimeline + +variable {w cap small : ℕ} {Q : Type*} {P : BurstRAM.Program w Q} {st st' : Option (Word w)} {m : Memory w} + {A : Script} {pub : Fin 11 → Word w} {I : Type*} + +private def segmentAt (s : Segment P cap st m) (eq : st' = st) : Segment P cap st' m := + ⟨s.bits,s.logs,by rw [eq]; exact s.run⟩ + +private def cutAt (c : Cut P cap st m I) (eq : st' = st) : Cut P cap st' m I where + part i := segmentAt (c.part i) eq + separate i j a b e := c.separate i j a b e + cover bs rs run halt := by rw [eq] at run halt; exact c.cover bs rs run halt + +/-- Use the register state actually returned by a preceding interval, +leaving all tapes, reports, source costs and memories definitionally equal. -/ +def QuietInterval.atState (s : QuietInterval A pub cap small st m) (eq : st' = st) : + QuietInterval A pub cap small st' m where + segment := segmentAt s.segment eq + quiet := s.quiet + stable := s.stable + state := by change endState st' s.segment.logs = some 0; rw [eq]; exact s.state + source := ⟨s.source.logs,by subst st'; exact s.source.run,s.source.frame⟩ + +/-- Transport a selector interval and its branch evidence to an equal initial state. -/ +def SelectorInterval.atState (s : SelectorInterval A pub cap small st m I) (eq : st' = st) : + SelectorInterval A pub cap small st' m I where + cut := cutAt s.cut eq + frame := ⟨s.frame.parts,fun bs rs run => s.frame.prefix bs rs (eq ▸ run)⟩ + state i := by change endState st' (s.cut.part i).logs = some 0; rw [eq]; exact s.state i + source i := ⟨(s.source i).logs,by subst st'; exact (s.source i).run,(s.source i).frame⟩ + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} {resident : Resident B f hf w} + {pitch : Word w} {total rate : ℕ} {loc : Located S.steps} {a g b n : ℕ} {X : State a g} + {p : StatePass R X b n} {o : PassOrigin B f hf p} {encode : p.step.Choice → List Bool} + {past : List (SelectedLevel B f hf)} +local notation "script" => BlockProgram.script B + +/-- Assemble one mathematical pass from its actual before/selection/after +workspace intervals. The side conditions concern only the physical sums and +the data resident in the actual final memory of the completion interval. -/ +def PassRun.ofIntervals (before : QuietInterval script pub cap small (some 0) m) + (select : SelectorInterval script pub cap small (some 0) before.segment.memory p.step.Choice) + (after : ∀ i, QuietInterval script pub cap small (some 0) (select.cut.part i).memory) + (charge : ∀ i, RAMBuckets.cost Report.probes before.source.logs + + RAMBuckets.cost Report.probes (select.source i).logs + + RAMBuckets.cost Report.probes (after i).source.logs ≤ rate) + (boundary : ∀ i, Boundary resident pub pitch total (loc.finish B) (past++[level o encode i]) + (p.next i) (after i).segment.memory) : + PassRun resident pub pitch total cap small rate loc o encode past m := by + let choose := select.atState before.state + let endAt (i : p.step.Choice) := (after i).atState (choose.state i) + let rest := choose.cut.afterChoice (fun i => (endAt i).segment) + (fun i => (endAt i).segment.bits.length) (fun i => (endAt i).quiet) + let combined := Cut.before before.segment before.segment.bits.length before.quiet rest + let core (i : p.step.Choice) : OnlineWorkspace.Core script pub (combined.part i) small := + before.source.append ((choose.source i).append (endAt i).source) + refine ⟨combined,?_,?_,core,?_,?_⟩ + · exact Cut.PrefixFrame.before before.segment before.segment.bits.length before.quiet before.stable + (choose.frame.afterChoice (fun i => (endAt i).segment) (fun i => (endAt i).segment.bits.length) + (fun i => (endAt i).quiet) (fun i => (endAt i).stable)) + · intro i + change (before.segment.append ((choose.cut.part i).append (endAt i).segment)).state = some 0 + exact (Segment.append_state _ _).trans ((Segment.append_state (choose.cut.part i) (endAt i).segment).trans (endAt i).state) + · intro i + change RAMBuckets.cost Report.probes (before.source.logs ++ ((select.source i).logs ++ (after i).source.logs)) ≤ rate + rw [RAMBuckets.cost_append,RAMBuckets.cost_append,← Nat.add_assoc] + exact charge i + · intro i + change Boundary _ _ _ _ _ _ _ (before.segment.append ((choose.cut.part i).append (endAt i).segment)).memory + have h := (Segment.append_memory before.segment ((choose.cut.part i).append (endAt i).segment)).trans + (Segment.append_memory (choose.cut.part i) (endAt i).segment) + exact h.symm ▸ boundary i + +end CompressorRecords.ScheduledTrace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPassTimeline.lean b/lean/OAI/Computability/VPVNP/CompressorPassTimeline.lean new file mode 100644 index 0000000000..e2bba05fbc --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPassTimeline.lean @@ -0,0 +1,173 @@ +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorExecutionCalendar + +/-! # Physical pass intervals in the repeated block calendar + +Each shrinking substep and degree refresh occupies its own window in the +fixed block script. Their absolute row intervals concatenate from the end +of the initial cursor setup through the exclusive calendar bound. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.PassTimeline + +open Compression BlockPlanner + +/-- An elementary pass of the repeated block script, either a bounded shrink index or the final +refresh. -/ +inductive Pass (steps : ℕ) where + | shrink (index : Fin steps) + | refresh + deriving DecidableEq + +/-- An occurrence of an elementary pass together with its zero-based block number. -/ +structure Located (steps : ℕ) where + /-- Number of the block repetition containing this pass occurrence. -/ + block : ℕ + /-- Shrink or refresh pass executed at this occurrence in the block. -/ + pass : Pass steps + deriving DecidableEq + +/-- Calendar phase label of the located pass, forgetting its block number. -/ +def Located.phase {steps : ℕ} (z : Located steps) : ExecutionCalendar.Phase := + match z.pass with | .shrink i => .shrink i.val | .refresh => .refresh + +/-- Pass occurrences within one specified block, listing all shrink indices before its refresh. -/ +def oneBlock (steps t : ℕ) : List (Located steps) := + (List.finRange steps).map (fun i => ⟨t,.shrink i⟩) ++ [⟨t,.refresh⟩] + +/-- Chronological pass occurrences across all block repetitions in the script. -/ +def timeline (steps T : ℕ) : List (Located steps) := (List.range T).flatMap (oneBlock steps) + +theorem oneBlock_phases (steps t : ℕ) : (oneBlock steps t).map Located.phase = ExecutionCalendar.oneBlock steps := by + have h : (List.finRange steps).map Fin.val = List.range steps := by + apply List.ext_getElem <;> simp + unfold oneBlock ExecutionCalendar.oneBlock + rw [List.map_append,← h,List.map_map,List.map_map] + rfl + +theorem timeline_phases (steps T : ℕ) : (timeline steps T).map Located.phase = ExecutionCalendar.blocks steps T := by + induction T with + | zero => rfl + | succ t ih => + simp only [timeline,List.range_succ,List.flatMap_append,List.flatMap_singleton,List.map_append] at ih ⊢ + rw [ih,oneBlock_phases] + unfold ExecutionCalendar.blocks + rw [List.replicate_add,List.flatten_append] + simp + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} + +/-- Concrete visits installed by this occurrence of the shrinking or refresh pass. -/ +def Located.visits (z : Located S.steps) (B : S.Templates) : List Visit := + match z.pass with | .shrink i => BlockProgram.shrink B i | .refresh => BlockProgram.refresh B + +/-- Contiguous script window occupied by the located pass's visits within its block. -/ +def Located.window (z : Located S.steps) (B : S.Templates) : + Window (BlockProgram.script B) (z.visits B) := by + cases z with | mk t p => + cases p with + | shrink i => exact BlockGroups.shrinkWindow B i + | refresh => exact BlockGroups.refreshWindow B + +/-- Absolute directory ordinal of the first visit, accounting for initialization, preceding +blocks, and the within-block offset. -/ +def Located.first (z : Located S.steps) (B : S.Templates) := + (BlockProgram.script B).initial.length + z.block * (BlockProgram.script B).block.length + (z.window B).before.length + +/-- First directory ordinal following the last visit of this pass occurrence. -/ +def Located.finish (z : Located S.steps) (B : S.Templates) := z.first B + (z.visits B).length + +/-- Each row of the interval is the actual indexed visit in the script; +its calendar level is the block at which the occurrence was located. -/ +theorem Located.calendar_row (z : Located S.steps) (B : S.Templates) (i : Fin (z.visits B).length) : + let A := BlockProgram.script B + let j := (z.window B).index i + A.visit j = (z.visits B)[i.val] ∧ + (Schedule.Online.calendar A.plan).phase (z.first B + i.val) = j.val ∧ + (Schedule.Online.calendar A.plan).level (z.first B + i.val) = z.block := by + intro A j + refine ⟨(z.window B).visit i,?_⟩ + have h := A.block_phase z.block ((z.window B).position i) + simpa only [A,j,Located.first,Window.position,Window.index,Nat.add_assoc] using h + +/-- The listed pass windows meet consecutively and span exactly the supplied start and finish +ordinals. -/ +def Consecutive (B : S.Templates) (start : ℕ) : List (Located S.steps) → ℕ → Prop + | [], stop => start = stop + | z :: zs, stop => z.first B = start ∧ Consecutive B (z.finish B) zs stop + +theorem Consecutive.append {B : S.Templates} {start middle stop : ℕ} {xs ys : List (Located S.steps)} + (h : Consecutive B start xs middle) (h' : Consecutive B middle ys stop) : + Consecutive B start (xs++ys) stop := by + induction xs generalizing start with + | nil => change start = middle at h; subst start; exact h' + | cons z zs ih => exact ⟨h.1,ih h.2⟩ + +private def blockStart (B : S.Templates) (t : ℕ) := + (BlockProgram.script B).initial.length + t * (BlockProgram.script B).block.length + +private def shrinkPrefix (B : S.Templates) (j : ℕ) := ((List.finRange S.steps).take j).flatMap (BlockProgram.shrink B) + +set_option maxHeartbeats 800000 in +private theorem shrink_consecutive (B : S.Templates) (t j : ℕ) (hj : j ≤ S.steps) : + Consecutive B (blockStart B t) (((List.finRange S.steps).take j).map (fun i => ⟨t,.shrink i⟩)) + (blockStart B t + (shrinkPrefix B j).length) := by + induction j with + | zero => simp only [List.take_zero,List.map_nil,shrinkPrefix,List.flatMap_nil,List.length_nil,Nat.add_zero,Consecutive] + | succ j ih => + let i : Fin S.steps := ⟨j,hj⟩ + have htake : (List.finRange S.steps).take (j+1) = (List.finRange S.steps).take j ++ [i] := by + rw [List.take_succ_eq_append_getElem (by simpa using hj)] + simp [i] + have hend : (shrinkPrefix B (j+1)).length = (shrinkPrefix B j).length + (BlockProgram.shrink B i).length := by + simp only [shrinkPrefix,htake,List.flatMap_append,List.flatMap_singleton,List.length_append] + rw [htake,List.map_append,hend,← Nat.add_assoc] + apply Consecutive.append (ih (Nat.le_of_succ_le hj)) + exact ⟨rfl,rfl⟩ + +theorem oneBlock_consecutive (B : S.Templates) (t : ℕ) : + Consecutive B (blockStart B t) (oneBlock S.steps t) (blockStart B (t+1)) := by + have h := shrink_consecutive B t S.steps le_rfl + have htake : (List.finRange S.steps).take S.steps = List.finRange S.steps := by simp + simp only [htake,shrinkPrefix] at h + apply Consecutive.append h + refine ⟨rfl,?_⟩ + change blockStart B t + ((List.finRange S.steps).flatMap (BlockProgram.shrink B)).length + + (BlockProgram.refresh B).length = blockStart B (t+1) + simp [blockStart,BlockProgram.script,BlockProgram.block,Nat.add_mul,Nat.add_assoc] + +/-- The fold of successive half-open pass intervals, with the actual +calendar bound even when the block is never entered. -/ +theorem timeline_consecutive (B : S.Templates) (T : ℕ) : + Consecutive B (BlockProgram.script B).initial.length (timeline S.steps T) + ((Schedule.Online.calendar (BlockProgram.script B).plan).total T) := by + rw [(BlockProgram.script B).calendar_total] + change Consecutive B (BlockProgram.script B).initial.length (timeline S.steps T) (blockStart B T) + induction T with + | zero => simp [timeline,Consecutive,blockStart] + | succ t ih => + simp only [timeline,List.range_succ,List.flatMap_append,List.flatMap_singleton] at ih ⊢ + exact ih.append (oneBlock_consecutive B t) + +/-- The state-dependent mathematical execution follows this same list of +located visits on every sequence of terms. -/ +theorem execute_follows_timeline (B : S.Templates) {R : Type*} [CommRing R] (f : B.Entry → R) + (hf : B.IsSolution f) (T : ℕ) {n : ℕ} (h : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) : + ExecutionCalendar.Follows (B.execute f hf T h X) (executeOrigins B f hf T h X) + ((timeline S.steps T).map Located.phase) := by + rw [timeline_phases] + exact ExecutionCalendar.execute_follows T h X + +end CompressorRecords.PassTimeline + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPassWindowBounds.lean b/lean/OAI/Computability/VPVNP/CompressorPassWindowBounds.lean new file mode 100644 index 0000000000..fad6451dd1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPassWindowBounds.lean @@ -0,0 +1,34 @@ +import OAI.Computability.VPVNP.CompressorPassTimeline + +/-! # The exclusive bound of every located pass in a live block -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PassTimeline + +open Compression BlockPlanner + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} + +theorem Located.finish_le_calendar (z : Located S.steps) (B : S.Templates) {blocks : ℕ} (live : z.block < blocks) : + z.finish B ≤ (Schedule.Online.calendar (BlockProgram.script B).plan).total blocks := by + let A := BlockProgram.script B + have window := congrArg List.length (z.window B).block + simp only [List.length_append] at window + have span : (z.window B).before.length + (z.visits B).length ≤ A.block.length := by + change (z.window B).before.length + (z.visits B).length ≤ (BlockProgram.script B).block.length + omega + have nxt := Nat.mul_le_mul_right A.block.length (show z.block+1 ≤ blocks from live) + rw [Nat.succ_mul] at nxt + rw [A.calendar_total] + change A.initial.length + z.block*A.block.length+(z.window B).before.length+(z.visits B).length ≤ + A.initial.length+blocks*A.block.length + omega + +end CompressorRecords.PassTimeline + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPayloadCall.lean b/lean/OAI/Computability/VPVNP/CompressorPayloadCall.lean new file mode 100644 index 0000000000..bf8ef052ee --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPayloadCall.lean @@ -0,0 +1,293 @@ +import OAI.Computability.VPVNP.CompressorPayloadWrite + +/-! +# A native descriptor call from a stored repetition count + +The persistent word gives the first payload address. Its predecessor holds +the repetition word computed for this motif. The call reads that word, sets +the bounds, admits the outer vector, and writes all of its supply coordinates. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PayloadWrite + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM +open MotifChoiceRAM +open scoped Fin.CommRing + +variable {w n : ℕ} + +/-- Read the repetition word immediately preceding the output slice. -/ +def loadRepetition (n : ℕ) : Flow (6+n) n := + .seq (.line (.stateWord (low n 0))) <| + .seq (.line (.constant (low n 1) 1)) <| + .seq (.line (.binary .sub (low n 0) (low n 0) (low n 1))) (.line (.read (low n 2) (low n 0))) + +/-- Native flow that reads a motif's stored repetition word, prepares the admission bounds, +chooses its payload, and writes it. -/ +def storedCall (n factor denominator : ℕ) : Flow (6+n) n := + .seq ((loadRepetition n).seq (prepareBounds n factor denominator)) (chooseAndStore n) + +private def loadEvents (base : Word w) (mem : Memory w) : List (Event w) := + [.tick,.tick,.tick,.read (base-1) (mem (base-1).val)] + +private theorem load_exec (pub : Fin n → Word w) (base : Word w) (rs : Regs w (6+n)) (m : Memory w) : + ∃ out, Flow.Exec pub base (loadRepetition n) rs m (loadEvents base m) out m ∧ + out (low n 2) = m (base-1).val := by + let q := Function.update rs (low n 0) base + let r := Function.update q (low n 1) 1 + let t := Function.update r (low n 0) (base-1) + let z := Function.update t (low n 2) (m (base-1).val) + have ha : Flow.Exec pub base (.line (.stateWord (low n 0))) rs m [.tick] q m := .line rfl + have hb : Flow.Exec pub base (.line (.constant (low n 1) 1)) q m [.tick] r m := .line rfl + have hc : Flow.Exec pub base (.line (.binary .sub (low n 0) (low n 0) (low n 1))) r m [.tick] t m := by + apply Flow.Exec.line + simp (config := { decide := true }) [Op.effect,BinaryOp.eval,r,q,t,Function.update] + have hd : Flow.Exec pub base (.line (.read (low n 2) (low n 0))) t m + [.read (base-1) (m (base-1).val)] z m := by + apply Flow.Exec.line + simp [Op.effect,t,z] + exact ⟨z,.seq ha (.seq hb (.seq hc hd)),by simp [z]⟩ + +private theorem accept_linked {p r k : ℕ} {a : Flow r k} {M : Machine w p r k} + {label : a.Label → Fin p} {stop bad : Fin p} (hl : Flow.Linked M a label stop bad) + (hstop : M.code stop = .accept) (hbad : M.code bad = .reject) + (state : Word w) (priv : Word w → Word w) (fuel : ℕ) (rs : Regs w r) (m : Memory w) (bits : List Bool) : + execute M.program fuel ⟨label a.entry,state,rs,priv⟩ m bits = + execute ((a.template none).instantiate w M.publicData).program fuel ⟨a.pc a.entry,state,rs,priv⟩ m bits := by + let N := (a.template none).instantiate w M.publicData + have hb : N.code a.rejectPC = .reject := by simp [N,Template.instantiate,Flow.template_reject,Instr.resize] + have hs : N.code a.exitPC = .accept := by simp [N,Template.instantiate,Flow.template_exit,Instr.resize] + have hn := Flow.template_linked a none M.publicData + rw [hl.execute hbad state priv fuel a.entry rs m bits, hn.execute hb state priv fuel a.entry rs m bits] + congr 1 + funext left regs mem bs + cases left with + | zero => rfl + | succ left => + change execute M.program (left+1) ⟨stop,state,regs,priv⟩ mem bs = + execute N.program (left+1) ⟨a.exitPC,state,regs,priv⟩ mem bs + simp [execute,Machine.program,hstop,hs,Instr.run] + +private theorem ticks_spec (t : ℕ) (m : Memory w) : + let es := List.replicate t (.tick : Event w) + choiceBits es = [] ∧ countProbes es = 0 ∧ after m es = m := by + induction t with + | zero => exact ⟨rfl,rfl,rfl⟩ + | succ t ih => + rw [List.replicate_succ] + exact ih + +private theorem count_append (es fs : List (Event w)) : + countProbes (es ++ fs) = countProbes es + countProbes fs := by + induction es with + | nil => simp [countProbes] + | cons e es ih => cases e <;> simp [countProbes,ih,Nat.add_assoc] + +open MotifGrid MotifBlocks MotifConversion MotifSelector + +variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S] +variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ} +variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H') + +private abbrev factor := B.scale * B.radius.num.natAbs +private abbrev denominator (_B : FixedBlock k a b P (realWidths p) (realWidths q) H H') := + MotifAdmission.denominator q + +/-- Word-width instance of the stored-payload worker with the selected supply order and scaled +admission weights as public operands. -/ +def storedMachine (order : Fin n ≃ S) (w : ℕ) := + ((storedCall n (factor B) (denominator B)).template none).instantiate w + (fun i => Fin.ofNat (2^w) (MotifAdmission.weight q (order i) * B.radius.den^2)) + +/-- Fuel bound for reading the repetition count, preparing bounds, admitting coordinates, and +writing the payload. -/ +def storedFuel (n w : ℕ) : ℕ := + (4 + (prepareBounds n (factor B) (denominator B)).length) + (n*(4*w+10)+3+(2*n+3)) + +/-- Only the word reader scales with the machine width. The threshold +preparation cost depends on the fixed binary motif coefficients. -/ +theorem storedFuel_le (n w : ℕ) : + storedFuel B n w ≤ n*(4*w+12) + 2*(B.scale*B.radius.num.natAbs).size + + 4*(MotifAdmission.denominator q).size + 20 := by + have h := prepareBounds_length n (factor B) (denominator B) + unfold storedFuel + simp only [Nat.mul_add] + dsimp only [factor,denominator] at h ⊢ + omega + +private theorem outer_admitted (order : Fin n ≃ S) (hq : ∀ e, 0 < q e) (demand : D → ℕ) + (hw : outerCap B demand < 2^w) (rs : Regs w (6+n)) (weights : Fin n → BurstRAM.Word w) + (hreps : (rs (low n 2)).val = repetitions B demand) (hzero : rs (low n 4) = 0) + (hcap : (rs (low n 3)).val = outerCap B demand + 1) + (hlimit : (rs (low n 5)).val = + (repetitions B demand * B.scale * B.radius.num.natAbs)^2 * MotifAdmission.denominator q + 1) + (hweights : ∀ i, (weights i).val = MotifAdmission.weight q (order i) * B.radius.den^2) + (v : ↥(outerIndices B demand)) : + let vec := fun i => (v.val (order i) : BurstRAM.Word w) + Admitted weights rs vec ∧ payloadBits rs vec = (outerReader B order hq demand w hw).encode v := by + dsimp only + let vec := fun i => (v.val (order i) : BurstRAM.Word w) + have ha := (mem_outerIndices_iff B hq _ _).mp v.property + have hbox e := MotifAdmission.payload_le_cap q hq _ _ _ _ ha e + have hval (i : Fin n) : (vec i).val = v.val (order i) := Nat.mod_eq_of_lt ((hbox _).trans_lt hw) + by_cases hu : repetitions B demand = 0 + · have hz : rs (low n 2) = rs (low n 4) := by rw [hzero]; exact Fin.ext (hreps.trans hu) + simp only [Admitted,payloadBits,hz,↓reduceIte] + constructor + · intro i + have h := hbox (order i) + simp only [MotifAdmission.payloadCap,hu,zero_mul,Nat.le_zero] at h + rw [h]; rfl + · apply Eq.symm + apply List.length_eq_zero_iff.mp + simp [outerReader_length,coordinateBits,hu] + · have hz : rs (low n 2) ≠ rs (low n 4) := by + intro he + apply hu + rw [← hreps,he,hzero]; rfl + simp only [Admitted,payloadBits,hz,↓reduceIte] + refine ⟨⟨fun i => ?_,?_⟩,?_⟩ + · apply Fin.lt_def.mpr + change (vec i).val < _ + rw [hval,hcap]; exact Nat.lt_succ_of_le (hbox _) + · change (rs (low n 4)).val + score (List.finRange n) weights vec < _ + rw [hzero,hlimit,full_score order q B.radius weights vec hweights] + simpa only [Fin.val_zero,Nat.zero_add,hval,Equiv.apply_symm_apply,Nat.lt_succ_iff] using + (of_decide_eq_true ha) + · have hr : (outerReader B order hq demand w hw).read ((outerReader B order hq demand w hw).encode v) = + some (v,[]) := (ChoiceReader.read_iff ..).mpr (by simp) + have he := (read_outer_iff B order hq demand w hw _ [] v).mp hr + rw [he,List.append_nil,full_encoding,show coordinateBits B demand w = w from ite_eq_right hu] + rfl + +private theorem setup_exec (u factor den : ℕ) (pub : Fin n → BurstRAM.Word w) (base : BurstRAM.Word w) + (m : Memory w) (hrep : (m (base-1).val).val = u) + (hcap : u*factor*den+1 < 2^w) (hlimit : (u*factor)^2*den+1 < 2^w) : + let prep := prepareBounds n factor den + ∃ es rs, Flow.Exec pub base ((loadRepetition n).seq prep) (fun _ => 0) m es rs m ∧ + es.length = 4+prep.length ∧ choiceBits es = [] ∧ countProbes es = 1 ∧ after m es = m ∧ + (rs (low n 2)).val = u ∧ (rs (low n 3)).val = u*factor*den+1 ∧ rs (low n 4) = 0 ∧ + (rs (low n 5)).val = (u*factor)^2*den+1 := by + let prep := prepareBounds n factor den + obtain ⟨mid,hload,hu⟩ := load_exec pub base (fun _ => 0) m + obtain ⟨out,hr,_,_,h2,h3,h4,h5,_⟩ := prepareBounds_exec factor den u pub base m mid + (by rw [hu,hrep]) hcap hlimit + obtain ⟨htbits,htp,htm⟩ := ticks_spec prep.length m + let ticks := List.replicate prep.length (.tick : Event w) + have hm : after m (loadEvents base m) = m := rfl + refine ⟨loadEvents base m ++ ticks,out,.seq hload hr,?_,?_,?_,?_,by rw [h2,hu,hrep],h3,h4,h5⟩ + · simp [loadEvents,ticks,prep]; omega + · rw [Flow.choiceBits_append,htbits]; rfl + · rw [count_append,htp]; rfl + · rw [show after m (loadEvents base m ++ ticks) = after (after m (loadEvents base m)) ticks from + List.foldl_append,hm,htm] + +/-- Starting at reset with the descriptor base as persistent state, the +accepted streams are precisely the motif's outer encodings. On each stream +the output memory contains the chosen coordinates and agrees elsewhere with +the input. The call reads the repetition word once and writes each supply coordinate once. -/ +theorem stored_outer_paths (order : Fin n ≃ S) (hq : ∀ e, 0 < q e) : + ∃ K : ℕ, ∀ M (demand : D → ℕ), (∀ i, demand i ≤ M) → ∀ w, + K + 2*Nat.clog 2 (M+1) ≤ w → ∀ (base : BurstRAM.Word w) (m : Memory w), base.val+n ≤ 2^w → + (m (base-1).val).val = repetitions B demand → + ∃ hw : outerCap B demand < 2^w, + (∀ bits, (execute (storedMachine B order w).program (storedFuel B n w) + ((storedMachine B order w).program.start base) m bits).isSome ↔ + ∃ v, (outerReader B order hq demand w hw).read bits = some (v,[])) ∧ + ∀ v : ↥(outerIndices B demand), ∃ es, + execute (storedMachine B order w).program (storedFuel B n w) + ((storedMachine B order w).program.start base) m ((outerReader B order hq demand w hw).encode v) = + some ⟨es,none⟩ ∧ after m es = overlay m base.val (List.ofFn fun i => (v.val (order i) : BurstRAM.Word w)) ∧ + countProbes es = n+1 ∧ es.length < storedFuel B n w ∧ + choiceBits es = (outerReader B order hq demand w hw).encode v := by + obtain ⟨K,hK⟩ := native_word_fit p q B.scale B.scale_pos B.radius + refine ⟨K,fun M demand hD w hW base m haddr hu => ?_⟩ + obtain ⟨_,hc,hl,hs,ht⟩ := hK M demand hD + have hpow := Nat.pow_le_pow_right (by decide : 0 < 2) hW + let u := repetitions B demand + let den := denominator B + let fac := factor B + let code := storedCall n fac den + let machine := storedMachine B order w + let pub := machine.publicData + let prep := prepareBounds n fac den + let chooseFuel := n*(4*w+10)+3 + let remaining := chooseFuel+(2*n+3) + have hpub i : (pub i).val = MotifAdmission.weight q (order i) * B.radius.den^2 := + Nat.mod_eq_of_lt ((ht _).trans_le hpow) + have hcap : u*fac*den+1 < 2^w := by + simpa [u,fac,factor,den,denominator,MotifAdmission.payloadCap,repetitions,Nat.mul_assoc] using hc.trans_le hpow + have hlim : (u*fac)^2*den+1 < 2^w := by + simpa [u,fac,factor,den,denominator,repetitions,Nat.mul_assoc] using hl.trans_le hpow + obtain ⟨pre,rs,hpre,hplen,hpbits,hpp,hpm,h2,h3,h4,h5⟩ := setup_exec u fac den pub base m hu hcap hlim + have hbox : (rs (low n 3)).val = outerCap B demand+1 := by + simpa [u,fac,factor,den,denominator,MotifAdmission.payloadCap,Nat.mul_assoc] using h3 + have hbound : (rs (low n 5)).val = + (u*B.scale*B.radius.num.natAbs)^2*MotifAdmission.denominator q+1 := by + simpa [fac,factor,den,denominator,Nat.mul_assoc] using h5 + have hw : outerCap B demand < 2^w := by have hh := (rs (low n 3)).isLt; omega + have hscore : score (List.finRange n) pub (fun _ => rs (low n 3)) < 2^w := by + rw [full_score order q B.radius _ _ hpub] + simpa [hbox,outerCap,repetitions] using hs.trans_le hpow + have link := Flow.template_linked (w := w) code none pub + have hstop : machine.code code.exitPC = .accept := by + change ((code.template none).code code.exitPC).resize w = _ + rw [Flow.template_exit]; rfl + have hbad : machine.code code.rejectPC = .reject := by + change ((code.template none).code code.rejectPC).resize w = _ + rw [Flow.template_reject]; rfl + let mid : Config w (code.length+2) (6+n) := ⟨code.pc (.inr (chooseAndStore n).entry),base,rs,fun _ => 0⟩ + have start (bits : List Bool) : + execute machine.program (storedFuel B n w) (machine.program.start base) m bits = + (execute machine.program remaining mid m bits).map (Flow.prependEvents pre) := by + have hr := hpre.execute link.seqLeft hbad (fun _ => 0) remaining bits + rw [hpbits,List.nil_append,hplen] at hr + exact hr + refine ⟨hw,?_,fun v => ?_⟩ + · intro bits + rw [start,Option.isSome_map] + have hlift := accept_linked link.seqRight hstop hbad base (fun _ => 0) remaining rs m bits + change execute machine.program remaining mid m bits = _ at hlift + rw [hlift] + refine (template_store_iff pub base (fun _ => 0) rs m haddr chooseFuel bits).trans ?_ + let choice := choosePayload n + let ch := (choice.template none).instantiate w pub + have ca : ch.code choice.exitPC = .accept := by simp [ch,Template.instantiate,Flow.template_exit,Instr.resize] + have cb : ch.code choice.rejectPC = .reject := by simp [ch,Template.instantiate,Flow.template_reject,Instr.resize] + exact choosePayload_execute_iff B order hq demand (Flow.template_linked choice none pub) ca cb + ⟨choice.pc choice.entry,base,rs,fun _ => 0⟩ rfl hpub h2 hbox (by simp [h4]) hbound hscore m bits + · let vec := fun i => (v.val (order i) : BurstRAM.Word w) + let bits := (outerReader B order hq demand w hw).encode v + obtain ⟨ha,hb⟩ := outer_admitted B order hq demand hw rs pub h2 h4 hbox hbound hpub v + obtain ⟨es,out,hlen,hprobes,hbits,hm,hfinish⟩ := + chooseAndStore_execute link.seqRight hbad base (fun _ => 0) rs m vec ha haddr + have hsmall : admissionSteps rs ≤ n*(4*w+10)+2 := by + have h := Nat.le_mul_of_pos_right n (by omega : 0 < 4*w+10) + unfold admissionSteps + split <;> omega + have he : es.length < remaining := by dsimp [remaining,chooseFuel]; omega + let extra := remaining-es.length-1 + have hrem : es.length+(extra+1) = remaining := by dsimp [extra]; omega + have hr := hfinish (extra+1) [] + rw [hrem,List.append_nil,hb] at hr + change execute machine.program remaining mid m bits = + (execute machine.program (extra+1) ⟨code.exitPC,base,out,fun _ => 0⟩ _ []).map _ at hr + simp only [execute,Machine.program,hstop,Instr.run,ite_true,Option.map_some,Flow.prependEvents,List.append_nil] at hr + change execute machine.program remaining mid m bits = some ⟨es,none⟩ at hr + refine ⟨pre++es,?_,?_,?_,?_,?_⟩ + · rw [start,hr]; rfl + · rw [show after m (pre++es) = after (after m pre) es from List.foldl_append,hpm,hm] + · rw [count_append,hpp,hprobes,Nat.add_comm] + · change (pre++es).length < (4+prep.length)+remaining + rw [List.length_append,hplen]; exact Nat.add_lt_add_left he _ + · rw [Flow.choiceBits_append,hpbits,List.nil_append,hbits,hb] + +end CompressorRecords.PayloadWrite + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPayloadFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorPayloadFootprint.lean new file mode 100644 index 0000000000..dea0649e92 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPayloadFootprint.lean @@ -0,0 +1,110 @@ +import OAI.Computability.VPVNP.CompressorPayloadCall +import OAI.Computability.VPVNP.CompressorFlowFootprint + +/-! +# Probe addresses of the admitted motif payload call + +The only external read obtains the repetition count from the preceding header +word. All writes fall in the reserved supply-coordinate array. These address +bounds apply to every admitted execution and every initial register bank. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PayloadFootprint + +open BurstRAM PrimedInputRAM PrimedStackRAM MotifChoiceRAM SourceTransport +open FlowFootprint +open private storeEvents from OAI.Computability.VPVNP.CompressorPayloadWrite +open private load_exec loadEvents from OAI.Computability.VPVNP.CompressorPayloadCall + +variable {r k w n : ℕ} + +private theorem scale_private (dst src : Fin r) (bits : List Bool) : + privateOnly (scaleDigits (k := k) dst src bits) = true := by + induction bits with + | nil => rfl + | cons b bs ih => cases b <;> simp [scaleDigits,privateOnly,privateOp,ih] + +theorem prepare_private (n factor den : ℕ) : privateOnly (prepareBounds n factor den) = true := by + simp [prepareBounds,privateOnly,scaleFixed,scale_private,privateOp] + +theorem choose_private (n : ℕ) : privateOnly (choosePayload n) = true := by + have zero (is : List (Fin n)) : privateOnly (unitSlots is) = true := by + induction is with + | nil => rfl + | cons i is ih => simp [unitSlots,privateOnly,privateOp,ih] + have scan (is : List (Fin n)) : privateOnly (MotifChoiceRAM.scan is) = true := by + induction is with + | nil => rfl + | cons i is ih => exact Bool.and_eq_true_iff.mpr ⟨rfl,ih⟩ + exact Bool.and_eq_true_iff.mpr ⟨zero _,scan _⟩ + +private theorem append {readable writable : ℕ → Prop} {es fs : List (Event w)} + (first : Reads readable es ∧ Writes writable es) (rest : Reads readable fs ∧ Writes writable fs) : + Reads readable (es++fs) ∧ Writes writable (es++fs) := + ⟨fun a v h => (List.mem_append.mp h).elim (first.1 a v) (rest.1 a v), + fun a v h => (List.mem_append.mp h).elim (first.2 a v) (rest.2 a v)⟩ + +private theorem store_bounds (base : ℕ) (vs : List (Word w)) (fit : base+vs.length ≤ 2^w) : + Reads (fun _ => False) (storeEvents base vs) ∧ + Writes (fun i => base ≤ i ∧ i < base+vs.length) (storeEvents base vs) := by + induction vs generalizing base with + | nil => simp [storeEvents,Reads,Writes] + | cons x xs ih => + simp only [List.length_cons] at fit + obtain ⟨rd,wr⟩ := ih (base+1) (by omega) + constructor <;> intro a v hv + · apply rd a v + simpa [storeEvents] using hv + · simp only [storeEvents,List.mem_cons,Event.write.injEq,reduceCtorEq,false_or] at hv + rcases hv with ⟨rfl,rfl⟩ | hv + · simp [Fin.val_natCast,Nat.mod_eq_of_lt (show base < 2^w by omega)] + · have h := wr a v hv + simp only [List.length_cons]; omega + +private theorem write_bounds (base : Word w) (v : Fin n → Word w) (fit : base.val+n ≤ 2^w) : + Reads (fun i => i = (base-1).val) (PayloadWrite.writeEvents base v) ∧ + Writes (fun i => base.val ≤ i ∧ i < base.val+n) (PayloadWrite.writeEvents base v) := by + obtain ⟨rd,wr⟩ := store_bounds base.val (List.ofFn v) (by simpa using fit) + constructor <;> intro a x hv <;> simp only [PayloadWrite.writeEvents,List.mem_cons,reduceCtorEq,false_or] at hv + · exact (rd a x hv).elim + · simpa using wr a x hv + +theorem storedCall (pub : Fin n → Word w) (base : Word w) {factor denominator : ℕ} + {rs out : Regs w (6+n)} {m m' es} (fit : base.val+n ≤ 2^w) + (run : Flow.Exec pub base (PayloadWrite.storedCall n factor denominator) rs m es out m') : + Reads (fun i => i = (base-1).val) es ∧ Writes (fun i => base.val ≤ i ∧ i < base.val+n) es := by + cases run with | seq start store => + cases start with | seq load prep => + cases store with | seq choice write => + obtain ⟨_,hl,_⟩ := load_exec pub base rs m + have eqLoad := events_eq hl (by rfl) load + obtain ⟨_,hs⟩ := PayloadWrite.writePayload_exec pub base _ _ _ (fun _ => rfl) fit + have eqWrite := events_eq hs (PayloadWrite.writeEvents_spec _ _ m fit).2.2.1 write + apply append (append ?_ (bounds_of_noProbes _ _ (noProbes (prepare_private ..) prep))) + (append (bounds_of_noProbes _ _ (noProbes (choose_private _) choice)) ?_) + · rw [← eqLoad] + constructor <;> intro a v hv <;> simp [loadEvents] at hv + exact congrArg Fin.val hv.1 + · rw [← eqWrite] + exact write_bounds base _ fit + +/-- Native form of the payload call's read and write bounds. -/ +theorem execute (pub : Fin n → Word w) (base : Word w) (factor denominator : ℕ) + (mem : Memory w) (fuel : ℕ) (bits : List Bool) (rep : Report w) (fit : base.val+n ≤ 2^w) + (run : let machine := ((PayloadWrite.storedCall n factor denominator).template none).instantiate w pub + BurstRAM.execute machine.program fuel (machine.program.start base) mem bits = some rep) : + Reads (fun i => i = (base-1).val) rep.events ∧ + Writes (fun i => base.val ≤ i ∧ i < base.val+n) rep.events := by + obtain ⟨_,_,he,_⟩ := (Flow.template_execute_iff (PayloadWrite.storedCall n factor denominator) + none pub base (fun _ => 0) (fun _ => 0) mem fuel bits rep).mp run + exact storedCall pub base fit he + +end CompressorRecords.PayloadFootprint + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPayloadWrite.lean b/lean/OAI/Computability/VPVNP/CompressorPayloadWrite.lean new file mode 100644 index 0000000000..08826e3449 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPayloadWrite.lean @@ -0,0 +1,309 @@ +import OAI.Computability.VPVNP.CompressorChoiceRAM +import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete + +/-! +# Writing the selected motif payload to descriptor memory + +The incoming persistent word gives the base of a contiguous descriptor. The +admission block receives the prepared registers of the motif choice reader. +After admission, the write block copies every supply coordinate, in order, +from its retained register to an external memory word. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PayloadWrite + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM +open PrimedCounter.GuessWord MotifChoiceRAM +open scoped Fin.CommRing + +variable {w n p : ℕ} + +/-- Replace a contiguous slice of external memory with the given words. -/ +def overlay (m : Memory w) (base : ℕ) (vs : List (Word w)) : Memory w := + fun a => if base ≤ a then vs[a-base]?.getD (m a) else m a + +@[simp] theorem overlay_nil (m : Memory w) (base : ℕ) : overlay m base [] = m := by + funext a + simp [overlay] + +theorem overlay_slot (m : Memory w) (base : ℕ) (v : Fin n → Word w) (i : Fin n) : + overlay m base (List.ofFn v) (base+i.val) = v i := by + simp [overlay, i.isLt] + +theorem overlay_outside (m : Memory w) (base : ℕ) (v : Fin n → Word w) (a : ℕ) + (h : a < base ∨ base+n ≤ a) : overlay m base (List.ofFn v) a = m a := by + rcases h with h | h + · simp [overlay, Nat.not_le.mpr h] + · have hn : n ≤ a-base := by omega + simp [overlay, List.getElem?_eq_none (by simpa using hn : (List.ofFn v).length ≤ a-base)] + +private theorem overlay_cons (m : Memory w) (base : ℕ) (v : Word w) (vs : List (Word w)) + (h : base < 2^w) : + overlay m base (v :: vs) = overlay (writeMemory m (base : Word w) v) (base+1) vs := by + funext a + have hb : (base : Word w).val = base := Nat.mod_eq_of_lt h + rcases lt_trichotomy a base with ha | rfl | ha + · simp [overlay, writeMemory, hb, ha.ne, Nat.not_le.mpr ha, show ¬ base+1 ≤ a by omega] + · simp [overlay, writeMemory, hb] + · have hs : a-base = (a-(base+1))+1 := by omega + simp [overlay, writeMemory, hb, ha.ne', hs, ha.le, Nat.succ_le_of_lt ha] + +/-- The cursor and its increment use registers 0 and 1. Each coordinate costs +one external write and one cursor increment. The terminal copy provides a +continuation even for a motif with empty supply. -/ +def writeSlots : List (Fin n) → Flow (6+n) n + | [] => .line (.copy (low n 0) (low n 0)) + | i :: rest => + .seq (.line (.write (low n 0) (slot i))) <| + .seq (.line (.binary .add (low n 0) (low n 0) (low n 1))) (writeSlots rest) + +/-- Instructions that take the descriptor base from persistent state and write every retained +supply coordinate to its slot. -/ +def writePayload (n : ℕ) : Flow (6+n) n := + .seq (.line (.stateWord (low n 0))) <| + .seq (.line (.constant (low n 1) 1)) (writeSlots (List.finRange n)) + +/-- A single linked table admits a motif vector and writes it at the persistent +base address. -/ +def chooseAndStore (n : ℕ) : Flow (6+n) n := .seq (choosePayload n) (writePayload n) + +private def storeEvents (base : ℕ) : List (Word w) → List (Event w) + | [] => [.tick] + | v :: vs => .write (base : Word w) v :: .tick :: storeEvents (base+1) vs + +private theorem storeEvents_cost (base : ℕ) (vs : List (Word w)) : + (storeEvents base vs).length = 2*vs.length+1 ∧ countProbes (storeEvents base vs) = vs.length ∧ + choiceBits (storeEvents base vs) = [] := by + induction vs generalizing base with + | nil => simp [storeEvents, countProbes, choiceBits] + | cons v vs ih => + obtain ⟨hl,hp,hb⟩ := ih (base+1) + simp [storeEvents, countProbes, choiceBits, hl, hp, hb]; omega + +private theorem storeEvents_after (base : ℕ) (vs : List (Word w)) (m : Memory w) + (h : base+vs.length ≤ 2^w) : + after m (storeEvents base vs) = overlay m base vs := by + induction vs generalizing base m with + | nil => simp [storeEvents, after, update] + | cons v vs ih => + simp only [List.length_cons] at h + rw [overlay_cons m base v vs (by omega)] + exact ih (base+1) _ (by omega) + +private theorem low_ne : low n 1 ≠ low n 0 := fun h => + (by decide : (1 : Fin 6) ≠ 0) ((Fin.castAddEmb n).injective h) + +private theorem writeSlots_exec (is : List (Fin n)) (base : ℕ) (v : Fin n → Word w) + (pub : Fin n → Word w) (state : Word w) (rs : Regs w (6+n)) (m : Memory w) + (haddr : rs (low n 0) = (base : Word w)) (hone : rs (low n 1) = 1) + (hslot : ∀ i, rs (slot i) = v i) (hfit : base + is.length ≤ 2^w) : + ∃ out, Flow.Exec pub state (writeSlots is) rs m (storeEvents base (is.map v)) out + (overlay m base (is.map v)) := by + induction is generalizing rs m base with + | nil => + rw [List.map_nil, overlay_nil] + exact ⟨_, .line rfl⟩ + | cons i is ih => + let m' := writeMemory m (base : Word w) (v i) + let rs' := Function.update rs (low n 0) ((base+1 : ℕ) : Word w) + have hwrite : Flow.Exec pub state (.line (.write (low n 0) (slot i))) rs m + [.write (base : Word w) (v i)] rs m' := by + apply Flow.Exec.line + simp only [Op.effect,haddr,hslot,m'] + have hinc : Flow.Exec pub state (.line (.binary .add (low n 0) (low n 0) (low n 1))) + rs m' [.tick] rs' m' := by + apply Flow.Exec.line + simp [Op.effect,BinaryOp.eval,haddr,hone,rs'] + simp only [List.length_cons] at hfit + obtain ⟨out,hr⟩ := ih (base+1) rs' m' (by simp [rs']) (by simp [rs',hone]) + (fun j => by simp [rs',hslot]) (by omega) + rw [List.map_cons,overlay_cons m base _ _ (by omega)] + exact ⟨out,.seq hwrite (.seq hinc hr)⟩ + +/-- Exact events of the write block, including the two setup instructions. -/ +def writeEvents (base : Word w) (v : Fin n → Word w) : List (Event w) := + .tick :: .tick :: storeEvents base.val (List.ofFn v) + +theorem writePayload_exec (pub : Fin n → Word w) (base : Word w) (rs : Regs w (6+n)) + (m : Memory w) (v : Fin n → Word w) (hslot : ∀ i, rs (slot i) = v i) + (hfit : base.val + n ≤ 2^w) : + ∃ out, Flow.Exec pub base (writePayload n) rs m (writeEvents base v) out + (overlay m base.val (List.ofFn v)) := by + let q := Function.update rs (low n 0) base + let r := Function.update q (low n 1) 1 + have ha : Flow.Exec pub base (.line (.stateWord (low n 0))) rs m [.tick] q m := .line rfl + have hb : Flow.Exec pub base (.line (.constant (low n 1) 1)) q m [.tick] r m := .line rfl + obtain ⟨out,ht⟩ := writeSlots_exec (List.finRange n) base.val v pub base r m + (by simp [r,q,Ne.symm low_ne]) (by simp [r]) (fun i => by simp [r,q,hslot]) (by simpa using hfit) + rw [← List.ofFn_eq_map] at ht + exact ⟨out,.seq ha (.seq hb ht)⟩ + +theorem writeEvents_spec (base : Word w) (v : Fin n → Word w) (m : Memory w) + (hfit : base.val + n ≤ 2^w) : + (writeEvents base v).length = 2*n+3 ∧ countProbes (writeEvents base v) = n ∧ + choiceBits (writeEvents base v) = [] ∧ after m (writeEvents base v) = overlay m base.val (List.ofFn v) := by + obtain ⟨hl,hp,hb⟩ := storeEvents_cost base.val (List.ofFn v) + have hm := storeEvents_after base.val (List.ofFn v) m (by simpa using hfit) + simp only [List.length_ofFn] at hl hp + exact ⟨by simp [writeEvents,hl], hp, hb, hm⟩ + +/-- The arithmetic input contract of the admission reader. Zero repetitions +produce the unit descriptor, whose coordinates are all zero. -/ +def Admitted (pub : Fin n → Word w) (rs : Regs w (6+n)) (v : Fin n → Word w) : Prop := + if rs (low n 2) = rs (low n 4) then ∀ i, v i = 0 else + (∀ i, v i < rs (low n 3)) ∧ + (rs (low n 4)).val + score (List.finRange n) pub v < (rs (low n 5)).val + +/-- Choice stream for the payload, empty on the forced branch and otherwise the ordered word +encoding of the supply vector. -/ +def payloadBits (rs : Regs w (6+n)) (v : Fin n → Word w) : List Bool := + if rs (low n 2) = rs (low n 4) then [] else encoding (List.finRange n) v + +/-- Number of admission steps for the forced branch or the full word-by-word vector choice, as +selected by the prepared registers. -/ +def admissionSteps (rs : Regs w (6+n)) : ℕ := + if rs (low n 2) = rs (low n 4) then n+2 else n*(4*w+10)+2 + +private theorem admitted_prefix {M : Machine w p (6+n) n} + {label : (choosePayload n).Label → Fin p} {stop bad : Fin p} + (hl : Flow.Linked M (choosePayload n) label stop bad) + (c : Config w p (6+n)) (hpc : c.pc = label (choosePayload n).entry) + (v : Fin n → Word w) (ha : Admitted M.publicData c.reg v) : + ∃ out es, Prefix M c es out ∧ es.length = admissionSteps c.reg ∧ + choiceBits es = payloadBits c.reg v ∧ out.pc = stop ∧ + (∀ i, out.reg (slot i) = v i) ∧ out.privateMem = c.privateMem ∧ out.persistent = c.persistent := by + by_cases hu : c.reg (low n 2) = c.reg (low n 4) + · obtain ⟨out,es,h,hl',hb,hpc',hz,hp,hs⟩ := choosePayload_unit hl c hpc hu + have hz' : ∀ i, v i = 0 := by simpa [Admitted,hu] using ha + exact ⟨out,es,h,by simpa [admissionSteps,hu] using hl',by simpa [payloadBits,hu] using hb, + hpc',fun i => (hz i).trans (hz' i).symm,hp,hs⟩ + · simp only [Admitted,hu,↓reduceIte] at ha + obtain ⟨hc,hs⟩ := ha + simpa only [admissionSteps,payloadBits,hu,↓reduceIte] using choosePayload_vector hl c hpc hu v hc hs + +private theorem prefix_memory {M : Machine w p (6+n) n} {c c' : Config w p (6+n)} {es} + (h : Prefix M c es c') (m : Memory w) : + countProbes es = 0 ∧ after m es = m := by + induction h with + | nil => exact ⟨rfl,rfl⟩ + | tick _ _ ih | choice _ _ ih => exact ih + +private theorem probes_append (es fs : List (Event w)) : + countProbes (es ++ fs) = countProbes es + countProbes fs := by + induction es with + | nil => simp [countProbes] + | cons e es ih => cases e <;> simp [countProbes,ih,Nat.add_assoc] + +/-- Exact execution of the linked admission and emission code. It hands the +next native instruction its original bit suffix and the updated external +memory. The probe count is exactly the number of supply coordinates. -/ +theorem chooseAndStore_execute {M : Machine w p (6+n) n} + {label : (chooseAndStore n).Label → Fin p} {stop bad : Fin p} + (hl : Flow.Linked M (chooseAndStore n) label stop bad) (hbad : M.code bad = .reject) + (base : Word w) (priv : Word w → Word w) (rs : Regs w (6+n)) (m : Memory w) + (v : Fin n → Word w) (ha : Admitted M.publicData rs v) (hfit : base.val+n ≤ 2^w) : + ∃ es out, es.length = admissionSteps rs + (2*n+3) ∧ countProbes es = n ∧ + choiceBits es = payloadBits rs v ∧ after m es = overlay m base.val (List.ofFn v) ∧ + ∀ fuel bits, execute M.program (es.length + fuel) + ⟨label (chooseAndStore n).entry,base,rs,priv⟩ m (payloadBits rs v ++ bits) = + (execute M.program fuel ⟨stop,base,out,priv⟩ (overlay m base.val (List.ofFn v)) bits).map + (Flow.prependEvents es) := by + let c : Config w p (6+n) := ⟨label (chooseAndStore n).entry,base,rs,priv⟩ + obtain ⟨q,es,hpre,hlen,hbits,hpc,hslot,hpriv,hbase⟩ := admitted_prefix hl.seqLeft c rfl v ha + have hq : q = ⟨label (.inr (writePayload n).entry),base,q.reg,priv⟩ := by + cases q + simp_all [c] + obtain ⟨out,hstore⟩ := writePayload_exec M.publicData base q.reg m v hslot hfit + obtain ⟨hslen,hsprobes,hsbits,hsm⟩ := writeEvents_spec base v m hfit + obtain ⟨hprobes,hm⟩ := prefix_memory hpre m + refine ⟨es ++ writeEvents base v,out,by simp [hlen,hslen,c],by simp [probes_append,hprobes,hsprobes], + by simp [Flow.choiceBits_append,hbits,c,hsbits],?_,fun fuel bits => ?_⟩ + · rw [show after m (es ++ _) = after (after m es) (writeEvents base v) from List.foldl_append,hm,hsm] + · have h₁ := hpre.execute ((writeEvents base v).length + fuel) m bits + have h₂ := hstore.execute hl.seqRight hbad priv fuel bits + rw [hsbits, List.nil_append] at h₂ + rw [hq] at h₁ + change choiceBits es = payloadBits rs v at hbits + rw [hbits] at h₁ + rw [List.length_append, Nat.add_assoc, Nat.add_comm es.length, ← show c = + ⟨label (chooseAndStore n).entry,base,rs,priv⟩ from rfl, h₁] + erw [h₂, Option.map_map] + congr 1 + funext r + simp [Flow.prependEvents, List.append_assoc] + +private def linear {r k : ℕ} : Flow r k → Prop + | .line _ => True + | .seq a b => linear a ∧ linear b + | _ => False + +private theorem linear_trace {r k : ℕ} {a : Flow r k} {pub : Fin k → Word w} {s rs m es out m'} + (h : Flow.Exec pub s a rs m es out m') (ha : linear a) : + es.length = a.length ∧ choiceBits es = [] := by + induction h with + | line he => exact ⟨rfl,Flow.line_choices he⟩ + | seq _ _ iha ihb => + obtain ⟨hla,hba⟩ := iha ha.1 + obtain ⟨hlb,hbb⟩ := ihb ha.2 + simp [Flow.length,Flow.choiceBits_append,hla,hlb,hba,hbb] + | ifEqYes | ifEqNo | ifLtYes | ifLtNo | branchYes | branchNo | whileDone | whileStep => contradiction + +private theorem writer_linear : linear (writePayload n) ∧ (writePayload n).length = 2*n+3 := by + have slots (is : List (Fin n)) : linear (writeSlots is) ∧ (writeSlots is).length = 2*is.length+1 := by + induction is with + | nil => simp [writeSlots,linear,Flow.length] + | cons i is ih => simp [writeSlots,linear,Flow.length,ih]; omega + obtain ⟨hl,hlen⟩ := slots (List.finRange n) + simp [writePayload,linear,Flow.length,hl,hlen]; omega + +private theorem split_seq {r k : ℕ} {a b : Flow r k} {pub : Fin k → Word w} {s rs m es out m'} + (h : Flow.Exec pub s (.seq a b) rs m es out m') : + ∃ fs mid mem gs, Flow.Exec pub s a rs m fs mid mem ∧ Flow.Exec pub s b mid mem gs out m' ∧ + es = fs ++ gs := by + cases h with + | seq h₁ h₂ => exact ⟨_,_,_,_,h₁,h₂,rfl⟩ + +/-- Appending the writer preserves exactly the complete bit streams of the +standalone admission template. The additional budget is its exact native +step count. The assertion holds at every admission budget. -/ +theorem template_store_iff (pub : Fin n → Word w) (base : Word w) (priv : Word w → Word w) + (rs : Regs w (6+n)) (m : Memory w) (hfit : base.val+n ≤ 2^w) (fuel : ℕ) (bits : List Bool) : + let code := chooseAndStore n + let choice := choosePayload n + (execute ((code.template none).instantiate w pub).program (fuel+(2*n+3)) + ⟨code.pc code.entry,base,rs,priv⟩ m bits).isSome ↔ + (execute ((choice.template none).instantiate w pub).program fuel + ⟨choice.pc choice.entry,base,rs,priv⟩ m bits).isSome := by + dsimp only + let code := chooseAndStore n + let choice := choosePayload n + have whole := Flow.template_execute_iff code none pub base priv rs m (fuel+(2*n+3)) bits + have part := Flow.template_execute_iff choice none pub base priv rs m fuel bits + rw [Option.isSome_iff_exists, Option.isSome_iff_exists] + constructor + · rintro ⟨r,hr⟩ + obtain ⟨out,m',he,_,hlen,hbits⟩ := (whole r).mp hr + obtain ⟨es,r₁,m₁,fs,left,right,hevents⟩ := split_seq (a := choice) (b := writePayload n) he + obtain ⟨hfl,hfb⟩ := linear_trace right writer_linear.1 + rw [writer_linear.2] at hfl + simp only [hevents,List.length_append,hfl] at hlen + simp only [hevents,Flow.choiceBits_append,hfb,List.append_nil] at hbits + exact ⟨⟨es,none⟩,(part _).mpr ⟨r₁,m₁,left,rfl,by dsimp; omega,hbits⟩⟩ + · rintro ⟨r,hr⟩ + obtain ⟨mid,mem,he,_,hlen,hbits⟩ := (part r).mp hr + let v := fun i => mid (slot i) + obtain ⟨out,hs⟩ := writePayload_exec pub base mid mem v (fun _ => rfl) hfit + obtain ⟨hsl,_,hsb,_⟩ := writeEvents_spec base v mem hfit + refine ⟨⟨r.events ++ writeEvents base v,none⟩,(whole _).mpr ⟨out,_,.seq he hs,rfl,?_,?_⟩⟩ + · simp only [List.length_append,hsl]; omega + · simp [Flow.choiceBits_append,hsb,hbits] + +end CompressorRecords.PayloadWrite + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPhaseVisits.lean b/lean/OAI/Computability/VPVNP/CompressorPhaseVisits.lean new file mode 100644 index 0000000000..0867257bc3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPhaseVisits.lean @@ -0,0 +1,260 @@ +import OAI.Computability.VPVNP.CompressorLevelCounts +import OAI.Computability.VPVNP.CompressorRecordsDirectory +import OAI.Computability.VPVNP.RAMFinite + +/-! +# Charged native directory scans on a selected compression branch + +A phase may dispatch one flat scan or use short rows for each site of a +fixed kind. The two forms have different launch counts. The scope indexes +the actual base, slots, motifs or resulting sites of the selected kernel. +The directory bound charges launches, closing calls and the final controller +as well as every original data call, even for empty scans. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.PhaseVisits + +open BurstRAM Compression Schedule + +/-- Objects traversed by the native workers at a single level. -/ +inductive Scope where + | once | oldBase | oldSites | oldSlots | motifs | newSites | newSlots | reservedSites + deriving DecidableEq + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f} + +/-- Number of objects in the phase's scope for the selected pass, using its base, sites, slots, +or motifs as appropriate. -/ +def Scope.count (sites : ℕ) (v : SelectedLevel B f hf) : Scope → ℕ + | .once => 1 + | .oldBase => Fintype.card v.input.Base + | .oldSites => v.input.positions + | .oldSlots => v.oldSlots + | .motifs => v.origin.motifCount + | .newSites => v.outputSites + | .newSlots => v.outputSlots + | .reservedSites => sites + +theorem Scope.count_le (s : Scope) (sites : ℕ) (v : SelectedLevel B f hf) (hv : v.input.positions ≤ sites) : + s.count sites v ≤ sites * max 1 (slotDegree S) := by + have hsites := Nat.le_mul_of_pos_right sites (le_max_left 1 (slotDegree S)) + have hp := hv.trans hsites + have hold := Nat.mul_le_mul hv (v.oldDegree_le.trans (le_max_right 1 _)) + cases s with + | once => exact v.input.positions_pos.trans_le hp + | oldBase => exact v.baseSites_le.trans hp + | oldSites => exact hp + | oldSlots => exact hold + | motifs => exact v.origin.motifCount_le.trans hold + | newSites => exact v.outputSites_le.trans hp + | newSlots => exact v.outputSlots_le.trans (Nat.mul_le_mul hv (le_max_right _ _)) + | reservedSites => exact hsites + +/-- A fixed scan prescription. `perObject` counts data calls at each +physical object or the full work of its short rows. -/ +structure Phase where + /-- Set of objects over which this native phase is scheduled. -/ + scope : Scope + /-- Bound on worker visits charged to each object in the phase's scope. -/ + perObject : ℕ + +/-- Per-object charge including the worker visit budget and two calls for entering and closing +a row. -/ +def Phase.weight (p : Phase) := p.perObject + 2 + +/-- Native pass families of the fixed finite block. -/ +structure Plan (S : BlockSchedule k) where + /-- List of native phases assigned to each shrinking substep of a block. -/ + shrink : Fin S.steps → List Phase + /-- List of native phases assigned to the degree refresh at the end of a block. -/ + refresh : List Phase + +/-- Recover the phase list appropriate to the origin of the actual state pass. -/ +def Plan.phases {a g b n : ℕ} {X : State a g} {p : StatePass A X b n} + (P : Plan S) : PassOrigin B f hf p → List Phase + | .shrink i .. => P.shrink i + | .refresh .. => P.refresh + +/-- Largest total phase weight among the refresh and all indexed shrinking passes. -/ +noncomputable def Plan.levelRate (P : Plan S) := + max ((P.refresh.map Phase.weight).sum) (Finset.univ.sup fun i ↦ ((P.shrink i).map Phase.weight).sum) + +theorem Plan.phases_rate (P : Plan S) {a g b n : ℕ} {X : State a g} {p : StatePass A X b n} + (o : PassOrigin B f hf p) : ((P.phases o).map Phase.weight).sum ≤ P.levelRate := by + cases o with + | shrink i _ _ => exact (Finset.le_sup (f := fun j : Fin S.steps ↦ ((P.shrink j).map Phase.weight).sum) + (Finset.mem_univ i)).trans (le_max_right _ _) + | refresh => exact le_max_left _ _ + +variable {d w : ℕ} + +/-- Number of charged calls in a row list, adding launch and close to each row's data-report +count. -/ +def calls (rows : List (Directory.Row d w)) : ℕ := + (rows.map fun r ↦ r.reports.length+2).sum + +private theorem calls_append (rs ss : List (Directory.Row d w)) : + calls (rs++ss) = calls rs + calls ss := by simp [calls] + +/-- Either a whole-phase cursor scan, or an ordered family of short row +groups. In the second form each group pays its own launches and closes. -/ +inductive Rows (d w jobs visits : ℕ) where + | flat (row : Directory.Row d w) (length : row.reports.length ≤ jobs*visits) + | indexed (atObject : Fin jobs → List (Directory.Row d w)) + (length : ∀ i, calls (atObject i) ≤ visits) + +/-- Chronological directory rows of a phase, either one flat scan or the concatenation of its +per-object rows. -/ +def Rows.log {jobs visits : ℕ} : Rows d w jobs visits → List (Directory.Row d w) + | .flat row _ => [row] + | .indexed rows _ => (List.finRange jobs).flatMap rows + +private theorem flat_calls {ι : Type*} (g : ι → List (Directory.Row d w)) (is : List ι) (C : ℕ) + (hg : ∀ i ∈ is, calls (g i) ≤ C) : calls (is.flatMap g) ≤ is.length*C := by + induction is with + | nil => simp [calls] + | cons i is ih => + rw [List.flatMap_cons,calls_append,List.length_cons,Nat.succ_mul] + rw [Nat.add_comm (is.length*C) C] + exact Nat.add_le_add (hg i (by simp)) (ih fun j hj ↦ hg _ (by simp [hj])) + +theorem Rows.calls_le {jobs visits cap : ℕ} (r : Rows d w jobs visits) (h : jobs ≤ cap) (hc : 1 ≤ cap) : + calls r.log ≤ cap*(visits+2) := by + cases r with + | flat row hlen => + have h' := hlen.trans (Nat.mul_le_mul_right visits h) + have htwo : 2 ≤ cap*2 := by omega + simp only [Rows.log,calls,List.map_cons,List.map_nil,List.sum_cons,List.sum_nil,Nat.add_zero,Nat.mul_add] + omega + | indexed rows hr => + exact (flat_calls rows _ visits (fun i _ ↦ hr i)).trans (by + simp only [List.length_finRange]; exact Nat.mul_le_mul h (by omega)) + +/-- Each occurrence has its own physical memory and worker. The two +ordinals distinguish equal phase sizes and repeated equal input states. -/ +abbrev LevelRows (sites : ℕ) (v : SelectedLevel B f hf) := + (levelOrdinal phaseOrdinal : ℕ) → (p : Phase) → Rows d w (p.scope.count sites v) p.perObject + +private def phaseLog {sites : ℕ} {v : SelectedLevel B f hf} (rows : LevelRows (d := d) (w := w) sites v) + (level : ℕ) : ℕ → List Phase → List (Directory.Row d w) + | _, [] => [] + | i, p::ps => (rows level i p).log ++ phaseLog rows level (i+1) ps + +/-- Directory log for the phases of one selected level, numbered from phase zero at that level. -/ +def levelLog (P : Plan S) (sites : ℕ) (v : SelectedLevel B f hf) (rows : LevelRows (d := d) (w := w) sites v) + (level : ℕ := 0) := phaseLog rows level 0 (P.phases v.origin) + +private theorem phaseSum (sites : ℕ) (v : SelectedLevel B f hf) (rows : LevelRows (d := d) (w := w) sites v) + (hv : v.input.positions ≤ sites) (ps : List Phase) (level i : ℕ) : + calls (phaseLog rows level i ps) ≤ (sites*max 1 (slotDegree S))*(ps.map Phase.weight).sum := by + have hc := Nat.mul_pos (v.input.positions_pos.trans_le hv) (le_max_left 1 (slotDegree S)) + induction ps generalizing i with + | nil => simp [phaseLog,calls] + | cons p ps ih => + rw [phaseLog,calls_append,List.map_cons,List.sum_cons,Nat.mul_add] + exact Nat.add_le_add ((rows level i p).calls_le (p.scope.count_le sites v hv) hc) (ih _) + +theorem levelLog_calls (P : Plan S) (sites : ℕ) (v : SelectedLevel B f hf) (rows : LevelRows (d := d) (w := w) sites v) + (hv : v.input.positions ≤ sites) (level : ℕ := 0) : + calls (levelLog P sites v rows level) ≤ sites * max 1 (slotDegree S) * P.levelRate := + (phaseSum sites v rows hv _ _ _).trans (Nat.mul_le_mul_left _ (P.phases_rate v.origin)) + +/-- Concatenate the directory logs of successive selected levels while advancing the level +index. -/ +def levelLogs (P : Plan S) (sites : ℕ) + (groups : ∀ v : SelectedLevel B f hf, LevelRows (d := d) (w := w) sites v) : + ℕ → List (SelectedLevel B f hf) → List (Directory.Row d w) + | _, [] => [] + | i, v::vs => levelLog P sites v (groups v) i ++ levelLogs P sites groups (i+1) vs + +/-- Chronological rows on the selected branch, including the level-zero +cursor initialization in `initial`. -/ +def branchRows (P : Plan S) (sites : ℕ) (levels : List (SelectedLevel B f hf)) + (initial : List (Directory.Row d w)) (groups : ∀ v : SelectedLevel B f hf, LevelRows (d := d) (w := w) sites v) := + initial ++ levelLogs P sites groups 0 levels + +private theorem levelLogs_calls (P : Plan S) (sites : ℕ) (levels : List (SelectedLevel B f hf)) + (groups : ∀ v : SelectedLevel B f hf, LevelRows (d := d) (w := w) sites v) + (hs : ∀ v ∈ levels, v.input.positions ≤ sites) (i : ℕ) : + calls (levelLogs P sites groups i levels) ≤ levels.length*(sites*max 1 (slotDegree S)*P.levelRate) := by + induction levels generalizing i with + | nil => simp [calls,levelLogs] + | cons v vs ih => + rw [levelLogs,calls_append,List.length_cons,Nat.succ_mul,Nat.add_comm (vs.length*_) _] + exact Nat.add_le_add (levelLog_calls P sites v _ (hs v List.mem_cons_self) i) + (ih (fun j hj ↦ hs j (List.mem_cons_of_mem _ hj)) _) + +theorem branchRows_calls (P : Plan S) {T n : ℕ} (h : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) + (z : (B.execute f hf T h X).Choices) (initial : List (Directory.Row d w)) + (groups : ∀ v : SelectedLevel B f hf, LevelRows (d := d) (w := w) X.positions v) : + calls (branchRows P X.positions (executeLevels B f hf T h X z) initial groups) ≤ + calls initial + (S.steps+1)*T*(X.positions*max 1 (slotDegree S)*P.levelRate) := by + rw [branchRows,calls_append] + apply Nat.add_le_add_left + exact (levelLogs_calls _ _ _ _ (fun v hv ↦ (executeLevels_limits B f hf T h X z v hv).1) _).trans + (Nat.mul_le_mul_right _ (executeLevels_length B f hf T h X z)) + +private theorem count_le_events (es : List (Event w)) : countProbes es ≤ es.length := by + induction es with + | nil => rfl + | cons e es ih => cases e <;> simp only [countProbes,List.length_cons] <;> omega + +private theorem cost_cap (rs : List (Report w)) (cap : ℕ) (h : ∀ r ∈ rs, r.events.length < cap) : + RAMBuckets.cost Report.probes rs ≤ rs.length*cap := by + induction rs with + | nil => simp [RAMBuckets.cost] + | cons r rs ih => + change 1+r.probes+_ ≤ (rs.length+1)*cap + rw [Nat.succ_mul,Nat.add_comm (rs.length*cap) cap] + apply Nat.add_le_add _ (ih fun s hs ↦ h _ (by simp [hs])) + have hp := (count_le_events r.events).trans_lt (h r (by simp)) + change 1+countProbes r.events ≤ cap + omega + +private theorem linked_length (C : Catalog d) (i : Fin d) (ports : Ports w) (m : Memory w) (rs : List (Report w)) : + (linkedRows C i ports m rs).length = rs.length := by + induction rs generalizing m with + | nil => rfl + | cons r rs ih => exact congrArg Nat.succ (ih _) + +theorem directory_length (C : Catalog d) (ports : Ports w) (m : Memory w) (rows : List (Directory.Row d w)) : + (rows.flatMap (Directory.Row.log C ports) ++ [Directory.terminalReport (d := d) ports + (Directory.finalMemory C ports m rows)]).length = calls rows+1 := by + simp only [List.length_append,List.length_cons,List.length_nil] + congr 1 + induction rows with + | nil => rfl + | cons r rs ih => + rw [List.flatMap_cons,List.length_append,ih] + simp only [Directory.Row.log,List.length_cons,List.length_append,linked_length,List.length_nil, + calls,List.map_cons,List.sum_cons] + +/-- Run the linked table on a physically valid directory and charge all +returned reports, including launch, stop and terminal controller. -/ +theorem directory_run (C : Catalog d) (ports : Ports w) (m : Memory w) (rows : List (Directory.Row d w)) (cap : ℕ) + (fit : d+1 ≤ 2^w) (hcap : 6+2*(d+1)+5 ≤ cap) (valid : Directory.Valid C ports cap m rows) : + ∃ reports, runSegment (Directory.program C ports) cap (some 0) m + (rows.flatMap Directory.Row.choicesWithControl ++ [[]]) = some reports ∧ + (∀ r ∈ reports, r.events.length < cap ∧ r.probes < cap) ∧ + RAMBuckets.cost Report.probes reports ≤ (calls rows+1)*cap := by + let rs := rows.flatMap (Directory.Row.log C ports) ++ [Directory.terminalReport (d := d) ports + (Directory.finalMemory C ports m rows)] + have hr := Directory.run C ports rows m cap fit hcap valid + have steps := localSegment_event_bound ((runSegment_iff ..).mp hr).1 + exact ⟨rs,hr,fun r h ↦ ⟨steps r h,(count_le_events r.events).trans_lt (steps r h)⟩, + (cost_cap rs cap steps).trans_eq (congrArg (· * cap) (directory_length C ports m rows))⟩ + +end CompressorRecords.PhaseVisits + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPlacementPersistence.lean b/lean/OAI/Computability/VPVNP/CompressorPlacementPersistence.lean new file mode 100644 index 0000000000..211ea608e6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPlacementPersistence.lean @@ -0,0 +1,72 @@ +import OAI.Computability.VPVNP.PairTraversalScanDirectory +import OAI.Computability.VPVNP.CompressorSourceTransport + +/-! +# Retaining a completed placement directory through later stages + +The traversal only reads the owner column, count column and bounded child +rows of each elementary placement. Preserving those three regions carries +the typed directory from the producing memory to the final descriptor +memory, even as later workers update the scheduler and other levels. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace PairSimulation.TraversalRows.Directory + +open BurstRAM CompressorRecords LocalHistory NetworkKernel Compression +open private countAt_val rowAt_val from OAI.Computability.VPVNP.CompressorRecordPreimageScan +open scoped Classical + +variable {w : ℕ} {A : Type*} [CommRing A] {N : Network} {t : Term A N} +variable {old : Order N.Site} {next : Order t.output.Site} {m m' : Memory w} {limit : ℕ} + +/-- The bounded physical data cells of the raw placement, including +the unused capacity in every child row. -/ +def cells (pub : Fin 6 → Word w) (x : ℕ) : Prop := + ((pub 1).val ≤ x ∧ x < (pub 1).val+(pub 0).val) ∨ + ((pub 3).val ≤ x ∧ x < (pub 3).val+(pub 2).val) ∨ + ((pub 5).val ≤ x ∧ x < (pub 5).val+(pub 2).val*(pub 4).val) + +omit [CommRing A] in +theorem cells_interval (d : Directory t old next m limit) {x : ℕ} (h : cells d.pub x) : + (d.pub 1).val ≤ x ∧ x < limit := by + obtain ⟨hc,hr,_⟩ := d.regions + have hlim := d.inputEnd + rcases h with h|h|h <;> omega + +/-- A later worker can change any address outside the actual placement +arrays. The same table, bounds and ordered preimage witnesses then apply +in the later memory. -/ +def transport (d : Directory t old next m limit) (agree : SourceTransport.Agree (cells d.pub) m m') : + Directory t old next m' limit := by + refine ⟨d.pub,d.oldCount,d.newCount,d.regions,d.inputEnd,⟨?_,?_⟩,d.capacity⟩ + · intro i hi + change m' (d.pub 1+i).val = _ + have hlo := d.regions.ownersBeforeCounts + have hv : i.val < (d.pub 0).val := hi + have haddr : (d.pub 1+i).val = (d.pub 1).val+i.val := + (Fin.val_add ..).trans (Nat.mod_eq_of_lt (by have h' := (d.pub 3).isLt; omega)) + have region : cells d.pub (d.pub 1+i).val := Or.inl (by rw [haddr]; omega) + exact (agree _ region).symm.trans (d.collected.owners i hi) + · intro v hv + obtain ⟨hc,hr⟩ := d.collected.rows v hv + have count := countAt_val d.regions hv + have row := rowAt_val d.regions hv + have vmax : v.val < (d.pub 2).val := hv + have cap := d.capacity v hv + refine ⟨(congrArg Fin.val (agree _ (Or.inr (Or.inl (by rw [count]; omega))))).symm.trans hc,?_⟩ + intro i + have hi := i.isLt.trans_le cap + have hg := Nat.mul_le_mul_right (d.pub 4).val (Nat.succ_le_of_lt vmax) + rw [Nat.succ_mul] at hg + have region : cells d.pub ((rowAt d.pub v).val+i.val) := Or.inr (Or.inr (by rw [row]; omega)) + exact (agree _ region).symm.trans (hr i) + +end PairSimulation.TraversalRows.Directory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPrefixFrames.lean b/lean/OAI/Computability/VPVNP/CompressorPrefixFrames.lean new file mode 100644 index 0000000000..c2452dade2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPrefixFrames.lean @@ -0,0 +1,142 @@ +import OAI.Computability.VPVNP.CompressorExecutionTrace +import OAI.Computability.VPVNP.CompressorSourceBankFrame + +/-! # Low-memory frames for arbitrary finite native prefixes + +A partial successful execution may stop inside a pass with no accepting +extension. The frame invariant covers such prefixes directly. Once a +complete choice segment has been consumed, the same test continues in +its actual successor state and memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BranchSegments + +open BurstRAM SourceBankFrame Compression + +variable {w cap lo : ℕ} {Q : Type*} {P : BurstRAM.Program w Q} {st : Option (Word w)} {m : Memory w} + +namespace Cut + +/-- Low-memory stability of each branch and each successful prefix of the branch cut, including +prefixes ending before branch selection completes. -/ +structure PrefixFrame {I : Type*} (c : Cut P cap st m I) (lo : ℕ) : Prop where + parts : ∀ i, Stable lo m (c.part i).logs + «prefix» : ∀ bs rs, runSegment P cap st m bs = some rs → + Stable lo m rs ∨ ∃ i tail, bs = (c.part i).bits ++ tail + +private theorem partial_empty (n : ℕ) {logs rs : List (Report w)} {bs : List (List Bool)} + (empty : runSegment P cap st m (List.replicate n []) = some logs) (frame : Stable lo m logs) + (run : runSegment P cap st m bs = some rs) : Stable lo m rs ∨ ∃ tail, bs = List.replicate n [] ++ tail := by + induction n generalizing st m logs rs bs with + | zero => exact Or.inr ⟨bs,rfl⟩ + | succ n ih => + simp only [List.replicate_succ] at empty ⊢ + cases st with + | none => contradiction + | some a => + cases bs with + | nil => + cases Option.some.inj run + exact Or.inl trivial + | cons b bs => + rw [runSegment] at empty run + cases he : execute P cap (P.start a) m [] with + | none => simp [he] at empty + | some x => + cases hb : execute P cap (P.start a) m b with + | none => simp [hb] at run + | some y => + obtain ⟨rfl,rfl⟩ := execute_empty_forces he hb + simp only [he,Option.map_eq_some_iff] at empty run + obtain ⟨more,hm,rfl⟩ := empty + obtain ⟨rest,hr,rfl⟩ := run + rcases ih hm frame.2 hr with f | ⟨tail,ht⟩ + · exact Or.inl ⟨frame.1,f⟩ + · exact Or.inr ⟨tail,congrArg (List.cons []) ht⟩ + +/-- An arbitrary finite run either preserves all reserved low cells or +has already consumed the entire forced interval. -/ +theorem deterministic_prefix (s : Segment P cap st m) (n : ℕ) (quiet : s.bits = List.replicate n []) + (frame : Stable lo m s.logs) {bs rs} (run : runSegment P cap st m bs = some rs) : + Stable lo m rs ∨ ∃ tail, bs = s.bits ++ tail := by + rw [quiet] + exact partial_empty n (quiet ▸ s.run) frame run + +theorem PrefixFrame.deterministic (s : Segment P cap st m) (n : ℕ) (quiet : s.bits = List.replicate n []) + (stable : Stable lo m s.logs) : (Cut.deterministic s n quiet).PrefixFrame lo := by + refine ⟨fun _ => stable,fun bs rs run => ?_⟩ + exact (deterministic_prefix s n quiet stable run).imp id fun ⟨t,ht⟩ => ⟨(),t,ht⟩ + +variable {I : Type*} {c : Cut P cap st m I} + +theorem PrefixFrame.bind (h : c.PrefixFrame lo) {J : I → Type*} + {k : ∀ i, Cut P cap (c.part i).state (c.part i).memory (J i)} + (hk : ∀ i, (k i).PrefixFrame lo) : (c.bind k).PrefixFrame lo := by + refine ⟨fun i => (h.parts i.1).append ((hk i.1).parts i.2),fun bs rs run => ?_⟩ + rcases h.prefix bs rs run with stable | ⟨i,tail,rfl⟩ + · exact Or.inl stable + · rw [PrimedSchedule.runSegment_append,(c.part i).run] at run + change (runSegment P cap (c.part i).state (c.part i).memory tail).map _ = some rs at run + obtain ⟨more,rest,rfl⟩ := Option.map_eq_some_iff.mp run + rcases (hk i).prefix tail more rest with f | ⟨j,t,ht⟩ + · exact Or.inl ((h.parts i).append f) + · exact Or.inr ⟨⟨i,j⟩,t,by simp only [ht,Cut.bind,Segment.append,List.append_assoc]⟩ + +theorem PrefixFrame.before (s : Segment P cap st m) (n : ℕ) (quiet : s.bits = List.replicate n []) + (stable : Stable lo m s.logs) {k : Cut P cap s.state s.memory I} (hk : k.PrefixFrame lo) : + (Cut.before s n quiet k).PrefixFrame lo := by + have joined := (PrefixFrame.deterministic s n quiet stable).bind (fun _ : Unit => hk) + refine ⟨fun i => joined.parts ⟨(),i⟩,fun bs rs run => ?_⟩ + exact (joined.prefix bs rs run).imp id fun ⟨z,tail,ht⟩ => ⟨z.2,tail,ht⟩ + +theorem PrefixFrame.afterChoice (h : c.PrefixFrame lo) (k : ∀ i, Segment P cap (c.part i).state (c.part i).memory) + (n : I → ℕ) (quiet : ∀ i, (k i).bits = List.replicate (n i) []) + (stable : ∀ i, Stable lo (c.part i).memory (k i).logs) : (c.afterChoice k n quiet).PrefixFrame lo := by + have joined := h.bind fun i => PrefixFrame.deterministic (k i) (n i) (quiet i) (stable i) + refine ⟨fun i => joined.parts ⟨i,()⟩,fun bs rs run => ?_⟩ + exact (joined.prefix bs rs run).imp id fun ⟨z,tail,ht⟩ => ⟨z.1,tail,ht⟩ + +end Cut + +namespace ExecutionTrace + +variable {R : Type*} [CommSemiring R] {a g b n : ℕ} {X : State a g} {E : StateExecution R b n X} + +/-- The local frame proof required at each actual pass and terminal close. -/ +def Framed {a g b n : ℕ} {X : State a g} {E : StateExecution R b n X} {st m} + (t : ExecutionTrace P cap E st m) (lo : ℕ) : Prop := + match t with + | .done s _ _ _ => Stable lo m s.logs + | .more c next => c.PrefixFrame lo ∧ ∀ i, Framed (next i) lo + +theorem Framed.cut {t : ExecutionTrace P cap E st m} (h : Framed t lo) : t.cut.PrefixFrame lo := by + induction t with + | done s n quiet halt => exact Cut.PrefixFrame.deterministic s n quiet h + | more c next ih => exact h.1.bind fun i => ih i (h.2 i) + +/-- Every finite successful prefix of the whole native execution preserves +the low bank, including prefixes on branches that cannot reach a leaf. -/ +theorem Framed.stable {t : ExecutionTrace P cap E st m} (h : Framed t lo) {bs rs} + (run : runSegment P cap st m bs = some rs) : Stable lo m rs := by + rcases h.cut.prefix bs rs run with frame | ⟨z,tail,rfl⟩ + · exact frame + · rw [PrimedSchedule.runSegment_append,(t.cut.part z).run] at run + change (runSegment P cap (t.cut.part z).state (t.cut.part z).memory tail).map _ = some rs at run + rw [t.stopped z] at run + cases tail with + | nil => + change some ((t.cut.part z).logs ++ []) = some rs at run + rw [List.append_nil] at run + exact Option.some.inj run ▸ h.cut.parts z + | cons b tail => contradiction + +end ExecutionTrace +end CompressorRecords.BranchSegments + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPrefixLevelScale.lean b/lean/OAI/Computability/VPVNP/CompressorPrefixLevelScale.lean new file mode 100644 index 0000000000..344dbd3119 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPrefixLevelScale.lean @@ -0,0 +1,114 @@ +import OAI.Computability.VPVNP.CompressorExecutionCalendar +import OAI.Computability.VPVNP.CompressorLevelCounts +import OAI.Computability.VPVNP.CursorBranchBudget + +/-! +# Uniform size bounds along partial descriptor runs + +The next graph is determined by the current selected term. Its width bound +holds as soon as that term has been chosen, even when a later selector has +no admissible terms. The remaining calendar length pays for the growth of +the field widths at every such boundary. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PrefixLevelScale + +open Compression CursorBounds CursorNetwork Filter + +variable {R : Type*} [CommRing R] {a g b l : ℕ} {X : State a g} + +/-- Bounds on the current state and on every branch reached after one more +selection. The terminal graph is included. -/ +def Within (positions width : ℕ) : {a g : ℕ} → {X : State a g} → + StateExecution R b l X → Prop + | _, _, X, .done _ => X.positions ≤ positions ∧ X.maxWireWidth ≤ width + | _, _, X, .more _ next => X.positions ≤ positions ∧ X.maxWireWidth ≤ width ∧ + ∀ i, Within positions width (next i) + +theorem Within.current {P M : ℕ} {E : StateExecution R b l X} (h : Within P M E) : + X.positions ≤ P ∧ X.maxWireWidth ≤ M := by + cases E with + | done => exact h + | more => exact ⟨h.1, h.2.1⟩ + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {f : B.Entry → R} {hf : B.IsSolution f} + +private theorem of_calendar (E : StateExecution R b l X) (o : PassOrigins B f hf E) + (rec : E.Records) {C P M : ℕ} (hC : 0 < C) (bounded : E.Bounded C rec) + (phases : List ExecutionCalendar.Phase) (follows : ExecutionCalendar.Follows E o phases) + (positions : X.positions ≤ P) (width : C ^ phases.length * (X.maxWireWidth + 1) ≤ M) : + Within P M E := by + induction E generalizing phases with + | done X => + have cur := Nat.le_mul_of_pos_left (X.maxWireWidth + 1) (Nat.pow_pos (n := phases.length) hC) + exact ⟨positions, (Nat.le_succ _).trans (cur.trans width)⟩ + | @more _ _ _ _ graph p next ih => + cases phases with + | nil => exact follows.elim + | cons phase rest => + have cur := Nat.le_mul_of_pos_left (n := C ^ (rest.length + 1)) + (graph.maxWireWidth + 1) (Nat.pow_pos hC) + have current := cur.trans width + refine ⟨positions, (Nat.le_succ _).trans current, fun i ↦ ?_⟩ + apply ih i (o.2 i) (rec.2 i) (bounded.2 i) rest (follows.2 i) + ((o.1.next_positions_le i).trans positions) + have nxt := Nat.succ_le_succ (bounded.1 i).2.2 + have stepBound := nxt.trans (bounded.1 i).2.1 + simpa only [List.length_cons, pow_succ, Nat.mul_assoc] using + (Nat.mul_le_mul_left (C ^ rest.length) stepBound).trans + (by simpa only [List.length_cons, pow_succ, Nat.mul_assoc] using width) + +theorem execute (T : ℕ) {lanes : ℕ} (h : T * S.laneBits ≤ lanes) + (X : State (S.degreeExponent 0) lanes) {P M : ℕ} (positions : X.positions ≤ P) + (width : B.growthConstant ^ T * (X.maxWireWidth + 1) ≤ M) : + Within P M (B.execute f hf T h X) := by + have bounded := (Procedure.repeat_recordBounds (B.recordBounds f hf) _ T lanes + (Nat.add_sub_of_le h).symm X).1 + apply of_calendar (B.execute f hf T h X) (executeOrigins B f hf T h X) (B.records f hf T h X) + (C := B.recordLimit) (le_max_left 1 _) bounded _ (ExecutionCalendar.execute_follows T h X) + positions + have count : (ExecutionCalendar.blocks S.steps T).length = (S.steps + 1) * T := by + simp [ExecutionCalendar.blocks, ExecutionCalendar.oneBlock, Nat.mul_comm] + rw [count, pow_mul] + exact (Nat.mul_le_mul_right _ (Nat.pow_le_pow_left (le_max_right 2 _) T)).trans width + +/-- The input-length threshold precedes the coefficient solution, the lane +split, and all partial choices of the actual descriptor program. -/ +theorem eventually_execute (B : S.Templates) (u : PairExponents B.growthConstant) + (b : ℕ) (hb : max S.laneBits 5 ≤ b) : ∀ᶠ n : ℕ in atTop, + ∀ {base lanes : ℕ} (labels : Fin (virtualBits b n) ≃ Fin base ⊕ Fin lanes) + (hD : 1 < virtualBits b n) (hT : blockCount (u.θ : ℝ) n * S.laneBits ≤ lanes) + (A : Type*) [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f), + Within (initialPositions b n) n + (B.execute f hf (blockCount (u.θ : ℝ) n) hT (pairInput S labels hD)) := by + have pos := (Rat.cast_pos (K := ℝ)).mpr u.theta_pos + have small := (Rat.cast_lt (K := ℝ)).mpr u.theta_lt + norm_num at small + have growth : 1 ≤ (B.growthConstant : ℝ) := by + exact_mod_cast (show 1 ≤ B.growthConstant by linarith [B.growthConstant_ge_two]) + filter_upwards [cursorResource_bounds b S.laneBits pos.le (by linarith) growth u.growth + (A := 1) (by norm_num) hb, eventually_ge_atTop 1] with n bounds hn + intro base lanes labels hD hT A _ f hf + apply execute _ hT _ (pairInput_positions S labels hD).le + apply Nat.cast_le (α := ℝ) |>.mp + push_cast + have hwidth : ((pairInput S labels hD).maxWireWidth : ℝ) + 1 ≤ (initialWidth b n : ℝ) + 1 := by + exact_mod_cast Nat.succ_le_succ (pairInput_maxWireWidth S labels hD) + have hr : (n : ℝ) ^ (3 / 10 : ℝ) ≤ n := by + simpa using Real.rpow_le_rpow_of_exponent_le (Nat.one_le_cast.mpr hn) + (by norm_num : (3 / 10 : ℝ) ≤ 1) + have resource := bounds.2.1 + rw [one_mul] at resource + exact (mul_le_mul_of_nonneg_left hwidth (pow_nonneg (Nat.cast_nonneg _) _)).trans + (resource.trans hr) + +end CompressorRecords.PrefixLevelScale + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPrefixScoreFit.lean b/lean/OAI/Computability/VPVNP/CompressorPrefixScoreFit.lean new file mode 100644 index 0000000000..db737f3dfa --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPrefixScoreFit.lean @@ -0,0 +1,61 @@ +import OAI.Computability.VPVNP.CompressorPrefixWorkerFit + +/-! +# Both selected layout scores fit at every reachable shrinking state + +The bound depends on the number of old sites and the largest old wire. +The selected term may be followed by an empty admissible set at a later +stage. Both score words are already bounded when the term is chosen. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.PrefixLevelScale + +open Compression CursorBounds Filter ShrinkMotif +open private shrinkMotif_count from OAI.Computability.VPVNP.PairSimulationSelectorBounds + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +open Classical in +theorem eventually_scores (b : ℕ) (hb : 1 ≤ b) : ∀ᶠ n : ℕ in atTop, + B.shrink.selectorBits < 2 ^ wordBits b n ∧ + (∀ t : Fin 4, MotifAdmission.weight relativeMass t < 2 ^ wordBits b n) ∧ + ∀ (i : Fin S.steps) {g : ℕ} + (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)), + X.positions ≤ initialPositions b n → X.maxWireWidth ≤ n → + ∀ (s : SelectedScore.Selection B X) (l : Bool), + layoutScore relativeMass (X.packingData.termWidths B.shrink X.shrinkNumber X.packingWidth s) + l < 2 ^ wordBits b n := by + let weights := ∑ t : Fin 4, MotifAdmission.weight relativeMass t + let K := weights * (fieldFactor B.shrink) ^ 2 + let bound n := K * (initialPositions b n * slotDegree S) * (n + 1) ^ 2 + have poly : PolynomiallyBounded bound := + ((PolynomiallyBounded.const K).mul ((CursorRAM.bounded_positions b).mul + (PolynomiallyBounded.const (slotDegree S)))).mul (PolynomiallyBounded.succ.pow 2) + filter_upwards [CursorRAM.eventual_word_room b hb poly, + CursorRAM.eventual_word_room b hb (PolynomiallyBounded.const weights), + CursorRAM.eventual_word_room b hb (PolynomiallyBounded.const B.shrink.selectorBits)] + with n large weightRoom selector + refine ⟨selector, fun t ↦ ?_, fun i g X sites width s l ↦ ?_⟩ + · exact (Finset.single_le_sum (f := MotifAdmission.weight relativeMass) + (fun _ _ ↦ Nat.zero_le _) (Finset.mem_univ t)).trans_lt weightRoom + · have deg : 2 ^ S.degreeExponent i.castSucc ≤ slotDegree S := + (Finset.le_sup (f := fun j : Fin (S.steps + 1) ↦ 2 ^ S.degreeExponent j) + (Finset.mem_univ i.castSucc)).trans (le_max_right _ _) + have motifs := (shrinkMotif_count X).trans (Nat.mul_le_mul sites deg) + exact (shrink_layoutScore_le B X s l).trans_lt + ((Nat.mul_le_mul (Nat.mul_le_mul_left K motifs) + (Nat.pow_le_pow_left (Nat.succ_le_succ width) 2)).trans_lt large) + +end CompressorRecords.PrefixLevelScale + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPrefixWorkerFit.lean b/lean/OAI/Computability/VPVNP/CompressorPrefixWorkerFit.lean new file mode 100644 index 0000000000..93e1639c48 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPrefixWorkerFit.lean @@ -0,0 +1,78 @@ +import OAI.Computability.VPVNP.CompressorPrefixLevelScale +import OAI.Computability.VPVNP.CompressorBlockShrinkPrefixFits +import OAI.Computability.VPVNP.CompressorRecordRefreshAdmitted +import OAI.Computability.VPVNP.CompressorSelectedTermWorker + +/-! +# Motif selector word and clock bounds at reachable boundaries + +The shrinking and refresh selectors use different native tables. Both accept +a fixed clock determined by the input length and the templates. The refresh +bound also covers the width cells emitted by the chosen continuation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.PrefixLevelScale + +open Compression CursorBounds Filter DescriptorSpace + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Fixed word-width contribution of the refresh selector for the schedule's expander and motif +tie order. -/ +def refreshConstant := PortRefresh.termConstant S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh (RefreshBlockPlan.order B) + +/-- Uniform width and clock arithmetic used in the selected refresh run. -/ +theorem eventually_refresh (b : ℕ) (hb : 1 ≤ b) : ∀ᶠ n : ℕ in atTop, + ∀ (R : Type*) [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) {g : ℕ} + (X : State S.portExponent (S.portExponent + g)), + let p := Refresh.dyadicRefreshPass X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2 + (f ∘ Sum.inr) ((B.solution_iff f).mp hf).2 + ∀ (choice : p.step.Choice), X.maxWireWidth ≤ n → (p.next choice).maxWireWidth ≤ n → + let w := wordBits b n + let s := RefreshBlockPlan.shape B + refreshConstant B + 4 * Nat.clog 2 (X.maxWireWidth + 1) ≤ w ∧ + TermWorker.budget B.refresh s.ties (s.ports * s.dH) w X.maxWireWidth ≤ + SelectedTermWorker.clock B w ∧ + (p.next choice).maxWireWidth < 2 ^ w := by + let K := max (refreshConstant B) (SelectedTermWorker.fitConstant B) + filter_upwards [DemandPreparation.eventually_live_word_fits b hb K 4 1 1, + CursorRAM.eventual_word_room b hb PolynomiallyBounded.id] with n hfit room + intro R _ f hf g X p choice input output w s + have hw : K + 4 * Nat.clog 2 (X.maxWireWidth + 1) ≤ w := + hfit _ (by simpa using input) + have native := SelectedTermWorker.budget_le (.refresh X : PassOrigin B f hf p) + ((Nat.add_le_add_right (le_max_right (refreshConstant B) _) _).trans hw) + exact ⟨(Nat.add_le_add_right (le_max_left _ _) _).trans hw, native, output.trans_lt room⟩ + +/-- Apply the actual shrinking prefix bounds directly to a partial semantic +execution at its current graph. -/ +theorem eventually_shrink (b : ℕ) (hb : 1 ≤ b) : ∀ᶠ n : ℕ in atTop, + ∀ (R : Type*) [CommRing R] (i : Fin S.steps) {g b' l' : ℕ} + (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) + (E : StateExecution R b' l' X), + Within (initialPositions b n) n E → ∀ (base blocks : ℕ) + (level : Fin (BlockProgram.layout B base (initialPositions b n) blocks).levels), + let L := BlockProgram.layout B base (initialPositions b n) blocks + let w := wordBits b n + endAddress L < 2 ^ w → ∀ cap, ShrinkBranch.prefixClock B b n ≤ cap → + ShrinkBranch.PrefixFits B X (packedIncidence L w level.val (DemandRAM.oldCount X)) + (tableBase L level.val (0 : Fin 6)) (Fin.ofNat _ 10) cap := by + filter_upwards [ShrinkBranch.eventually_prefixFits B b hb] with n fit + intro R _ i g b' l' X E live + exact fit i X live.current.1 live.current.2 + +end CompressorRecords.PrefixLevelScale + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPublishedHeadPackets.lean b/lean/OAI/Computability/VPVNP/CompressorPublishedHeadPackets.lean new file mode 100644 index 0000000000..ae5d5e8f30 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPublishedHeadPackets.lean @@ -0,0 +1,78 @@ +import OAI.Computability.VPVNP.CompressorPublishedHeadsRun +import OAI.Computability.VPVNP.CompressorBlockProgram + +/-! # Source packets for the term and DFS address publications + +The actual block uses four term pointers, then either fourteen shrinking +addresses or one refresh pointer. Each publication retains its input +outside its own field block. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PublishedHeads + +open BurstRAM DescriptorSpace BlockPlanner PhaseRecipe SourceTransport +open scoped Fin.CommRing + +variable {w : ℕ} (L : Layout) (first step : ℕ) (pub : Fin 5 → Word w) (state : Word w) + (original : Memory w) (entry : LevelFields.Entry L first pub state original) (hw : 1 < 2^w) + +/-- The four expressions published for a term's record head, stride, layout, and absolute +address. -/ +def termValues (head stride layout absolute : Expr) : Fin 4 → Expr := ![head,stride,layout,absolute] + +include entry hw in +theorem termPointers (head stride layout absolute : Expr) (fit : levelStart L (first+step)+36+4 ≤ 2^w) + (pitch : Outside (levelStart L (first+step)+36) 4 (pub 1-1).val) + (stable : ∀ m, Agree (Outside (levelStart L (first+step)+36) 4) m original → ∀ j, + (termValues head stride layout absolute j).eval pub state m = + (termValues head stride layout absolute j).eval pub state original) : + let rhs := termValues head stride layout absolute + let base := levelStart L (first+step)+36 + Published L pub state original base (fun j ↦ LevelFields.address step (36+j.val)) rhs ∧ + SourceWalk (BlockHeaderRun.OneCall pub state) (BlockProgram.termPointers step head stride layout absolute) + original (List.ofFn fun j : Fin 4 ↦ report ((base+j.val : ℕ) : Word w) ((rhs j).eval pub state original)) := by + have h := run_fields L first step 36 pub state original _ entry hw fit pitch stable + exact ⟨h, h.source⟩ + +variable {k : Type*} [_root_.Field k] {S : Compression.BlockSchedule k} (B : S.Templates) + (shape : DescriptorSpace.Shape) (i : Fin S.steps) + +include hw in +theorem dataHeads (origin abArena widthArena slotArena : Expr) + (entry' : LevelFields.Entry L first pub state original) (fit : levelStart L (first+i.val)+40+14 ≤ 2^w) + (pitch : Outside (levelStart L (first+i.val)+40) 14 (pub 1-1).val) + (stable : ∀ m, Agree (Outside (levelStart L (first+i.val)+40) 14) m original → ∀ j, + (BlockDataHeads.values B shape i origin abArena widthArena slotArena j).eval pub state m = + (BlockDataHeads.values B shape i origin abArena widthArena slotArena j).eval pub state original) : + let rhs := BlockDataHeads.values B shape i origin abArena widthArena slotArena + let base := levelStart L (first+i.val)+40 + Published L pub state original base (fun j ↦ LevelFields.address i.val (40+j.val)) rhs ∧ + SourceWalk (BlockHeaderRun.OneCall pub state) (BlockDataHeads.visits B shape i origin abArena widthArena slotArena) + original (List.ofFn fun j : Fin 14 ↦ report ((base+j.val : ℕ) : Word w) ((rhs j).eval pub state original)) := by + have h := run_fields L first i.val 40 pub state original _ entry' hw fit pitch stable + exact ⟨h, h.source⟩ + +include entry hw in +theorem refreshHead (fit : levelStart L (first+step)+40+1 ≤ 2^w) + (pitch : Outside (levelStart L (first+step)+40) 1 (pub 1-1).val) : + let base := levelStart L (first+step)+40 + let next := LevelFields.atLevel (step+1) + Published L pub state original base (fun j : Fin 1 ↦ LevelFields.address step (40+j.val)) (fun _ ↦ next) ∧ + SourceWalk (BlockHeaderRun.OneCall pub state) [publish (LevelFields.address step 40) next] + original [report ((base : ℕ) : Word w) (next.eval pub state original)] := by + have h := run_fields L first step 40 pub state original (fun _ : Fin 1 ↦ LevelFields.atLevel (step+1)) + entry hw fit pitch (fun m frame _ ↦ by + let e : LevelFields.Entry L first pub state m := ⟨entry.pointer,(frame _ pitch).trans entry.pitch⟩ + rw [LevelFields.eval_atLevel e,LevelFields.eval_atLevel entry]) + refine ⟨h,?_⟩ + simpa only [List.ofFn_succ, Fin.val_zero, Nat.add_zero, List.ofFn_zero] using h.source + +end CompressorRecords.PublishedHeads + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPublishedHeadWindows.lean b/lean/OAI/Computability/VPVNP/CompressorPublishedHeadWindows.lean new file mode 100644 index 0000000000..0dc6473580 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPublishedHeadWindows.lean @@ -0,0 +1,167 @@ +import OAI.Computability.VPVNP.CompressorPublishedHeadPackets +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorWindowPackets +import OAI.Computability.VPVNP.CompressorSourceScanned + +/-! # Installing consecutive header writes at their block ordinals + +The emitted source reports determine both the frame at every intermediate +visit and the physical branch tapes. The global fixed catalog supplies a +uniform clock for the six-instruction publishers. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PublishedHeads + +open BurstRAM DescriptorSpace BlockPlanner PhaseRecipe SourceTransport Schedule +open scoped Fin.CommRing + + +variable {w N : ℕ} + +/-- One publication visit per consecutive header field, using the corresponding right-hand-side +expression. -/ +def fieldVisits (step offset : ℕ) (rhs : Fin N → Expr) : List Visit := + List.ofFn fun j ↦ publish (LevelFields.address step (offset+j.val)) (rhs j) + +/-- Reports writing consecutive fields from the supplied base, with each right-hand side +evaluated in the entry memory. -/ +def fieldReports (base : ℕ) (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) (rhs : Fin N → Expr) := + List.ofFn fun j ↦ report ((base+j.val : ℕ) : Word w) ((rhs j).eval pub st m) + +private theorem reports_write (base : ℕ) (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) + (rhs : Fin N → Expr) (fit : base+N ≤ 2^w) : + Writes (fun a ↦ ¬ Outside base N a) (eventLog (fieldReports base pub st m rhs)) := by + intro a v hav + obtain ⟨r,hr,hev⟩ := List.mem_flatMap.mp hav + obtain ⟨j,rfl⟩ := List.mem_ofFn.mp hr + have address : ((base+j.val : ℕ) : Word w).val = base+j.val := Nat.mod_eq_of_lt (by have := j.isLt; omega) + simp only [report,List.mem_cons,List.not_mem_nil,or_false,reduceCtorEq,false_or,or_self] at hev + rw [(Event.write.inj hev).1,address] + unfold Outside + have := j.isLt + omega + +/-- Strengthen each actual visit along a chronological walk. The common +frame is propagated using the write footprint of the complete report list. -/ +private theorem framedWalk {J : Type*} {run more : J → Memory w → List (Report w) → Prop} + {js : List J} {m original : Memory w} {rs : List (Report w)} {keep : ℕ → Prop} + (walk : SourceWalk run js m rs) (write : Writes (fun a ↦ ¬ keep a) (eventLog rs)) + (frame : Agree keep m original) + (lift : ∀ j ∈ js, ∀ mem log, Agree keep mem original → run j mem log → more j mem log) : + SourceWalk more js m rs := by + induction walk with + | done => exact .done _ + | @next j js mem head tail step _ ih => + have wr (a v) (h : Event.write a v ∈ eventLog head ++ eventLog tail) : ¬ keep a.val := + write a v (by simpa only [eventLog,List.flatMap_append] using h) + refine .next (lift j (List.mem_cons_self ..) mem head frame step) (ih ?_ ?_ ?_) + · exact fun a v h ↦ wr a v (List.mem_append_right _ h) + · intro a ha + exact (after_outside (data := fun a ↦ ¬ keep a) mem (fun x y h ↦ wr x y (List.mem_append_left _ h)) (not_not_intro ha)).trans (frame a ha) + · exact fun q h ↦ lift q (List.mem_cons_of_mem j h) + +theorem chronological_tapes {A : Script} (m : Memory w) + (ps : List (SourceWalk.Packet (SourceOnline.Visit A w) w)) (chron : SourceWalk.Chronological SourceOnline.Visit.Runs m ps) : + ps.flatMap (fun p ↦ p.stage.choices) = branchPaths (ps.flatMap SourceWalk.Packet.reports) := by + induction ps generalizing m with + | nil => rfl + | cons p ps ih => + obtain ⟨rfl,run,tail⟩ := chron + rw [List.flatMap_cons,List.flatMap_cons,branchPaths,List.map_append,ih _ tail] + exact congrArg (· ++ _) ((runSegment_iff ..).mp run).2.2.symm + +variable {k : Type*} [_root_.Field k] {S : Compression.BlockSchedule k} (B : S.Templates) +variable (base : Word w) (positions blocks t step offset : ℕ) (rhs : Fin N → Expr) +local notation "prog" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog prog)) base +local notation "pub" => Schedule.Ports.data pt +local notation "first" => Script.levelsPerBlock prog * t +local notation "st" => (levelStart L (first) : Word w) +local notation "head" => levelStart L (first+step) +local notation "D" => Window.operandRegion prog L base +local notation "stages" => fieldVisits step offset rhs +local notation "Pkt" => SourceWalk.Packet (SourceOnline.Visit prog w) w + +/-- The exact source image and its verified occurrence in the fixed online +program. All packets have the ordinal at which their planner will run. -/ +structure Installed (W : Window prog stages) (cap : ℕ) (m : Memory w) : Prop where + source : Published L pub st m (head+offset) (fun j ↦ LevelFields.address step (offset+j.val)) rhs + online : ∃ ps : List Pkt, SourceOnline.Group prog L base cap ((prog).initial.length+t*(prog).block.length+W.before.length) (directoryRows L) m ps ∧ + ps.map (fun p ↦ p.stage.phase) = W.indices ∧ + ps.flatMap SourceWalk.Packet.reports = fieldReports (head+offset) pub st m rhs ∧ + ps.flatMap (fun p ↦ p.stage.choices) = List.replicate N [] + +theorem level_room (ltBlock : t < blocks) (substep : step ≤ S.steps) (fit : endAddress L < 2^w) : + head+66 ≤ 2^w := by + have idx : first+step < (L).levels := by + have hb := Nat.mul_le_mul_left (S.steps+1) ltBlock + change (S.steps+1)*t+step < 1+(S.steps+1)*blocks + rw [Nat.mul_succ] at hb + omega + have h := DescriptorSpace.level_room L fit ⟨first+step,idx⟩ + change levelStart L (first+step+1) < 2^w at h + have nh : levelHeaderWords L = 66 := rfl + simp only [levelStart,Nat.succ_mul,levelWords,nh] at * + omega + +theorem windowLive {visits : List Visit} (W : Window prog visits) (ltBlock : t < blocks) (j : Fin visits.length) : + Window.ordinal (A:=prog) t (W.index j) < directoryRows L := by + rw [W.ordinal_index,BlockProgram.directory_rows,(prog).calendar_total] + have hp := (W.position j).isLt + have hb := Nat.mul_le_mul_right (prog).block.length ltBlock + rw [Nat.succ_mul] at hb + omega + +/-- Install one of the actual publication groups. Each source load has a +specified read address, and preceding writes in the group preserve it. -/ +theorem install (W : Window prog stages) (cap : ℕ) (m : Memory w) (ltBlock : t < blocks) + (fit : endAddress L < 2^w) (substep : step ≤ S.steps) (high : offset+N ≤ 54) + (rows : m (pt).rows.val = (directoryRows L : Word w)) (pitch : m (pub 1-1).val = (levelWords L : Word w)) + (clock : SourceOnline.scanCap prog 7 ≤ cap) + (stable : ∀ mem, Agree (Outside (head+offset) N) mem m → ∀ j, + (rhs j).eval pub st mem = (rhs j).eval pub st m) + (support : ∀ mem, Agree (Outside (head+offset) N) mem m → ∀ j, + (rhs j).ReadsFrom D pub st mem) : Installed B base positions blocks t step offset rhs W cap m := by + have room := level_room B base positions blocks t step ltBlock substep fit + have fits : levelStart L 0 < 2^w := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + have controls := Window.lowCells (A:=prog) L base rfl rfl fits + have pp : Outside (head+offset) N (pub 1-1).val := .inl (controls.2.trans_le + ((levelStart_mono L (Nat.zero_le _)).trans (Nat.le_add_right ..))) + have extent : head+offset+N ≤ 2^w := by omega + have entry : LevelFields.Entry L (first) pub st m := ⟨rfl,pitch⟩ + have published := run_fields L (first) step offset pub st m rhs entry (by omega) extent pp stable + refine ⟨published,?_⟩ + let reports := fieldReports (head+offset) pub st m rhs + have raw : SourceWalk (Window.Raw (A:=prog) L base t 7) stages m reports := by + apply framedWalk published.walk (reports_write _ pub st m rhs extent) (fun _ _ ↦ rfl) + intro v hv mem log frame run + obtain ⟨j,rfl⟩ := List.mem_ofFn.mp hv + refine ⟨7,[[]],le_rfl,run,⟨trivial,trivial,?_⟩⟩ + intro l + fin_cases l + · exact ⟨⟨trivial,trivial,⟨trivial,trivial⟩,Or.inr (.inl rfl)⟩,trivial⟩ + · exact support mem frame j + have bounds (j : Fin (prog).size) : + ((prog).plan.recipes j).2.code.length+1+2*Online.N (prog).size (prog).size+5 ≤ cap ∧ + 7+3+4*(((prog).catalog j).params+1)+2*Online.N (prog).size (prog).size+5 ≤ cap := by + let p : SourceOnline.Visit prog w := HeaderPacket.attach prog j pub st m 7 [[]] + exact SourceOnline.scanCap_clocks (p := ⟨p,m,[]⟩) 7 (by rfl) clock + obtain ⟨ps,hp,ph,rs⟩ := W.group L base t rfl rfl fits cap 7 m reports raw rows pitch + (windowLive B base positions blocks t W ltBlock) (fun j _ ↦ (bounds j).1) (fun j _ ↦ (bounds j).2) + refine ⟨ps,hp,ph,rs,?_⟩ + rw [chronological_tapes m ps hp.chronological,rs] + change branchPaths (List.ofFn _) = _ + rw [branchPaths,List.map_ofFn] + change List.ofFn (fun _ : Fin N ↦ ([] : List Bool)) = _ + simp + +end CompressorRecords.PublishedHeads + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPublishedHeadsRun.lean b/lean/OAI/Computability/VPVNP/CompressorPublishedHeadsRun.lean new file mode 100644 index 0000000000..40040c6fb3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPublishedHeadsRun.lean @@ -0,0 +1,195 @@ +import OAI.Computability.VPVNP.CompressorBlockHeaderPacket + +/-! +# Native publication of consecutive DFS header words + +Each published head executes one fixed six-instruction write and returns its +cursor at one. The following source packet evaluates its operands on the +memory left by that write. The frame and readback proofs ensure that each +value is the one computed from the original graph and its arena pointers. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PublishedHeads + +open BurstRAM DescriptorSpace PhaseRecipe BlockPlanner BlockHeaderRun SourceTransport SourceOnline +open scoped Fin.CommRing + +variable {w N : ℕ} + +/-- Native six-event report for publishing one word at a specified address and returning cursor +one. -/ +def report (dest value : Word w) : Report w := + ⟨[.tick,.tick,.tick,.write dest value,.tick,.tick],some 1⟩ + +theorem one (L : Layout) (pub : Fin 5 → Word w) (s : Word w) (dest val : Expr) (m : Memory w) + (hw : 1 < 2^w) (hd : levelStart L 0 ≤ (dest.eval pub s m).val) : + let d := dest.eval pub s m + let x := val.eval pub s m + HeaderPacket.Run L pub s (publish dest val) m [report d x] 7 [[]] ∧ + after m (eventLog [report d x]) = writeMemory m d x := by + intro d x + let par : Fin 2 → Word w := ![d,x] + have raw : rawCall (publish dest val) pub s m 7 = some (report d x) := by + have eq : (fun i ↦ ((publish dest val).params i).eval pub s m) = par := by + funext i; fin_cases i <;> rfl + unfold rawCall + rw [eq] + have h := (publish_native dest val par 0 m).1 + have i₀ : (publish dest val).initial.eval pub s m = 0 := Nat.cast_zero + have p₀ : par 0 = d := rfl + have p₁ : par 1 = x := rfl + simpa only [i₀,p₀,p₁,report,zero_add] using h + refine ⟨HeaderPacket.singleton (by decide) raw ?_ ?_ ?_ ?_,rfl⟩ + · apply Fin.lt_def.mpr + change 0 % 2^w < 1 % 2^w + simp [Nat.mod_eq_of_lt hw] + · change some (1 : Word w) = some ((1 : ℕ) : Word w); simp + · intro a v hv; simp [report] at hv + · intro a v hv; simp [report] at hv; exact hv.1 ▸ hd + +/-- Memory after the fixed ordered publication, expressed solely using the +original graph operands and the destination block. -/ +def image (pub : Fin 5 → Word w) (state : Word w) (original : Memory w) (base : ℕ) (rhs : Fin N → Expr) := + after original (eventLog (List.ofFn fun j : Fin N ↦ report ((base+j.val : ℕ) : Word w) + ((rhs j).eval pub state original))) + +/-- All addresses outside a contiguous field block retain their old words. -/ +def Outside (base count a : ℕ) := a < base ∨ base+count ≤ a + +variable (L : Layout) (pub : Fin 5 → Word w) (state : Word w) (original : Memory w) + (base : ℕ) (dst rhs : Fin N → Expr) + +local notation "stage" => (fun j ↦ publish (dst j) (rhs j)) +local notation "packet" => (fun j : Fin N ↦ report ((base + Fin.val j : ℕ) : Word w) (Expr.eval pub state original (rhs j))) +local notation "kernel" => (fun v m rs ↦ HeaderPacket.Run L pub state v m rs 7 [[]]) + +variable (hw : 1 < 2^w) (data : levelStart L 0 ≤ base) (fit : base+N ≤ 2^w) + (stable : ∀ m, Agree (Outside base N) m original → ∀ j : Fin N, + (dst j).eval pub state m = ((base+j.val : ℕ) : Word w) ∧ + (rhs j).eval pub state m = (rhs j).eval pub state original) + +include hw data fit stable in +private theorem run_list (js : List (Fin N)) (nd : js.Nodup) (mem : Memory w) + (frame : Agree (Outside base N) mem original) : + let rs := js.map packet + SourceWalk kernel (js.map stage) mem rs ∧ + (∀ j ∈ js, after mem (eventLog rs) (base+j.val) = (rhs j).eval pub state original) ∧ + ∀ a, (∀ j ∈ js, a ≠ base+j.val) → after mem (eventLog rs) a = mem a := by + induction js generalizing mem with + | nil => + refine ⟨.done _,?_,fun _ _ ↦ rfl⟩ + intro j hj; cases hj + | cons j js ih => + let addr : Word w := ((base+j.val : ℕ) : Word w) + let x := (rhs j).eval pub state original + let mid := writeMemory mem addr x + have atAddr : addr.val = base+j.val := Nat.mod_eq_of_lt (by have := j.isLt; omega) + obtain ⟨dval,xval⟩ := stable mem frame j + have hmin : levelStart L 0 ≤ ((dst j).eval pub state mem).val := by + rw [dval]; change _ ≤ addr.val; rw [atAddr]; omega + obtain ⟨call,update⟩ := one L pub state (dst j) (rhs j) mem hw hmin + rw [dval,xval] at call update + have midFrame : Agree (Outside base N) mid original := by + intro a ha + have neq : a ≠ base+j.val := by have := j.isLt; unfold Outside at ha; omega + change (if a = addr.val then _ else _) = _ + rw [atAddr,ite_eq_right neq] + exact frame _ ha + obtain ⟨tail,read,keep⟩ := ih (List.nodup_cons.mp nd).2 mid midFrame + have eq : after mem (eventLog ((j::js).map packet)) = after mid (eventLog (js.map packet)) := by + exact (SourceWalk.after_append mem [packet j] (js.map packet)).trans + (congrArg (fun m ↦ after m (eventLog (js.map packet))) update) + have tail' : SourceWalk kernel (js.map stage) (after mem (eventLog [packet j])) (js.map packet) := by + rw [update]; exact tail + refine ⟨SourceWalk.next call tail',?_,?_⟩ + · intro k hk + rw [eq] + rcases List.mem_cons.mp hk with rfl | hk + · rw [keep _ (fun l hl e ↦ (List.nodup_cons.mp nd).1 (by + rw [show k = l from Fin.ext (Nat.add_left_cancel e)]; exact hl))] + simp [mid,writeMemory,atAddr,x] + · exact read k hk + · intro a ha + rw [eq,keep _ (fun k hk ↦ ha k (List.mem_cons_of_mem _ hk))] + simp [mid,writeMemory,atAddr,ha j (List.mem_cons_self ..)] + +/-- A complete contiguous publication supplies a chronological native source +walk, the fourteen/four/one-word readback and the frame of every other cell. -/ +structure Published : Prop where + walk : SourceWalk kernel (List.ofFn stage) original (List.ofFn packet) + stored (j : Fin N) : after original (eventLog (List.ofFn packet)) (base+j.val) = + (rhs j).eval pub state original + outside (a : ℕ) : Outside base N a → after original (eventLog (List.ofFn packet)) a = original a + +include hw data fit stable in +theorem run : Published L pub state original base dst rhs := by + obtain ⟨walk,read,keep⟩ := run_list L pub state original base dst rhs hw data fit stable + (List.finRange N) (List.nodup_finRange _) original (fun _ _ ↦ rfl) + have ofFn {α : Type} (f : Fin N → α) : (List.finRange N).map f = List.ofFn f := by + apply List.ext_getElem <;> simp + rw [ofFn stage,ofFn packet] at walk + rw [ofFn packet] at read keep + refine ⟨walk,fun j ↦ read j (List.mem_finRange _),fun a ha ↦ keep _ (fun j _ ↦ ?_)⟩ + have := j.isLt + unfold Outside at ha + omega + +/-- Specialize the consecutive destinations to fields of the old level +header. Its physical pitch survives every publication. -/ +theorem run_fields (L : Layout) (first step offset : ℕ) (pub : Fin 5 → Word w) (state : Word w) + (original : Memory w) (rhs : Fin N → Expr) (entry : LevelFields.Entry L first pub state original) + (hw : 1 < 2^w) (fit : levelStart L (first+step)+offset+N ≤ 2^w) + (pitch : Outside (levelStart L (first+step)+offset) N (pub 1-1).val) + (stable : ∀ m, Agree (Outside (levelStart L (first+step)+offset) N) m original → + ∀ j, (rhs j).eval pub state m = (rhs j).eval pub state original) : + Published L pub state original (levelStart L (first+step)+offset) + (fun j ↦ LevelFields.address step (offset+j.val)) rhs := by + apply run _ _ _ _ _ _ _ hw _ fit + · intro m frame j + have e : LevelFields.Entry L first pub state m := ⟨entry.pointer,(frame _ pitch).trans entry.pitch⟩ + refine ⟨?_, stable m frame j⟩ + rw [LevelFields.eval_address e] + simp only [Nat.add_assoc] + · unfold levelStart; omega + +theorem Published.source (h : Published L pub state original base dst rhs) : + SourceWalk (OneCall pub state) (List.ofFn stage) original (List.ofFn packet) := by + have weaken {js : List BlockPlanner.Visit} {m : Memory w} {rs : List (Report w)} + (walk : SourceWalk kernel js m rs) : SourceWalk (OneCall pub state) js m rs := by + induction walk with + | done => exact .done _ + | next head _ ih => exact .next ⟨7,head.execute⟩ ih + exact weaken h.walk + +/-- The chronological packets have the exact execution, progress and source +footprints required by the online scheduler. -/ +theorem Published.packets (h : Published L pub state original base dst rhs) : + ∃ ps : List (SourceWalk.Packet BlockPlanner.Visit w), + ps.map SourceWalk.Packet.stage = List.ofFn stage ∧ + ps.flatMap SourceWalk.Packet.reports = List.ofFn packet ∧ + SourceWalk.Chronological kernel original ps := h.walk.packets + +theorem packet_cost : RAMBuckets.cost Report.probes (List.ofFn packet) = 2*N := by + generalize h : List.ofFn packet = rs + have lens : rs.length = N := h ▸ List.length_ofFn + have cap (r : Report w) (hr : r ∈ rs) : r.probes = 1 := by + rw [← h,List.mem_ofFn] at hr + obtain ⟨i,rfl⟩ := hr; rfl + rw [← lens] + clear h lens + induction rs with + | nil => rfl + | cons r rs ih => + change 1+r.probes+RAMBuckets.cost Report.probes rs = _ + rw [cap r (List.mem_cons_self ..),ih (fun z hz ↦ cap z (List.mem_cons_of_mem _ hz)),List.length_cons] + omega + +end CompressorRecords.PublishedHeads + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorPublishedScoreRoom.lean b/lean/OAI/Computability/VPVNP/CompressorPublishedScoreRoom.lean new file mode 100644 index 0000000000..e9f3cd3522 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorPublishedScoreRoom.lean @@ -0,0 +1,90 @@ +import OAI.Computability.VPVNP.CompressorBlockHeadStability +import OAI.Computability.VPVNP.CompressorShrinkScoreOperands + +/-! +# The shrinking layout bit lies beyond the published heads + +The term planner starts in the old level's first scratch table. The selected +layout bit follows the motif term rows in that table. Its numerical address +therefore lies above the scalar cells at offsets 36 through 53. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PublishedScoreRoom + +open BurstRAM Compression DescriptorSpace ShrinkBlockInputs +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) +variable {pub : Fin 5 → Word w} {st : Word w} {mem : Memory w} {first : ℕ} + +local notation "chosen" => selectedInputs B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0) + +/-- Reading the typed old header identifies the actual term base and row count. -/ +theorem of_header (start : ℕ) {L : Layout} + (header : ShrinkHeaderReads.Header i X T start L first mem) + (entry : LevelFields.Entry L first pub st mem) + (afterHeader : levelStart L (first+i.val)+54 ≤ start) + (termRoom : ShrinkInput.termEnd X start 10 < 2^w) + (selectedFit : SelectedArena.Fits X (ShrinkInput.termHead X start) (10 : Word w)) : + levelStart L (first+i.val)+54 ≤ ((SelectedPlan.layoutCell chosen).eval pub st mem).val := by + let term := ShrinkInput.termHead (w := w) X start + obtain ⟨hn,ht⟩ := ScorePackets.term_values B i X T start pub st mem (header.reads B entry) termRoom + have word : (term.val : Word w) = term := Fin.ext (Nat.mod_eq_of_lt term.isLt) + have stride : (10 : Word w).val = 10 := by + change (10 : ℕ) % 2^w = 10 + exact Nat.mod_eq_of_lt (by have := header.room; omega) + have below : term.val+SelectedArena.motifs X*10+2 < 2^w := by + change term.val+SelectedArena.motifs X*(10 : Word w).val+3+4*SelectedArena.positions X+ + 4*DemandRAM.absoluteCount X < 2^w at selectedFit + rw [stride] at selectedFit + omega + exact BlockHeadStability.layoutCell_after B i (levelStart L (first+i.val)) term.val (SelectedArena.motifs X) + (ht.trans word.symm) hn (afterHeader.trans (ScorePackets.start_le_term i X start termRoom)) below + +variable (base positions blocks : ℕ) + +local notation "L" => BlockProgram.layout B base positions blocks +local notation "idx" => first+i.val +local notation "start" => tableBase L idx (0 : Fin 6) + +/-- The compiled table allocation supplies all address bounds, including the +room needed for the ten-word motif rows and the selected-layout score. -/ +theorem allocated (header : ShrinkHeaderReads.Header i X T start L first mem) + (entry : LevelFields.Entry L first pub st mem) (levelValid : idx < (L).levels) + (sites : X.positions ≤ positions) (totalRoom : endAddress L < 2^w) : + levelStart L idx+54 ≤ ((SelectedPlan.layoutCell chosen).eval pub st mem).val := by + let amount := X.positions*ShrinkLevelSpace.tableFactor S + have degree : 2^S.degreeExponent i.castSucc ≤ slotDegree S := + (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ _)).trans + (le_max_right ..) + have factors : ShrinkLevelSpace.tableFactor S ≤ slotDegree S*BlockProgram.fieldCount B := by + have h : ShrinkLevelSpace.tableFactor S ≤ BlockProgram.fieldCount B := + (le_max_left ..).trans (Nat.le_add_right ..) + exact h.trans (Nat.le_mul_of_pos_left _ ((Nat.two_pow_pos _).trans_le degree)) + have capacity : amount ≤ tableWords L := by + change _ ≤ positions*slotDegree S*BlockProgram.fieldCount B + rw [Nat.mul_assoc] + exact Nat.mul_le_mul sites factors + have fits := tableStop_lt L ⟨idx,levelValid⟩ (0 : Fin 6) capacity totalRoom + have ends := ShrinkLevelSpace.packed_ends S i X start 0 0 0 w + have termRoom := ends.2.1.trans_lt fits + have retained : SelectedFinish.stop X (ShrinkInput.termHead (w := w) X start) (10 : Word w) < 2^w := + ends.2.2.1.trans_lt fits + have selectedFit : SelectedArena.Fits X (ShrinkInput.termHead X start) (10 : Word w) := + ((Nat.le_add_right ..).trans (Nat.le_add_right ..) : SelectedArena.endAddr X _ _ ≤ + SelectedFinish.stop X (ShrinkInput.termHead X start) (10 : Word w)).trans_lt retained + have afterHeader : levelStart L idx+54 ≤ start := by + change levelStart L idx+54 ≤ levelStart L idx+66+6*slotCapacity L+0*tableWords L + omega + exact of_header B i X T start header entry afterHeader termRoom selectedFit + +end CompressorRecords.PublishedScoreRoom + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorReaderBudgets.lean b/lean/OAI/Computability/VPVNP/CompressorReaderBudgets.lean new file mode 100644 index 0000000000..fc4759146e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorReaderBudgets.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.CompressorEvaluatorAdvice +import OAI.Computability.VPVNP.CompressorLabelReadback +import OAI.Computability.VPVNP.LabelEvaluatorReaderWidth +import OAI.Computability.VPVNP.MacaulayLeafBudgets +import OAI.Computability.VPVNP.JointScalarLeafResources + +/-! # Uniform raw matrix-reader budgets for the actual compressor equations + +The widths and the two bounds are fixed for the input length and circuit-size +exponent. They cover the prime and affine slice selected from any circuit at +that length, all integer equation queries, and the operation-dependent target +row. The word width can be increased for the outer rank computation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open LabelEvaluator JointLabelSystem RadicalCertificate.MonomialIndex +open PolynomiallyBounded + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Reader plan sized for the compressor's equations, joint labels, degree bound, and advised +prime header. -/ +noncomputable def compressorReaderPlan (q c n : ℕ) : ReaderPlan := + readerPlan (2^n+Fintype.card B.EquationIndex) (B.compressorLabelCount c n) + (B.compressorDegree n) (B.compressorHeaderWidth q c n) + +/-- Upper bound on the extension degree needed by the compressor reader at the given +characteristic and input length. -/ +noncomputable def readerDegreeBudget (q c n : ℕ) := + readerExtensionBound (B.compressorLabelCount c n) (B.compressorDegree n) (B.compressorHeaderWidth q c n) + +/-- Arithmetic limb-width budget derived from the compressor's prime-header width. -/ +noncomputable def readerLimbBudget (q c n : ℕ) := + readerLimbWidth (B.compressorHeaderWidth q c n) + +theorem compressorReaderWidths (q c : ℕ) : + PolynomiallyBounded (fun n => (B.compressorReaderPlan q c n).wordWidth) ∧ + PolynomiallyBounded (B.readerDegreeBudget q c) ∧ PolynomiallyBounded (B.readerLimbBudget q c) := by + have he := clog_add (clog_pow (clog (PolynomiallyBounded.const 2)) PolynomiallyBounded.id) + (clog (PolynomiallyBounded.const (Fintype.card B.EquationIndex))) + have ht := B.compressorLabelCount_polynomial c + have hd := B.compressorDegree_polynomial.clog + have hb := B.compressorHeaderWidth_polynomial q c + have h := readerFieldWidths_polynomial ht hd hb + exact ⟨readerWordWidth_polynomial he ht hd hb,h.2,h.1⟩ + +theorem compressorReaderCovers (q c : ℕ) {n : ℕ} (hn : 2 ≤ n) (p : Nat.Primes) + (M : Model p (B.compressorDegree n) (B.compressorEquations hn c)) + (hp : q ≠ 0 → p.val = q) (hz : q=0 → p.val ≤ 2^B.compressorPrimeBits c n) : + (B.compressorReaderPlan q c n).Covers (M.queryData (B.compressorCoeff hn c)) ∧ + SliceField.extensionDegree p.val (columnCountBound (B.compressorLabelCount c n) (B.compressorDegree n)) + ≤ B.readerDegreeBudget q c n ∧ SliceArithmetic.Word.workingWidth p.val ≤ B.readerLimbBudget q c n := by + have hb := (B.prime_fits_compressorHeader p hp hz).le + have h := readerFieldWidths (t := B.compressorLabelCount c n) (d := B.compressorDegree n) hb + exact ⟨readerPlan_covers M (B.compressorCoeff hn c) hb,h.2,h.1⟩ + +/-- The bank, peak space and binary clock exponent supplied to the actual +Macaulay reader are polynomially bounded before selecting the circuit. -/ +theorem compressorRawReaderBudgets (q c : ℕ) {w : ℕ → ℕ} (hw : PolynomiallyBounded w) : + ∃ signedSpace signedExp : ℕ → ℕ, PolynomiallyBounded signedSpace ∧ PolynomiallyBounded signedExp ∧ + (PolynomiallyBounded fun n => (B.compressorReaderPlan q c n).live + (B.readerDegreeBudget q c n) (B.readerLimbBudget q c n) (w n) (signedSpace n)) ∧ + (PolynomiallyBounded fun n => (B.compressorReaderPlan q c n).armSpace + (B.readerDegreeBudget q c n) (B.readerLimbBudget q c n) (w n) (signedSpace n)) ∧ + (PolynomiallyBounded fun n => Nat.clog 2 ((B.compressorReaderPlan q c n).readTime + (B.readerDegreeBudget q c n) (B.readerLimbBudget q c n) (w n) (signedSpace n) (signedExp n))) ∧ + ∀ n (hn : 2 ≤ n) (p e v : ℕ), e ≤ B.readerDegreeBudget q c n → v ≤ B.readerLimbBudget q c n → + let L := JointScalar.Leaf.layout B.Entry B.EquationIndex B.equation c hn (w n) p e v + let C := JointScalar.checker B.Entry B.EquationIndex B.equation c hn (w n) + let b := JointScalar.Leaf.bankSize L (w n) (B.compressorLabelCount c n * w n) + let work := JointScalar.Leaf.localCost L b + max (UniversalCountStack.stackLimit C) b + work ≤ signedSpace n ∧ + 2*(2^L.witnessBits * UniversalCountStack.perChoice C) + work ≤ 2^(signedExp n) := by + obtain ⟨_,he,hv⟩ := B.compressorReaderWidths q c + obtain ⟨sp,ex,hsp,hex,hcall⟩ := JointScalar.Leaf.budgets B.Entry B.EquationIndex B.equation c hw hw he hv + have ht := B.compressorLabelCount_polynomial c + have hd := B.compressorDegree_polynomial.clog + have hb := B.compressorHeaderWidth_polynomial q c + have hq := clog_pow ((PolynomiallyBounded.const 2).clog) + (((PolynomiallyBounded.const 1).add (columnCountBound_clog ht hd)).add hb) + obtain ⟨hl,hs,hx⟩ := ReaderPlan.leaf_resources (B.compressorReaderPlan q c) hw he hv hsp hex ht hd + (pointCountBound_clog ht hd) hq + exact ⟨sp,ex,hsp,hex,hl,hs,hx,fun n hn p e v hed hvw => hcall n hn p e v (w n) hed hvw le_rfl⟩ + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorReaderEnvelope.lean b/lean/OAI/Computability/VPVNP/CompressorReaderEnvelope.lean new file mode 100644 index 0000000000..2f74fb26d4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorReaderEnvelope.lean @@ -0,0 +1,47 @@ +import OAI.Computability.VPVNP.CompressorUniformEvaluator +import OAI.Computability.VPVNP.CompressorSliceReader + +/-! # Uniform envelope of the physical compressor-coordinate readers + +For fixed characteristic and circuit exponent the same advice length bound +covers every eligible prime, compressor slice and coordinate call. The +Cramer query clock and its peak space enter on different scales. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression.BlockSchedule.Templates + +open LabelEvaluator RankQuery.Stack.Coordinate + +variable {k : Type*} [Field k] {S : BlockSchedule k} (B : S.Templates) + +theorem exists_compressor_reader_envelope + (ps : List (Evaluator.WeightedStep.Port CompressorReader.Ports)) (q c : ℕ) : + ∃ a : ℕ → ℕ, PolynomiallyBounded a ∧ ∀ n, ∀ (hn : 2≤n) (p : Nat.Primes), + (q ≠ 0 → p.val=q) → (q=0 → p.val ≤ 2^B.compressorPrimeBits c n) → + ∀ M : Model p (B.compressorDegree n) (B.compressorEquations hn c), + ∃ H : B.SliceReaderAdvice M (CompressorReader.read true) (CompressorReader.read false), H.envelope ps ≤ a n := by + have hw := B.coordinateWidth_polynomial q c + obtain ⟨sp,ex,_,_,hfit,hcost⟩ := B.coordinateBudgets CompressorReader.Parts CompressorReader.Work + CompressorReader.K q c hw + let cost (n : ℕ) := B.coordinateBudget CompressorReader.Parts CompressorReader.Work CompressorReader.K + q c n (B.coordinateWidth q c n) (sp n) (ex n) + obtain ⟨_,he,hv⟩ := B.compressorReaderWidths q c + have hspace : PolynomiallyBounded (fun n => (cost n).space) := hcost.space + have htime : PolynomiallyBounded (fun n => Nat.clog 2 (cost n).time) := hcost.time + obtain ⟨a,ha,bound⟩ := B.exists_reader_envelope ps (CompressorReader.read true) (CompressorReader.read false) + q c (B.coordinateWidth q c) (B.readerDegreeBudget q c) (B.readerLimbBudget q c) + (fun n => (cost n).space) (fun n => (cost n).space) (fun n => Nat.clog 2 (cost n).time) + hw he hv hspace hspace htime 0 (fun n _ hn p hp hz M => by + obtain ⟨H,hi,hd,hv,hs,hm,hx⟩ := B.exists_sliceReaderAdvice q c hfit n hn p hp hz M + exact ⟨H,hi.le,hd,hv,hs,hm,hx⟩) + exact ⟨a,ha,fun n => bound n (Nat.zero_le _)⟩ + +end Compression.BlockSchedule.Templates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorReaderTypes.lean b/lean/OAI/Computability/VPVNP/CompressorReaderTypes.lean new file mode 100644 index 0000000000..afc6252a84 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorReaderTypes.lean @@ -0,0 +1,57 @@ +import OAI.Computability.VPVNP.MacaulayOrdinary +import OAI.Computability.VPVNP.RankCoordinateSelectedAdvice + +/-! # Fixed ports of the advised compressor-coordinate reader + +The index and scalar values vary with the model, while the set of advice and +workspace ports below is the same for every prime, length and operation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +set_option maxRecDepth 10000 + +namespace CompressorReader + +open RankQuery.Stack RankQuery.Stack.Coordinate + +/-- Raw advice-port type used for Macaulay matrix entries by the compressor coordinate reader. -/ +abbrev K := MacaulayRead.BaseAdvice.RawPort +/-- Denominator, raw, and side preparation components for the selected coordinate advice. -/ +abbrev Parts := SelectedAdvice.Parts K +/-- Advice ports for the compressor's selected coordinate preparation over the raw Macaulay +port bank. -/ +abbrev Advice := SelectedAdvice.Advice K +/-- Working ports used by the selected coordinate preparation routines. -/ +abbrev Work := SelectedAdvice.Work K +/-- Combined reader port type separating advised inputs from working storage. -/ +abbrev Ports := Advice ⊕ Work + +set_option synthInstance.maxSize 8000 in +instance rawDecidable : DecidableEq K := inferInstanceAs (DecidableEq + (MacaulayRowDispatch.Small ⊕ MacaulayRead.Arms.Leaf MacaulayRead.Arms.CoefficientPort)) + +set_option synthInstance.maxSize 12000 in +instance partsFinite : Fintype Parts := inferInstanceAs (Fintype + (Prepare.Root (SelectedAdvice.Den K) (SelectedAdvice.Raw K) ⊕ + (Dynamic.Host (SelectedAdvice.Side K) ⊕ RAMTape.UnaryWord.Port))) + +set_option synthInstance.maxSize 12000 in +instance partsDecidable : DecidableEq Parts := Prepare.partsDecidable + +instance adviceDecidable : DecidableEq Advice := inferInstanceAs (DecidableEq (Parts ⊕ Bool)) +instance workDecidable : DecidableEq Work := inferInstanceAs (DecidableEq (Parts ⊕ Unit)) +instance adviceFinite : Fintype Advice := inferInstanceAs (Fintype (Parts ⊕ Bool)) +instance workFinite : Fintype Work := inferInstanceAs (Fintype (Parts ⊕ Unit)) + +end CompressorReader + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordChoices.lean b/lean/OAI/Computability/VPVNP/CompressorRecordChoices.lean new file mode 100644 index 0000000000..85bbe94022 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordChoices.lean @@ -0,0 +1,337 @@ +import OAI.Computability.VPVNP.MotifConversion +import OAI.Computability.VPVNP.CompressionState +import OAI.Computability.VPVNP.PrimedCounterBits + +/-! +# Reading the outer compressor term choices + +In the second shrinking scan of Appendix E, and in the corresponding port-block +scan, the term index consists of one integer per supply edge. The reader checks +each binary word against the payload cap and tests the quadratic energy of the +result. Its successful streams are in bijection with the outer indices of +Theorem 6.1. The readers compose in motif order and along branch-dependent +compression passes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +/-- A prefix parser with exactly one code per output. The untouched suffix can +contain the choices of all later motifs and compression levels. -/ +structure ChoiceReader (α : Type*) where + /-- Boolean word encoding an individual choice so that the reader can consume it as a prefix. -/ + encode : α → List Bool + /-- Decode the next choice and return its unconsumed suffix, or fail when the stream has no + valid choice prefix. -/ + read : List Bool → Option (α × List Bool) + read_iff : ∀ bits i tail, read bits = some (i, tail) ↔ bits = encode i ++ tail + +namespace ChoiceReader + +universe u +variable {α : Type u} {β : Type*} + +/-- Successful complete transcripts carry exactly one admitted choice each. -/ +def completeEquiv (C : ChoiceReader α) : + α ≃ {bits : List Bool // ∃ i, C.read bits = some (i, [])} where + toFun i := ⟨C.encode i, i, (C.read_iff _ _ _).mpr (List.append_nil _).symm⟩ + invFun b := ((C.read b.val).get (b.property.elim fun i hi => hi ▸ rfl)).1 + left_inv i := by + have h := (C.read_iff (C.encode i) i []).mpr (List.append_nil _).symm + simp [h] + right_inv b := by + obtain ⟨i, hi⟩ := b.property + apply Subtype.ext + change C.encode ((C.read b.val).get _).1 = b.val + simp only [hi, Option.get_some] + simpa using ((C.read_iff _ _ _).mp hi).symm + +/-- A deterministic choice takes no bits. -/ +def single (a : α) (h : ∀ x, x = a) : ChoiceReader α where + encode _ := [] + read bits := some (a, bits) + read_iff bits x tail := by simp [h x] + +/-- Keep the same concrete reader under a change of indices. -/ +def reindex (C : ChoiceReader α) (e : α ≃ β) : ChoiceReader β where + encode i := C.encode (e.symm i) + read bits := (C.read bits).map (fun (a, tail) => (e a, tail)) + read_iff bits i tail := by + constructor + · intro h + obtain ⟨⟨a, rest⟩, hr, he⟩ := Option.map_eq_some_iff.mp h + obtain ⟨rfl, rfl⟩ := Prod.mk.inj he + simpa using (C.read_iff _ _ _).mp hr + · intro h + rw [(C.read_iff _ _ _).mpr h] + simp + +/-- Read the first choice before looking up the next reader. This preserves +multiplicity when two first choices lead to identical continuation data. -/ +def sigma {β : α → Type u} (C : ChoiceReader α) (D : ∀ i, ChoiceReader (β i)) : + ChoiceReader ((i : α) × β i) where + encode p := C.encode p.1 ++ (D p.1).encode p.2 + read bits := do + let (i, mid) ← C.read bits + let (j, tail) ← (D i).read mid + return (⟨i, j⟩, tail) + read_iff bits p tail := by + obtain ⟨i, j⟩ := p + constructor + · intro h + cases hc : C.read bits with + | none => simp [hc] at h + | some x => + obtain ⟨i', mid⟩ := x + cases hd : (D i').read mid with + | none => simp [hc, hd] at h + | some y => + obtain ⟨j', rest⟩ := y + have he : ((⟨i', j'⟩ : Sigma β), rest) = (⟨i, j⟩, tail) := by simpa [hc, hd] using h + cases he + rw [(C.read_iff _ _ _).mp hc, ((D i).read_iff _ _ _).mp hd, List.append_assoc] + · intro h + simp only [List.append_assoc] at h + rw [(C.read_iff _ _ _).mpr h] + simp [((D i).read_iff ((D i).encode j ++ tail) j tail).mpr rfl] + +/-- Reject a candidate which fails the deterministic admission test. -/ +def restrict (C : ChoiceReader α) (ok : α → Bool) : ChoiceReader {i // ok i = true} where + encode i := C.encode i.val + read bits := do + let (a, tail) ← C.read bits + if h : ok a = true then return (⟨a, h⟩, tail) else none + read_iff bits i tail := by + constructor + · intro h + cases hc : C.read bits with + | none => simp [hc] at h + | some x => + obtain ⟨a, rest⟩ := x + by_cases ha : ok a = true + · have he : ((⟨a, ha⟩ : {i // ok i = true}), rest) = (i, tail) := by simpa [hc, ha] using h + cases he + exact (C.read_iff _ _ _).mp hc + · simp [hc, ha] at h + · intro h + rw [(C.read_iff _ _ _).mpr h] + simp [i.property] + +/-- Read a finite ordered list of motifs. Each motif can have its own set of +terms and its own number of supply coordinates. -/ +def vector : (d : ℕ) → (A : Fin d → Type*) → + (∀ i, ChoiceReader (A i)) → ChoiceReader (∀ i, A i) + | 0, _, _ => single (fun i => nomatch i) (fun _ => funext fun i => nomatch i) + | d + 1, A, C => + let rest := vector d (fun i => A i.succ) (fun i => C i.succ) + let merge : ((_ : A 0) × ((i : Fin d) → A i.succ)) ≃ ((i : Fin (d + 1)) → A i) := + { toFun := fun x => Fin.cons x.1 x.2 + invFun := fun f => ⟨f 0, Fin.tail f⟩ + left_inv := fun ⟨_, _⟩ => rfl + right_inv := Fin.cons_self_tail } + ((C 0).sigma fun _ => rest).reindex merge + +theorem vector_length (d : ℕ) (A : Fin d → Type*) (C : ∀ i, ChoiceReader (A i)) (a : ∀ i, A i) : + ((vector d A C).encode a).length = ∑ i, ((C i).encode (a i)).length := by + induction d with + | zero => simp [vector, single] + | succ d ih => + rw [Fin.sum_univ_succ] + change ((C 0).encode (a 0) ++ (vector d (fun i => A i.succ) (fun i => C i.succ)).encode (Fin.tail a)).length = _ + rw [List.length_append, ih] + rfl + +theorem vector_encode (d : ℕ) (A : Fin d → Type*) (C : ∀ i, ChoiceReader (A i)) (a : ∀ i, A i) : + (vector d A C).encode a = (List.ofFn (fun i => (C i).encode (a i))).flatten := by + induction d with + | zero => rfl + | succ d ih => + rw [List.ofFn_succ] + change (C 0).encode (a 0) ++ (vector d (fun i => A i.succ) (fun i => C i.succ)).encode (Fin.tail a) = _ + rw [ih] + rfl + +/-- One checked machine-word candidate. -/ +def bounded (w bound : ℕ) (h : bound ≤ 2 ^ w) : ChoiceReader (Fin bound) where + encode a := PrimedCounter.digits w a.val + read := PrimedCounter.takeBounded w bound + read_iff := PrimedCounter.takeBounded_eq bound h + +end ChoiceReader + +open MotifGrid MotifBlocks MotifConversion MotifSelector + +variable {k : Type*} [Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S] +variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ} +variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H') + +/-- The bound on each coordinate checked before the quadratic admission test. -/ +abbrev outerCap (demand : D → ℕ) := + MotifAdmission.payloadCap q (repetitions B demand) B.scale B.radius + +/-- With zero repetitions every payload is forced to zero and no choice bit is used. -/ +def coordinateBits (demand : D → ℕ) (w : ℕ) := + if repetitions B demand = 0 then 0 else w + +theorem coordinate_fit (demand : D → ℕ) (w : ℕ) (hw : outerCap B demand < 2 ^ w) : + outerCap B demand + 1 ≤ 2 ^ coordinateBits B demand w := by + by_cases h : repetitions B demand = 0 + · simp [coordinateBits, outerCap, MotifAdmission.payloadCap, h] + · simpa [coordinateBits, h] using hw + +private def admittedBoxEquiv (demand : D → ℕ) (hq : ∀ e, 0 < q e) : + {v : S → Fin (outerCap B demand + 1) // + MotifAdmission.admit q (fun e => (v e).val) (repetitions B demand) B.scale B.radius = true} + ≃ ↥(outerIndices B demand) where + toFun v := ⟨fun e => (v.val e).val, (mem_outerIndices_iff B hq _ _).mpr v.property⟩ + invFun v := + let h := (mem_outerIndices_iff B hq _ _).mp v.property + ⟨fun e => ⟨v.val e, Nat.lt_succ_of_le (MotifAdmission.payload_le_cap q hq _ _ _ _ h e)⟩, h⟩ + left_inv _ := rfl + right_inv _ := rfl + +/-- The concrete binary reader for exactly the terms of the fixed conversion. +The numbering of the supply edges is chosen once for the motif. -/ +def outerReader {n : ℕ} (order : Fin n ≃ S) (hq : ∀ e, 0 < q e) (demand : D → ℕ) + (w : ℕ) (hw : outerCap B demand < 2 ^ w) : ChoiceReader ↥(outerIndices B demand) := + let cap := outerCap B demand + 1 + let one := ChoiceReader.bounded (coordinateBits B demand w) cap (coordinate_fit B demand w hw) + let box := (ChoiceReader.vector n (fun _ => Fin cap) (fun _ => one)).reindex + (Equiv.arrowCongr order (Equiv.refl (Fin cap))) + (box.restrict (fun v => MotifAdmission.admit q (fun e => (v e).val) + (repetitions B demand) B.scale B.radius)).reindex (admittedBoxEquiv B demand hq) + +/-- A successful read consumes just the specified edge order, including the +leading zero bits of each word. Rejection can occur after the cap check or +after the total energy test. -/ +theorem read_outer_iff {n : ℕ} (order : Fin n ≃ S) (hq : ∀ e, 0 < q e) (demand : D → ℕ) + (w : ℕ) (hw : outerCap B demand < 2 ^ w) (bits tail : List Bool) (v : ↥(outerIndices B demand)) : + (outerReader B order hq demand w hw).read bits = some (v, tail) ↔ + bits = (List.ofFn (fun i => PrimedCounter.digits (coordinateBits B demand w) + (v.val (order i)))).flatten ++ tail := by + rw [ChoiceReader.read_iff] + unfold outerReader ChoiceReader.restrict ChoiceReader.reindex + dsimp only + rw [ChoiceReader.vector_encode] + rfl + +theorem outerReader_length {n : ℕ} (order : Fin n ≃ S) (hq : ∀ e, 0 < q e) + (demand : D → ℕ) (w : ℕ) (hw : outerCap B demand < 2 ^ w) (v : ↥(outerIndices B demand)) : + ((outerReader B order hq demand w hw).encode v).length = n * coordinateBits B demand w := by + unfold outerReader ChoiceReader.restrict ChoiceReader.reindex + dsimp only + rw [ChoiceReader.vector_length] + simp [ChoiceReader.bounded, PrimedCounter.digits] + +theorem zero_repetitions (demand : D → ℕ) (h : ∀ i, demand i = 0) : + repetitions B demand = 0 := by + simp [repetitions, MotifAdmission.copies, MotifAdmission.ceilRoot, MotifAdmission.energy, h] + +/-- A motif with zero-width demands has the zero vector as its sole outer index. -/ +theorem zero_outerIndices (demand : D → ℕ) (h : ∀ i, demand i = 0) (hq : ∀ e, 0 < q e) : + outerIndices B demand = {fun _ => 0} := by + classical + ext v + rw [mem_outerIndices_iff B hq, Finset.mem_singleton] + constructor + · intro hv + funext e + have hcap := MotifAdmission.payload_le_cap q hq v _ _ _ hv e + simpa [MotifAdmission.payloadCap, zero_repetitions B demand h] using hcap + · rintro rfl + simp [MotifAdmission.admit, MotifAdmission.energy] + +theorem zero_outer_code {n : ℕ} (order : Fin n ≃ S) (hq : ∀ e, 0 < q e) + (demand : D → ℕ) (hd : ∀ i, demand i = 0) (w : ℕ) (hw : outerCap B demand < 2 ^ w) + (v : ↥(outerIndices B demand)) : (outerReader B order hq demand w hw).encode v = [] := by + apply List.length_eq_zero_iff.mp + simp [outerReader_length, coordinateBits, zero_repetitions B demand hd] + +/-- At zero demand the sole term's local map multiplies an empty list of +parameters. This proves its unit value independently of the parameter ring. -/ +theorem zero_entry_value {A : Type*} [CommMonoidWithZero A] (κ : (parameterData B).Entry → A) + (hp : ∀ i, 0 < p i) (demand : D → ℕ) (hd : ∀ i, demand i = 0) (j : J) + (x : MotifDemandPadding.HalfBits a b demand j) + (y : Half P (fun e => Word (supplyWidths B demand (fun _ => 0) e)) j) : + evalEntry κ (entry B hp demand (fun _ => 0) j x y) = 1 := by + classical + let : IsEmpty (Fin (repetitions B demand)) := Fin.isEmpty_iff.mpr (zero_repetitions B demand hd) + have agrees (fields : Half P (fun _ => (Fin (repetitions B demand) → Word B.selectorBits) × Word 0) j) : + HalfAgrees P j fields := + ⟨fun _ _ => Subsingleton.elim _ _, fun _ _ => Subsingleton.elim _ _⟩ + have tags (v : Fin (repetitions B demand) → Word B.selectorBits) : + v ∈ Set.range (sequenceCode (selectorCode B) (repetitions B demand)) := + ⟨fun i => isEmptyElim i, Subsingleton.elim _ _⟩ + have widths (v : Fin (repetitions B demand) → Selector B) : + (fun _ => 0) = totalWidth (basePayload B) v := by funext e; simp [totalWidth] + simp [entry, groupedIndices, agrees, tagIndices, tags, payloadIndices, evalEntry] + rw [dite_eq_left (widths _)] + rfl + +/-- For a fixed motif the required word width is logarithmic in the maximum +demand width. The cap itself is computed by the same fixed integer formula +used in the reader. -/ +theorem outerCap_bits_le (demand : D → ℕ) (M : ℕ) (hd : ∀ i, demand i ≤ M) : + (outerCap B demand).size ≤ + (((∑ i, MotifAdmission.weight p i) + 1) * B.scale * B.radius.num.natAbs * + MotifAdmission.denominator q).size + Nat.clog 2 (M + 1) := by + let K := ((∑ i, MotifAdmission.weight p i) + 1) * B.scale * B.radius.num.natAbs * + MotifAdmission.denominator q + have hcap : outerCap B demand ≤ K * (M + 1) := + MotifAdmission.payloadCap_le p q demand B.scale M B.radius B.scale_pos hd + apply Nat.size_le.mpr + rw [pow_add] + exact hcap.trans_lt (mul_lt_mul_of_lt_of_le_of_pos_of_nonneg (Nat.lt_size_self K) + (Nat.le_pow_clog (by decide) _) (Nat.succ_pos _) (Nat.zero_le _)) + +/-- One complete ordered pass over the motifs, as in the shrinking and +degree-refresh scans. Demand widths may vary independently from motif to motif. -/ +def motifPassReader {I : Type} {n t : ℕ} (motifs : Fin t ≃ I) (edges : Fin n ≃ S) + (hq : ∀ e, 0 < q e) (demand : I → D → ℕ) (w : ℕ) (hw : ∀ i, outerCap B (demand i) < 2 ^ w) : + ChoiceReader ((i : I) → ↥(outerIndices B (demand i))) := + (ChoiceReader.vector t _ (fun j => outerReader B edges hq (demand (motifs j)) w (hw (motifs j)))).reindex + (Equiv.piCongrLeft (fun i => ↥(outerIndices B (demand i))) motifs) + +theorem motifPass_bits_le {I : Type} {n t : ℕ} (motifs : Fin t ≃ I) (edges : Fin n ≃ S) + (hq : ∀ e, 0 < q e) (demand : I → D → ℕ) (w : ℕ) (hw : ∀ i, outerCap B (demand i) < 2 ^ w) + (v : ∀ i, ↥(outerIndices B (demand i))) : + ((motifPassReader B motifs edges hq demand w hw).encode v).length ≤ t * (n * w) := by + unfold motifPassReader ChoiceReader.reindex + dsimp only + rw [ChoiceReader.vector_length] + calc + _ ≤ ∑ _ : Fin t, n * w := Finset.sum_le_sum fun i _ => by + rw [outerReader_length] + apply Nat.mul_le_mul_left + unfold coordinateBits + split <;> omega + _ = _ := by simp + +namespace ChoiceReader + +open Compression + +/-- At each compression pass, the complete next set of motifs can depend on +the earlier layout and widths. A pass reader consumes just its own prefix. -/ +def passReaders {R : Type*} [CommSemiring R] {b n : ℕ} {a g : ℕ} {X : State a g} : + StateExecution R b n X → Type + | .done _ => Unit + | .more p tail => ChoiceReader p.step.Choice × (∀ i, passReaders (tail i)) + +/-- The complete descriptor-phase reader on a branch-dependent sequence of +compression passes. Its output is the existing compressor's term sequence. -/ +def execution {R : Type*} [CommSemiring R] {b n : ℕ} {a g : ℕ} {X : State a g} + (P : StateExecution R b n X) : passReaders P → ChoiceReader P.Choices := + match P with + | .done _ => fun _ => single () (fun _ => rfl) + | .more _ tail => fun readers => readers.1.sigma fun i => execution (tail i) (readers.2 i) + +end ChoiceReader +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordFrame.lean b/lean/OAI/Computability/VPVNP/CompressorRecordFrame.lean new file mode 100644 index 0000000000..bf034f6a7f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordFrame.lean @@ -0,0 +1,454 @@ +import OAI.Computability.VPVNP.LiveStageLinkRun +import Mathlib.Data.ZMod.Defs + +/-! +# Loading a descriptor frame into native registers + +The compressor's component templates have finite parameter banks. At call +entry a fixed prelude reads the bank from consecutive external words. The +relocated body executes each original public-word instruction as a register +copy, so repeated accesses to a parameter inside a long private computation +require no additional probes. The bank is a snapshot taken before the body. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Frame + +open BurstRAM BurstRAM.PrivateRAM +open scoped Fin.CommRing + +variable {p r k w : ℕ} + +/-- Program-counter count for the frame-loading prelude and relocated body, with four +instructions per parameter. -/ +abbrev PCs (p k : ℕ) := k*4+p +/-- Register count for the framed body, its parameter cache, and the temporary frame-address +register. -/ +abbrev Regs (r k : ℕ) := r+(k+1) + +/-- Four prelude labels per frame word and one label for each original instruction. -/ +def labels (p k : ℕ) : (Fin k × Fin 4) ⊕ Fin p ≃ Fin (PCs p k) := + (finProdFinEquiv.sumCongr (Equiv.refl _)).trans finSumFinEquiv + +/-- Program counter for a specified parameter and one of its four loading instructions. -/ +def prePC (p : ℕ) (j : Fin k) (phase : Fin 4) := labels p k (.inl (j,phase)) +/-- Relocated program counter of an original body instruction, following the frame-loading +prelude. -/ +def bodyPC (k : ℕ) (i : Fin p) := labels p k (.inr i) + +/-- Embed a body register into the leading bank of the framed machine. -/ +def ordinary (k : ℕ) (i : Fin r) : Fin (Regs r k) := i.castAdd (k+1) +/-- Cache register holding the selected public parameter throughout the body execution. -/ +def cacheReg (r : ℕ) (j : Fin k) : Fin (Regs r k) := j.castSucc.natAdd r +/-- Temporary register used to address external parameter words during frame loading. -/ +def addressReg (r k : ℕ) : Fin (Regs r k) := (Fin.last k).natAdd r + +/-- Public-word instructions are the only instructions whose operation +changes. Component destinations never address a cached parameter. -/ +def bodyCode : Instr w p r k → Instr w (PCs p k) (Regs r k) 1 + | .constant a v j => .constant (ordinary k a) v (bodyPC k j) + | .publicWord a i j => .copy (ordinary k a) (cacheReg r i) (bodyPC k j) + | .stateWord a j => .stateWord (ordinary k a) (bodyPC k j) + | .copy a b j => .copy (ordinary k a) (ordinary k b) (bodyPC k j) + | .binary op a b c j => .binary op (ordinary k a) (ordinary k b) (ordinary k c) (bodyPC k j) + | .loadPrivate a b j => .loadPrivate (ordinary k a) (ordinary k b) (bodyPC k j) + | .storePrivate a b j => .storePrivate (ordinary k a) (ordinary k b) (bodyPC k j) + | .jumpEq a b y n => .jumpEq (ordinary k a) (ordinary k b) (bodyPC k y) (bodyPC k n) + | .jumpLt a b y n => .jumpLt (ordinary k a) (ordinary k b) (bodyPC k y) (bodyPC k n) + | .choose y n => .choose (bodyPC k y) (bodyPC k n) + | .readExternal a b j => .readExternal (ordinary k a) (ordinary k b) (bodyPC k j) + | .writeExternal a b j => .writeExternal (ordinary k a) (ordinary k b) (bodyPC k j) + | .returnState a => .returnState (ordinary k a) + | .accept => .accept + | .reject => .reject + +/-- Reading a cached parameter costs the same private word work as the +original public-word access; all other body instructions keep their charge. -/ +@[simp] theorem bodyCode_wordWork (op : Instr w p r k) : (bodyCode op).wordWork = op.wordWork := by + cases op <;> rfl + +variable (T : Template p r k) + +/-- Enter the next parameter's loading sequence, or the body entry once the entire frame is +cached. -/ +def nextPC (j : ℕ) : Fin (PCs p k) := + if hj : j < k then prePC p ⟨j,hj⟩ 0 else bodyPC k T.entry + +private def literalWidth := max T.literalWidth (Nat.clog 2 k) + +private def code : (Fin k × Fin 4) ⊕ Fin p → Instr (literalWidth T) (PCs p k) (Regs r k) 1 + | .inl (j,0) => .publicWord (addressReg r k) 0 (prePC p j 1) + | .inl (j,1) => .constant (cacheReg r j) (Fin.ofNat _ j.val) (prePC p j 2) + | .inl (j,2) => .binary .add (cacheReg r j) (addressReg r k) (cacheReg r j) (prePC p j 3) + | .inl (j,3) => .readExternal (cacheReg r j) (cacheReg r j) (nextPC T (j.val+1)) + | .inr j => bodyCode ((T.code j).resize _) + +/-- A single fixed compiled template whose sole public word is the +address of the descriptor frame. An empty bank needs no prelude. -/ +def compile : Template (PCs p k) (Regs r k) 1 where + literalWidth := literalWidth T + entry := nextPC T 0 + code i := code T ((labels p k).symm i) + +/-- Instantiate the compiled framed template with the external frame base as its public +operand. -/ +def machine (base : Word w) := (compile T).instantiate w (fun _ ↦ base) + +private theorem literal_fits (j : Fin k) : j.val < 2^literalWidth T := + j.isLt.trans_le ((Nat.le_pow_clog (by decide : 1 < 2) k).trans + (Nat.pow_le_pow_right (by decide) (le_max_right ..))) + +private theorem code_0 (base : Word w) (j : Fin k) : + (machine T base).code (prePC p j 0) = .publicWord (addressReg r k) 0 (prePC p j 1) := by + simp [machine, compile, Template.instantiate, prePC, code, Instr.resize] + +private theorem code_1 (base : Word w) (j : Fin k) : + (machine T base).code (prePC p j 1) = .constant (cacheReg r j) (j.val : Word w) + (prePC p j 2) := by + simp [machine, compile, Template.instantiate, prePC, code, Instr.resize, Nat.mod_eq_of_lt + (literal_fits T j)] + +private theorem code_2 (base : Word w) (j : Fin k) : + (machine T base).code (prePC p j 2) = + .binary .add (cacheReg r j) (addressReg r k) (cacheReg r j) (prePC p j 3) := by + simp [machine, compile, Template.instantiate, prePC, code, Instr.resize] + +private theorem code_3 (base : Word w) (j : Fin k) : + (machine T base).code (prePC p j 3) = + .readExternal (cacheReg r j) (cacheReg r j) (nextPC T (j.val+1)) := by + simp [machine, compile, Template.instantiate, prePC, code, Instr.resize] + +/-- The private dispatch charges of the four prelude instructions total +seventeen elementary word operations per parameter. -/ +theorem load_wordWork (base : Word w) (j : Fin k) : + ((machine T base).code (prePC p j 0)).wordWork + + ((machine T base).code (prePC p j 1)).wordWork + + ((machine T base).code (prePC p j 2)).wordWork + + ((machine T base).code (prePC p j 3)).wordWork = 17 := by + rw [code_0, code_1, code_2, code_3] + rfl + +theorem code_body (base : Word w) (j : Fin p) : + (machine T base).code (bodyPC k j) = bodyCode ((T.code j).resize w) := by + simp only [machine, compile, Template.instantiate, bodyPC, Equiv.symm_apply_apply, code] + have h (v : Word T.literalWidth) : v.val < 2^literalWidth T := + v.isLt.trans_le (Nat.pow_le_pow_right (by decide) (le_max_left ..)) + generalize T.code j = op + cases op <;> simp [Instr.resize, bodyCode, Nat.mod_eq_of_lt (h _)] + +private def registers (small : Fin r → Word w) (cache : Fin k → Word w) (addr : Word w) : + Fin (Regs r k) → Word w := Fin.append small (Fin.snoc cache addr) + +private theorem update_left {m n : ℕ} {α : Type*} (f : Fin m → α) (g : Fin n → α) (i : Fin m) + (v : α) : + Function.update (Fin.append f g) (i.castAdd n) v = Fin.append (Function.update f i v) g := by + funext t + cases t using Fin.addCases with + | left j => by_cases hj : j = i <;> simp [Function.update, hj] + | right j => + have h : j.natAdd m ≠ i.castAdd n := fun e ↦ by have := congrArg Fin.val e; simp at this; omega + simp [Function.update_of_ne h] + +private theorem update_right {m n : ℕ} {α : Type*} (f : Fin m → α) (g : Fin n → α) (i : Fin n) + (v : α) : + Function.update (Fin.append f g) (i.natAdd m) v = Fin.append f (Function.update g i v) := by + funext t + cases t using Fin.addCases with + | left j => + have h : j.castAdd n ≠ i.natAdd m := fun e ↦ by have := congrArg Fin.val e; simp at this; omega + simp [Function.update_of_ne h] + | right j => by_cases hj : j = i <;> simp [Function.update, hj] + +private theorem update_cache (f : Fin r → Word w) (cache : Fin k → Word w) (addr : Word w) + (i : Fin k) (v : Word w) : + Function.update (registers f cache addr) (cacheReg r i) v = registers f + (Function.update cache i v) addr := by + unfold registers cacheReg + rw [update_right] + congr 1 + funext t + cases t using Fin.lastCases with + | last => simp [Function.update_of_ne (Fin.castSucc_ne_last i).symm] + | cast j => by_cases h : j = i <;> simp [Function.update, h] + +private theorem update_addr (f : Fin r → Word w) (cache : Fin k → Word w) (addr v : Word w) : + Function.update (registers f cache addr) (addressReg r k) v = registers f cache v := by + unfold registers addressReg + rw [update_right] + congr 1 + funext t + cases t using Fin.lastCases with + | last => simp + | cast j => simp + +private def embed (cache : Fin k → Word w) (addr : Word w) (c : Config w p r) : Config w (PCs p k) + (Regs r k) := + ⟨bodyPC k c.pc, c.persistent, registers c.reg cache addr, c.privateMem⟩ + +private def mapAction {C D : Type*} (f : C → D) : CallAction w C → CallAction w D + | .localStep c => .localStep (f c) + | .branch g => .branch (f ∘ g) + | .read a g => .read a (f ∘ g) + | .write a v c => .write a v (f c) + | .finish s => .finish s + | .reject => .reject + +private theorem body_step (base addr : Word w) (pub : Fin k → Word w) (c : Config w p r) : + (machine T base).program.step (embed pub addr c) = + mapAction (embed pub addr) ((T.instantiate w pub).program.step c) := by + change ((machine T base).code (bodyPC k c.pc)).run _ _ = mapAction _ + (((T.code c.pc).resize w).run pub c) + rw [code_body] + generalize (T.code c.pc).resize w = op + cases op <;> simp only [bodyCode, Instr.run, embed, mapAction, Config.put, Config.store, + registers, + ordinary, cacheReg, Fin.append_left, Fin.append_right, Fin.snoc_castSucc, update_left, + Function.comp_def] + all_goals first | rfl | (split <;> rfl) | (congr 1; funext b; cases b <;> rfl) + +/-- Within the relocated body, every finite-fuel execution is exactly the +original execution with its cached public data. This includes arbitrary +external writes (even to the frame), adaptive reads, and all choices. -/ +theorem execute_body (base addr : Word w) (pub : Fin k → Word w) (fuel : ℕ) (c : Config w p r) + (m : Memory w) (bs : List Bool) : + execute (machine T base).program fuel (embed pub addr c) m bs = + execute (T.instantiate w pub).program fuel c m bs := by + induction fuel generalizing c m bs with + | zero => rfl + | succ fuel ih => + rw [execute, body_step, execute] + cases hs : (T.instantiate w pub).program.step c <;> simp only [mapAction, Function.comp_apply] + all_goals first | rfl | rw [ih] | (cases bs <;> simp [ih]) + +/-- The source machine's public bank is the external frame at call entry. -/ +def data (base : Word w) (m : Memory w) : Fin k → Word w := + fun j ↦ m (base + (j.val : Word w)).val + +theorem data_at (base : Word w) (m : Memory w) (fit : base.val + k ≤ 2 ^ w) (j : Fin k) : + data base m j = m (base.val+j.val) := by + have hj := (Nat.add_lt_add_left j.isLt base.val).trans_le fit + have hv : ((j.val : Word w) : ℕ) = j.val := Nat.mod_eq_of_lt (by omega) + have hsum : base.val + (j.val : Word w).val < 2^w := by simpa only [hv] using hj + rw [data, Fin.val_add_eq_of_add_lt hsum, hv] + +private def chunk (base : Word w) (m : Memory w) (j : ℕ) : List (Event w) := + let a := base + (j : Word w) + [.tick,.tick,.tick,.read a (m a.val)] + +/-- Chronological trace of the descriptor-frame loads starting at offset j. -/ +def loadEvents (base : Word w) (m : Memory w) (j : ℕ) : ℕ → List (Event w) + | 0 => [] + | n+1 => chunk base m j ++ loadEvents base m (j+1) n + +/-- Each frame parameter adds one probe and three private ticks. The +continuation's report retains every branch bit and memory update. -/ +theorem frame_cost (base : Word w) (m : Memory w) (j n : ℕ) (rep : Report w) : + let out := LiveStageLink.prependLog (loadEvents base m j n) rep + out.events.length = 4*n+rep.events.length ∧ out.probes = n+rep.probes ∧ + choiceBits out.events = choiceBits rep.events ∧ after m out.events = after m rep.events ∧ + out.result = rep.result := by + induction n generalizing j with + | zero => simp [LiveStageLink.prependLog, loadEvents] + | succ n ih => + obtain ⟨hl,hp,hb,hm,hr⟩ := ih (j+1) + dsimp only [LiveStageLink.prependLog] at * + simp only [loadEvents, chunk, List.cons_append, List.nil_append, List.length_cons, + Report.probes, countProbes, choiceBits] at * + exact ⟨by omega, by omega, hb, hm, hr⟩ + +private def control (atPC : Fin (PCs p k)) (c : Config w p r) (bank : Fin k → Word w) + (addr : Word w) : + Config w (PCs p k) (Regs r k) := ⟨atPC,c.persistent,registers c.reg bank addr,c.privateMem⟩ + +private theorem exec_tick {P : Program w (Config w (PCs p k) (Regs r k))} + {c c' : Config w (PCs p k) (Regs r k)} (hs : P.step c = .localStep c') (f : ℕ) + (m : Memory w) (bs : List Bool) : execute P (f+1) c m bs = + (execute P f c' m bs).map (Report.prepend .tick) := by simp only [execute, hs] + +private theorem exec_read {P : Program w (Config w (PCs p k) (Regs r k))} + {c : Config w (PCs p k) (Regs r k)} {a : Word w} {g : Word w → Config w (PCs p k) (Regs r k)} + (hs : P.step c = .read a g) (f : ℕ) (m : Memory w) (bs : List Bool) : + execute P (f+1) c m bs = (execute P f (g (m a.val)) m bs).map (Report.prepend (.read a + (m a.val))) := by + simp only [execute, hs] + +private theorem execute_load (base addr : Word w) (m : Memory w) (bs : List Bool) (j : Fin k) + (c : Config w p r) (bank : Fin k → Word w) (f : ℕ) : + execute (machine T base).program (f+4) (control (nextPC T j.val) c bank addr) m bs = + (execute (machine T base).program f (control (nextPC T (j.val+1)) c + (Function.update bank j (data base m j)) base) m bs).map (LiveStageLink.prependLog + (chunk base m j)) := by + let L := (machine T base).program + let a := base + (j.val : Word w) + let c0 := control (nextPC T j.val) c bank addr + let c1 := control (prePC p j 1) c bank base + let c2 := control (prePC p j 2) c (Function.update bank j (j.val : Word w)) base + let c3 := control (prePC p j 3) c (Function.update bank j a) base + let next (v : Word w) := control (nextPC T (j.val+1)) c (Function.update bank j v) base + have s0 : L.step c0 = .localStep c1 := by + change ((machine T base).code (nextPC T j.val)).run _ c0 = _ + simp only [nextPC, j.isLt, ↓reduceDIte, code_0, Instr.run] + change CallAction.localStep (c0.put _ (addressReg r k) base) = _ + simp [c0, c1, control, Config.put, update_addr] + have s1 : L.step c1 = .localStep c2 := by + change ((machine T base).code (prePC p j 1)).run _ c1 = _ + rw [code_1] + simp [Instr.run, c1, c2, control, Config.put, update_cache] + have s2 : L.step c2 = .localStep c3 := by + change ((machine T base).code (prePC p j 2)).run _ c2 = _ + rw [code_2] + have haddr : c2.reg (addressReg r k) = base := by simp only [c2, control, registers, + addressReg, Fin.append_right, Fin.snoc_last] + have hi : c2.reg (cacheReg r j) = (j.val : Word w) := by simp [c2, control, registers, cacheReg] + change CallAction.localStep (c2.put _ (cacheReg r j) (c2.reg (addressReg r k) + c2.reg + (cacheReg r j))) = _ + rw [haddr, hi] + simp [c2, c3, control, Config.put, update_cache, Function.update_idem, a] + have s3 : L.step c3 = .read a next := by + change ((machine T base).code (prePC p j 3)).run _ c3 = _ + rw [code_3] + have haddr : c3.reg (cacheReg r j) = a := by simp [c3, control, registers, cacheReg] + change CallAction.read (c3.reg (cacheReg r j)) _ = _ + rw [haddr] + congr 1 + funext v + simp [c3, next, control, Config.put, update_cache, Function.update_idem] + rw [exec_tick s0, exec_tick s1, exec_tick s2, exec_read s3] + simp [Report.prepend, Option.map_map, Function.comp_def, chunk, next, a, data] + rfl + +private def partialBank (pub : Fin k → Word w) (j : ℕ) : Fin k → Word w := + fun i ↦ if i.val < j then pub i else 0 + +private theorem update_partial (pub : Fin k → Word w) (j : Fin k) : + Function.update (partialBank pub j.val) j (pub j) = partialBank pub (j.val+1) := by + funext i + by_cases h : i = j + · subst i; simp [partialBank] + · have hv : i.val ≠ j.val := fun e ↦ h (Fin.ext e) + simp [Function.update_of_ne h, partialBank, show i.val < j.val+1 ↔ i.val < j.val by omega] + +private theorem execute_remaining (base addr : Word w) (m : Memory w) (bs : List Bool) + (c : Config w p r) (hc : c.pc = T.entry) (f j n : ℕ) (hlen : j + n = k) : + execute (machine T base).program (f+4*n) + (control (nextPC T j) c (partialBank (data base m) j) addr) m bs = + (execute (T.instantiate w (data base m)).program f c m bs).map + (LiveStageLink.prependLog (loadEvents base m j n)) := by + induction n generalizing j addr with + | zero => + have hj : j = k := by simpa using hlen + subst j + have full : partialBank (data base m) k = (data base m : Fin k → Word w) := by + funext i; simp [partialBank, i.isLt] + simp only [Nat.mul_zero, Nat.add_zero, full, nextPC, lt_self_iff_false, ↓reduceDIte, loadEvents] + rw [← hc] + change execute _ f (embed (data base m) addr c) m bs = _ + rw [execute_body] + cases execute (T.instantiate w (data base m)).program f c m bs <;> rfl + | succ n ih => + let i : Fin k := ⟨j,by omega⟩ + rw [show f+4*(n+1) = (f+4*n)+4 by omega, execute_load T base addr m bs i, + update_partial (data base m) i, ih base (j+1) (by omega)] + simp [loadEvents, LiveStageLink.prependLog, Option.map_map, Function.comp_def, i] + rfl + +/-- Exact native execution from fresh call entry for every component fuel +and branch stream. The original persistent input is passed through the +prelude. Subsequent calls take a new snapshot of their current frame. -/ +theorem execute_frame (base : Word w) (state : Word w) (f : ℕ) (m : Memory w) (bs : List Bool) : + let P := (machine T base).program + let Q := (T.instantiate w (data base m)).program + execute P (f+4*k) (P.start state) m bs = + (execute Q f (Q.start state) m bs).map (LiveStageLink.prependLog + (loadEvents base m 0 k)) := by + let Q := (T.instantiate w (data base m)).program + have hs : (machine T base).program.start state = + control (nextPC T 0) (Q.start state) (partialBank (data base m) 0) 0 := by + change Config.mk _ _ (fun _ ↦ 0) _ = Config.mk _ _ (registers (fun _ ↦ 0) _ 0) _ + congr 1 + funext i + cases i using Fin.addCases with + | left i => simp [registers] + | right i => + cases i using Fin.lastCases with + | last => simp only [registers, Fin.append_right, Fin.snoc_last] + | cast j => simp [registers, partialBank] + dsimp only + rw [hs, execute_remaining T base 0 m bs (Q.start state) rfl f 0 k (by omega)] + +private theorem extend_fuel {C : Type*} {P : Program w C} {f : ℕ} {c : C} {es result} + (h : Guessed P f c es result) (pad : ℕ) : Guessed P (f+pad) c es result := by + induction h with + | done hs => simpa [Nat.succ_add] using Guessed.done (f := _+pad) hs + | step hs _ ih => simpa [Nat.succ_add] using Guessed.step hs ih + | branch hs _ ih => simpa [Nat.succ_add] using Guessed.branch hs ih + | read hs _ ih => simpa [Nat.succ_add] using Guessed.read hs ih + | write hs _ ih => simpa [Nat.succ_add] using Guessed.write hs ih + +/-- At every caller fuel cap, including a cap too small to finish the +prelude, the original component has exactly the remaining fuel. -/ +theorem execute_cap (base : Word w) (state : Word w) (cap : ℕ) (m : Memory w) (bs : List Bool) : + let P := (machine T base).program + let Q := (T.instantiate w (data base m)).program + execute P cap (P.start state) m bs = + (execute Q (cap-4*k) (Q.start state) m bs).map (LiveStageLink.prependLog + (loadEvents base m 0 k)) := by + dsimp only + by_cases hf : 4*k ≤ cap + · simpa only [Nat.sub_add_cancel hf] using execute_frame T base state (cap-4*k) m bs + · have he : cap-4*k = 0 := by omega + rw [he] + cases h : execute (machine T base).program cap ((machine T base).program.start state) m bs with + | none => rfl + | some rep => + obtain ⟨hg,hm,hb⟩ := execute_spec h + have hg' := extend_fuel hg (4*k-cap) + rw [show cap+(4*k-cap) = 0+4*k by omega] at hg' + have h' := execute_iff.mpr ⟨hg',hm,hb⟩ + rw [execute_frame T base state 0 m bs] at h' + contradiction + +/-- The source execution for a sequence of calls fetches the public bank +from the current external memory at each boundary. Only the original +component's writes change the bank for later calls. -/ +def segment (base : Word w) (cap : ℕ) : + Option (Word w) → Memory w → List (List Bool) → Option (List (Report w)) + | _, _, [] => some [] + | none, _, _ :: _ => none + | some st, m, bs :: rest => do + let Q := (T.instantiate w (data base m)).program + let rep ← execute Q (cap-4*k) (Q.start st) m bs + let tail ← segment base cap rep.result (after m rep.events) rest + return LiveStageLink.prependLog (loadEvents base m 0 k) rep :: tail + +/-- Pathwise equality through successive calls, including frames overwritten +by earlier calls and streams that propose extra choices after a halt. -/ +theorem runSegment_frame (base : Word w) (cap : ℕ) (st : Option (Word w)) + (m : Memory w) (bits : List (List Bool)) : + runSegment (machine T base).program cap st m bits = segment T base cap st m bits := by + induction bits generalizing st m with + | nil => rfl + | cons bs rest ih => + cases st with + | none => rfl + | some st => + rw [runSegment, segment, execute_cap T base st cap m bs] + let Q := (T.instantiate w (data base m)).program + cases h : execute Q (cap-4*k) (Q.start st) m bs with + | none => rfl + | some rep => + have cost := frame_cost base m 0 k rep + dsimp only [Option.map_some, Option.bind_some] + rw [cost.2.2.2.1, cost.2.2.2.2, ih] + change (segment T base cap rep.result (after m rep.events) rest).map _ = + (segment T base cap rep.result (after m rep.events) rest).bind _ + cases segment T base cap rep.result (after m rep.events) rest <;> rfl + +end CompressorRecords.Frame + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordGreedy.lean b/lean/OAI/Computability/VPVNP/CompressorRecordGreedy.lean new file mode 100644 index 0000000000..3e26b182fd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordGreedy.lean @@ -0,0 +1,395 @@ +import OAI.Computability.VPVNP.PrimedStackRAMCode +import OAI.Computability.VPVNP.RAMRecords +import Mathlib.Data.ZMod.Defs +import Mathlib.Tactic.Ring + +/-! +# Word code for the greedy descriptor choices + +A vertex's record contains a fixed number of forbidden expressions. Each +expression is the xor of the words named by its row of pointers. A color +test uses one pointer to the neighbor's current assignment. The tag tests +in Appendix C use the arc displacement, up to two increments, and the +neighbor's current offset. Zero terms can be supplied by a shared zero cell. +The instruction table is fixed once the degree and row arity are fixed. + +Starting from candidate zero, each pass increments the candidate exactly +when it occurs among the forbidden expressions. The length of that list +bounds the number of passes needed, including when entries are repeated. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +private abbrev Code := List (Op 8 0) +variable {w : ℕ} + +/-- Pointer row traversal, with ordinary word-address arithmetic. -/ +def readExpression (m : Memory w) : ℕ → Word w → Word w → Word w × Word w + | 0, ptr, acc => (ptr, acc) + | n + 1, ptr, acc => readExpression m n (ptr + 1) + (BinaryOp.bitXor.eval acc (m (m ptr.val).val)) + +/-- Values of all forbidden expressions, in descriptor order. -/ +def readRows (m : Memory w) (arity : ℕ) : ℕ → Word w → List (Word w) + | 0, _ => [] + | n + 1, ptr => + let (next, value) := readExpression m arity ptr 0 + value :: readRows m arity n next + +@[simp] theorem readRows_length (m : Memory w) (arity n : ℕ) (ptr : Word w) : + (readRows m arity n ptr).length = n := by + induction n generalizing ptr <;> simp [readRows, *] + +private def fetchOne : Code := + [.read 7 3, .read 7 7, .binary .bitXor 4 4 7, .binary .add 3 3 1] + +private def fetch : ℕ → Code + | 0 => [] + | n + 1 => fetchOne ++ fetch n + +/-- The unsigned quotient of a word by itself tests whether it is nonzero. +The product in register 6 stays one precisely while every comparison differs. -/ +private def compareWord : Code := + [.binary .sub 5 2 4, .binary .div 5 5 5, .binary .mul 6 6 5] + +private def scan (arity : ℕ) : ℕ → Code + | 0 => [] + | n + 1 => [.constant 4 0] ++ fetch arity ++ compareWord ++ scan arity n + +private def pass (arity n : ℕ) : Code := + [.copy 3 0, .copy 6 1] ++ scan arity n ++ + [.binary .sub 6 1 6, .binary .add 2 2 6] + +private def passes (arity n : ℕ) : ℕ → Code + | 0 => [] + | j + 1 => pass arity n ++ passes arity n j + +/-- Register 0 holds the first descriptor address. The other input registers +may contain arbitrary values. Register 2 returns the least missing index. -/ +def choose (arity n : ℕ) : List (Op 8 0) := + [.constant 1 1, .constant 2 0] ++ passes arity n n + +theorem probes_append (es fs : List (Event w)) : + countProbes (es ++ fs) = countProbes es + countProbes fs := by + induction es with + | nil => simp [countProbes] + | cons e es ih => cases e <;> simp [countProbes, ih, Nat.add_assoc] + +private abbrev Run (state : Word w) (m : Memory w) (code : Code) + (rs out : Regs w 8) (steps probes : ℕ) := + ∃ es, trace (Fin.elim0) state code rs m = some (es, out, m) ∧ + es.length = steps ∧ countProbes es = probes + +private theorem Run.nil (s : Word w) (m : Memory w) (rs : Regs w 8) : + Run s m [] rs rs 0 0 := ⟨[], rfl, rfl, rfl⟩ + +private theorem Run.append {s : Word w} {m : Memory w} {a b : Code} + {r t u : Regs w 8} {sa sb pa pb : ℕ} + (ha : Run s m a r t sa pa) (hb : Run s m b t u sb pb) : + Run s m (a ++ b) r u (sa + sb) (pa + pb) := by + obtain ⟨es, he, hse, hpe⟩ := ha + obtain ⟨fs, hf, hsf, hpf⟩ := hb + refine ⟨es ++ fs, by simp [trace_append, he, hf], by simp [hse, hsf], ?_⟩ + simp [probes_append, hpe, hpf] + +private theorem fetch_run (s : Word w) (m : Memory w) (n : ℕ) (rs : Regs w 8) + (hu : rs 1 = 1) : + ∃ out, Run s m (fetch n) rs out (4 * n) (2 * n) ∧ + out 3 = (readExpression m n (rs 3) (rs 4)).1 ∧ + out 4 = (readExpression m n (rs 3) (rs 4)).2 ∧ + ∀ i : Fin 8, i ≠ 3 → i ≠ 4 → i ≠ 7 → out i = rs i := by + induction n generalizing rs with + | zero => exact ⟨rs, Run.nil s m rs, rfl, rfl, fun _ _ _ _ => rfl⟩ + | succ n ih => + let ptr := rs 3 + let addr := m ptr.val + let val := m addr.val + let v := BinaryOp.bitXor.eval (rs 4) val + let mid := Function.update (Function.update (Function.update rs (7 : Fin 8) val) 4 v) 3 (ptr + 1) + have hmid : Run s m fetchOne rs mid 4 2 := by + refine ⟨[.read ptr addr, .read addr val, .tick, .tick], ?_, rfl, rfl⟩ + simp (config := { decide := true }) [fetchOne, trace, Op.effect, BinaryOp.eval, hu, + mid, ptr, addr, val, v, Function.update] + obtain ⟨out, ho, h3, h4, hk⟩ := ih mid (by simpa [mid] using hu) + refine ⟨out, ?_, ?_, ?_, fun i a b c => ?_⟩ + · simpa [fetch, Nat.mul_succ, Nat.add_comm] using hmid.append ho + · simpa [readExpression, mid, ptr, addr, val, v] using h3 + · simpa [readExpression, mid, ptr, addr, val, v] using h4 + · rw [hk i a b c]; simp [mid, Function.update_of_ne a, Function.update_of_ne b, Function.update_of_ne c] + +private theorem quotient_ne (a b : Word w) : + BinaryOp.div.eval (a - b) (a - b) = if a = b then 0 else 1 := by + by_cases he : a = b + · simp [he, BinaryOp.eval] + · have h : (a - b).val ≠ 0 := by + intro hz + exact he (sub_eq_zero.mp (Fin.ext hz)) + simp [BinaryOp.eval, he, Nat.div_self (Nat.pos_of_ne_zero h)] + rfl + +private theorem compare_run (s : Word w) (m : Memory w) (rs : Regs w 8) : + ∃ out, Run s m compareWord rs out 3 0 ∧ + out 6 = (if rs 2 = rs 4 then 0 else rs 6) ∧ + ∀ i : Fin 8, i ≠ 5 → i ≠ 6 → out i = rs i := by + let val := BinaryOp.div.eval (rs 2 - rs 4) (rs 2 - rs 4) + let out := Function.update (Function.update rs (5 : Fin 8) val) 6 (rs 6 * val) + refine ⟨out, ⟨[.tick, .tick, .tick], ?_, rfl, rfl⟩, ?_, fun i h5 h6 => ?_⟩ + · simp (config := { decide := true }) [trace, Op.effect, compareWord, val, out, BinaryOp.eval, + Function.update] + · by_cases h : rs 2 = rs 4 <;> simp [out, val, quotient_ne, h] + · simp [out, Function.update_of_ne h5, Function.update_of_ne h6] + +private theorem scan_run (s : Word w) (m : Memory w) (arity n : ℕ) (rs : Regs w 8) + (hu : rs 1 = 1) : + ∃ out, Run s m (scan arity n) rs out ((4 * arity + 4) * n) (2 * arity * n) ∧ + out 6 = (if rs 2 ∈ readRows m arity n (rs 3) then 0 else rs 6) ∧ + ∀ i : Fin 8, i < 3 → out i = rs i := by + induction n generalizing rs with + | zero => exact ⟨rs, Run.nil s m rs, by simp [readRows], fun _ _ => rfl⟩ + | succ n ih => + let reset := Function.update rs (4 : Fin 8) 0 + have hreset : Run s m [.constant 4 0] rs reset 1 0 := ⟨[.tick], rfl, rfl, rfl⟩ + obtain ⟨f, hf, hp, hv, hfk⟩ := fetch_run s m arity reset (by simpa [reset] using hu) + have fp : f 3 = (readExpression m arity (rs 3) 0).1 := by simpa [reset] using hp + have fv : f 4 = (readExpression m arity (rs 3) 0).2 := by simpa [reset] using hv + have fkeep (i : Fin 8) (h : i < 3 ∨ i = 6) : f i = rs i := by + have h3 : i ≠ 3 := by omega + have h4 : i ≠ 4 := by omega + have h7 : i ≠ 7 := by omega + rw [hfk i h3 h4 h7]; simp [reset, Function.update_of_ne h4] + obtain ⟨c, hc, hc6, hck⟩ := compare_run s m f + have ck (i : Fin 8) (h : i < 3) : c i = rs i := + (hck i (by omega) (by omega)).trans (fkeep i (.inl h)) + obtain ⟨out, ho, ho6, hok⟩ := ih c ((ck 1 (by decide)).trans hu) + refine ⟨out, ?_, ?_, fun i hi => (hok i hi).trans (ck i hi)⟩ + · have h := ((hreset.append hf).append hc).append ho + convert h using 1 <;> first | rfl | ring + · rw [ho6, hc6, ck 2 (by decide), hck 3 (by decide) (by decide), fp, + fkeep 2 (.inl (by decide)), fkeep 6 (.inr rfl), fv] + simp only [readRows, List.mem_cons] + split_ifs <;> simp_all + +/-- Successive candidates produced by the fixed number of complete row passes. -/ +def climb (forbidden : List ℕ) : ℕ → ℕ → ℕ + | 0, start => start + | steps + 1, start => + climb forbidden steps (if start ∈ forbidden then start + 1 else start) + +theorem climb_to_missing {xs : List ℕ} {target : ℕ} (absent : target ∉ xs) + (earlier : ∀ i < target, i ∈ xs) (steps start : ℕ) (hs : start ≤ target) + (enough : target ≤ start + steps) : climb xs steps start = target := by + induction steps generalizing start with + | zero => simp [climb]; omega + | succ steps ih => + by_cases he : start = target + · subst start; simp [climb, absent, ih target le_rfl (by omega)] + · have hl : start < target := by omega + simp [climb, earlier _ hl, ih (start + 1) (by omega) (by omega)] + + +private theorem pass_run (s : Word w) (m : Memory w) (arity n : ℕ) (rs : Regs w 8) + (hu : rs 1 = 1) : + ∃ out, Run s m (pass arity n) rs out ((4 * arity + 4) * n + 4) (2 * arity * n) ∧ + out 2 = (if rs 2 ∈ readRows m arity n (rs 0) then rs 2 + 1 else rs 2) ∧ + out 0 = rs 0 ∧ out 1 = rs 1 := by + let reset := Function.update (Function.update rs (3 : Fin 8) (rs 0)) 6 (rs 1) + have hr : Run s m [.copy 3 0, .copy 6 1] rs reset 2 0 := by + refine ⟨[.tick, .tick], ?_, rfl, rfl⟩ + simp [trace, Op.effect, reset] + obtain ⟨c, hc, h6, hk⟩ := scan_run s m arity n reset (by simpa [reset] using hu) + have keep (i : Fin 8) (hi : i < 3) : c i = rs i := by + rw [hk i hi]; simp [reset, Function.update_of_ne (show i ≠ 3 by omega), + Function.update_of_ne (show i ≠ 6 by omega)] + have hflag : c 6 = if rs 2 ∈ readRows m arity n (rs 0) then 0 else 1 := by + simpa [reset, hu] using h6 + let diff := c 1 - c 6 + let out := Function.update (Function.update c (6 : Fin 8) diff) 2 (c 2 + diff) + have ht : Run s m [.binary .sub 6 1 6, .binary .add 2 2 6] c out 2 0 := by + refine ⟨[.tick, .tick], ?_, rfl, rfl⟩ + simp [trace, Op.effect, out, diff, BinaryOp.eval] + refine ⟨out, ?_, ?_, ?_, ?_⟩ + · convert (hr.append hc).append ht using 1 <;> first | rfl | omega + · by_cases h : rs 2 ∈ readRows m arity n (rs 0) <;> + simp [out, diff, hflag, keep 1 (by decide), keep 2 (by decide), hu, h] + · simpa [out] using keep 0 (by decide) + · simpa [out] using keep 1 (by decide) + +private theorem mem_values (x : Word w) (xs : List (Word w)) : + x.val ∈ xs.map Fin.val ↔ x ∈ xs := by + constructor + · intro h + obtain ⟨y, hy, hval⟩ := List.mem_map.mp h + rwa [← Fin.ext hval] + · exact List.mem_map_of_mem + +private theorem passes_run (s : Word w) (m : Memory w) (arity n j : ℕ) (rs : Regs w 8) + (hu : rs 1 = 1) (hfit : (rs 2).val + j < 2 ^ w) : + ∃ out, Run s m (passes arity n j) rs out (((4 * arity + 4) * n + 4) * j) + (2 * arity * n * j) ∧ + (out 2).val = climb ((readRows m arity n (rs 0)).map Fin.val) j (rs 2).val := by + induction j generalizing rs with + | zero => exact ⟨rs, Run.nil s m rs, rfl⟩ + | succ j ih => + obtain ⟨c, hc, h2, h0, h1⟩ := pass_run s m arity n rs hu + have hv : (c 2).val = if (rs 2).val ∈ (readRows m arity n (rs 0)).map Fin.val + then (rs 2).val + 1 else (rs 2).val := by + simp only [mem_values, h2] + split_ifs with h + · have hone : (1 : Word w).val = 1 := by + rw [Fin.val_one', Nat.mod_eq_of_lt (by omega)] + rw [Fin.val_add, hone, Nat.mod_eq_of_lt (by omega)] + · rfl + have hfit' : (c 2).val + j < 2 ^ w := by rw [hv]; split <;> omega + obtain ⟨out, ho, hval⟩ := ih c (h1.trans hu) hfit' + refine ⟨out, ?_, ?_⟩ + · simpa [passes, Nat.mul_succ, Nat.add_comm] using hc.append ho + · rw [hval, h0, hv, climb] + +/-- The block reads from the descriptor address in register zero. The stated +event counts include all row dereferences, even for a repeated forbidden word. -/ +theorem choose_trace (s : Word w) (m : Memory w) (arity n : ℕ) (rs : Regs w 8) + (hfit : n < 2 ^ w) : + ∃ es out, trace Fin.elim0 s (choose arity n) rs m = some (es, out, m) ∧ + es.length = 2 + ((4 * arity + 4) * n + 4) * n ∧ + countProbes es = 2 * arity * n * n ∧ + (out 2).val = climb ((readRows m arity n (rs 0)).map Fin.val) n 0 := by + let init := Function.update (Function.update rs (1 : Fin 8) 1) 2 0 + have hi : Run s m [.constant 1 1, .constant 2 0] rs init 2 0 := ⟨[.tick, .tick], rfl, rfl, rfl⟩ + obtain ⟨out, ho, hv⟩ := passes_run s m arity n n init (by simp [init]) (by simpa [init] using hfit) + obtain ⟨es, he, hl, hp⟩ := hi.append ho + exact ⟨es, out, he, hl, by simpa using hp, by simpa [init] using hv⟩ + +/-- Starting a fresh burst call uses the persistent input as the row address. -/ +def chooseFromState (arity n : ℕ) : List (Op 8 0) := + [.stateWord 0] ++ choose arity n + +/-- Native execution from freshly reset private memory and registers. The candidate +returned in the persistent state is the least omitted nonnegative index. -/ +theorem choose_native (m : Memory w) (base : Word w) (arity n target : ℕ) + (hfit : n < 2 ^ w) (absent : target ∉ (readRows m arity n base).map Fin.val) + (earlier : ∀ i < target, i ∈ (readRows m arity n base).map Fin.val) : + let code := chooseFromState arity n + let M := (template code 2).instantiate w Fin.elim0 + ∃ es, execute M.program (1 + code.length) (M.program.start base) m [] = + some ⟨es, some (Fin.ofNat _ target)⟩ ∧ + es.length = 3 + ((4 * arity + 4) * n + 4) * n ∧ countProbes es = 2 * arity * n * n := by + dsimp only + let rs : Regs w 8 := Function.update (fun _ => 0) 0 base + have hbase : rs 0 = base := by simp [rs] + have hn : target ≤ n := by + have hsub : List.range target ⊆ (readRows m arity n base).map Fin.val := by + intro i hi; exact earlier _ (List.mem_range.mp hi) + simpa using List.nodup_range.length_le_of_subset hsub + obtain ⟨es, out, he, hl, hp, hv⟩ := choose_trace base m arity n rs hfit + rw [hbase, climb_to_missing absent earlier n 0 (Nat.zero_le _) (by omega)] at hv + have result : out 2 = Fin.ofNat _ target := + Fin.ext (hv.trans (Nat.mod_eq_of_lt (hn.trans_lt hfit)).symm) + have init : trace Fin.elim0 base [.stateWord 0] (fun _ : Fin 8 => 0) m = + some ([.tick], rs, m) := rfl + refine ⟨.tick :: es, ?_, by simp [hl]; omega, hp⟩ + let M := (template (chooseFromState arity n) 2).instantiate w Fin.elim0 + change execute M.program (1 + (chooseFromState arity n).length) + ⟨M.entry, base, fun _ => 0, fun _ => 0⟩ m [] = _ + rw [execute_template, run_eq_trace, chooseFromState, trace_append, init] + simp [he, result] + + +/-- A visitor's header contains the label destination and the next vertex's +header address. The forbidden operand rows immediately follow that header. -/ +private def visitHead : Code := + [.stateWord 0, .constant 1 1, .binary .add 0 0 1, .binary .add 0 0 1] + +private def visitTail : Code := + [.stateWord 7, .read 5 7, .constant 1 1, .binary .add 7 7 1, .read 4 7, .write 5 2] + +/-- Instructions for one greedy vertex visit, loading its record, choosing a label that passes +the forbidden-expression tests, and advancing the cursor. -/ +def visitCode (arity n : ℕ) : List (Op 8 0) := visitHead ++ choose arity n ++ visitTail + +/-- Instantiate the greedy visit at the specified word width with register four as its return +register and no public operands. -/ +def visitMachine (w arity n : ℕ) := (template (visitCode arity n) 4).instantiate w Fin.elim0 + +/-- Observable execution of one complete vertex visit. The output label is +stored externally and the persistent return word is the next record address. -/ +def Visit (m : Memory w) (base : Word w) (arity n : ℕ) (v : Word w) : Prop := + let P := (visitMachine w arity n).program + ∃ es, execute P (1 + (visitCode arity n).length) (P.start base) m [] = + some ⟨es, some (m (base + 1).val)⟩ ∧ + after m es = writeMemory m (m base.val) v ∧ + es.length = 12 + ((4 * arity + 4) * n + 4) * n ∧ + countProbes es = 3 + 2 * arity * n * n + +private theorem effect_memory {k r : ℕ} {op : Op r k} {pub : Fin k → Word w} {s : Word w} + {rs out : Regs w r} {m final : Memory w} {e : Event w} + (he : op.effect pub s rs m = some (e, out, final)) : update m e = final := by + cases op <;> simp only [Op.effect, Option.some.injEq, Prod.mk.injEq] at he + all_goals first + | obtain ⟨rfl, rfl, rfl⟩ := he; rfl + | split at he <;> simp only [Option.some.injEq, Prod.mk.injEq, reduceCtorEq] at he + all_goals obtain ⟨rfl, rfl, rfl⟩ := he; rfl + +theorem trace_after {k r : ℕ} {pub : Fin k → Word w} {s : Word w} + {ops : List (Op r k)} {rs out : Regs w r} {m final : Memory w} {es : List (Event w)} + (h : trace pub s ops rs m = some (es, out, final)) : after m es = final := by + induction ops generalizing rs m es with + | nil => simp [trace] at h; rw [h.1, h.2.2]; rfl + | cons op ops ih => + cases he : op.effect pub s rs m with + | none => simp [trace, he] at h + | some t => + obtain ⟨e, rs', m'⟩ := t + cases ht : trace pub s ops rs' m' with + | none => simp [trace, he, ht] at h + | some u => + obtain ⟨fs, rs'', m''⟩ := u + simp [trace, he, ht] at h + obtain ⟨rfl, rfl, rfl⟩ := h + change after (update m e) fs = m'' + rw [effect_memory he] + exact ih ht + +theorem visit_native (m : Memory w) (base v : Word w) (arity n : ℕ) (hfit : n < 2 ^ w) + (hvalue : climb ((readRows m arity n (base + 1 + 1)).map Fin.val) n 0 = v.val) : + Visit m base arity n v := by + let init : Regs w 8 := Function.update (Function.update (Function.update (fun _ => 0) (0 : Fin 8) base) 1 1) 0 (base + 1 + 1) + have hhead : trace Fin.elim0 base visitHead (fun _ : Fin 8 => 0) m = + some ([.tick, .tick, .tick, .tick], init, m) := by + simp (config := {decide := true}) [visitHead, trace, Op.effect, BinaryOp.eval, init, Function.update] + rfl + obtain ⟨es, c, hc, hl, hp, hv⟩ := choose_trace base m arity n init hfit + have cv : c 2 = v := Fin.ext (by simpa [init, hvalue] using hv) + let a := m base.val + let next := m (base + 1).val + let tailEvents : List (Event w) := [.tick, .read base a, .tick, .tick, .read (base + 1) next, .write a v] + let out := Function.update (Function.update (Function.update (Function.update (Function.update c (7 : Fin 8) base) 5 a) + 1 1) 7 (base + 1)) 4 next + let final := writeMemory m a v + have ht : trace Fin.elim0 base visitTail c m = some (tailEvents, out, final) := by + simp (config := {decide := true}) [visitTail, trace, Op.effect, BinaryOp.eval, a, next, tailEvents, cv, + out, final, Function.update] + exact ⟨⟨rfl, rfl⟩, rfl⟩ + let events := ([.tick, .tick, .tick, .tick] ++ es) ++ tailEvents + have he : trace Fin.elim0 base (visitCode arity n) (fun _ : Fin 8 => 0) m = some (events, out, final) := by + simp [visitCode, trace_append, hhead, hc, ht, events] + refine ⟨events, ?_, trace_after he, ?_, ?_⟩ + · let M := visitMachine w arity n + change execute M.program (1 + (visitCode arity n).length) + ⟨M.entry, base, fun _ => 0, fun _ => 0⟩ m [] = _ + dsimp only [M, visitMachine] + rw [execute_template, run_eq_trace, he] + simp [out, next] + · simp [events, tailEvents, hl]; omega + · simp [events, probes_append, tailEvents, countProbes, hp]; omega + +end CompressorRecords.Greedy + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordGreedyDirectory.lean b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyDirectory.lean new file mode 100644 index 0000000000..8fdec1b1ac --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyDirectory.lean @@ -0,0 +1,206 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedyPrepare + +/-! +# Installing the greedy directory in external memory + +After the first `k` calls, the first `k` mutable labels and the first `k` +records agree with the complete directory. The remaining words still have +their original values. In particular, each call sees the original control +words and both directed mate arrays. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy.WalkLayout + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.SlotGraph + +variable {w N width d : ℕ} {V C : Type*} +variable (L : WalkLayout w N width) + +/-- Memory after installing the first `k` indexed vertices. -/ +def prefixMemory (ptrs : Fin N → List (Word w)) (outside : Memory w) (k : ℕ) : Memory w := + fun z ↦ if (L.origin ≤ z ∧ z < L.origin + k) ∨ + (L.origin + N ≤ z ∧ z < L.origin + N + k * (2 + width)) + then L.initialMemory ptrs outside z else outside z + +@[simp] theorem prefixMemory_zero (ptrs : Fin N → List (Word w)) (outside : Memory w) : + L.prefixMemory ptrs outside 0 = outside := by + funext z + simp [prefixMemory] + +theorem prefixMemory_full (ptrs : Fin N → List (Word w)) (outside : Memory w) : + L.prefixMemory ptrs outside N = L.initialMemory ptrs outside := by + funext z + unfold prefixMemory + split + · rfl + · rename_i h + by_cases hz : z < L.origin + · simp [initialMemory, hz] + · exact (L.initialMemory_after ptrs outside (by unfold limit; omega)).symm + +private theorem stores_iff_fields (m : Memory w) (p : Word w) (xs : List (Word w)) + (fit : p.val + xs.length ≤ 2 ^ w) : + Stores m p xs ↔ ∀ t : Fin xs.length, m (p.val + t.val) = xs[t.val] := by + induction xs generalizing p with + | nil => simp [Stores] + | cons x xs ih => + cases xs with + | nil => + simp [Stores] + | cons y ys => + have hn : (p + 1).val = p.val + 1 := by + simp only [List.length_cons] at fit + rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (by omega : 1 < 2 ^ w), + Nat.mod_eq_of_lt (by omega)] + rw [Stores, ih _ (by simp only [hn, List.length_cons] at *; omega)] + simp [Fin.forall_fin_succ, hn, Nat.add_assoc, Nat.add_comm 1] + +/-- One complete row write, including the zero label, advances the memory invariant. -/ +theorem write_prefixMemory (ptrs : Fin N → List (Word w)) (outside : Memory w) + (size : ∀ i, (ptrs i).length = width) (i : Fin N) : + writeRow (writeMemory (L.prefixMemory ptrs outside i.val) (L.label i) 0) + (L.base i.val) (L.record ptrs i) = L.prefixMemory ptrs outside (i.val + 1) := by + let p := L.origin + N + i.val * (2 + width) + have bound := Nat.mul_le_mul_right (2 + width) (Nat.succ_le_of_lt i.isLt) + rw [Nat.succ_mul] at bound + have fit := L.fits + have hv : (L.base i.val).val = p := Nat.mod_eq_of_lt (by omega) + have len : (L.record ptrs i).length = 2 + width := by simp [record, size]; omega + have hfit : (L.base i.val).val + (L.record ptrs i).length ≤ 2 ^ w := by + rw [hv, len]; dsimp [p]; omega + funext z + by_cases hz : p ≤ z ∧ z < p + (2 + width) + · let t := z - p + have ht : t < 2 + width := by dsimp [t]; omega + have eq : z = p + t := by dsimp [t]; omega + let m := writeMemory (L.prefixMemory ptrs outside i.val) (L.label i) 0 + have stored := (stores_iff_fields _ _ _ hfit).mp (writeRow_stores m _ _ hfit) + ⟨t, by simpa only [len] using ht⟩ + rw [hv, ← eq] at stored + rw [stored, prefixMemory, ite_eq_left (Or.inr ⟨by dsimp [p] at hz; omega, + by rw [Nat.succ_mul]; dsimp [p] at hz; omega⟩), eq] + rw [L.initialMemory_field ptrs outside i ht, List.getElem?_eq_getElem (len ▸ ht), + Option.getD_some] + · rw [writeRow_outside _ _ _ _ hfit (by rw [hv, len]; omega)] + by_cases hl : z = (L.label i).val + · subst z + rw [writeMemory, ite_eq_left rfl, prefixMemory, ite_eq_left (Or.inl (by rw [label_val]; omega)), + L.initialMemory_label] + · rw [writeMemory, ite_eq_right hl] + unfold prefixMemory + rw [label_val] at hl + dsimp [p] at hz + rw [Nat.succ_mul] + congr 1 + apply propext + omega + +/-- Partial installation preserves every word outside the walk allocation. -/ +theorem prefixMemory_outside (ptrs : Fin N → List (Word w)) (outside : Memory w) + {k z : ℕ} (hk : k ≤ N) (hz : z < L.origin ∨ L.limit ≤ z) : + L.prefixMemory ptrs outside k z = outside z := by + have h := Nat.mul_le_mul_right (2 + width) hk + unfold limit at hz + exact ite_eq_right (by omega) + +/-- The prefix writes preserve the two mate arrays supplied to the initializer. -/ +theorem prefixMemory_tables (ptrs : Fin N → List (Word w)) (outside : Memory w) + {k : ℕ} {T : PortTables w} {G : SlotGraph V d} {order : V ≃ Fin N} (hk : k ≤ N) + (rep : T.Represents G order outside) (free : GraphOutside (d := d) L T order) : + T.Represents G order (L.prefixMemory ptrs outside k) := by + refine ⟨rep.degree, rep.fits, rep.vertices, fun e ↦ ?_, fun e ↦ ?_⟩ + · rw [prefixMemory_outside L ptrs outside hk (free e _ (by simp)), rep.outgoing] + · rw [prefixMemory_outside L ptrs outside hk (free e _ (by simp)), rep.incoming] + +/-- The low control words are readable throughout preparation. -/ +theorem prefixMemory_controls (ptrs : Fin N → List (Word w)) (outside : Memory w) + {k : ℕ} {xs : List (Word w)} (hk : k ≤ N) (hs : Stores outside 0 xs) + (h : xs.length ≤ L.origin) (fit : xs.length ≤ 2 ^ w) : + Stores (L.prefixMemory ptrs outside k) 0 xs := by + have hf : (0 : Word w).val + xs.length ≤ 2 ^ w := by simpa using fit + rw [stores_iff_fields _ _ _ hf] at hs ⊢ + intro t + rw [prefixMemory_outside L ptrs outside hk (.inl (by simpa using t.isLt.trans_le h))] + exact hs t + +/-- Lift native vertex writes along the successive prefix memories. -/ +theorem prepare_segment (P : Program w C) (fuel probes steps : ℕ) (mem : ℕ → Memory w) + (call : ∀ i : Fin N, ∃ es, + execute P fuel (P.start (Fin.ofNat _ i.val)) (mem i.val) [] = + some ⟨es, some (Fin.ofNat _ (i.val + 1))⟩ ∧ + after (mem i.val) es = mem (i.val + 1) ∧ es.length ≤ steps ∧ countProbes es = probes) + (k remaining : ℕ) (bound : k + remaining ≤ N) : + ∃ rs, runSegment P fuel (some (Fin.ofNat _ k)) (mem k) (List.replicate remaining []) = some rs ∧ + endState (some (Fin.ofNat _ k)) rs = some (Fin.ofNat _ (k + remaining)) ∧ + after (mem k) (eventLog rs) = mem (k + remaining) ∧ rs.length = remaining ∧ + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = remaining * (1 + probes) ∧ + ∀ r ∈ rs, r.events.length ≤ steps ∧ countProbes r.events = probes := by + induction remaining generalizing k with + | zero => exact ⟨[], rfl, rfl, rfl, rfl, by simp [RAMBuckets.cost], by simp⟩ + | succ remaining ih => + obtain ⟨es, he, hm, hs, hp⟩ := call ⟨k, by omega⟩ + let r : Report w := ⟨es, some (Fin.ofNat _ (k + 1))⟩ + obtain ⟨rs, run, hend, hfinal, hlen, hcost, hwork⟩ := ih (k + 1) (by omega) + refine ⟨r :: rs, ?_, ?_, ?_, by simp [hlen], ?_, ?_⟩ + · simp only [List.replicate_succ, runSegment, he, hm, run, Option.map_some, r] + · simpa only [endState, r, Nat.add_right_comm k 1, Nat.add_assoc] using hend + · change List.foldl update (mem k) (es ++ eventLog rs) = _ + rw [List.foldl_append] + change after (after (mem k) es) (eventLog rs) = _ + rw [hm, hfinal] + congr 1 + omega + · simp only [RAMBuckets.cost, r, hp, hcost, Nat.succ_mul, Nat.add_comm] + · intro s h + rcases List.mem_cons.mp h with rfl | h + · exact ⟨hs, hp⟩ + · exact hwork _ h + +/-- The native initializer visits every vertex, returns its final cursor and installs the +complete directory. Calls include the control reads, the label and header writes, +and the probes used to obtain and store the operand pointers. -/ +theorem prepare_directory (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows : OperandRows d) (outside : Memory w) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order outside) + (control : Stores outside 0 (controlWords L T)) (low : 8 ≤ L.origin) + (space : L.limit < 2 ^ w) (free : GraphOutside (d := d) L T order) + (size : ∀ i : Fin N, (rowWords T G order (order.symm i) rows).length = width) : + let P := (prepareMachine w rows).program + let ptrs := fun i : Fin N ↦ rowWords T G order (order.symm i) rows + ∃ rs, runSegment P (1 + (prepareCode rows).length) (some 0) outside + (List.replicate N []) = some rs ∧ + endState (some 0) rs = some (Fin.ofNat _ N) ∧ + after outside (eventLog rs) = L.initialMemory ptrs outside ∧ rs.length = N ∧ + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = + N * (12 + rows.length + width) ∧ + ∀ r ∈ rs, r.events.length ≤ 32 + 8 * rows.length + 6 * width ∧ + countProbes r.events = 11 + rows.length + width := by + let ptrs := fun i : Fin N ↦ rowWords T G order (order.symm i) rows + have lowFit : (controlWords L T).length ≤ 2 ^ w := by + change 8 ≤ 2 ^ w + unfold limit at space + omega + have call (i : Fin N) := + prepare_one L T G order rows (L.prefixMemory ptrs outside i.val) i labels + (L.prefixMemory_tables ptrs outside i.isLt.le rep free) + (L.prefixMemory_controls ptrs outside i.isLt.le control low lowFit) + space free (size i) + have whole := prepare_segment (N := N) (prepareMachine w rows).program + (1 + (prepareCode rows).length) (11 + rows.length + width) (32 + 8 * rows.length + 6 * width) + (L.prefixMemory ptrs outside) (fun i ↦ by + obtain ⟨es, he, hm, hs, hp⟩ := call i + exact ⟨es, he, hm.trans (L.write_prefixMemory ptrs outside size i), hs, hp⟩) + 0 N (by omega) + have zero : Fin.ofNat _ 0 = (0 : Word w) := Fin.ext (Nat.zero_mod _) + have cost : 1 + (11 + rows.length + width) = 12 + rows.length + width := by omega + simpa only [prefixMemory_zero, Nat.zero_add, prefixMemory_full, zero, cost] using whole + +end CompressorRecords.Greedy.WalkLayout + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordGreedyInit.lean b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyInit.lean new file mode 100644 index 0000000000..c43c40278e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyInit.lean @@ -0,0 +1,510 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedySlots + +/-! +# Emitting greedy operand rows from the level's slot tables + +Outgoing and incoming mate arrays are indexed by `vertex * degree + port`. +Each cell contains the packed vertex and port at the opposite incidence. +Displacements use the outgoing slot index. Labels use the vertex index. +The row initializer reads exactly one mate, obtains the neighbor by division, +and writes the one or four operand addresses used by the greedy visitor. + +Registers 0–7 carry the vertex index, destination cursor, degree, outgoing +and incoming table bases, displacement base, assignment base and zero cell. +The finite public table holds the local slot numbers and is common to all +vertices and all compression levels of the same degree. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.SlotGraph + +variable {V : Type*} {N w d : ℕ} + +/-- The degree and external table addresses used to initialize greedy operand rows from a +level's directed slots. -/ +structure PortTables (w : ℕ) where + /-- The vertex degree, used to pack and unpack a vertex and local port as one word. -/ + degree : Word w + /-- Base address of the array mapping outgoing ports to their incoming mates. -/ + outgoing : Word w + /-- Base address of the inverse array mapping incoming ports to their outgoing mates. -/ + incoming : Word w + /-- Base address of the displacement array indexed by outgoing ports. -/ + displacements : Word w + /-- Base address of the greedy assignment cells, one per vertex. -/ + labels : Word w + /-- Address of the cell supplying zero to a padded tag comparison. -/ + zero : Word w + +/-- Encode a vertex's ordinal in the supplied vertex order as a machine word. -/ +def vertexNumber (order : V ≃ Fin N) (x : V) : Word w := Fin.ofNat _ (order x).val + +/-- Encode a vertex and port as the vertex ordinal times the degree plus the local port number. -/ +def portNumber (order : V ≃ Fin N) (e : V × Fin d) : Word w := + Fin.ofNat _ ((order e.1).val * d + e.2.val) + +/-- The level's two directed incidence arrays, including inverse slot numbers. -/ +structure PortTables.Represents (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (m : Memory w) : Prop where + degree : T.degree.val = d + fits : N * d ≤ 2 ^ w + vertices : N ≤ 2 ^ w + outgoing : ∀ e, m (T.outgoing + portNumber order e).val = portNumber order (G.target e) + incoming : ∀ e, m (T.incoming + portNumber order e).val = portNumber order (G.target.symm e) + +/-- The same address convention in the operand-record reader. -/ +def PortTables.addresses (T : PortTables w) (order : V ≃ Fin N) : TagAddresses V d w where + zero := T.zero + label x := T.labels + vertexNumber order x + displacement e := T.displacements + portNumber order e + +private theorem port_fit (order : V ≃ Fin N) (e : V × Fin d) (fit : N * d ≤ 2 ^ w) : + (order e.1).val * d + e.2.val < 2 ^ w := by + have h := Nat.mul_le_mul_right d (Nat.succ_le_of_lt (order e.1).isLt) + rw [Nat.succ_mul] at h + have := e.2.isLt + omega + +/-- The public constant at index `i` is the word encoding its ordinal, from zero through the +degree. -/ +def slotNumbers (w d : ℕ) (i : Fin (d+1)) : Word w := Fin.ofNat _ i.val + +private theorem packed_eq {T : PortTables w} {G : SlotGraph V d} {order : V ≃ Fin N} + {m : Memory w} (rep : T.Represents G order m) (x : V) (i : Fin d) : + vertexNumber order x * T.degree + slotNumbers w d i.castSucc = portNumber order (x, i) := by + apply Fin.ext + have hi : i.val < 2 ^ w := i.isLt.trans (rep.degree ▸ T.degree.isLt) + have hx := (order x).isLt.trans_le rep.vertices + have hp := port_fit order (x, i) rep.fits + have hmul : (order x).val * d < 2 ^ w := (Nat.le_add_right ..).trans_lt hp + simp [vertexNumber, slotNumbers, portNumber, Fin.val_add, Fin.val_mul, rep.degree, + Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt hmul, Nat.mod_eq_of_lt hp] + +private theorem unpack_eq {T : PortTables w} {G : SlotGraph V d} {order : V ≃ Fin N} + {m : Memory w} (rep : T.Represents G order m) (e : V × Fin d) : + BinaryOp.div.eval (portNumber order e) T.degree = vertexNumber order e.1 := by + have hpos : 0 < d := Nat.zero_lt_of_lt e.2.isLt + have hv : (portNumber (w := w) order e).val = (order e.1).val * d + e.2.val := + Nat.mod_eq_of_lt (port_fit order e rep.fits) + change Fin.ofNat _ ((portNumber (w := w) order e).val / T.degree.val) = _ + rw [hv, rep.degree, Nat.mul_comm (order e.1).val d, Nat.mul_add_div hpos, Nat.div_eq_of_lt e.2.isLt, Nat.add_zero] + rfl + +/-- Operand address formulas sharing the single mate lookup in one row. -/ +inductive Operand (d : ℕ) where + | zero + | arc + | increment (remote : Bool) (port : Fin d) + | neighborLabel + +private def localIncrement (remote : Bool) : Option (Fin d) → Operand d + | none => .zero + | some i => .increment remote i + +/-- List the four operands for a tag exclusion, padding a local test with two zero operands or +including the neighbor's label for a two-end test. -/ +def tagOperands : TagTests d → List (Operand d) + | (_, .inl a) => [.arc, localIncrement false a, .zero, .zero] + | ((out, _), .inr (a, b)) => + [.arc, localIncrement (!out) a, localIncrement out b, .neighborLabel] + +/-- Compile the shared endpoint and directed displacement index. -/ +def loadMate (out : Bool) (i : Fin d) : List (Op 13 (d+1)) := + [.constant 11 1, .publicWord 10 i.castSucc, .binary .mul 8 0 2, .binary .add 8 8 10, + .binary .add 9 (if out then 3 else 4) 8, .read 9 9, .copy 8 (if out then 8 else 9), + .binary .div 9 9 2] + +private def valueCode : Operand d → List (Op 13 (d+1)) + | .zero => [.copy 10 7] + | .arc => [.binary .add 10 5 8] + | .neighborLabel => [.binary .add 10 6 9] + | .increment remote i => + [.binary .mul 10 (if remote then 9 else 0) 2, .publicWord 12 i.castSucc, + .binary .add 10 10 12, .binary .add 10 5 10] + +/-- Emit the computed operand address at the row cursor and advance the cursor by one word. -/ +def emitOperand (a : Operand d) : List (Op 13 (d+1)) := + valueCode a ++ [.write 1 10, .binary .add 1 1 11] + +/-- Initialize one operand row by reading the selected port's mate and emitting the requested +operand addresses in order. -/ +def initRow (t : Bool × Fin d) (args : List (Operand d)) : List (Op 13 (d+1)) := + loadMate t.1 t.2 ++ args.flatMap emitOperand + +/-- Register contract for starting a row, specifying its vertex, destination cursor, degree, +and five table addresses. -/ +structure RowInput (T : PortTables w) (vertex dest : Word w) (rs : Regs w 13) : Prop where + vertex : rs 0 = vertex + dest : rs 1 = dest + degree : rs 2 = T.degree + outgoing : rs 3 = T.outgoing + incoming : rs 4 = T.incoming + shifts : rs 5 = T.displacements + labels : rs 6 = T.labels + zero : rs 7 = T.zero + +/-- Recover the outgoing arc of an incidence, using the inverse slot matching when the +incidence is incoming. -/ +def arcOf (G : SlotGraph V d) (x : V) : Bool × Fin d → V × Fin d + | (true, i) => (x, i) + | (false, i) => G.target.symm (x, i) + +private theorem mate_trace (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (m : Memory w) (rep : T.Represents G order m) (s dest : Word w) (rs : Regs w 13) + (x : V) (t : Bool × Fin d) (h : RowInput T (vertexNumber order x) dest rs) : + ∃ es out, trace (slotNumbers w d) s (loadMate t.1 t.2) rs m = some (es, out, m) ∧ + es.length = 8 ∧ countProbes es = 1 ∧ + RowInput T (vertexNumber order x) dest out ∧ out 11 = 1 ∧ + out 8 = portNumber order (arcOf G x t) ∧ out 9 = vertexNumber order (neighbor G x t) := by + obtain ⟨out, i⟩ := t + have hpack := packed_eq rep x i + cases out + all_goals + simp (config := {decide := true}) [loadMate, trace, Op.effect, BinaryOp.eval, Function.update, + countProbes, h.vertex, h.degree, h.outgoing, h.incoming, hpack, rep.outgoing, rep.incoming, + arcOf, neighbor] + all_goals + refine ⟨⟨h.vertex, h.dest, h.degree, h.outgoing, h.incoming, h.shifts, h.labels, h.zero⟩, rfl, ?_⟩ + exact unpack_eq rep _ + +/-- Resolve a symbolic greedy operand to its address in the zero, displacement, or label table. -/ +def operandAddress (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (x : V) (t : Bool × Fin d) : Operand d → Word w + | .zero => T.zero + | .arc => T.displacements + portNumber order (arcOf G x t) + | .increment remote i => + T.displacements + portNumber order ((if remote then neighbor G x t else x), i) + | .neighborLabel => T.labels + vertexNumber order (neighbor G x t) + +theorem tagOperands_addresses (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (x : V) (t : TagTests d) : + (tagOperands t).map (operandAddress T G order x t.1) = tagPointers G (T.addresses order) x t := by + obtain ⟨⟨out, i⟩, a | ⟨a, b⟩⟩ := t + · cases out <;> cases a <;> rfl + · cases out <;> cases a <;> cases b <;> rfl + + +/-- External writes of the packed output words, starting at the supplied cursor. -/ +def writeRow (m : Memory w) (dest : Word w) : List (Word w) → Memory w + | [] => m + | v :: vs => writeRow (writeMemory m dest v) (dest + 1) vs + +private theorem count_append (es fs : List (Event w)) : + countProbes (es ++ fs) = countProbes es + countProbes fs := by + induction es with + | nil => simp [countProbes] + | cons e es ih => cases e <;> simp [countProbes, ih, Nat.add_assoc] + +private def regValue (rs : Regs w 13) : Operand d → Word w + | .zero => rs 7 + | .arc => rs 5 + rs 8 + | .neighborLabel => rs 6 + rs 9 + | .increment remote i => + rs 5 + (rs (if remote then 9 else 0) * rs 2 + slotNumbers w d i.castSucc) + +private theorem emit_trace (s : Word w) (m : Memory w) (rs : Regs w 13) + (one : rs 11 = 1) (a : Operand d) : + ∃ es out, trace (slotNumbers w d) s (emitOperand a) rs m = + some (es, out, writeMemory m (rs 1) (regValue rs a)) ∧ + es.length = (emitOperand a).length ∧ countProbes es = 1 ∧ out 1 = rs 1 + 1 ∧ + ∀ i : Fin 13, i ≠ 1 → i ≠ 10 → i ≠ 12 → out i = rs i := by + cases a + case' increment remote i => cases remote + all_goals + simp (config := {decide := true}) [trace, Op.effect, emitOperand, valueCode, BinaryOp.eval, one, + regValue, countProbes, Function.update] + intro i h1 h10 h12 + simp_all + +private theorem emit_list (s : Word w) (m : Memory w) (rs : Regs w 13) + (one : rs 11 = 1) (args : List (Operand d)) : + ∃ es out, trace (slotNumbers w d) s (args.flatMap emitOperand) rs m = + some (es, out, writeRow m (rs 1) (args.map (regValue rs))) ∧ + es.length = (args.flatMap emitOperand).length ∧ countProbes es = args.length ∧ + out 1 = advance (rs 1) args.length ∧ + ∀ i : Fin 13, i ≠ 1 → i ≠ 10 → i ≠ 12 → out i = rs i := by + induction args generalizing m rs with + | nil => exact ⟨[], rs, rfl, rfl, rfl, rfl, fun _ _ _ _ => rfl⟩ + | cons a args ih => + obtain ⟨es, mid, he, hl, hp, hd, keep⟩ := emit_trace s m rs one a + have hval : regValue (d := d) mid = regValue rs := by + funext b + cases b + case' increment remote i => cases remote + all_goals simp (config := {decide := true}) [regValue, keep] + obtain ⟨fs, out, hf, hfl, hfp, hout, finalKeep⟩ := ih (writeMemory m (rs 1) (regValue rs a)) mid + ((keep 11 (by decide) (by decide) (by decide)).trans one) + refine ⟨es ++ fs, out, ?_, by simp [hl, hfl], by simp [count_append, hp, hfp, Nat.add_comm], ?_, + fun i h1 h10 h12 => (finalKeep i h1 h10 h12).trans (keep i h1 h10 h12)⟩ + · simp only [List.flatMap_cons, trace_append, he, Option.bind_some, hf, Option.map_some, + List.map_cons, writeRow, hd, hval] + · simpa [advance, hd] using hout + +/-- The machine reads one directed mate and writes exactly the specified operand +row. No later lookup in this row depends on the overwritten external cells. -/ +theorem initRow_trace (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (m : Memory w) (rep : T.Represents G order m) (s dest : Word w) (rs : Regs w 13) + (x : V) (t : Bool × Fin d) (h : RowInput T (vertexNumber order x) dest rs) (args : List (Operand d)) : + ∃ es out, trace (slotNumbers w d) s (initRow t args) rs m = + some (es, out, writeRow m dest (args.map (operandAddress T G order x t))) ∧ + es.length = (initRow t args).length ∧ countProbes es = 1 + args.length ∧ + RowInput T (vertexNumber order x) (advance dest args.length) out := by + obtain ⟨es, mid, hm, hl, hp, mi, hu, h8, h9⟩ := mate_trace T G order m rep s dest rs x t h + have hval : regValue mid = operandAddress T G order x t := by + funext a + cases a + case' increment remote i => cases remote + all_goals simp only [regValue, operandAddress, mi.zero, mi.shifts, mi.labels, mi.degree, mi.vertex, + Bool.false_eq_true, ↓reduceIte, h8, h9, packed_eq rep] + obtain ⟨fs, out, hf, hfl, hfp, hout, hk⟩ := emit_list s m mid hu args + refine ⟨es ++ fs, out, ?_, ?_, by simp [count_append, hp, hfp], ?_⟩ + · simp [initRow, trace_append, hm, hf, mi.dest, hval] + · simp [initRow, loadMate, hl, hfl]; omega + · constructor + all_goals first + | simpa [mi.dest] using hout + | rw [hk _ (by decide) (by decide) (by decide)]; first + | exact mi.vertex | exact mi.degree | exact mi.outgoing | exact mi.incoming + | exact mi.shifts | exact mi.labels | exact mi.zero + +theorem initRow_length_le (t : Bool × Fin d) (args : List (Operand d)) : + (initRow t args).length ≤ 8 + 6 * args.length := by + suffices (args.flatMap emitOperand).length ≤ 6 * args.length by + rw [initRow, List.length_append, show (loadMate t.1 t.2).length = 8 by rfl] + omega + induction args with + | nil => simp + | cons a args ih => + have ha : (emitOperand a).length ≤ 6 := by cases a <;> simp [emitOperand, valueCode] + simp only [List.flatMap_cons, List.length_append, List.length_cons, Nat.mul_succ] + omega + + +private theorem next_val (p : Word w) (h : p.val + 1 < 2 ^ w) : (p + 1).val = p.val + 1 := by + rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2 ^ w by omega), Nat.mod_eq_of_lt h] + +/-- Sequential writes preserve the complete external memory outside the row. -/ +theorem writeRow_outside (m : Memory w) (dest : Word w) (xs : List (Word w)) (addr : ℕ) + (fit : dest.val + xs.length ≤ 2 ^ w) + (outside : addr < dest.val ∨ dest.val + xs.length ≤ addr) : + writeRow m dest xs addr = m addr := by + induction xs generalizing m dest with + | nil => rfl + | cons v vs ih => + have hn : addr ≠ dest.val := by simp only [List.length_cons] at outside; omega + cases vs with + | nil => simp [writeRow, writeMemory, hn] + | cons u us => + have hd : (dest + 1).val = dest.val + 1 := + next_val dest (by simp only [List.length_cons] at fit; omega) + rw [writeRow, ih _ (dest + 1) (by simp only [hd, List.length_cons] at *; omega) + (by simp only [hd, List.length_cons] at *; omega)] + simp [writeMemory, hn] + +theorem writeRow_stores (m : Memory w) (dest : Word w) (xs : List (Word w)) + (fit : dest.val + xs.length ≤ 2 ^ w) : Stores (writeRow m dest xs) dest xs := by + induction xs generalizing m dest with + | nil => trivial + | cons v vs ih => + cases vs with + | nil => simp [writeRow, Stores, writeMemory] + | cons u us => + have hd : (dest + 1).val = dest.val + 1 := + next_val dest (by simp only [List.length_cons] at fit; omega) + have hf : (dest + 1).val + (u :: us).length ≤ 2 ^ w := by + simp only [hd, List.length_cons] at *; omega + constructor + · rw [writeRow, writeRow_outside _ _ _ _ hf (.inl (by omega))] + simp [writeMemory] + · exact ih _ _ hf + +/-- Execution at the normal entry of the compiled word program with the level's +register arguments. Its event log installs the reader's operand words in external +memory and leaves every word outside their address interval unchanged. -/ +theorem initRow_native (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (m : Memory w) (rep : T.Represents G order m) (s dest : Word w) (rs : Regs w 13) + (x : V) (t : Bool × Fin d) (h : RowInput T (vertexNumber order x) dest rs) (args : List (Operand d)) + (fit : dest.val + args.length ≤ 2 ^ w) (priv : Word w → Word w) : + let code := initRow t args + let M := (template code 1).instantiate w (slotNumbers w d) + let words := args.map (operandAddress T G order x t) + ∃ es, execute M.program (1 + code.length) ⟨M.entry, s, rs, priv⟩ m [] = + some ⟨es, some (advance dest args.length)⟩ ∧ + after m es = writeRow m dest words ∧ Stores (after m es) dest words ∧ + es.length ≤ 8 + 6 * args.length ∧ countProbes es = 1 + args.length := by + dsimp only + obtain ⟨es, out, ht, hl, hp, h1⟩ := initRow_trace T G order m rep s dest rs x t h args + have hm := trace_after ht + refine ⟨es, ?_, hm, ?_, hl.le.trans (initRow_length_le t args), hp⟩ + · rw [execute_template, run_eq_trace, ht] + simp [h1.dest] + · rw [hm] + exact writeRow_stores _ _ _ (by simpa using fit) + + +/-- One output interval is disjoint from both directed mate arrays. -/ +def PortTables.Free (T : PortTables w) (order : V ≃ Fin N) (start size : ℕ) : Prop := + ∀ e : V × Fin d, ∀ base ∈ [T.outgoing, T.incoming], + (base + portNumber order e).val < start ∨ start + size ≤ (base + portNumber order e).val + +theorem keep_tables (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (m : Memory w) (dest : Word w) (words : List (Word w)) (fit : dest.val + words.length ≤ 2 ^ w) + (rep : T.Represents G order m) (free : T.Free (d := d) order dest.val words.length) : + T.Represents G order (writeRow m dest words) := by + refine ⟨rep.degree, rep.fits, rep.vertices, fun e => ?_, fun e => ?_⟩ + · rw [writeRow_outside _ _ _ _ fit (free e T.outgoing (by simp))] + exact rep.outgoing e + · rw [writeRow_outside _ _ _ _ fit (free e T.incoming (by simp))] + exact rep.incoming e + +theorem advance_val (dest : Word w) (n : ℕ) (fit : dest.val + n < 2 ^ w) : + (advance dest n).val = dest.val + n := by + induction n generalizing dest with + | zero => simp [advance] + | succ n ih => + have hv := next_val dest (by omega) + rw [advance, ih _ (by omega), hv]; omega + +private theorem advance_add (dest : Word w) (a b : ℕ) : + advance dest (a + b) = advance (advance dest a) b := by + induction a generalizing dest with + | zero => simp [advance] + | succ a ih => rw [Nat.succ_add, advance, advance, ih] + +theorem writeRow_append (m : Memory w) (dest : Word w) (xs ys : List (Word w)) : + writeRow m dest (xs ++ ys) = writeRow (writeRow m dest xs) (advance dest xs.length) ys := by + induction xs generalizing m dest with + | nil => rfl + | cons x xs ih => simp only [List.cons_append, writeRow, List.length_cons, advance, ih] + +/-- The ordered incidence and operand lists used to initialize one vertex's greedy record. -/ +abbrev OperandRows (d : ℕ) := List ((Bool × Fin d) × List (Operand d)) + +/-- Flatten the resolved operand addresses of all rows for a vertex in their emission order. -/ +def rowWords (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) (x : V) + (rows : OperandRows d) : List (Word w) := + rows.flatMap fun row => row.2.map (operandAddress T G order x row.1) + +/-- Concatenate the native row initializers in the order of the supplied incidence rows. -/ +def initRows (rows : OperandRows d) : List (Op 13 (d+1)) := + rows.flatMap fun row => initRow row.1 row.2 + +theorem initRows_trace (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (s : Word w) (x : V) (rows : OperandRows d) (m : Memory w) (dest : Word w) (rs : Regs w 13) + (h : RowInput T (vertexNumber order x) dest rs) (rep : T.Represents G order m) + (fit : dest.val + (rowWords T G order x rows).length < 2 ^ w) + (free : T.Free (d := d) order dest.val (rowWords T G order x rows).length) : + let words := rowWords T G order x rows + ∃ es out, trace (slotNumbers w d) s (initRows rows) rs m = + some (es, out, writeRow m dest words) ∧ + es.length = (initRows rows).length ∧ countProbes es = rows.length + words.length ∧ + RowInput T (vertexNumber order x) (advance dest words.length) out := by + induction rows generalizing m dest rs with + | nil => exact ⟨[], rs, rfl, rfl, rfl, h⟩ + | cons row rows ih => + dsimp only + obtain ⟨t, args⟩ := row + let words := args.map (operandAddress T G order x t) + let rest := rowWords T G order x rows + have hwords : rowWords T G order x ((t, args) :: rows) = words ++ rest := rfl + have len : words.length = args.length := List.length_map _ + rw [hwords, List.length_append] at fit free + have hd : (advance dest words.length).val = dest.val + words.length := advance_val dest _ (by omega) + have left : T.Free (d := d) order dest.val words.length := fun e b hb => by + obtain hl | hr := free e b hb + · exact Or.inl hl + · exact Or.inr (by omega) + have right : T.Free (d := d) order (advance dest words.length).val rest.length := fun e b hb => by + obtain hl | hr := free e b hb + · exact Or.inl (by omega) + · exact Or.inr (by omega) + obtain ⟨es, mid, he, hl, hp, hm⟩ := initRow_trace T G order m rep s dest rs x t h args + obtain ⟨fs, out, hf, hfl, hfp, ho⟩ := ih (writeRow m dest words) (advance dest words.length) mid + (by simpa only [len] using hm) (keep_tables T G order m dest words (by omega) rep left) + (by change (advance dest words.length).val + rest.length < _; omega) right + refine ⟨es ++ fs, out, ?_, ?_, ?_, ?_⟩ + · simp only [initRows, List.flatMap_cons, hwords, writeRow_append, trace_append, he, + Option.bind_some] + change (trace (slotNumbers w d) s (initRows rows) mid (writeRow m dest words)).map _ = _ + rw [hf]; rfl + · simp only [List.length_append, hl, hfl, initRows, List.flatMap_cons] + · rw [count_append, hp, hfp, hwords, List.length_append, List.length_cons, len] + change 1 + args.length + (rows.length + rest.length) = _ + omega + · simpa only [hwords, List.length_append, advance_add] using ho + +theorem initRows_length_le (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (x : V) (rows : OperandRows d) : + (initRows rows).length ≤ 8 * rows.length + 6 * (rowWords T G order x rows).length := by + induction rows with + | nil => simp [initRows, rowWords] + | cons row rows ih => + change ((initRow row.1 row.2) ++ initRows rows).length ≤ + 8 * (rows.length + 1) + 6 * ((row.2.map _ ++ rowWords T G order x rows).length) + rw [List.length_append, List.length_append, List.length_map, Nat.mul_add, Nat.mul_add] + have h := initRow_length_le row.1 row.2 + omega + +/-- A single fixed instruction table emits every forbidden pointer for a vertex, +retaining the current external memory between rows. -/ +theorem initRows_native (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) + (s : Word w) (x : V) (rows : OperandRows d) (m : Memory w) (dest : Word w) (rs : Regs w 13) + (h : RowInput T (vertexNumber order x) dest rs) (rep : T.Represents G order m) + (fit : dest.val + (rowWords T G order x rows).length < 2 ^ w) + (free : T.Free (d := d) order dest.val (rowWords T G order x rows).length) + (priv : Word w → Word w) : + let code := initRows rows + let M := (template code 1).instantiate w (slotNumbers w d) + let words := rowWords T G order x rows + ∃ es, execute M.program (1 + code.length) ⟨M.entry, s, rs, priv⟩ m [] = + some ⟨es, some (advance dest words.length)⟩ ∧ + after m es = writeRow m dest words ∧ Stores (after m es) dest words ∧ + es.length ≤ 8 * rows.length + 6 * words.length ∧ countProbes es = rows.length + words.length := by + dsimp only + obtain ⟨es, out, ht, hl, hp, h1⟩ := initRows_trace T G order s x rows m dest rs h rep fit free + have hm := trace_after ht + refine ⟨es, ?_, hm, ?_, hl.le.trans (initRows_length_le T G order x rows), hp⟩ + · rw [execute_template, run_eq_trace, ht] + simp [h1.dest] + · rw [hm] + exact writeRow_stores _ _ _ fit.le + + +/-- The two vertex programs use the exact exclusion order of the greedy reader. -/ +def colorOperandRows (d : ℕ) : OperandRows d := + (incidences d).map (fun t => (t, [.neighborLabel])) + +/-- Enumerate the four-operand rows for all tag exclusions of a degree-`d` vertex. -/ +def tagOperandRows (d : ℕ) : OperandRows d := + (tagTests d).map (fun t => (t.1, tagOperands t)) + +theorem rowWords_color (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) (x : V) : + rowWords T G order x (colorOperandRows d) = (colorRows G x (T.addresses (d := d) order).label).flatten := by + simp [rowWords, colorOperandRows, colorRows, operandAddress, PortTables.addresses, + Function.comp_def, List.flatMap_def] + +theorem rowWords_tag (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) (x : V) : + rowWords T G order x (tagOperandRows d) = + ((tagTests d).map (tagPointers G (T.addresses order) x)).flatten := by + simp [rowWords, tagOperandRows, Function.comp_def, List.flatMap_def, tagOperands_addresses] + +theorem rowWords_color_length (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) (x : V) : + (rowWords T G order x (colorOperandRows d)).length = 2 * d := by + simp [rowWords, colorOperandRows, List.flatMap_map] + +theorem rowWords_tag_length (T : PortTables w) (G : SlotGraph V d) (order : V ≃ Fin N) (x : V) : + (rowWords T G order x (tagOperandRows d)).length = (tagTests d).length * 4 := by + have h (t : TagTests d) : (tagOperands t).length = 4 := by + obtain ⟨⟨b,i⟩, a | ⟨a,c⟩⟩ := t <;> rfl + simp [rowWords, tagOperandRows, List.flatMap_map, h] + +end CompressorRecords.Greedy + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordGreedyPass.lean b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyPass.lean new file mode 100644 index 0000000000..b2b9ecddcb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyPass.lean @@ -0,0 +1,150 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedyDirectory + +/-! +# Preparing and reading the current compressor level + +The initializer derives both greedy operand directories from the evolving level's +forward and inverse mate arrays. The color reader follows label pointers. The tag +reader additionally uses the zero and outgoing displacement cells already present +in that level. These arrays may occur anywhere outside the current output region. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy.WalkLayout + +open BurstRAM Compression Compression.SlotGraph + +variable {w N width d j : ℕ} {V : Type*} + +private theorem assignment_addresses (L : WalkLayout w N width) (T : PortTables w) + (order : V ≃ Fin N) (h : T.labels = Fin.ofNat _ L.origin) : + (T.addresses (d := d) order).label = L.label ∘ order := by + funext x + apply Fin.ext + simp only [PortTables.addresses, WalkLayout.label, vertexNumber, h, Fin.val_add, Fin.val_ofNat, + Nat.mod_add_mod, Nat.add_mod_mod, Function.comp_apply] + +/-- A field outside both mutable assignments and the directory has its supplied +value throughout the complete reader scan. -/ +private theorem fixed_value {L : WalkLayout w N width} {A : Type*} {ptrs : Fin N → List (Word w)} + {outside m : Memory w} {encode : A → Word w} {order : V ≃ Fin N} {f : V → A} + (r : L.Represents (L.initialMemory ptrs outside) m encode order f) (a : Word w) + (ha : a.val < L.origin ∨ L.limit ≤ a.val) : m a.val = outside a.val := by + rcases ha with h | h + · rw [r.frame _ (Or.inl h)] + simp [initialMemory, h] + · rw [r.frame _ (.inr (by unfold limit at h; omega))] + exact initialMemory_after L _ _ h + +/-- Existing immutable displacement data for the native tag pass. -/ +structure OffsetData (L : WalkLayout w N width) (T : PortTables w) (order : V ≃ Fin N) + (hw : j ≤ w) (τ : V × Fin d → BitWord j) (m : Memory w) : Prop where + zero : m T.zero.val = 0 + zeroOutside : T.zero.val < L.origin ∨ L.limit ≤ T.zero.val + displacement : ∀ e, m ((T.addresses order).displacement e).val = tagWord hw (τ e) + displacementOutside : ∀ e : V × Fin d, let a := ((T.addresses order).displacement e).val + a < L.origin ∨ L.limit ≤ a + +theorem color_read_prepared (L : WalkLayout w N (2 * d)) (T : PortTables w) + (G : SlotGraph V d) (order : V ≃ Fin N) (outside : Memory w) + (labels : T.labels = Fin.ofNat _ L.origin) (hfit : 2 * d < 2 ^ w) : + L.Pass (L.initialMemory (fun i => rowWords T G order (order.symm i) (colorOperandRows d)) outside) + 1 (2 * d) (fun v : Fin (2 * d + 1) => Fin.ofNat _ v.val) order (G.orderedColor order) := by + have eqn : (fun i => rowWords T G order (order.symm i) (colorOperandRows d)) = L.colorOperands G order := by + funext i + rw [rowWords_color, assignment_addresses (d := d) L T order labels] + rfl + rw [eqn] + exact color_pass L G order outside hfit + +theorem tag_read_prepared (L : WalkLayout w N (4 * tagCount d)) (T : PortTables w) + (G : SlotGraph V d) (order : V ≃ Fin N) (outside : Memory w) + (labels : T.labels = Fin.ofNat _ L.origin) (τ : V × Fin d → BitWord j) + (hw : j ≤ w) (hcard : tagCount d < 2 ^ j) (data : OffsetData L T order hw τ outside) : + L.Pass (L.initialMemory (fun i => rowWords T G order (order.symm i) (tagOperandRows d)) outside) + 4 (tagCount d) (tagWord hw) order (G.orderedTagOffsets order (bitWordFinEquiv j) τ hcard) := by + classical + rw [orderedTagOffsets_fold] + apply scan_pass L 0 (tagWord_zero hw) order (G.chooseTag (bitWordFinEquiv j) τ hcard) + (fun i => rowWords T G order (order.symm i) (tagOperandRows d)) _ outside + · intro m f i rep rows + apply tag_visit G (order.symm i) τ f hcard hw m _ (T.addresses order) _ + (by simpa only [rowWords_tag] using rows) + constructor + · exact (fixed_value rep _ data.zeroOutside).trans data.zero + · exact fun e => (fixed_value rep _ (data.displacementOutside e)).trans (data.displacement e) + · rw [assignment_addresses (d := d) L T order labels] + exact rep.labels + · intro i + rw [rowWords_tag_length, tagTests_length, Nat.mul_comm] + + +/-- Two consecutive native phases. The reader starts in exactly the external +memory left by the preparer's report log. Both machines reset private storage +on every call. -/ +def PreparedPass {A : Type*} (L : WalkLayout w N width) (rows : OperandRows d) + (outside : Memory w) (arity n : ℕ) (encode : A → Word w) (order : V ≃ Fin N) + (f : V → A) : Prop := + ∃ rs, runSegment (prepareMachine w rows).program (1 + (prepareCode rows).length) + (some 0) outside (List.replicate N []) = some rs ∧ + endState (some 0) rs = some (Fin.ofNat _ N) ∧ rs.length = N ∧ + RAMBuckets.cost (fun r : Report w => countProbes r.events) rs = N * (12 + rows.length + width) ∧ + (∀ r ∈ rs, r.events.length ≤ 32 + 8 * rows.length + 6 * width ∧ + countProbes r.events = 11 + rows.length + width) ∧ + L.Pass (after outside (eventLog rs)) arity n encode order f + +theorem prepared_color_pass (L : WalkLayout w N (2 * d)) (T : PortTables w) + (G : SlotGraph V d) (order : V ≃ Fin N) (m : Memory w) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (control : Stores m 0 (controlWords L T)) (low : 8 ≤ L.origin) (space : L.limit < 2 ^ w) + (outside : GraphOutside (d := d) L T order) (hfit : 2 * d < 2 ^ w) : + L.PreparedPass (colorOperandRows d) m 1 (2 * d) + (fun v : Fin (2 * d + 1) => Fin.ofNat _ v.val) order (G.orderedColor order) := by + obtain ⟨rs, hr, hend, hm, hl, hc, hwork⟩ := + L.prepare_directory T G order (colorOperandRows d) m labels rep control low space outside + (fun _ => rowWords_color_length T G order _) + refine ⟨rs, hr, hend, hl, hc, hwork, ?_⟩ + rw [hm] + exact color_read_prepared L T G order m labels hfit + +theorem prepared_tag_pass (L : WalkLayout w N (4 * tagCount d)) (T : PortTables w) + (G : SlotGraph V d) (order : V ≃ Fin N) (m : Memory w) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (control : Stores m 0 (controlWords L T)) (low : 8 ≤ L.origin) (space : L.limit < 2 ^ w) + (outside : GraphOutside (d := d) L T order) (τ : V × Fin d → BitWord j) + (hw : j ≤ w) (hcard : tagCount d < 2 ^ j) (data : OffsetData L T order hw τ m) : + L.PreparedPass (tagOperandRows d) m 4 (tagCount d) (tagWord hw) order + (G.orderedTagOffsets order (bitWordFinEquiv j) τ hcard) := by + have size (x : V) : (rowWords T G order x (tagOperandRows d)).length = 4 * tagCount d := by + rw [rowWords_tag_length, tagTests_length, Nat.mul_comm] + obtain ⟨rs, hr, hend, hm, hl, hc, hwork⟩ := + L.prepare_directory T G order (tagOperandRows d) m labels rep control low space outside + (fun _ => size _) + refine ⟨rs, hr, hend, hl, hc, hwork, ?_⟩ + rw [hm] + exact tag_read_prepared L T G order m labels τ hw hcard data + +/-- Total calls plus probes for preparing and scanning a level with `N` base vertices. -/ +theorem PreparedPass.cost {A : Type*} {L : WalkLayout w N width} {rows : OperandRows d} + {outside : Memory w} {arity n : ℕ} {encode : A → Word w} {order : V ≃ Fin N} {f : V → A} + (h : L.PreparedPass rows outside arity n encode order f) : + ∃ prep reads, runSegment (prepareMachine w rows).program (1 + (prepareCode rows).length) + (some 0) outside (List.replicate N []) = some prep ∧ + runSegment (visitMachine w arity n).program (1 + (visitCode arity n).length) + (some (L.base 0)) (after outside (eventLog prep)) (List.replicate N []) = some reads ∧ + RAMBuckets.cost (fun r : Report w => countProbes r.events) prep + + RAMBuckets.cost (fun r : Report w => countProbes r.events) reads = + N * (16 + rows.length + width + 2 * arity * n * n) := by + obtain ⟨prep, hp, _, _, hcost, _, hr⟩ := h + obtain ⟨reads, he, hc⟩ := hr.cost + refine ⟨prep, reads, hp, he, ?_⟩ + rw [hc, hcost]; ring + +end CompressorRecords.Greedy.WalkLayout + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordGreedyPrepare.lean b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyPrepare.lean new file mode 100644 index 0000000000..fd0964e785 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyPrepare.lean @@ -0,0 +1,228 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedyInit +import OAI.Computability.VPVNP.CompressorRecordGreedyWalk + +/-! +# Preparing a greedy vertex record in a fresh burst call + +Eight header words in external memory identify the current level's mate, +displacement and assignment arrays, its first record, and the record stride. +One finite instruction table uses the persistent vertex index to initialize +its label, write the two header fields and emit all operand rows. It returns +the next vertex index. The public slot-number table is independent of the +graph, the current level and the word width. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression + +variable {V : Type*} {N w width d : ℕ} + +/-- The eight control words for preparing a greedy record, including its first address and its +stride of two header words plus operand width. -/ +def controlWords (L : WalkLayout w N width) (T : PortTables w) : List (Word w) := + [T.degree, T.outgoing, T.incoming, T.displacements, T.labels, T.zero, L.base 0, + Fin.ofNat _ (2 + width)] + +private def loadControls (d : ℕ) : List (Op 13 (d+1)) := + [.stateWord 0, .constant 11 1, .constant 12 0] ++ + ([2,3,4,5,6,7,8,9] : List (Fin 13)).flatMap fun dst => + [.read dst 12, .binary .add 12 12 11] + +private def putHeader (d : ℕ) : List (Op 13 (d+1)) := + [.binary .mul 10 0 9, .binary .add 1 8 10, .binary .add 10 6 0, .constant 12 0, + .write 10 12, .write 1 10, .binary .add 10 1 9, .binary .add 1 1 11, .write 1 10, .binary .add 1 1 11] + +private def nextVertex (d : ℕ) : List (Op 13 (d+1)) := [.constant 11 1, .binary .add 0 0 11] + +/-- The shared record writer runs once the eight controls occupy registers 2 through 9. -/ +def prepareBody (rows : OperandRows d) : List (Op 13 (d+1)) := + putHeader d ++ initRows rows ++ nextVertex d + +/-- Native preparation code that loads the eight control words and initializes the vertex +record and its operand rows. -/ +def prepareCode (rows : OperandRows d) : List (Op 13 (d+1)) := + loadControls d ++ prepareBody rows + +/-- Instantiate the record-preparation machine with the given word width and public slot-number +table. -/ +def prepareMachine (w : ℕ) (rows : OperandRows d) := + (template (prepareCode rows) 0).instantiate w (slotNumbers w d) + +private theorem loaded (L : WalkLayout w N width) (T : PortTables w) (m : Memory w) + (control : Stores m 0 (controlWords L T)) (s : Word w) (d : ℕ) : + ∃ es rs, trace (slotNumbers w d) s (loadControls d) (fun _ => 0) m = some (es,rs,m) ∧ + es.length = 19 ∧ countProbes es = 8 ∧ RowInput T s 0 rs ∧ rs 11 = 1 ∧ + rs 8 = L.base 0 ∧ rs 9 = Fin.ofNat _ (2 + width) := by + obtain ⟨h2,h3,h4,h5,h6,h7,h8,h9,_⟩ := control + simp (config := {decide := true}) [loadControls, trace, Op.effect, BinaryOp.eval, countProbes, + Function.update] + simp only [zero_add] at h3 h4 h5 h6 h7 h8 h9 + exact ⟨⟨rfl, rfl, h2, h3, h4, h5, h6, h7⟩, rfl, h8, h9⟩ + +private theorem index_add (a b : ℕ) : + (Fin.ofNat _ a : Word w) + Fin.ofNat _ b = Fin.ofNat _ (a + b) := by + apply Fin.ext + simp only [Fin.val_ofNat, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + +private theorem index_mul (a b : ℕ) : + (Fin.ofNat _ a : Word w) * Fin.ofNat _ b = Fin.ofNat _ (a * b) := by + apply Fin.ext + simp only [Fin.val_ofNat, Fin.val_mul, Nat.mod_mul_mod, Nat.mul_mod_mod] + +private theorem base_index (L : WalkLayout w N width) (i : ℕ) : + L.base 0 + Fin.ofNat _ i * Fin.ofNat _ (2 + width) = L.base i := by + simp only [WalkLayout.base, Nat.zero_mul, Nat.add_zero, index_mul, index_add] + +private theorem base_next (L : WalkLayout w N width) (i : ℕ) : + L.base i + Fin.ofNat _ (2 + width) = L.base (i+1) := by + simp only [WalkLayout.base, index_add, Nat.succ_mul, Nat.add_assoc] + +private theorem header_written (L : WalkLayout w N width) (T : PortTables w) + (m : Memory w) (i : Fin N) (d : ℕ) (rs : Regs w 13) (labels : T.labels = Fin.ofNat _ L.origin) + (h : RowInput T (Fin.ofNat _ i.val) 0 rs) (unit : rs 11 = 1) + (first : rs 8 = L.base 0) (stride : rs 9 = Fin.ofNat _ (2+width)) : + ∃ es out, trace (slotNumbers w d) (Fin.ofNat _ i.val) (putHeader d) rs m = + some (es, out, writeRow (writeMemory m (L.label i) 0) (L.base i.val) [L.label i, L.base (i.val+1)]) ∧ + es.length = 10 ∧ countProbes es = 3 ∧ + RowInput T (Fin.ofNat _ i.val) (L.base i.val + 1 + 1) out := by + have hl : T.labels + (Fin.ofNat _ i.val) = L.label i := by rw [labels, index_add]; rfl + simp (config := {decide := true}) [-Fin.ofNat_eq_cast, putHeader, trace, Op.effect, BinaryOp.eval, countProbes, Function.update, + writeRow, h.vertex, h.labels, unit, first, stride, base_index, base_next, hl] + exact ⟨h.vertex, rfl, h.degree, h.outgoing, h.incoming, h.shifts, h.labels, h.zero⟩ + +/-- Both directed mate arrays are outside the entire prepared directory. -/ +def GraphOutside (L : WalkLayout w N width) (T : PortTables w) (order : V ≃ Fin N) : Prop := + ∀ e : V × Fin d, ∀ b ∈ [T.outgoing, T.incoming], + (b + portNumber order e).val < L.origin ∨ L.limit ≤ (b + portNumber order e).val + +theorem GraphOutside.free {L : WalkLayout w N width} {T : PortTables w} {order : V ≃ Fin N} + (g : GraphOutside (d := d) L T order) (start size : ℕ) + (hstart : L.origin ≤ start) (hend : start + size ≤ L.limit) : + T.Free (d := d) order start size := by + intro e b hb + obtain h | h := g e b hb + · exact Or.inl (by omega) + · exact Or.inr (by omega) + +private theorem base_bounds (L : WalkLayout w N width) (i : Fin N) : + (L.base i.val).val = L.origin + N + i.val * (2 + width) ∧ + (L.base i.val).val + (2 + width) ≤ L.limit := by + have h := Nat.mul_le_mul_right (2 + width) (Nat.succ_le_of_lt i.isLt) + rw [Nat.succ_mul] at h + have := L.fits + have hv : L.origin + N + i.val * (2 + width) < 2 ^ w := by omega + refine ⟨Nat.mod_eq_of_lt hv, ?_⟩ + change (L.origin + N + i.val * (2 + width)) % (2 ^ w) + (2 + width) ≤ L.origin + N + N * (2 + width) + rw [Nat.mod_eq_of_lt hv] + omega + +/-- Installing a vertex record from loaded controls. Both the low-address +initializer and the scheduler's frame-based initializer run this same suffix. -/ +theorem prepareBody_trace (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows : OperandRows d) (m : Memory w) (i : Fin N) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (space : L.limit < 2 ^ w) (outside : GraphOutside (d := d) L T order) + (size : (rowWords T G order (order.symm i) rows).length = width) + (r : Regs w 13) (hr : RowInput T (Fin.ofNat _ i.val) 0 r) (hu : r 11 = 1) + (hfirst : r 8 = L.base 0) (hstride : r 9 = Fin.ofNat _ (2+width)) : + let ptrs := fun k : Fin N ↦ rowWords T G order (order.symm k) rows + ∃ es last, trace (slotNumbers w d) (Fin.ofNat _ i.val) (prepareBody rows) r m = + some (es, last, writeRow (writeMemory m (L.label i) 0) (L.base i.val) (L.record ptrs i)) ∧ + last 0 = Fin.ofNat _ (i.val+1) ∧ es.length ≤ 12 + 8*rows.length + 6*width ∧ + countProbes es = 3 + rows.length + width := by + let s : Word w := Fin.ofNat _ i.val + let b := L.base i.val + let dest := b + 1 + 1 + let header := [L.label i, L.base (i.val+1)] + let cleared := writeMemory m (L.label i) 0 + let mid := writeRow cleared b header + let ptrs := fun k : Fin N => rowWords T G order (order.symm k) rows + have hlen : (ptrs i).length = width := size + obtain ⟨bs, bound⟩ := base_bounds L i + change b.val = _ at bs + change b.val + (2 + width) ≤ _ at bound + have hd : dest.val = b.val + 2 := advance_val b 2 (by omega) + have labBounds : (L.label i).val + 1 ≤ L.limit := by + simp only [WalkLayout.label_val, WalkLayout.limit] + have := i.isLt + omega + have repClear : T.Represents G order cleared := keep_tables T G order m (L.label i) [0] + (by change (L.label i).val + 1 ≤ 2^w; omega) rep + (outside.free _ 1 (by simp) labBounds) + have repMid : T.Represents G order mid := keep_tables T G order cleared b header + (by change b.val + 2 ≤ 2 ^ w; omega) repClear (outside.free _ 2 (by omega) (by omega)) + obtain ⟨bEvents, r', hb, hlb, hpb, hr'⟩ := header_written L T m i d r labels hr hu hfirst hstride + have input : RowInput T (vertexNumber order (order.symm i)) dest r' := by + simpa [vertexNumber, dest, b] using hr' + obtain ⟨c, r'', hc, hlc, hpc, hr''⟩ := initRows_trace T G order s (order.symm i) rows mid dest r' + input repMid (by rw [size]; omega) (outside.free _ _ (by omega) (by rw [size]; omega)) + let final := writeRow mid dest (ptrs i) + let res := Fin.ofNat (2 ^ w) (i.val + 1) + have hr0 : r'' 0 = s := by simpa [s, vertexNumber] using hr''.vertex + have hres : s + 1 = res := index_add i.val 1 + let last := Function.update (Function.update r'' (11 : Fin 13) 1) 0 res + have ht : trace (slotNumbers w d) s (nextVertex d) r'' final = + some ([.tick, .tick], last, final) := by + simp (config := {decide := true}) [-Fin.ofNat_eq_cast, nextVertex, trace, Op.effect, BinaryOp.eval, last, hr0] + change Function.update (Function.update r'' (11 : Fin 13) 1) 0 (s + 1) = _ + rw [hres] + let es := (bEvents ++ c) ++ [.tick, .tick] + have he : trace (slotNumbers w d) s (prepareBody rows) r m = some (es, last, final) := by + change trace (slotNumbers w d) s (putHeader d) r m = some (bEvents, r', mid) at hb + change trace (slotNumbers w d) s (initRows rows) r' mid = some (c, r'', final) at hc + simp [prepareBody, trace_append, hb, hc, ht, es] + have hfinal : final = writeRow cleared b (L.record ptrs i) := by + change writeRow (writeRow cleared b header) dest (ptrs i) = writeRow cleared b (header ++ ptrs i) + rw [writeRow_append] + rfl + have hcBound := initRows_length_le T G order (order.symm i) rows + rw [size] at hcBound hpc + refine ⟨es, last, hfinal ▸ he, by simp [last, res], ?_, ?_⟩ + · simp [es, hlb, hlc]; omega + · simp [es, probes_append, hpb, hpc, countProbes]; omega + +/-- The call installs the complete record and clears the corresponding mutable +label. All inputs other than the fixed slot numbers come from external memory. -/ +theorem prepare_one (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows : OperandRows d) (m : Memory w) (i : Fin N) + (labels : T.labels = Fin.ofNat _ L.origin) (rep : T.Represents G order m) + (control : Stores m 0 (controlWords L T)) (space : L.limit < 2 ^ w) + (outside : GraphOutside (d := d) L T order) + (size : (rowWords T G order (order.symm i) rows).length = width) : + let P := (prepareMachine w rows).program + let words := fun k : Fin N => rowWords T G order (order.symm k) rows + ∃ es, execute P (1 + (prepareCode rows).length) (P.start (Fin.ofNat _ i.val)) m [] = + some ⟨es, some (Fin.ofNat _ (i.val + 1))⟩ ∧ + after m es = writeRow (writeMemory m (L.label i) 0) (L.base i.val) + (L.record (fun k => words k) i) ∧ + es.length ≤ 32 + 8 * rows.length + 6 * width ∧ + countProbes es = 11 + rows.length + width := by + let s : Word w := Fin.ofNat _ i.val + obtain ⟨a,r,ha,hla,hpa,hr,hu,hfirst,hstride⟩ := loaded L T m control s d + obtain ⟨b,last,hb,hresult,hlen,hprobes⟩ := + prepareBody_trace L T G order rows m i labels rep space outside size r hr hu hfirst hstride + have he : trace (slotNumbers w d) s (prepareCode rows) (fun _ ↦ 0) m = + some (a++b,last,writeRow (writeMemory m (L.label i) 0) (L.base i.val) + (L.record (fun k ↦ rowWords T G order (order.symm k) rows) i)) := by + rw [prepareCode,trace_append,ha] + simp only [Option.bind_some] + rw [hb]; rfl + refine ⟨a++b, ?_, trace_after he, ?_, ?_⟩ + · let M := prepareMachine w rows + change execute M.program (1 + (prepareCode rows).length) ⟨M.entry, s, fun _ => 0, fun _ => 0⟩ m [] = _ + dsimp only [M, prepareMachine] + rw [execute_template, run_eq_trace, he] + simp [hresult] + · rw [List.length_append, hla]; omega + · rw [probes_append,hpa,hprobes]; omega + +end CompressorRecords.Greedy + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordGreedySlots.lean b/lean/OAI/Computability/VPVNP/CompressorRecordGreedySlots.lean new file mode 100644 index 0000000000..24fa35471b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordGreedySlots.lean @@ -0,0 +1,269 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedy +import OAI.Computability.VPVNP.SlotGreedyScan +import OAI.Computability.VPVNP.BitSlotXor + +/-! +# Descriptor rows for the greedy vertex scan + +Each record lists addresses of the fields needed for its comparisons. +The pointer-row invariant is independent of the current partial assignment. +Reading through those pointers in the native template recovers the forbidden +indices of the mathematical scan, including at as-yet unassigned neighbors. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.SlotGraph + +variable {w : ℕ} + +/-- Consecutive descriptor words, in word-address order. -/ +def Stores (m : Memory w) : Word w → List (Word w) → Prop + | _, [] => True + | base, x :: xs => m base.val = x ∧ Stores m (base + 1) xs + +/-- Advance a word address by one cell for each of the given number of steps. -/ +def advance : Word w → ℕ → Word w + | base, 0 => base + | base, n + 1 => advance (base + 1) n + +theorem stores_append (m : Memory w) (base : Word w) (xs ys : List (Word w)) : + Stores m base (xs ++ ys) ↔ Stores m base xs ∧ Stores m (advance base xs.length) ys := by + induction xs generalizing base with + | nil => simp [Stores, advance] + | cons x xs ih => simp [Stores, advance, ih, and_assoc] + +/-- Dereference each operand address before taking the bitwise sum. -/ +def rowValue (m : Memory w) (xs : List (Word w)) (acc : Word w) : Word w := + xs.foldl (fun v p => BinaryOp.bitXor.eval v (m p.val)) acc + +theorem readExpression_stored {m : Memory w} {base : Word w} {xs : List (Word w)} + (hs : Stores m base xs) (acc : Word w) : + readExpression m xs.length base acc = (advance base xs.length, rowValue m xs acc) := by + induction xs generalizing base acc with + | nil => rfl + | cons x xs ih => simp [readExpression, advance, rowValue, hs.1, ih hs.2] + +theorem readRows_stored (m : Memory w) (arity : ℕ) (base : Word w) + (rows : List (List (Word w))) (size : ∀ row ∈ rows, row.length = arity) + (hs : Stores m base rows.flatten) : + readRows m arity rows.length base = rows.map (fun row => rowValue m row 0) := by + induction rows generalizing base with + | nil => rfl + | cons row rows ih => + obtain ⟨hrow, hrest⟩ := (stores_append m base row rows.flatten).mp hs + have hlen := size row List.mem_cons_self + simp only [List.length_cons, readRows, ← hlen, readExpression_stored hrow, List.map_cons] + congr 1 + simpa only [← hlen] using ih _ (fun r hr => size r (List.mem_cons_of_mem _ hr)) hrest + +/-- The result and the exact accounting of the call from a fresh private state. -/ +def Returns (m : Memory w) (base : Word w) (arity n result : ℕ) : Prop := + let code := chooseFromState arity n + let M := (template code 2).instantiate w Fin.elim0 + ∃ es, execute M.program (1 + code.length) (M.program.start base) m [] = + some ⟨es, some (Fin.ofNat _ result)⟩ ∧ + es.length = 3 + ((4 * arity + 4) * n + 4) * n ∧ countProbes es = 2 * arity * n * n + +private theorem indexed_returns {T : Type*} {J : ℕ} (tests : List T) (covers : ∀ t, t ∈ tests) + (forbid : T → Fin J) (chosen : Fin J) (absent : ∀ t, chosen ≠ forbid t) + (early : ∀ k < chosen, ∃ t, forbid t = k) + (m : Memory w) (base : Word w) (arity : ℕ) (ptrs : T → List (Word w)) + (hlen : ∀ t, (ptrs t).length = arity) (hs : Stores m base (tests.map ptrs).flatten) + (hvalue : ∀ t, (rowValue m (ptrs t) 0).val = (forbid t).val) + (hfit : tests.length < 2 ^ w) : + Returns m base arity tests.length chosen.val := by + have hread := readRows_stored m arity base (tests.map ptrs) + (by intro row hr; obtain ⟨t, _, rfl⟩ := List.mem_map.mp hr; exact hlen _) hs + simp only [List.length_map] at hread + have hm (i : ℕ) : i ∈ (readRows m arity tests.length base).map Fin.val ↔ + ∃ t, (forbid t).val = i := by + rw [hread] + simp only [List.map_map, List.mem_map, Function.comp_apply, hvalue, covers, true_and] + apply choose_native m base arity tests.length chosen.val hfit + · intro h + obtain ⟨t, he⟩ := (hm _).mp h + exact absent t (Fin.ext he.symm) + · intro i hi + obtain ⟨t, ht⟩ := early (⟨i, hi.trans chosen.isLt⟩ : Fin J) hi + exact (hm _).mpr ⟨t, congrArg Fin.val ht⟩ + +variable {V : Type*} {d : ℕ} + +/-- Direction then local port, with both incidences even on a parallel edge. -/ +def incidences (d : ℕ) : List (Bool × Fin d) := [true, false] ×ˢ List.finRange d + +@[simp] theorem incidences_length (d : ℕ) : (incidences d).length = 2 * d := by + simp [incidences, two_mul] + +theorem incidences_cover (t : Bool × Fin d) : t ∈ incidences d := by + obtain ⟨b, i⟩ := t; cases b <;> simp [incidences] + +/-- Find the adjacent vertex at a directed incidence, following the target for outgoing ports +or its inverse for incoming ports. -/ +def neighbor (G : SlotGraph V d) (x : V) : Bool × Fin d → V + | (true, i) => (G.target (x, i)).1 + | (false, i) => (G.target.symm (x, i)).1 + +/-- Every color row has one operand, the address of the neighboring label. -/ +def colorRows (G : SlotGraph V d) (x : V) (address : V → Word w) : + List (List (Word w)) := (incidences d).map fun t => [address (neighbor G x t)] + +theorem color_returns (G : SlotGraph V d) (x : V) (f : V → Fin (2 * d + 1)) + (m : Memory w) (base : Word w) (address : V → Word w) + (labels : ∀ y, (m (address y).val).val = (f y).val) + (stored : Stores m base (colorRows G x address).flatten) (hfit : 2 * d < 2 ^ w) : + Returns m base 1 (2 * d) (G.chooseColor x f).val := by + obtain ⟨habs, hearly⟩ := G.chooseColor_spec x f + have hval (t : Bool × Fin d) : + (rowValue m [address (neighbor G x t)] 0).val = (G.colorForbidden x f t).val := by + have h (v : Word w) : BinaryOp.bitXor.eval 0 v = v := by + apply Fin.ext + simp [BinaryOp.eval] + obtain ⟨b, i⟩ := t + cases b <;> simp [rowValue, h, labels, neighbor, colorForbidden] + simpa using indexed_returns (incidences d) incidences_cover (G.colorForbidden x f) + (G.chooseColor x f) habs hearly m base 1 (fun t => [address (neighbor G x t)]) + (fun _ => rfl) stored hval (by simpa using hfit) + +/-- Enumerate zero and all the outgoing tag increments, with multiplicities. -/ +def increments (d : ℕ) : List (Option (Fin d)) := none :: (List.finRange d).map some + +private theorem increments_cover (a : Option (Fin d)) : a ∈ increments d := by + cases a <;> simp [increments] + +/-- Local exclusions come first, followed by all pairs of increments. -/ +def tagTests (d : ℕ) : List (TagTests d) := + incidences d ×ˢ ((increments d).map Sum.inl ++ (increments d ×ˢ increments d).map Sum.inr) + +@[simp] theorem tagTests_length (d : ℕ) : + (tagTests d).length = 2 * d * ((d + 1) + (d + 1) ^ 2) := by + simp [tagTests, List.length_product, increments, pow_two] + exact Or.inl (by ring) + +theorem tagTests_cover (t : TagTests d) : t ∈ tagTests d := by + obtain ⟨p, a | ⟨a, b⟩⟩ := t <;> + simp [tagTests, List.mem_product, incidences_cover, increments_cover] + + +/-- The immutable displacement cells and the current mutable assignment cells. -/ +structure TagAddresses (V : Type*) (d w : ℕ) where + /-- Address of the constant zero word used for absent tag increments. -/ + zero : Word w + /-- Address of the displacement word for a specified outgoing arc. -/ + displacement : V × Fin d → Word w + /-- Address of the current tag assignment for a specified vertex. -/ + label : V → Word w + +/-- Select the displacement address for a present local port and the zero cell for an absent +port. -/ +def TagAddresses.increment (A : TagAddresses V d w) (x : V) : Option (Fin d) → Word w + | none => A.zero + | some i => A.displacement (x, i) + +/-- The four operands of a local or a two-end tag exclusion. Padding a local +test with two references to the zero cell permits one fixed instruction table. -/ +def tagPointers (G : SlotGraph V d) (A : TagAddresses V d w) (x : V) : TagTests d → List (Word w) + | ((true, i), .inl a) => [A.displacement (x, i), A.increment x a, A.zero, A.zero] + | ((false, i), .inl a) => [A.displacement (G.target.symm (x, i)), A.increment x a, A.zero, A.zero] + | ((true, i), .inr (a, b)) => + let y := (G.target (x, i)).1 + [A.displacement (x, i), A.increment x a, A.increment y b, A.label y] + | ((false, i), .inr (a, b)) => + let e := G.target.symm (x, i) + [A.displacement e, A.increment e.1 a, A.increment x b, A.label e.1] + +variable {j : ℕ} + +/-- The addressed cells contain zero and the word encodings of the specified displacements and +vertex tags. -/ +structure TagAddresses.Represents (A : TagAddresses V d w) (hw : j ≤ w) + (m : Memory w) (τ : V × Fin d → BitWord j) (f : V → BitWord j) : Prop where + zero : m A.zero.val = 0 + displacement : ∀ e, m (A.displacement e).val = tagWord hw (τ e) + label : ∀ y, m (A.label y).val = tagWord hw (f y) + +theorem tagPointers_value (G : SlotGraph V d) (A : TagAddresses V d w) + (hw : j ≤ w) (m : Memory w) (τ : V × Fin d → BitWord j) (f : V → BitWord j) + (rep : A.Represents hw m τ f) (x : V) (t : TagTests d) : + rowValue m (tagPointers G A x t) 0 = tagWord hw (G.tagForbidden τ x f t) := by + have inc (y : V) (a : Option (Fin d)) : + m (A.increment y a).val = tagWord hw (tagIncrement τ y a) := by + cases a with + | none => simpa [TagAddresses.increment, tagIncrement] using rep.zero + | some i => exact rep.displacement (y, i) + have zx (u : Word w) : BinaryOp.bitXor.eval 0 u = u := by apply Fin.ext; simp [BinaryOp.eval] + have xz (u : Word w) : BinaryOp.bitXor.eval u 0 = u := by apply Fin.ext; simp [BinaryOp.eval] + have neg (u : BitWord j) : -u = u := funext fun i => CharTwo.neg_eq (u i) + obtain ⟨⟨b, i⟩, a | ⟨a, c⟩⟩ := t + all_goals cases b + all_goals simp only [rowValue, tagPointers, List.foldl_cons, List.foldl_nil, zx, tagForbidden, + rep.displacement, inc, rep.zero, xz, rep.label, tagWord_xor, sub_eq_add_neg, neg] + +/-- For a partially filled offset table the native output is exactly the +index used by the next visit in `orderedTagOffsets`. -/ +theorem tag_returns (G : SlotGraph V d) (x : V) (τ : V × Fin d → BitWord j) (f : V → BitWord j) + (hcard : 2 * d * ((d + 1) + (d + 1) ^ 2) < 2 ^ j) (hw : j ≤ w) + (m : Memory w) (base : Word w) (A : TagAddresses V d w) (rep : A.Represents hw m τ f) + (stored : Stores m base ((tagTests d).map (tagPointers G A x)).flatten) : + Returns m base 4 (2 * d * ((d + 1) + (d + 1) ^ 2)) + (bitWordFinEquiv j (G.chooseTag (bitWordFinEquiv j) τ hcard x f)).val := by + obtain ⟨habs, hearly⟩ := G.chooseTag_spec (bitWordFinEquiv j) τ hcard x f + have size (t : TagTests d) : (tagPointers G A x t).length = 4 := by + obtain ⟨⟨b, i⟩, a | ⟨a, c⟩⟩ := t <;> cases b <;> rfl + simpa using indexed_returns (tagTests d) tagTests_cover + (fun t => bitWordFinEquiv j (G.tagForbidden τ x f t)) + (bitWordFinEquiv j (G.chooseTag (bitWordFinEquiv j) τ hcard x f)) habs hearly m base 4 + (tagPointers G A x) size stored + (fun t => congrArg Fin.val (tagPointers_value G A hw m τ f rep x t)) + (by simpa using hcard.trans_le (Nat.pow_le_pow_right (by decide) hw)) + + +theorem Returns.visit {m : Memory w} {base : Word w} {arity n result : ℕ} + (hr : Returns m (base + 1 + 1) arity n result) (hfit : n < 2 ^ w) : + Visit m base arity n (Fin.ofNat _ result) := by + let rows := base + 1 + 1 + obtain ⟨events, he, _, _⟩ := hr + let M := (template (chooseFromState arity n) 2).instantiate w Fin.elim0 + change execute M.program (1 + (chooseFromState arity n).length) + ⟨M.entry, rows, fun _ => 0, fun _ => 0⟩ m [] = _ at he + let rs : Regs w 8 := Function.update (fun _ => 0) 0 rows + obtain ⟨es, c, hc, _, _, hv⟩ := choose_trace rows m arity n rs hfit + have hi : trace Fin.elim0 rows [.stateWord 0] (fun _ : Fin 8 => 0) m = + some ([.tick], rs, m) := rfl + rw [execute_template, run_eq_trace, chooseFromState, trace_append, hi] at he + simp only [Option.bind_some, hc, Option.map_some, Option.some.injEq, Report.mk.injEq] at he + apply visit_native _ _ _ _ _ hfit + have hval := congrArg Fin.val he.2 + simpa [rs, rows] using hv.symm.trans hval + +theorem color_visit (G : SlotGraph V d) (x : V) (f : V → Fin (2 * d + 1)) + (m : Memory w) (base : Word w) (address : V → Word w) + (labels : ∀ y, (m (address y).val).val = (f y).val) + (stored : Stores m (base + 1 + 1) (colorRows G x address).flatten) (hfit : 2 * d < 2 ^ w) : + Visit m base 1 (2 * d) (Fin.ofNat _ (G.chooseColor x f).val) := + (color_returns G x f m _ address labels stored hfit).visit hfit + +theorem tag_visit (G : SlotGraph V d) (x : V) (τ : V × Fin d → BitWord j) (f : V → BitWord j) + (hcard : 2 * d * ((d + 1) + (d + 1) ^ 2) < 2 ^ j) (hw : j ≤ w) + (m : Memory w) (base : Word w) (A : TagAddresses V d w) (rep : A.Represents hw m τ f) + (stored : Stores m (base + 1 + 1) ((tagTests d).map (tagPointers G A x)).flatten) : + Visit m base 4 (2 * d * ((d + 1) + (d + 1) ^ 2)) + (tagWord hw (G.chooseTag (bitWordFinEquiv j) τ hcard x f)) := by + let t := G.chooseTag (bitWordFinEquiv j) τ hcard x f + have h : Fin.ofNat (2 ^ w) (bitWordFinEquiv j t).val = tagWord hw t := by + apply Fin.ext + exact Nat.mod_eq_of_lt (tagWord hw t).isLt + rw [← h] + exact (tag_returns G x τ f hcard hw m _ A rep stored).visit + (hcard.trans_le (Nat.pow_le_pow_right (by decide) hw)) + +end CompressorRecords.Greedy + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordGreedyWalk.lean b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyWalk.lean new file mode 100644 index 0000000000..312e44ec8d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordGreedyWalk.lean @@ -0,0 +1,333 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedySlots +import OAI.Computability.VPVNP.RAMChain +import OAI.Computability.VPVNP.RAMBuckets + +/-! +# Indexed memory and complete greedy scans + +The mutable assignments occupy one word per base vertex. Each fixed-stride +record following those cells contains the assignment's address, the address +of the next record, and the operand pointers read by the native visit. This +layout permits the same fixed instruction table to visit the entire base. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Greedy + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.SlotGraph + +variable {w N width : ℕ} {V A : Type*} + +/-- `width` counts pointer words after each two-word header. -/ +structure WalkLayout (w N width : ℕ) where + /-- First address of the contiguous vertex assignments, followed by their fixed-stride greedy + records. -/ + origin : ℕ + fits : origin + N + N * (2 + width) ≤ 2 ^ w + +namespace WalkLayout + +variable (L : WalkLayout w N width) + +/-- The mutable word for an indexed vertex. -/ +def label (i : Fin N) : Word w := Fin.ofNat _ (L.origin + i.val) + +/-- The descriptor for cursor `k`. After the last visit this is the return cursor. -/ +def base (k : ℕ) : Word w := Fin.ofNat _ (L.origin + N + k * (2 + width)) + +@[simp] theorem label_val (i : Fin N) : (L.label i).val = L.origin + i.val := + Nat.mod_eq_of_lt (by have := L.fits; have := i.isLt; omega) + +/-- Natural start of the following region, reserved for fixed graph data. -/ +def limit : ℕ := L.origin + N + N * (2 + width) + +private theorem field_lt (i : Fin N) {t : ℕ} (ht : t < 2 + width) : + L.origin + N + i.val * (2 + width) + t < L.limit := by + have h := Nat.mul_le_mul_right (2 + width) (Nat.succ_le_of_lt i.isLt) + rw [Nat.succ_mul] at h + unfold limit + omega + +/-- The full descriptor, with the next pointer present also at the last vertex. -/ +def record (ptrs : Fin N → List (Word w)) (i : Fin N) : List (Word w) := + L.label i :: L.base (i.val + 1) :: ptrs i + +/-- Assemble the fixed-stride descriptor directory over the supplied memory. +The mutable assignment region starts at zero. Addresses beyond the table +retain their initial values, including fixed displacement operands. -/ +def initialMemory (ptrs : Fin N → List (Word w)) (outside : Memory w) : Memory w := fun z ↦ + if z < L.origin then outside z else if z < L.origin + N then 0 else + let off := z - (L.origin + N) + let row := off / (2 + width) + if h : row < N then ((L.record ptrs ⟨row, h⟩)[off % (2 + width)]?).getD 0 else outside z + +@[simp] theorem initialMemory_label_offset (ptrs : Fin N → List (Word w)) (outside : Memory w) + (i : Fin N) : L.initialMemory ptrs outside (L.origin + i.val) = 0 := by + simp [initialMemory, Nat.add_lt_add_left i.isLt, Nat.not_lt.mpr (Nat.le_add_right ..)] + +theorem initialMemory_label (ptrs : Fin N → List (Word w)) (outside : Memory w) + (i : Fin N) : L.initialMemory ptrs outside (L.label i).val = 0 := by + rw [label_val, initialMemory_label_offset] + +theorem initialMemory_field (ptrs : Fin N → List (Word w)) (outside : Memory w) + (i : Fin N) {t : ℕ} (ht : t < 2 + width) : + L.initialMemory ptrs outside (L.origin + N + i.val * (2 + width) + t) = + ((L.record ptrs i)[t]?).getD 0 := by + let z := L.origin + N + i.val * (2 + width) + t + have hsub : z - (L.origin + N) = i.val * (2 + width) + t := by dsimp [z]; omega + have hd : (i.val * (2 + width) + t) / (2 + width) = i.val := by + rw [Nat.mul_comm i.val, Nat.mul_add_div (by omega), Nat.div_eq_of_lt ht, Nat.add_zero] + change L.initialMemory ptrs outside z = _ + simp only [initialMemory, ite_eq_right (show ¬z < L.origin by dsimp [z]; omega), + ite_eq_right (show ¬z < L.origin + N by dsimp [z]; omega), hsub, hd, dite_eq_left i.isLt, + Nat.mul_add_mod_of_lt ht] + +/-- Contents of the table relative to an arbitrary partially filled label vector. -/ +structure Represents (initial m : Memory w) (encode : A → Word w) (order : V ≃ Fin N) + (f : V → A) : Prop where + labels : ∀ x, m (L.label (order x)).val = encode (f x) + frame : ∀ z, z < L.origin ∨ L.origin + N ≤ z → m z = initial z + +private theorem Represents.write [DecidableEq V] {initial m : Memory w} {encode : A → Word w} + {order : V ≃ Fin N} {f : V → A} (rep : L.Represents initial m encode order f) + (x : V) (v : A) : L.Represents initial (writeMemory m (L.label (order x)) (encode v)) + encode order (Function.update f x v) := by + constructor + · intro y + by_cases h : y = x + · subst y; simp [writeMemory] + · have hn : (order y).val ≠ (order x).val := fun e ↦ h (order.injective (Fin.ext e)) + simpa [writeMemory, hn, Function.update_of_ne h] using rep.labels y + · intro z hz + have hne : z ≠ (L.label (order x)).val := by rw [label_val]; have := (order x).isLt; omega + simpa only [writeMemory, ite_eq_right hne] using rep.frame z hz + +private theorem stores_read (m : Memory w) (start : ℕ) (xs : List (Word w)) + (fit : start + xs.length ≤ 2 ^ w) (h : ∀ t : Fin xs.length, m (start + t.val) = xs[t.val]) : + Stores m (Fin.ofNat _ start) xs := by + induction xs generalizing start with + | nil => trivial + | cons x xs ih => + have hstart : start < 2 ^ w := by simp only [List.length_cons] at fit; omega + constructor + · simpa only [Fin.val_ofNat, Nat.mod_eq_of_lt hstart, Fin.val_zero, Nat.add_zero, + List.getElem_cons_zero] using h 0 + · have hadd : (Fin.ofNat _ start : Word w) + 1 = Fin.ofNat _ (start + 1) := by + apply Fin.ext + simp only [Fin.val_add, Fin.val_ofNat, Fin.val_one', Nat.mod_add_mod, Nat.add_mod_mod] + rw [hadd] + apply ih (start + 1) (by simp only [List.length_cons] at fit; omega) + intro t + simpa [Nat.add_assoc, Nat.add_comm 1] using h t.succ + +/-- Writes to the assignment cells preserve all descriptor headers and pointers. -/ +theorem Represents.record {ptrs : Fin N → List (Word w)} {outside m : Memory w} + {encode : A → Word w} {order : V ≃ Fin N} {f : V → A} + (rep : L.Represents (L.initialMemory ptrs outside) m encode order f) + (size : ∀ i, (ptrs i).length = width) (i : Fin N) : + Stores m (L.base i.val) (L.record ptrs i) := by + have len : (L.record ptrs i).length = 2 + width := by simp [WalkLayout.record, size]; omega + apply stores_read + · rw [len] + have h := Nat.mul_le_mul_right (2 + width) (Nat.succ_le_of_lt i.isLt) + rw [Nat.succ_mul] at h + have := L.fits + omega + · intro t + have ht : t.val < 2 + width := len ▸ t.isLt + rw [rep.frame _ (.inr (by omega)), L.initialMemory_field ptrs outside i ht, + List.getElem?_eq_getElem t.isLt, Option.getD_some] + +private theorem finRange_indices (N : ℕ) : (List.finRange N).map Fin.val = List.range' 0 N := by + apply List.ext_getElem + · simp + · intro t ht ht' + simp + +/-- The machine's complete native execution, final cursor, labels, and exact per-call cost. -/ +def Pass (m : Memory w) (arity n : ℕ) (encode : A → Word w) (order : V ≃ Fin N) + (f : V → A) : Prop := + ∃ reports, runSegment (visitMachine w arity n).program (1 + (visitCode arity n).length) + (some (L.base 0)) m (List.replicate N []) = some reports ∧ + endState (some (L.base 0)) reports = some (L.base N) ∧ + L.Represents m (after m (eventLog reports)) encode order f ∧ reports.length = N ∧ + ∀ r ∈ reports, r.events.length = 12 + ((4 * arity + 4) * n + 4) * n ∧ + countProbes r.events = 3 + 2 * arity * n * n + +/-- Total calls plus probes in the native scan, linear in the base size at fixed degree. -/ +theorem Pass.cost {m : Memory w} {arity n : ℕ} {encode : A → Word w} + {order : V ≃ Fin N} {f : V → A} (h : L.Pass m arity n encode order f) : + ∃ rs, runSegment (visitMachine w arity n).program (1 + (visitCode arity n).length) + (some (L.base 0)) m (List.replicate N []) = some rs ∧ + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = N * (4 + 2 * arity * n * n) := by + obtain ⟨rs, run, _, _, len, work⟩ := h + refine ⟨rs, run, ?_⟩ + have count (xs : List (Report w)) (hs : ∀ r ∈ xs, countProbes r.events = 3 + 2 * arity * n * n) : + RAMBuckets.cost (fun r ↦ countProbes r.events) xs = xs.length * (4 + 2 * arity * n * n) := by + induction xs with + | nil => simp [RAMBuckets.cost] + | cons r xs ih => + rw [RAMBuckets.cost, hs r List.mem_cons_self, ih (fun s h ↦ hs s (List.mem_cons_of_mem _ h)), + List.length_cons] + ring + rw [count rs (fun r hr ↦ (work r hr).2), len] + +theorem scan_pass [DecidableEq V] {encode : A → Word w} (init : A) (hinit : encode init = 0) + (order : V ≃ Fin N) (select : V → (V → A) → A) (ptrs : Fin N → List (Word w)) + (size : ∀ i, (ptrs i).length = width) (outside : Memory w) (arity n : ℕ) + (step : ∀ m f i, L.Represents (L.initialMemory ptrs outside) m encode order f → + Stores m (L.base i.val + 1 + 1) (ptrs i) → + Visit m (L.base i.val) arity n (encode (select (order.symm i) f))) : + L.Pass (L.initialMemory ptrs outside) arity n encode order + ((List.finRange N).foldl (orderedUpdate order select) (fun _ ↦ init)) := by + let P := (visitMachine w arity n).program + let fuel := 1 + (visitCode arity n).length + let initial := L.initialMemory ptrs outside + have walk (ids : List (Fin N)) (k : ℕ) (seq : ids.map Fin.val = List.range' k ids.length) + (m : Memory w) (f : V → A) (rep : L.Represents initial m encode order f) : + ∃ rs, runSegment P fuel (some (L.base k)) m (List.replicate ids.length []) = some rs ∧ + endState (some (L.base k)) rs = some (L.base (k + ids.length)) ∧ + L.Represents initial (after m (eventLog rs)) encode order (ids.foldl (orderedUpdate order select) f) ∧ + rs.length = ids.length ∧ ∀ r ∈ rs, r.events.length = 12 + ((4 * arity + 4) * n + 4) * n ∧ + countProbes r.events = 3 + 2 * arity * n * n := by + induction ids generalizing k m f with + | nil => exact ⟨[], rfl, rfl, rep, rfl, by simp⟩ + | cons i ids ih => + simp only [List.map_cons, List.length_cons, List.range'_succ, List.cons.injEq] at seq + obtain ⟨rfl, tail⟩ := seq + obtain ⟨hout, hnext, rows⟩ := rep.record L size i + obtain ⟨es, he, hm, hsteps, hprobes⟩ := step m f i rep rows + rw [hout] at hm + rw [hnext] at he + let r : Report w := ⟨es, some (L.base (i.val + 1))⟩ + have rep' : L.Represents initial (after m es) encode order (orderedUpdate order select f i) := by + rw [hm] + simpa only [orderedUpdate, Equiv.apply_symm_apply] using rep.write L (order.symm i) (select (order.symm i) f) + obtain ⟨rs, run, hend, hfinal, hlen, hcost⟩ := ih _ tail _ _ rep' + refine ⟨r :: rs, ?_, ?_, ?_, by simp [hlen], ?_⟩ + · simp only [List.length_cons, List.replicate_succ, runSegment, P, fuel, he, run, Option.map_some, r] + · simpa only [endState, r, List.length_cons, Nat.add_right_comm i.val 1, Nat.add_assoc] using hend + · change L.Represents initial (List.foldl update m (es ++ eventLog rs)) _ _ _ + rw [List.foldl_append] + exact hfinal + · intro q hq + rcases List.mem_cons.mp hq with rfl | h + · exact ⟨hsteps, hprobes⟩ + · exact hcost _ h + have rep0 : L.Represents initial initial encode order (fun _ ↦ init) := + ⟨fun x ↦ (L.initialMemory_label ptrs outside (order x)).trans hinit.symm, fun _ _ ↦ rfl⟩ + simpa only [Pass, List.length_finRange, Nat.zero_add, P, fuel, initial] using + walk (List.finRange N) 0 (by simpa only [List.length_finRange] using finRange_indices N) _ _ rep0 + +/-- Fields beyond the fixed-stride records retain their supplied values. -/ +theorem initialMemory_after (ptrs : Fin N → List (Word w)) (outside : Memory w) + {z : ℕ} (hz : L.limit ≤ z) : L.initialMemory ptrs outside z = outside z := by + unfold limit at hz + have hq : N ≤ (z - (L.origin + N)) / (2 + width) := + (Nat.le_div_iff_mul_le (by omega)).mpr (by omega) + simp only [initialMemory, ite_eq_right (show ¬z < L.origin by omega), + ite_eq_right (show ¬z < L.origin + N by omega), dite_eq_right hq.not_gt] + +variable {d j : ℕ} + +/-- Actual operand addresses of the color visit, in incidence order. -/ +def colorOperands (L : WalkLayout w N (2 * d)) (G : SlotGraph V d) (order : V ≃ Fin N) + (i : Fin N) : List (Word w) := (colorRows G (order.symm i) (L.label ∘ order)).flatten + +/-- Starting from zero assignments, the full native scan writes precisely the +ordered coloring. No condition on the memory surrounding its directory is needed. -/ +theorem color_pass (L : WalkLayout w N (2 * d)) (G : SlotGraph V d) (order : V ≃ Fin N) + (outside : Memory w) (hfit : 2 * d < 2 ^ w) : + L.Pass (L.initialMemory (L.colorOperands G order) outside) 1 (2 * d) + (fun v : Fin (2 * d + 1) ↦ Fin.ofNat _ v.val) order (G.orderedColor order) := by + classical + rw [orderedColor_fold] + apply scan_pass L 0 (by simp) order G.chooseColor (L.colorOperands G order) _ outside + · intro m f i rep rows + apply color_visit G (order.symm i) f m _ (L.label ∘ order) _ rows hfit + intro x + have hx := congrArg Fin.val (rep.labels x) + simpa only [Fin.val_ofNat, Function.comp_apply, Nat.mod_eq_of_lt + (show (f x).val < 2 ^ w by have := (f x).isLt; omega)] using hx + · intro i + simp [colorOperands, colorRows, List.length_flatten, List.map_map, Function.comp_def] + +/-- Number of four-operand tests for one tag. -/ +abbrev tagCount (d : ℕ) := 2 * d * ((d + 1) + (d + 1) ^ 2) + +/-- Place the zero word and the vertex-major array of outgoing tag displacements +immediately after the pointer directory. -/ +def tagAddresses (L : WalkLayout w N (4 * tagCount d)) (order : V ≃ Fin N) : TagAddresses V d w := + ⟨Fin.ofNat _ L.limit, + fun e ↦ Fin.ofNat _ (L.limit + 1 + (order e.1).val * d + e.2.val), L.label ∘ order⟩ + +/-- The four addresses of every test, laid out consecutively in tag test order. -/ +def tagOperands (L : WalkLayout w N (4 * tagCount d)) (G : SlotGraph V d) (order : V ≃ Fin N) + (i : Fin N) : List (Word w) := + ((tagTests d).map (tagPointers G (L.tagAddresses order) (order.symm i))).flatten + +/-- Initialize the immutable operands from the indexed graph's displacements. -/ +def tagData (L : WalkLayout w N (4 * tagCount d)) (order : V ≃ Fin N) (hw : j ≤ w) + (τ : V × Fin d → BitWord j) (outside : Memory w) : Memory w := fun z ↦ + if z = L.limit then 0 else if z < L.limit + 1 then outside z else + let off := z - (L.limit + 1) + if hd : 0 < d then + if hn : off / d < N then tagWord hw (τ (order.symm ⟨off / d, hn⟩, ⟨off % d, Nat.mod_lt _ hd⟩)) + else outside z + else outside z + +private theorem tag_data_rep (L : WalkLayout w N (4 * tagCount d)) (G : SlotGraph V d) + (order : V ≃ Fin N) (hw : j ≤ w) (τ : V × Fin d → BitWord j) (outside : Memory w) + (hfit : L.limit + 1 + N * d ≤ 2 ^ w) {m : Memory w} {f : V → BitWord j} + (rep : L.Represents (L.initialMemory (L.tagOperands G order) (L.tagData order hw τ outside)) + m (tagWord hw) order f) : (L.tagAddresses order).Represents hw m τ f := by + have hframe (z : ℕ) (hz : L.limit ≤ z) : m z = L.tagData order hw τ outside z := + (rep.frame z (.inr (by unfold limit at hz; omega))).trans (L.initialMemory_after _ _ hz) + constructor + · change m (Fin.ofNat (2 ^ w) L.limit).val = 0 + rw [Fin.val_ofNat, Nat.mod_eq_of_lt (by omega), hframe _ le_rfl] + simp [tagData] + · rintro ⟨x, i⟩ + let z := L.limit + 1 + (order x).val * d + i.val + have hs := Nat.mul_le_mul_right d (Nat.succ_le_of_lt (order x).isLt) + rw [Nat.succ_mul] at hs + have hslot := i.isLt + have hval : z < 2 ^ w := by dsimp [z]; omega + have hd : ((order x).val * d + i.val) / d = (order x).val := by + rw [Nat.mul_comm, Nat.mul_add_div (by omega), Nat.div_eq_of_lt i.isLt, Nat.add_zero] + change m (Fin.ofNat (2 ^ w) z).val = _ + rw [Fin.val_ofNat, Nat.mod_eq_of_lt hval, hframe _ (by dsimp [z]; omega)] + simp only [tagData, ite_eq_right (show z ≠ L.limit by dsimp [z]; omega), + ite_eq_right (show ¬z < L.limit + 1 by dsimp [z]; omega), + show z - (L.limit + 1) = (order x).val * d + i.val by dsimp [z]; omega, + dite_eq_left (show 0 < d by omega), hd, dite_eq_left (order x).isLt, + Nat.mul_add_mod_of_lt i.isLt, Fin.eta, Equiv.symm_apply_apply] + · exact rep.labels + +/-- Starting from zero offsets and the graph's displacement array, the complete +native tag scan writes the same offsets as `orderedTagOffsets` in Appendix C. -/ +theorem tag_pass (L : WalkLayout w N (4 * tagCount d)) (G : SlotGraph V d) (order : V ≃ Fin N) + (τ : V × Fin d → BitWord j) (hw : j ≤ w) (hcard : tagCount d < 2 ^ j) + (hfit : L.limit + 1 + N * d ≤ 2 ^ w) (outside : Memory w) : + L.Pass (L.initialMemory (L.tagOperands G order) (L.tagData order hw τ outside)) + 4 (tagCount d) (tagWord hw) order (G.orderedTagOffsets order (bitWordFinEquiv j) τ hcard) := by + classical + rw [orderedTagOffsets_fold] + apply scan_pass L 0 (tagWord_zero hw) order (G.chooseTag (bitWordFinEquiv j) τ hcard) + (L.tagOperands G order) _ (L.tagData order hw τ outside) + · intro m f i rep rows + exact tag_visit G (order.symm i) τ f hcard hw m _ _ (tag_data_rep L G order hw τ outside hfit rep) rows + · intro i + have hlen (t : TagTests d) : (tagPointers G (L.tagAddresses order) (order.symm i) t).length = 4 := by + obtain ⟨⟨b, k⟩, a | ⟨a,c⟩⟩ := t <;> cases b <;> rfl + simp [tagOperands, List.length_flatten, List.map_map, Function.comp_def, hlen, Nat.mul_comm] + +end WalkLayout +end CompressorRecords.Greedy + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordIncidenceLayout.lean b/lean/OAI/Computability/VPVNP/CompressorRecordIncidenceLayout.lean new file mode 100644 index 0000000000..5f186e3fa3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordIncidenceLayout.lean @@ -0,0 +1,95 @@ +import OAI.Computability.VPVNP.CompressorRecordsCursor + +/-! +# Shared incidence columns between compressor levels + +The same slot numbering serves cursor, shrink and refresh states. This module records the +three actual columns independently of the three base columns. A packed six-column layout +assigns each cell a distinct address for the entire state, including at every parallel slot. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.IncidenceDirectory + +open BurstRAM Compression CursorRAM + +variable {w a l : ℕ} + +/-- The three actual columns use the common state-relative slot numbering. -/ +structure ActualColumns (T : IncidenceDirectory w) (X : State a l) (m : Memory w) : Prop where + actualOut : ∀ e, m (T.actualOut + actualPort X e).val = actualPort X (X.slots.actualGraph.target e) + actualIn : ∀ e, m (T.actualIn + actualPort X e).val = actualPort X (X.slots.actualGraph.target.symm e) + width : ∀ e, m (T.width + actualPort X e).val = encode w (X.width ((e.1.1,e.2),e.1.2)) + +theorem Represents.actual {T : IncidenceDirectory w} {X : State a l} {m : Memory w} + (h : T.Represents X m) : T.ActualColumns X m := ⟨h.actualOut,h.actualIn,h.width⟩ + +/-- Base forward, base inverse, displacement, actual forward, actual inverse and width. -/ +def column (T : IncidenceDirectory w) : Fin 6 → Word w := + ![T.baseOut, T.baseIn, T.shift, T.actualOut, T.actualIn, T.width] + +/-- Canonical base and actual slot orders as finite equivalences. -/ +def baseOrder (X : State a l) : X.Base × Fin (2^a) ≃ Fin (Fintype.card X.Base * 2^a) := + (X.baseIndex.prodCongr (Equiv.refl _)).trans finProdFinEquiv + +/-- Number actual slots in base-vertex, lane, then local-port order, with the local port +varying fastest. -/ +def actualOrder (X : State a l) : (X.Base × BitWord l) × Fin (2^a) ≃ Fin (Fintype.card X.Base * 2^l * 2^a) := + (((X.baseIndex.prodCongr (bitWordFinEquiv l)).trans finProdFinEquiv).prodCongr (Equiv.refl _)).trans finProdFinEquiv + +theorem baseOrder_val (X : State a l) (e : X.Base × Fin (2^a)) : + (baseOrder X e).val = (X.baseIndex e.1).val * 2^a + e.2.val := by + change e.2.val + 2^a * (X.baseIndex e.1).val = _ + ring + +theorem actualOrder_val (X : State a l) (e : (X.Base × BitWord l) × Fin (2^a)) : + (actualOrder X e).val = ((X.baseIndex e.1.1).val * 2^l + (bitWordFinEquiv l e.1.2).val) * 2^a + e.2.val := by + change e.2.val + 2^a * ((bitWordFinEquiv l e.1.2).val + 2^l * (X.baseIndex e.1.1).val) = _ + ring + +theorem basePort_number (X : State a l) (e : X.Base × Fin (2^a)) : + basePort (w := w) X e = encode w (baseOrder X e).val := by rw [baseOrder_val]; rfl + +theorem actualPort_number (X : State a l) (e : (X.Base × BitWord l) × Fin (2^a)) : + actualPort (w := w) X e = encode w (actualOrder X e).val := by rw [actualOrder_val]; rfl + +/-- Column addresses are disjoint through the last actual slot, and all slot IDs fit. -/ +structure Layout (T : IncidenceDirectory w) (X : State a l) : Prop where + fit : Fintype.card X.Base * 2^l * 2^a ≤ 2^w + apart : ∀ (c d : Fin 6) (i j : Word w), i.val < Fintype.card X.Base * 2^l * 2^a → + j.val < Fintype.card X.Base * 2^l * 2^a → ((T.column c + i).val = (T.column d + j).val ↔ c = d ∧ i = j) + +theorem Layout.packed {T : IncidenceDirectory w} (X : State a l) (start : ℕ) + (room : start + 6*(Fintype.card X.Base * 2^l * 2^a) ≤ 2^w) + (bases : ∀ c : Fin 6, (T.column c).val = start + c.val * (Fintype.card X.Base * 2^l * 2^a)) : + T.Layout X := by + let N := Fintype.card X.Base * 2^l * 2^a + change start + 6 * N ≤ 2^w at room + constructor + · change N ≤ 2^w; omega + · intro c d i j hi hj + change i.val < N at hi + change j.val < N at hj + have address (k : Fin 6) (u : Word w) (hu : u.val < N) : + (T.column k + u).val = start + k.val*N + u.val := by + have hk := Nat.mul_le_mul_right N k.isLt + rw [Nat.succ_mul] at hk + rw [Fin.val_add, bases k, Nat.mod_eq_of_lt (by change start + k.val*N + u.val < _; omega)] + rw [address _ _ hi, address _ _ hj] + constructor + · intro h + have ha : c.val*N + i.val = d.val*N + j.val := by omega + have hij : i = j := Fin.ext ((Nat.mul_add_mod_of_lt hi).symm.trans + ((congrArg (· % N) ha).trans (Nat.mul_add_mod_of_lt hj))) + subst j + exact ⟨Fin.ext (Nat.eq_of_mul_eq_mul_right (by omega : 0 < N) (Nat.add_right_cancel ha)),rfl⟩ + · rintro ⟨rfl,rfl⟩; rfl + +end CompressorRecords.IncidenceDirectory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordPlacement.lean b/lean/OAI/Computability/VPVNP/CompressorRecordPlacement.lean new file mode 100644 index 0000000000..7cdc881d13 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordPlacement.lean @@ -0,0 +1,81 @@ +import OAI.Computability.VPVNP.CompressorRecordPreimageScan +import OAI.Computability.VPVNP.PackingPreimages +import Mathlib.Data.Nat.Count + +/-! +# Typed placement fibers in the physical descriptor table + +Numbering sites transports the placement function to words in the old-site array. A full +preimage scan stores precisely the old identifiers mapping to each new owner. The number +of records in that row equals the cardinality of the original placement fiber, so the +native scan's capacity condition follows directly from the combinatorial bound. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM +open scoped Count + +variable {w : ℕ} + +/-- Size of the physical prefix list equals the size of the filtered ordinal set. -/ +theorem preimagePrefix_card (place : Word w → Word w) (owner : Word w) (k : ℕ) : + (preimagePrefix place owner k).length = + Fintype.card {i : Fin k // place (Fin.ofNat (2 ^ w) i.val) = owner} := by + let P (i : ℕ) := place (Fin.ofNat (2 ^ w) i) = owner + have hc : (preimagePrefix place owner k).length = Nat.count P k := by + simp [preimagePrefix, ← List.countP_eq_length_filter, List.countP_map, Nat.count, P, Function.comp_def] + congr 1 + rw [hc, Nat.count_eq_card_fintype] + apply Fintype.card_congr + exact ⟨fun i => ⟨⟨i.val, i.prop.1⟩, i.prop.2⟩, + fun i => ⟨i.val.val, i.val.prop, i.prop⟩, fun _ => rfl, fun _ => rfl⟩ + +variable {Old New : Type*} {oldCount newCount : ℕ} + +/-- Read a placement as numeric identifiers in the chosen site order. -/ +def encodedPlacement (oldOrder : Old ≃ Fin oldCount) (newOrder : New ≃ Fin newCount) + (place : Old → New) (i : Word w) : Word w := + if h : i.val < oldCount then Fin.ofNat (2 ^ w) (newOrder (place (oldOrder.symm ⟨i.val, h⟩))).val + else 0 + +theorem encodedPlacement_eq (oldOrder : Old ≃ Fin oldCount) (newOrder : New ≃ Fin newCount) + (place : Old → New) (ho : oldCount ≤ 2^w) (hn : newCount ≤ 2^w) (j : Fin oldCount) : + (encodedPlacement oldOrder newOrder place (Fin.ofNat (2^w) j.val)).val = + (newOrder (place (oldOrder.symm j))).val := by + simp [encodedPlacement, Nat.mod_eq_of_lt (j.isLt.trans_le ho), + Nat.mod_eq_of_lt ((newOrder (place (oldOrder.symm j))).isLt.trans_le hn)] + +/-- The preimage bound on the mathematical layout is the exact length of the +corresponding physical row. This also applies to repeated role occurrences by +numbering the occurrences themselves. -/ +theorem encodedPlacement_rowLength (oldOrder : Old ≃ Fin oldCount) (newOrder : New ≃ Fin newCount) + (place : Old → New) (ho : oldCount ≤ 2^w) (hn : newCount ≤ 2^w) (v : New) + [Fintype Old] [DecidableEq New] : + (preimagePrefix (encodedPlacement oldOrder newOrder place) + (Fin.ofNat (2 ^ w) (newOrder v).val) oldCount).length = + Fintype.card {u : Old // place u = v} := by + rw [preimagePrefix_card] + let target := Fin.ofNat (2 ^ w) (newOrder v).val + have ht : target.val = (newOrder v).val := Nat.mod_eq_of_lt ((newOrder v).isLt.trans_le hn) + have hg (j : Fin oldCount) : + encodedPlacement oldOrder newOrder place (Fin.ofNat (2 ^ w) j.val) = target ↔ + place (oldOrder.symm j) = v := by + rw [Fin.ext_iff, encodedPlacement_eq oldOrder newOrder place ho hn j, ht] + exact Fin.val_injective.eq_iff.trans newOrder.injective.eq_iff + apply Fintype.card_congr + exact { + toFun := fun i => ⟨oldOrder.symm i.val, (hg _).mp i.prop⟩ + invFun := fun u => ⟨oldOrder u.val, (hg _).mpr (by simpa using u.prop)⟩ + left_inv := fun i => Subtype.ext (oldOrder.apply_symm_apply i.val) + right_inv := fun u => Subtype.ext (oldOrder.symm_apply_apply u.val) } + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordPreimageScan.lean b/lean/OAI/Computability/VPVNP/CompressorRecordPreimageScan.lean new file mode 100644 index 0000000000..cc0ea36d93 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordPreimageScan.lean @@ -0,0 +1,222 @@ +import OAI.Computability.VPVNP.CompressorRecordPreimages +import OAI.Computability.VPVNP.RAMBuckets + +/-! +# The preimage-list pass of the descriptor builder + +Store the selected placement in increasing old-site order, followed by a count per new +site and a rectangular array of bounded preimage lists. The native visit from +`CompressorRecordPreimages` appends one old-site identifier to exactly its selected row. +The complete pass builds the placement fibers in scan order using five calls-plus-probes +per old site, starting with a zero count in each new-site row. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- The owner inputs, the list counters and the row data occupy disjoint address ranges. -/ +structure RowRegions (pub : Fin 6 → Word w) : Prop where + ownersBeforeCounts : (pub 1).val + (pub 0).val ≤ (pub 3).val + countsBeforeRows : (pub 3).val + (pub 2).val ≤ (pub 5).val + rowsFit : (pub 5).val + (pub 2).val * (pub 4).val ≤ 2 ^ w + +/-- All old identifiers below the scan cursor which have the specified owner. -/ +def preimagePrefix (place : Word w → Word w) (owner : Word w) (k : ℕ) : List (Word w) := + ((List.range k).map (fun j => Fin.ofNat (2 ^ w) j)).filter fun j => place j == owner + +private theorem preimagePrefix_succ (place : Word w → Word w) (owner : Word w) (k : ℕ) : + preimagePrefix place owner (k + 1) = + preimagePrefix place owner k ++ (if place (Fin.ofNat (2 ^ w) k) = owner then [(Fin.ofNat (2 ^ w) k)] else []) := by + simp only [preimagePrefix, List.range_succ, List.map_append, List.map_cons, List.map_nil, + List.filter_append, List.filter_cons, List.filter_nil, beq_iff_eq] + +private theorem preimagePrefix_mono (place : Word w → Word w) (owner : Word w) : + Monotone (fun k => (preimagePrefix place owner k).length) := by + apply monotone_nat_of_le_succ + intro k + rw [preimagePrefix_succ, List.length_append] + omega + +/-- Complete contents of the scan tables after the first `k` old sites. -/ +structure PreimagesAt (pub : Fin 6 → Word w) (place : Word w → Word w) + (mem : Memory w) (k : ℕ) : Prop where + owners : ∀ i : Word w, i < pub 0 → ownerAt pub mem i = place i + rows : ∀ v : Word w, v < pub 2 → + rowRepresents mem (countAt pub v) (rowAt pub v) (preimagePrefix place v k) + +private theorem countAt_val {pub : Fin 6 → Word w} (a : RowRegions pub) + {v : Word w} (hv : v < pub 2) : (countAt pub v).val = (pub 3).val + v.val := by + have h := a.countsBeforeRows + have hb := (pub 5).isLt + change v.val < (pub 2).val at hv + rw [countAt, Fin.val_add, Nat.mod_eq_of_lt (by omega)] + +private theorem rowAt_val {pub : Fin 6 → Word w} (a : RowRegions pub) + {v : Word w} (hv : v < pub 2) : (rowAt pub v).val = (pub 5).val + v.val * (pub 4).val := by + have h := a.rowsFit + have hstep := Nat.mul_le_mul_right (pub 4).val (show v.val + 1 ≤ (pub 2).val from hv) + rw [Nat.succ_mul] at hstep + by_cases hc : (pub 4).val = 0 + · simp [rowAt, Fin.val_add, Fin.val_mul, hc, Nat.mod_eq_of_lt (pub 5).isLt] + · rw [rowAt, Fin.val_add, Fin.val_mul, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)] + +/-- A valid row of a different owner is disjoint from the current owner's row. -/ +private theorem rows_apart {pub : Fin 6 → Word w} (a : RowRegions pub) + {v u : Word w} (hv : v < pub 2) (hu : u < pub 2) (hne : v ≠ u) : + (rowAt pub v).val + (pub 4).val ≤ (rowAt pub u).val ∨ + (rowAt pub u).val + (pub 4).val ≤ (rowAt pub v).val := by + rw [rowAt_val a hv, rowAt_val a hu] + have hn : v.val ≠ u.val := fun h => hne (Fin.ext h) + rcases lt_or_gt_of_ne hn with h | h + · left + have hh := Nat.mul_le_mul_right (pub 4).val (Nat.succ_le_of_lt h) + rw [Nat.succ_mul] at hh + omega + · right + have hh := Nat.mul_le_mul_right (pub 4).val (Nat.succ_le_of_lt h) + rw [Nat.succ_mul] at hh + omega + +private theorem row_fits {pub : Fin 6 → Word w} (a : RowRegions pub) + {v : Word w} (hv : v < pub 2) : + (rowAt pub v).val + (pub 4).val ≤ 2 ^ w := by + rw [rowAt_val a hv] + have h := Nat.mul_le_mul_right (pub 4).val (show v.val + 1 ≤ (pub 2).val from hv) + rw [Nat.succ_mul] at h + have := a.rowsFit + omega + +private theorem count_before_row {pub : Fin 6 → Word w} (a : RowRegions pub) + {u v : Word w} (hu : u < pub 2) (hv : v < pub 2) : + (countAt pub u).val < (rowAt pub v).val := by + rw [countAt_val a hu, rowAt_val a hv] + change u.val < (pub 2).val at hu + have := a.countsBeforeRows + omega + +theorem preimagesAt_step {pub : Fin 6 → Word w} (a : RowRegions pub) {place : Word w → Word w} + (legal : ∀ i : Word w, i < pub 0 → place i < pub 2) + (capacity : ∀ v : Word w, v < pub 2 → + (preimagePrefix place v (pub 0).val).length ≤ (pub 4).val) + {i : Word w} (hi : i < pub 0) {mem : Memory w} (h : PreimagesAt pub place mem i.val) : + ownerAt pub mem i < pub 2 ∧ mem (countAt pub (ownerAt pub mem i)).val < pub 4 ∧ + PreimagesAt pub place (collectUpdate pub mem i) (i.val + 1) := by + let v := place i + have hv : v < pub 2 := legal i hi + have howner : ownerAt pub mem i = v := h.owners i hi + have row := h.rows v hv + have hi' : i.val + 1 ≤ (pub 0).val := hi + have hiCast : Fin.ofNat (2 ^ w) i.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt) + have hprefix : preimagePrefix place v (i.val + 1) = preimagePrefix place v i.val ++ [i] := by + rw [preimagePrefix_succ, hiCast, ite_eq_left (show place i = v from rfl)] + have hlen : (preimagePrefix place v i.val).length < (pub 4).val := by + have hh := (preimagePrefix_mono place v hi').trans (capacity v hv) + simp only [hprefix, List.length_append, List.length_singleton] at hh + omega + have hcap : (mem (countAt pub v).val).val < (pub 4).val := row.1.trans_lt hlen + refine ⟨howner ▸ hv, howner ▸ hcap, ?_⟩ + let addr := rowAt pub v + mem (countAt pub v).val + have haddr : addr.val = (rowAt pub v).val + (mem (countAt pub v).val).val := by + have := row_fits a hv + rw [show addr = _ from rfl, Fin.val_add, Nat.mod_eq_of_lt (by omega)] + have hwrite : collectUpdate pub mem i = + writeMemory (writeMemory mem addr i) (countAt pub v) (mem (countAt pub v).val + 1) := by + simp [collectUpdate, howner, addr] + rw [hwrite] + constructor + · intro j hj + have hstart := a.ownersBeforeCounts + change j.val < (pub 0).val at hj + have hbefore : (pub 1 + j).val < (countAt pub v).val := by + rw [countAt_val a hv, Fin.val_add, Nat.mod_eq_of_lt (by have := (pub 3).isLt; omega)] + omega + have hrow := count_before_row a hv hv + simpa [ownerAt, writeMemory, hbefore.ne, show (pub 1 + j).val ≠ addr.val by omega] + using h.owners j hj + · intro u hu + by_cases he : u = v + · subst u + rw [hprefix] + exact appendRecord_represents row hlen (row_fits a hv) (Or.inl (count_before_row a hv hv)) + · rw [preimagePrefix_succ, hiCast, ite_eq_right (Ne.symm he), List.append_nil] + have hca : (countAt pub u).val ≠ (countAt pub v).val := by + rw [countAt_val a hu, countAt_val a hv] + exact fun hh => he (Fin.ext (Nat.add_left_cancel hh)) + have hur := count_before_row a hu hv + have huc := count_before_row a hv hu + obtain ⟨hl, hvals⟩ := h.rows u hu + constructor + · simpa [writeMemory, hca, show (countAt pub u).val ≠ addr.val by omega] using hl + · intro b + have hb := (preimagePrefix_mono place u (Nat.le_of_lt hi)).trans (capacity u hu) + change (preimagePrefix place u i.val).length ≤ (pub 4).val at hb + have hbl := b.isLt + have hrows := rows_apart a hu hv he + simpa [writeMemory, show (rowAt pub u).val + b.val ≠ (countAt pub v).val by omega, + show (rowAt pub u).val + b.val ≠ addr.val by omega] using hvals b + +/-- All calls of the actual preimage pass, starting at any valid intermediate cursor. +The final memory contains the complete ordered fibers through the resulting cursor. -/ +theorem collectPreimages_run {pub : Fin 6 → Word w} (a : RowRegions pub) + {place : Word w → Word w} (legal : ∀ i : Word w, i < pub 0 → place i < pub 2) + (capacity : ∀ v : Word w, v < pub 2 → + (preimagePrefix place v (pub 0).val).length ≤ (pub 4).val) + {mem : Memory w} {k : ℕ} (h : PreimagesAt pub place mem k) + (steps : ℕ) (hb : k + steps ≤ (pub 0).val) : + let M := (template collectPreimage 3).instantiate w pub + ∃ rs, runSegment M.program 23 (some (Fin.ofNat (2^w) k)) mem (List.replicate steps []) = some rs ∧ + PreimagesAt pub place (after mem (eventLog rs)) (k + steps) ∧ + rs.length = steps ∧ ∀ r ∈ rs, r.events.length = 22 ∧ countProbes r.events = 4 := by + let M := (template collectPreimage 3).instantiate w pub + induction steps generalizing k mem with + | zero => exact ⟨[], rfl, h, rfl, by simp⟩ + | succ s ih => + let i := Fin.ofNat (2 ^ w) k + have hmax := (pub 0).isLt + have hval : i.val = k := Nat.mod_eq_of_lt (by omega) + have hi : i < pub 0 := by change i.val < _; omega + obtain ⟨ho, hcap, hnext⟩ := preimagesAt_step a legal capacity hi (hval ▸ h) + have h1 : 1 % (2^w) = 1 := Nat.mod_eq_of_lt (by omega) + have hnexti : i + 1 = Fin.ofNat (2^w) (k+1) := by + apply Fin.ext + rw [Fin.val_add, Fin.val_one' _, h1, hval] + rfl + let es := collectEvents pub mem i + let r : Report w := ⟨es, some (i + 1)⟩ + obtain ⟨rs, hrun, hrows, hlength, hcounts⟩ := ih (k := k + 1) (hval ▸ hnext) (by omega) + refine ⟨r :: rs, ?_, ?_, by simp [hlength], ?_⟩ + · change runSegment M.program 23 (some i) mem (List.replicate (s+1) []) = _ + rw [List.replicate_succ, runSegment, collectPreimage_native pub mem i hi ho hcap] + simp only [M, r, es, after_collectEvents, hnexti, hrun, Option.map_some] + · have hm : after mem (eventLog (r :: rs)) = after (collectUpdate pub mem i) (eventLog rs) := by + change List.foldl update mem (es ++ eventLog rs) = _ + rw [List.foldl_append] + rfl + simpa [hm, Nat.add_assoc, Nat.add_comm 1 s] using hrows + · intro rep hr + rcases List.mem_cons.mp hr with rfl | hs + · exact collectEvents_work pub mem i + · exact hcounts rep hs + +/-- In particular the pass uses exactly one call and four external probes per old site. -/ +theorem preimagePass_cost {rs : List (Report w)} (h : ∀ r ∈ rs, countProbes r.events = 4) : + RAMBuckets.cost (fun r : Report w => countProbes r.events) rs = 5 * rs.length := by + induction rs with + | nil => simp [RAMBuckets.cost] + | cons r rs ih => + rw [RAMBuckets.cost, h r (List.mem_cons_self ..), ih (fun q hq => h q (List.mem_cons_of_mem _ hq)), + List.length_cons, Nat.mul_succ] + omega + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordPreimages.lean b/lean/OAI/Computability/VPVNP/CompressorRecordPreimages.lean new file mode 100644 index 0000000000..976b6a4ebb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordPreimages.lean @@ -0,0 +1,110 @@ +import OAI.Computability.VPVNP.CompressorRecordTable +import OAI.Computability.VPVNP.RAMChain + +/-! +# Scanning the placement array into local preimage lists + +In the third scan of Appendix E, the selected layout has assigned each old site to one +new owner. Visit the old sites in index order. One fixed RAM call reads the selected +owner, appends the old site's index to that owner's bounded list, and returns the next +old index in the persistent state. The call rejects a malformed owner or an exhausted +row. The local traversal of §13 then has all immediate preimages in directly addressed +order, even when the same old vertex supplied several distinct motif roles. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +/-- Public words give the old-site count, owner-array base, new-site count, count-array +base, row width, and row-array base. Register 3 is the old-site index. -/ +def prepareRow : List (Op 7 6) := + [.stateWord 3, .publicWord 4 0, .guardLt 3 4, .publicWord 4 1, + .binary .add 4 4 3, .read 5 4, .publicWord 4 2, .guardLt 5 4, + .publicWord 0 3, .binary .add 0 0 5, .publicWord 2 4, + .binary .mul 5 5 2, .publicWord 1 5, .binary .add 1 1 5] + +/-- One call per old index. Register 6 is the unit loaded by the append operation. -/ +def collectPreimage : List (Op 7 6) := + prepareRow ++ appendRecord ++ [.binary .add 3 3 6] + +variable {w : ℕ} + +/-- Read the selected new owner of an old site from the placement array. -/ +def ownerAt (pub : Fin 6 → Word w) (mem : Memory w) (i : Word w) : Word w := + mem (pub 1 + i).val + +/-- Address of the current preimage count for one new owner. -/ +def countAt (pub : Fin 6 → Word w) (owner : Word w) : Word w := pub 3 + owner + +/-- First address of an owner's preimage list, using the public row capacity as its stride. -/ +def rowAt (pub : Fin 6 → Word w) (owner : Word w) : Word w := pub 5 + owner * pub 4 + +/-- Exact physical update of the count and data cells by this one scan call. -/ +def collectUpdate (pub : Fin 6 → Word w) (mem : Memory w) (i : Word w) : Memory w := + let owner := ownerAt pub mem i + let c := countAt pub owner + let length := mem c.val + writeMemory (writeMemory mem (rowAt pub owner + length) i) c (length + 1) + +/-- The report of a successful visit includes the two reads and two writes. -/ +def collectEvents (pub : Fin 6 → Word w) (mem : Memory w) (i : Word w) : List (Event w) := + let owner := ownerAt pub mem i + let c := countAt pub owner + let length := mem c.val + [.tick, .tick, .tick, .tick, .tick, .read (pub 1 + i) owner, .tick, .tick, + .tick, .tick, .tick, .tick, .tick, .tick, .read c length, .tick, .tick, + .write (rowAt pub owner + length) i, .tick, .tick, .write c (length + 1), .tick] + +theorem collectPreimage_trace (pub : Fin 6 → Word w) (i : Word w) (regs : Regs w 7) + (mem : Memory w) (hi : i < pub 0) (ho : ownerAt pub mem i < pub 2) + (hcap : mem (countAt pub (ownerAt pub mem i)).val < pub 4) : + ∃ rs, trace pub i collectPreimage regs mem = + some (collectEvents pub mem i, rs, collectUpdate pub mem i) ∧ rs 3 = i + 1 := by + unfold ownerAt countAt at * + simp (config := { decide := true }) [collectPreimage, prepareRow, appendRecord, trace, + Op.effect, BinaryOp.eval, Function.update, hi, ho, hcap, collectEvents, collectUpdate, + ownerAt, countAt, rowAt] + exact ⟨⟨rfl, rfl⟩, rfl⟩ + +theorem collectPreimage_invalid (pub : Fin 6 → Word w) (i : Word w) (regs : Regs w 7) + (mem : Memory w) (h : ¬(i < pub 0 ∧ ownerAt pub mem i < pub 2 ∧ + mem (countAt pub (ownerAt pub mem i)).val < pub 4)) : + trace pub i collectPreimage regs mem = none := by + unfold ownerAt countAt at h + by_cases hi : i < pub 0 <;> + by_cases ho : mem (pub 1 + i).val < pub 2 <;> + simp (config := { decide := true }) [collectPreimage, prepareRow, appendRecord, trace, + Op.effect, BinaryOp.eval, Function.update, hi, ho] at h ⊢ + simp [not_lt_of_ge h] + +/-- The physical write log implements precisely the two updates used in the next call. -/ +theorem after_collectEvents (pub : Fin 6 → Word w) (mem : Memory w) (i : Word w) : + after mem (collectEvents pub mem i) = collectUpdate pub mem i := rfl + +theorem collectEvents_work (pub : Fin 6 → Word w) (mem : Memory w) (i : Word w) : + (collectEvents pub mem i).length = 22 ∧ countProbes (collectEvents pub mem i) = 4 := by + exact ⟨rfl, rfl⟩ + +/-- A scan visit through the fixed native table, starting with zeroed private state. -/ +theorem collectPreimage_native (pub : Fin 6 → Word w) (mem : Memory w) (i : Word w) + (hi : i < pub 0) (ho : ownerAt pub mem i < pub 2) + (hcap : mem (countAt pub (ownerAt pub mem i)).val < pub 4) : + let M := (template collectPreimage 3).instantiate w pub + execute M.program 23 (M.program.start i) mem [] = + some ⟨collectEvents pub mem i, some (i + 1)⟩ := by + obtain ⟨rs, ht, hrs⟩ := collectPreimage_trace pub i (fun _ => 0) mem hi ho hcap + let M := (template collectPreimage 3).instantiate w pub + change execute M.program (1 + collectPreimage.length) ⟨M.entry, i, fun _ => 0, fun _ => 0⟩ mem [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hrs] + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordPrivateDescriptor.lean b/lean/OAI/Computability/VPVNP/CompressorRecordPrivateDescriptor.lean new file mode 100644 index 0000000000..848c1c0713 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordPrivateDescriptor.lean @@ -0,0 +1,105 @@ +import OAI.Computability.VPVNP.PairSimulationLeafCacheWrite +import OAI.Computability.VPVNP.CompressorRecordRegisterSetup + +/-! +# Publishing computed operand words to a private call descriptor + +The same two-instruction store and increment used for the native scalar cache installs +an arbitrary fixed bank of words here. A two-instruction prelude copies the preserved +descriptor pointer and sets the increment to one. Every source register survives. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PrivateDescriptor + +open BurstRAM BurstRAM.PrivateRAM PrimedCounter.GuessWord PairSimulation.LeafSourceLoad +open scoped Fin.CommRing + +variable {n w p r k : ℕ} + +/-- The instruction that stores the selected register value at the private descriptor cursor +and jumps to its increment. -/ +def store (values : Fin n → Fin r) (cursor : Fin r) (inc : Fin n → Fin p) (j : Fin n) : Instr w p r k := + .storePrivate cursor (values j) (inc j) + +/-- The linked instruction addresses that copy the descriptor pointer, set a unit increment, +and store and advance through all values. -/ +structure Linked (M : Machine w p r k) (values : Fin n → Fin r) (ptr cursor unit : Fin r) + (header : Fin 2 → Fin p) (pc : Fin (n+1) → Fin p) (inc : Fin n → Fin p) : Prop where + copy : M.code (header 0) = .copy cursor ptr (header 1) + one : M.code (header 1) = .constant unit 1 (pc 0) + write : ∀ i, M.code (pc i.castSucc) = store values cursor inc i + advance : ∀ i, M.code (inc i) = incInstr cursor unit (pc i.succ) + +/-- The computed words are published contiguously while preserving the call pointer +and all private data outside its exact interval. -/ +theorem publish (M : Machine w p r k) (values : Fin n → Fin r) (ptr cursor unit : Fin r) + (header : Fin 2 → Fin p) (pc : Fin (n+1) → Fin p) (inc : Fin n → Fin p) + (link : Linked M values ptr cursor unit header pc inc) + (separate : unit ≠ cursor) (ptrCursor : ptr ≠ cursor) (ptrUnit : ptr ≠ unit) + (valuesApart : ∀ i, values i ≠ cursor ∧ values i ≠ unit) + (c : Config w p r) (entry : c.pc = header 0) (room : (c.reg ptr).val+n ≤ 2^w) : + ∃ out, Prefix M c (List.replicate (2+2*n) .tick) out ∧ out.pc = pc (Fin.last n) ∧ + out.persistent = c.persistent ∧ out.reg ptr = c.reg ptr ∧ + (∀ i : Fin n, out.privateMem (out.reg ptr+(i.val : Word w)) = c.reg (values i)) ∧ + (∀ a : Word w, a.val < (c.reg ptr).val ∨ (c.reg ptr).val+n ≤ a.val → out.privateMem a = c.privateMem a) ∧ + ∀ j, j ≠ cursor → j ≠ unit → out.reg j = c.reg j := by + let c₁ := c.put (header 1) cursor (c.reg ptr) + let c₂ := c₁.put (pc 0) unit 1 + have first : M.program.step c = .localStep c₁ := by + change (M.code c.pc).run M.publicData c = _ + rw [entry,link.copy]; rfl + have second : M.program.step c₁ = .localStep c₂ := by + change (M.code (header 1)).run M.publicData c₁ = _ + rw [link.one]; rfl + have head : Prefix M c [.tick,.tick] c₂ := .tick first (.tick second (.nil _)) + let ls := (List.finRange n).map (Static.operand (k := n)) + have len : ls.length = n := by simp [ls] + let source : Static n → Fin r := fun x => match x with + | .operand i => values i + | _ => unit + have hsource : ∀ i, source i ≠ cursor := by intro i; cases i <;> first | exact separate | exact (valuesApart _).1 + let addr := (c.reg ptr).val + let loc := fun i : Fin (ls.length+1) => pc (Fin.cast (by omega) i) + let next := fun i : Fin ls.length => inc (Fin.cast len i) + have writes (i : Fin ls.length) : + M.code (loc i.castSucc) = storeInstr source cursor (next i) ls[i.val] := by + let j := Fin.cast len i + have h := link.write j + change M.code (pc j.castSucc) = storeInstr source cursor (inc j) _ + rw [h] + simp only [ls,List.getElem_map,List.getElem_finRange,source,store,storeInstr] + congr 2 + have advance (i : Fin ls.length) : M.code (next i) = incInstr cursor unit (loc i.succ) := link.advance (Fin.cast len i) + have ha : (addr : Word w) = c.reg ptr := Fin.ext (Nat.mod_eq_of_lt (c.reg ptr).isLt) + have atCursor : c₂.reg cursor = (addr : Word w) := by + simp [c₂,c₁,Config.put,separate.symm,ha] + obtain ⟨out,tail,last,mem⟩ := write_rows M source cursor unit hsource separate ls (fun j => c₂.reg (source j)) loc next + writes advance addr c₂ rfl atCursor (Function.update_self ..) (fun _ => rfl) (by simpa only [len] using room) + have run := head.append tail + rw [len] at run + have frame (j : Fin r) (hc : j ≠ cursor) (hu : j ≠ unit) : out.reg j = c.reg j := by + rw [mem.frame _ hc]; simp only [c₂,c₁,Config.put,Function.update_of_ne hu,Function.update_of_ne hc] + have ptrEq := frame _ ptrCursor ptrUnit + have finalPC : loc (Fin.last ls.length) = pc (Fin.last n) := congrArg pc (Fin.ext len) + refine ⟨out,by simpa only [List.replicate_add,List.replicate_succ,List.replicate_zero,List.nil_append,List.cons_append] using run, + last.trans finalPC,mem.persistent,ptrEq,fun i => ?_,fun a h => mem.outside a (by simpa only [addr,List.length_map,len] using h),frame⟩ + let j : Fin (ls.map (fun x => c₂.reg (source x))).length := ⟨i.val,by simpa only [List.length_map,len] using i.isLt⟩ + have hv := mem.values j + rw [ptrEq,← ha] + change out.privateMem ((addr : Word w)+(i.val : Word w)) = _ + rw [← Nat.cast_add] + have h' : out.privateMem ((addr+i.val : ℕ) : Word w) = c₂.reg (values i) := by + simp only [ls,Fin.getElem_fin,List.getElem_map,List.getElem_finRange,source,j] at hv + exact hv.trans (congrArg (fun u => c₂.reg (values u)) (Fin.ext rfl)) + rw [h'] + simp only [c₂,c₁,Config.put,Function.update_of_ne (valuesApart i).2,Function.update_of_ne (valuesApart i).1] + +end CompressorRecords.PrivateDescriptor + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefresh.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefresh.lean new file mode 100644 index 0000000000..340fa66661 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefresh.lean @@ -0,0 +1,265 @@ +import OAI.Computability.VPVNP.BitSlotXor +import OAI.Computability.VPVNP.CompressorRecordRefreshRAM +import OAI.Computability.VPVNP.CompressorRecordSlices +import OAI.Computability.VPVNP.DegreeRefreshActualStep + +/-! +# Directly indexed records of the degree-restoring step + +A source bundle specifies the old base arc and the remaining lane. Its numbered segments +are in source-port order. At the destination the incoming slot and translated port index +the same segment. We relate the emitted offset and width records to the bit indices of the +actual refresh kernel, including local diagonal checks and the two copies of the off-diagonal +demand. We also give the endpoint and width tables for the external, expander and dummy slots. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh + +open Compression Compression.Refresh Compression.DegreeRefresh + +variable {V H L : Type} {D dH d₀ : ℕ} [AddCommGroup H] [AddCommGroup L] +variable (G : LiftedSlots V D (H × L)) (port : H ≃ Fin D) (w : (V × Fin D) × (H × L) → ℕ) + +/-- Both endpoint identifiers and one interval in the external word. An endpoint consists +of its block, its slot and its old port. Its first two components also locate the external +slot at which this interval is read. -/ +structure SegmentRecord (B : Type*) (D : ℕ) where + /-- The outgoing segment identified by its source bundle and numbered port. -/ + outgoing : Arc B D + /-- The same segment's incoming bundle and translated port at the destination. -/ + incoming : Arc B D + /-- Starting bit offset of the segment in the concatenation ordered by source port. -/ + offset : ℕ + /-- Number of bits contributed by this segment to its external bundle. -/ + width : ℕ + +/-- Generate the record of an old actual arc in source-bundle coordinates. -/ +def outgoingRecord (a : Arc (V × L) D) : SegmentRecord (V × L) D := + ⟨a, (bundleTarget G a.1, bundlePort G port a.1 a.2), + (numberedField (Equiv.refl _) (bundleWidths port w a.1) a.2).start, groupedWidths port w a⟩ + +/-- Destination slot lookup inverts the remaining-lane translation and then the port +translation. In particular, it retains the prefix total of the *source* ordering. -/ +def incomingRecord (q : Arc (V × L) D) : SegmentRecord (V × L) D := + let b := (bundleTarget G).symm q.1 + outgoingRecord G port w (b, (bundlePort G port b).symm q.2) + +theorem incomingRecord_matching (q : Arc (V × L) D) : + incomingRecord G port w q = outgoingRecord G port w ((oldPortMatching G port).symm q) := by + rcases q with ⟨b,j⟩ + rw [oldPortMatching_symm_apply] + rfl + +theorem incomingRecord_roundtrip (a : Arc (V × L) D) : + incomingRecord G port w (oldPortMatching G port a) = outgoingRecord G port w a := by + rw [incomingRecord_matching, Equiv.symm_apply_apply] + +/-- Every actual incoming half-slot receives exactly one of the emitted rows. -/ +theorem incoming_unique (q : Arc (V × L) D) : + ∃! a : Arc (V × L) D, (outgoingRecord G port w a).incoming = q := + ⟨(oldPortMatching G port).symm q, (oldPortMatching G port).apply_symm_apply q, + fun _ ha => (oldPortMatching G port).eq_symm_apply.mpr ha⟩ + +/-- The emitted old endpoint slots are those of the original lifted network. -/ +theorem old_slot_endpoints (a : Arc (V × L) D) : + G.actualTarget ((bundleCoordinates port).symm (outgoingRecord G port w a).outgoing) = + (bundleCoordinates port).symm (outgoingRecord G port w a).incoming := + (bundleCoordinates port).eq_symm_apply.mpr (actualTarget_bundleCoordinates G port a.1 a.2) + +/-- The prefix scan of the widths writes the exact record, also when its interval is empty. -/ +theorem segment_in_scan (a : Arc (V × L) D) : + let r := outgoingRecord G port w a + (⟨a.2.val, r.offset, r.width⟩ : Field) ∈ fieldsFrom 0 0 (List.ofFn (bundleWidths port w a.1)) := + orderedField_mem (Equiv.refl _) (bundleWidths port w a.1) a.2 + +theorem segment_fits (a : Arc (V × L) D) : + let r := outgoingRecord G port w a + r.offset + r.width ≤ ∑ k, bundleWidths port w a.1 k := by + simpa [List.sum_ofFn] using (fieldsFrom_bounds (segment_in_scan G port w a)).2.2.2 + +/-- For any chosen external payload the record's bit addresses recover the actual outgoing +and incoming segment arguments, as read by the local kernel. -/ +theorem port_bit_reads (p : (V × L) × Fin D) (j : Fin D) (z : External (groupedWidths port w)) : + let t := oldPortMatching G port + let widths := groupedWidths port w + let lists := incidentPortSegments t (bundleTarget G) (oldPortMatching_bundle G port) widths p + (z p) (z ((bundleTarget G).symm p)) + (∀ i : Fin (widths (p,j)), ∃ k : Fin (∑ l, widths (p,l)), + k.val = (outgoingRecord G port w (p,j)).offset + i.val ∧ lists.1 j i = z p k) ∧ + (∀ i : Fin (widths (t.symm (p,j))), ∃ k : Fin (∑ l, widths ((t.symm (p,j)).1,l)), + k.val = (incomingRecord G port w (p,j)).offset + i.val ∧ lists.2 j i = z (t.symm (p,j)).1 k) := by + dsimp only + rw [incidentPortSegments_external, incomingRecord_matching] + constructor + · intro i + exact ⟨_, segment_offset _ p j i, rfl⟩ + · intro i + let a := (oldPortMatching G port).symm (p,j) + exact ⟨_, segment_offset _ a.1 a.2 i, rfl⟩ + +/-- The same interval addresses work on arbitrary incident half-wires. The incoming and +outgoing external slots are distinct, so the two independently chosen words extend to a +single test assignment without imposing any extra equality. -/ +theorem local_bit_reads (p : (V × L) × Fin D) (j : Fin D) + (outWord : Word (∑ l, groupedWidths port w (p,l))) + (inWord : Word (∑ l, groupedWidths port w ((bundleTarget G).symm p,l))) : + let t := oldPortMatching G port + let widths := groupedWidths port w + let lists := incidentPortSegments t (bundleTarget G) (oldPortMatching_bundle G port) widths p outWord inWord + (∀ i : Fin (widths (p,j)), ∃ k : Fin (∑ l, widths (p,l)), + k.val = (outgoingRecord G port w (p,j)).offset + i.val ∧ lists.1 j i = outWord k) ∧ + (∀ i : Fin (widths (t.symm (p,j))), ∃ k : Fin (∑ l, widths ((bundleTarget G).symm p,l)), + k.val = (incomingRecord G port w (p,j)).offset + i.val ∧ lists.2 j i = inWord k) := by + classical + dsimp only + let q := (bundleTarget G).symm p + have hne : p ≠ q := fun he => G.base.ends_ne (p.1.1,p.2) + (congrArg (fun z : (V × L) × Fin D => z.1.1) ((bundleTarget G).eq_symm_apply.mp he)) + let z : External (groupedWidths port w) := Function.update + (Function.update (fun _ _ => false) p outWord) q inWord + have ho : z p = outWord := (Function.update_of_ne hne _ _).trans (Function.update_self ..) + have hi : z ((bundleTarget G).symm p) = inWord := Function.update_self .. + have reads := port_bit_reads G port w p j z + dsimp only at reads + simp only [ho, hi] at reads + refine ⟨reads.1, fun i => ?_⟩ + obtain ⟨k,hk,hval⟩ := reads.2 i + have transport (b : (V × L) × Fin D) (hb : b = q) (r : Fin (∑ l, groupedWidths port w (b,l))) : + ∃ r' : Fin (∑ l, groupedWidths port w (q,l)), r'.val = r.val ∧ z b r = inWord r' := by + subst b + exact ⟨r, rfl, congrFun hi r⟩ + obtain ⟨k',he,hz⟩ := transport _ (congrArg Prod.fst (oldPortMatching_symm_apply G port p j)) k + exact ⟨k', he.trans hk, hval.trans hz⟩ + +/-- Off-diagonal motif demand references the old half-slot at `tieSource` and its external +segment at `tieTarget`. The flag in `Tie` selects the outgoing or incoming records. -/ +def demandRecord (s : V × L) (e : Tie D) : SegmentRecord (V × L) D := + let q := ((s, tieTarget e), tieSource e) + if e.1 then outgoingRecord G port w q else incomingRecord G port w q + +theorem demandRecord_width (s : V × L) (e : Tie D) : + (demandRecord G port w s e).width = internalWidth (oldPortMatching G port) (groupedWidths port w) s e := by + unfold demandRecord internalWidth + split_ifs + · rfl + · rw [incomingRecord_matching]; rfl + +variable (P : SlotGraph (Fin D) dH) (hD : 1 < D) (hd : dH + 1 ≤ d₀) + +/-- Both numbered endpoints of one refreshed arc. Widths may vary across lanes and terms. -/ +structure NewSlot (V L : Type*) (D d₀ : ℕ) where + /-- Source site and outgoing slot number of a refreshed actual arc. -/ + src : ActualArc V L D d₀ + /-- Destination site and incoming slot number of the same refreshed arc. -/ + dst : ActualArc V L D d₀ + /-- Number of bits carried by this refreshed external, expander, or padding arc. -/ + width : ℕ + +/-- Append the sole external slot, the expander slots in expander order and the dummy slots +in padding order. The same expander edge table supplies the incoming slot number. -/ +def slotRecord (internal : (V × L) → Fin D × Fin dH → ℕ) (p : (V × L) × Fin D) : + RefreshSlot dH d₀ → NewSlot V L D d₀ + | .inl k => ⟨(promotedSites p, refreshSlots hd (.inl k)), + (promotedSites (bundleTarget G p), refreshSlots hd (.inl k)), ∑ j, bundleWidths port w p j⟩ + | .inr (.inl k) => ⟨(promotedSites p, refreshSlots hd (.inr (.inl k))), + (promotedSites (p.1,(P.target (p.2,k)).1), refreshSlots hd (.inr (.inl (P.target (p.2,k)).2))), + internal p.1 (p.2,k)⟩ + | .inr (.inr k) => ⟨(promotedSites p, refreshSlots hd (.inr (.inr k))), + (promotedSites (p.1,finRotate D p.2), refreshSlots hd (.inr (.inr k))), 0⟩ + +omit [AddCommGroup H] in +theorem slotRecord_spec (internal : (V × L) → Fin D × Fin dH → ℕ) (p : (V × L) × Fin D) + (c : RefreshSlot dH d₀) : + let r := slotRecord G port w P hd internal p c + r.src = (promotedSites p, refreshSlots hd c) ∧ + (degreeRefresh G P hD hd).actualGraph.target r.src = r.dst ∧ + actualWidths hd port w internal ((r.src.1.1,r.src.2),r.src.1.2) = r.width := by + rcases p with ⟨⟨v,l⟩,i⟩ + rcases c with k | k | k + · cases Subsingleton.elim k 0 + refine ⟨rfl, degreeRefresh_external G P hD hd (v,i) l, ?_⟩ + simp [slotRecord, actualWidths, refreshedCoordinates, promotedSites, newWidths] + · refine ⟨rfl, degreeRefresh_internal G P hD hd v i l k, ?_⟩ + simp [slotRecord, actualWidths, refreshedCoordinates, promotedSites, newWidths] + · refine ⟨rfl, degreeRefresh_padding G P hD hd v i l k, ?_⟩ + simp [slotRecord, actualWidths, refreshedCoordinates, promotedSites, newWidths] + +/-- A full output slot table at a physical port, generated in slot-number order. -/ +def slotTable (internal : (V × L) → Fin D × Fin dH → ℕ) (p : (V × L) × Fin D) := + List.ofFn fun k : Fin d₀ => slotRecord G port w P hd internal p ((refreshSlots hd).symm k) + +omit [AddCommGroup H] in +@[simp] theorem slotTable_length (internal : (V × L) → Fin D × Fin dH → ℕ) (p : (V × L) × Fin D) : + (slotTable G port w P hd internal p).length = d₀ := by simp [slotTable] + +/-- The number of segment visits and slot records is linear in the number of positions +for the fixed degrees of this substep. -/ +theorem visit_counts (B : Type*) [Fintype B] (D d₀ : ℕ) : + Fintype.card (Arc B D) = Fintype.card (B × Fin D) * D ∧ + Fintype.card ((B × Fin D) × Fin d₀) = Fintype.card (B × Fin D) * d₀ := by + simp [Refresh.Arc, Fintype.card_prod] + +section Numbered + +open BurstRAM BurstRAM.PrivateRAM + +/-- The source-major index is invertible by quotient and remainder with divisor `D`. -/ +def numbered {B : Type*} {n D : ℕ} (order : B × Fin D ≃ Fin n) : Refresh.Arc B D ≃ Fin (n * D) := + (order.prodCongr (Equiv.refl (Fin D))).trans finProdFinEquiv + +theorem numbered_val {B : Type*} {n D : ℕ} (order : B × Fin D ≃ Fin n) (b : B × Fin D) (j : Fin D) : + (numbered order (b,j)).val = (order b).val * D + j.val := by + change j.val + D * (order b).val = _ + rw [Nat.mul_comm, Nat.add_comm] + +variable {a n bits : ℕ} (X : LiftedSlots V (2 ^ a) (BitWord a × L)) + (order : (V × L) × Fin (2 ^ a) ≃ Fin n) + +/-- The numerical destination of a segment uses the bundle number, degree and translated port. -/ +theorem translated_index (degree target shift : BurstRAM.Word bits) + (b : (V × L) × Fin (2 ^ a)) (j : Fin (2 ^ a)) (i : BurstRAM.Word bits) + (hi : i.val = (numbered order (b,j)).val) (hd : degree.val = 2 ^ a) + (ht : target.val = (order (bundleTarget X b)).val) + (hs : shift.val = + (bitWordFinEquiv a (X.displacement (b.1.1,b.2)).1).val) (hfit : n * 2 ^ a ≤ 2 ^ bits) : + (target * degree + BinaryOp.bitXor.eval (BinaryOp.mod.eval i degree) shift).val = + (numbered order (oldPortMatching X (bitWordFinEquiv a) (b,j))).val := by + have hport : i.val % degree.val = j.val := by + rw [hi, hd, numbered_val, Nat.mul_add_mod_of_lt j.isLt] + have hport' : (BinaryOp.mod.eval i degree).val = j.val := by + change (i.val % degree.val) % _ = _ + rw [hport, Nat.mod_eq_of_lt (j.isLt.trans (hd ▸ degree.isLt))] + have hxor : (bundlePort X (bitWordFinEquiv a) b j).val = + j.val ^^^ (bitWordFinEquiv a (X.displacement (b.1.1,b.2)).1).val := by + rw [bundlePort_apply, bitWordFinEquiv_add_val, Equiv.apply_symm_apply] + have hrow : (order (bundleTarget X b)).val * 2 ^ a + (bundlePort X (bitWordFinEquiv a) b j).val < 2 ^ bits := + (numbered_val order (bundleTarget X b) (bundlePort X (bitWordFinEquiv a) b j) ▸ + (numbered order (bundleTarget X b, bundlePort X (bitWordFinEquiv a) b j)).isLt).trans_le hfit + have hb (x y : BurstRAM.Word bits) : (BinaryOp.bitXor.eval x y).val = x.val ^^^ y.val := + Nat.mod_eq_of_lt (Nat.xor_lt_two_pow x.isLt y.isLt) + rw [oldPortMatching_apply, numbered_val, Fin.val_add, Fin.val_mul, + hb, hport', hs, ht, hd, ← hxor, Nat.mod_add_mod, Nat.mod_eq_of_lt hrow] + +/-- With the target and shift supplied by the old slot table, the address computed by +`visit` is the number of the actual translated incoming half-slot. -/ +theorem visit_destination (p : Fin 8 → BurstRAM.Word bits) (m : Memory bits) + (b : (V × L) × Fin (2 ^ a)) (j : Fin (2 ^ a)) (i : BurstRAM.Word bits) + (hi : i.val = (numbered order (b,j)).val) (hd : (p 0).val = 2 ^ a) + (ht : (m (p 2 + RefreshRAM.bundle p i).val).val = (order (bundleTarget X b)).val) + (hs : (m (p 3 + RefreshRAM.bundle p i).val).val = + (bitWordFinEquiv a (X.displacement (b.1.1,b.2)).1).val) (hfit : n * 2 ^ a ≤ 2 ^ bits) : + (RefreshRAM.destination p m i).val = + (numbered order (oldPortMatching X (bitWordFinEquiv a) (b,j))).val := + translated_index X order _ _ _ b j i hi hd ht hs hfit + +end Numbered + +end CompressorRecords.PortRefresh + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshAdmitted.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshAdmitted.lean new file mode 100644 index 0000000000..5ef8683049 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshAdmitted.lean @@ -0,0 +1,180 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshPrepare +import OAI.Computability.VPVNP.CompressorRecordRefreshSupplyScan +import OAI.Computability.VPVNP.CompressorTermWorkerScan + +/-! +# The native term choices of a degree refresh + +Each port block's dense demand vector is read from its generated record. A single native +call at the block ordinal selects a fixed grid row, computes the repetition count and checks the admitted +supply payload. The successful bit streams biject with the actual branch choices of the +refresh. The width threshold is fixed before the number of blocks or the old widths. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry MotifConversion +open NewSlots RefreshRAM +open scoped Fin.CommRing + +variable {a a₀ g dH t bits : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') (ties : Fin t ≃ Tie (2^a)) + +private theorem massPos (e : Fin (2^a) × Fin dH) : 0 < expanderMass (2^a₀) e := + div_pos (Nat.cast_pos.mpr (Nat.two_pow_pos a)) (Nat.cast_pos.mpr (Nat.two_pow_pos a₀)) + +/-- A sufficient word-width constant for this fixed motif, independent of the old state +and the number of its port blocks. -/ +noncomputable def termConstant := (TermWorker.scan_native F ties finProdFinEquiv.symm + (fun _ => zero_lt_one) massPos).choose + +variable (X : State a (a+g)) (q : Fin 8 → BurstRAM.Word bits) + (demandBase termBase : BurstRAM.Word bits) (stride : ℕ) + +local notation "B" => Fintype.card X.Base * 2^g +local notation "D" => 2^a +local notation "S" => Fintype.card X.Base * D * 2^g * D +local notation "demand" => blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) + +/-- Tightly packed input rows and arbitrarily strided output records, both in block order. -/ +def termRows (wide : 2+D*dH ≤ stride) (sep : demandBase.val+B*t ≤ termBase.val) + (room : termBase.val+B*stride < 2^bits) := + TermRecordScan.strided B t (D*dH) bits demandBase.val termBase.val t stride le_rfl wide sep room + +variable (wide : 2+2^a*dH ≤ stride) (sep : demandBase.val + Fintype.card X.Base * 2^g * t ≤ termBase.val) + (room : termBase.val + Fintype.card X.Base * 2^g * stride < 2^bits) +local notation "L" => termRows X demandBase termBase stride wide sep room + +private theorem termRows_source (s : X.Base × BitWord g) : (L).source (DemandScan.blocks X s) = + DemandScan.rowBase X t demandBase s := by + apply Fin.ext + change (demandBase.val + (DemandScan.blocks X s).val * t) % _ = + (demandBase + word ((DemandScan.blocks X s).val * t)).val + rw [Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod] + +private theorem termRows_base (s : X.Base × BitWord g) : (L).base (DemandScan.blocks X s) = + SupplyScan.recordBase X termBase stride s := by + apply Fin.ext + change (termBase.val + (DemandScan.blocks X s).val * stride) % _ = + (termBase + word _ * word stride).val + rw [DemandScan.blocks_val,Fin.val_add,Fin.val_mul,Fin.val_ofNat,Fin.val_ofNat, + Nat.mul_mod_mod,Nat.mod_mul_mod,Nat.add_mod_mod] + +/-- The supplied numerical rows are read by the exact term compiler. -/ +private theorem termInputs (m : Memory bits) + (prepared : ∀ s, DemandPreparation.demandAt ties (DemandScan.rowBase X t demandBase s) m = demand s) : + TermRecordScan.Inputs ties L (fun i => demand ((DemandScan.blocks X).symm i)) m := by + intro i + obtain ⟨s,rfl⟩ := (DemandScan.blocks X).surjective i + rw [termRows_source] + simpa only [Equiv.symm_apply_apply] using prepared s + +/-- The concrete choice stream supplied to the block's nondeterministic calls. -/ +noncomputable def blockTapes (choice : DyadicRefreshChoice X E hdH conn F) (bits : ℕ) (i : Fin B) := + let s := (DemandScan.blocks X).symm i + TermRecordScan.tape F finProdFinEquiv.symm (demand s) bits (choice s).val + +/-- The admissible mathematical term families, reindexed in the native scan order. -/ +noncomputable def blockChoicesEquiv : DyadicRefreshChoice X E hdH conn F ≃ + TermRecordScan.Choices F (fun i : Fin B => demand ((DemandScan.blocks X).symm i)) := + Equiv.piCongrLeft' (fun s => ↥(outerIndices F (demand s))) (DemandScan.blocks X) + +/-- Four public address operands of the native term worker. -/ +def termAddresses (t : ℕ) : Fin 4 → BurstRAM.Word bits := ![demandBase.val, t, termBase.val, stride] + +/-- The same fixed native program serves every block ordinal. -/ +noncomputable abbrev termRun (cap : ℕ) (tapes : Fin B → List Bool) (m : Memory bits) := + runSegment (TermWorker.program F ties finProdFinEquiv.symm (termAddresses demandBase termBase stride t)) cap + (some 0) m (List.ofFn tapes) + +local notation "run" => termRun E hdH conn F ties X demandBase termBase stride + +include wide sep room in +/-- A successful complete native stream selects precisely one actual refresh branch, +including when the block needs zero copies and its term takes no bits. -/ +theorem term_stream_iff (m : Memory bits) (M : ℕ) + (bound : termConstant E hdH conn F ties + 4*Nat.clog 2 (M+1) ≤ bits) + (hw : ∀ s e, demand s e ≤ M) + (prepared : ∀ s, DemandPreparation.demandAt ties (DemandScan.rowBase X t demandBase s) m = demand s) + (cap : ℕ) (hcap : TermWorker.budget F t (D*dH) bits M ≤ cap) (tapes : Fin B → List Bool) : + (run cap tapes m).isSome ↔ ∃! choice : DyadicRefreshChoice X E hdH conn F, + tapes = blockTapes E hdH conn F X choice bits := by + let indexed := blockChoicesEquiv E hdH conn F X + let d := fun i : Fin B => demand ((DemandScan.blocks X).symm i) + have h := (TermWorker.scan_native F ties finProdFinEquiv.symm (fun _ => zero_lt_one) massPos).choose_spec + B M bits bound L (termAddresses demandBase termBase stride t) + (TermWorker.addresses_strided demandBase.val termBase.val t stride le_rfl wide sep room) d + (fun i => hw _) m (termInputs ties X demandBase termBase stride wide sep room m prepared) cap hcap + dsimp only at h + rw [h.1] + let P := fun c : TermRecordScan.Choices F d => + tapes = fun i => TermRecordScan.tape F finProdFinEquiv.symm (d i) bits (c i).val + change (∃! c, P c) ↔ ∃! c, P (indexed c) + constructor + · rintro ⟨c,hc,uniq⟩ + refine ⟨indexed.symm c, by simpa using hc, fun j hj => indexed.injective ?_⟩ + simpa using uniq _ hj + · rintro ⟨c,hc,uniq⟩ + refine ⟨indexed c,hc,fun j hj => ?_⟩ + have he := uniq (indexed.symm j) (by simpa using hj) + simpa using congrArg indexed he + +private theorem cost_reports (rs : List (Report bits)) : RAMBuckets.cost Report.probes rs = + rs.length + countProbes (eventLog rs) := by + induction rs with + | nil => rfl + | cons r rs ih => + rw [RAMBuckets.cost,ih,List.length_cons] + change 1 + countProbes r.events + (rs.length + countProbes (eventLog rs)) = + rs.length + 1 + countProbes (r.events ++ eventLog rs) + rw [DemandPreparation.probes_append]; omega + +include wide sep room in +/-- Each selected branch produces its grid IDs, repetition words and payload coordinates +through native calls. Every term field survives the complete pass. -/ +theorem term_pass (m : Memory bits) (M : ℕ) + (bound : termConstant E hdH conn F ties + 4*Nat.clog 2 (M+1) ≤ bits) + (hw : ∀ s e, demand s e ≤ M) + (prepared : ∀ s, DemandPreparation.demandAt ties (DemandScan.rowBase X t demandBase s) m = demand s) + (cap : ℕ) (hcap : TermWorker.budget F t (D*dH) bits M ≤ cap) (choice : DyadicRefreshChoice X E hdH conn F) : + ∃ rs, run cap (blockTapes E hdH conn F X choice bits) m = some rs ∧ + SupplyScan.TermFields X E hdH conn F choice termBase stride (after m (eventLog rs)) ∧ + (∀ s, TermRecordScan.Fields F finProdFinEquiv.symm (fun _ => zero_lt_one) + (demand s) (choice s).val (SupplyScan.recordBase X termBase stride s) (after m (eventLog rs))) ∧ + (∀ addr, (addr < termBase.val ∨ termBase.val + B * stride ≤ addr) → after m (eventLog rs) addr = m addr) ∧ + RAMBuckets.cost Report.probes rs ≤ B * (1 + TermRecordScan.probesPerRow F t (D*dH)) ∧ + (eventLog rs).length ≤ B * TermWorker.budget F t (D*dH) bits M := by + let d := fun i : Fin B => demand ((DemandScan.blocks X).symm i) + have h := (TermWorker.scan_native F ties finProdFinEquiv.symm (fun _ => zero_lt_one) massPos).choose_spec + B M bits bound L (termAddresses demandBase termBase stride t) + (TermWorker.addresses_strided demandBase.val termBase.val t stride le_rfl wide sep room) d + (fun i => hw _) m (termInputs ties X demandBase termBase stride wide sep room m prepared) cap hcap + dsimp only at h + obtain ⟨rs,hr,fields,frame,_,nr,_,probes,steps⟩ := h.2 (blockChoicesEquiv E hdH conn F X choice) + have hs (s) := fields (DemandScan.blocks X s) + have hs' (s : X.Base × BitWord g) : TermRecordScan.Fields F finProdFinEquiv.symm (fun _ => zero_lt_one) + (demand s) (choice s).val (SupplyScan.recordBase X termBase stride s) (after m (eventLog rs)) := by + have hv := congrArg (fun b => (choice b).val) ((DemandScan.blocks X).symm_apply_apply s) + simpa only [d, blockChoicesEquiv, Equiv.piCongrLeft'_apply,Equiv.symm_apply_apply,termRows_base,hv] using hs s + have tf := SupplyScan.TermFields.ofValues X E hdH conn F choice termBase stride (after m (eventLog rs)) + (fun s => (termRows_base X demandBase termBase stride wide sep room s) ▸ (L).termFits (DemandScan.blocks X s)) + (fun s => (hs' s).2.1) (fun s => (hs' s).2.2) + refine ⟨rs,hr,tf,hs',fun addr ha => frame addr (fun i => ?_),?_,steps⟩ + · change addr < ((L).base i).val ∨ ((L).base i).val + 2 + D*dH ≤ addr + have hi := Nat.mul_le_mul_right stride (Nat.succ_le_of_lt i.isLt) + rw [Nat.succ_mul] at hi + have hb : ((L).base i).val = termBase.val + i.val*stride := Nat.mod_eq_of_lt (by omega) + rw [hb]; omega + · rw [cost_reports,nr,Nat.mul_add,Nat.mul_one] + omega + +end CompressorRecords.PortRefresh + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshAllSlots.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshAllSlots.lean new file mode 100644 index 0000000000..e0b09b94d4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshAllSlots.lean @@ -0,0 +1,407 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshNewSlots +import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout +import OAI.Computability.VPVNP.DegreeRefreshPass + +/-! +# All actual incidence columns of a degree refresh + +In increasing local-slot order, each native table visits all the new sites. +The scans share external memory. The incoming link is indexed by the target +half-slot, which can have a different local number on an expander arc. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.AllSlots + +open BurstRAM PrimedStackRAM NewSlots +open Compression Compression.Refresh Compression.DegreeRefresh + +variable {bits d N : ℕ} + +section Sequence + +variable (kind : Fin d → Kind) (pub : Fin d → Public bits) + +/-- The expected incidence row for one local slot and site, computed from the reference memory +and that slot's public operands. -/ +abbrev entry (ref : Memory bits) (k : Fin d) (i : Fin N) : Row bits := + expected (kind k) (pub k) ref i + +/-- Native executions of consecutive slot scans. Each scan starts at site zero +with the actual external memory left by its predecessor. -/ +inductive Runs (N : ℕ) : List (Fin d) → Memory bits → List (Report bits) → Prop where + | nil (m) : Runs N [] m [] + | cons (k : Fin d) {ks m rs ts} + (head : let M := (template (code (kind k)) 0).instantiate bits (pub k) + runSegment M.program (1 + (code (kind k)).length) (some 0) m (List.replicate N []) = some rs) + (tail : Runs N ks (after m (eventLog rs)) ts) : Runs N (k :: ks) m (rs ++ ts) + +/-- The slot scans have disjoint inputs and outputs, and each output address identifies its +slot, site, and column uniquely. -/ +structure Layout (ref : Memory bits) (N : ℕ) : Prop where + reads : ∀ k j (i l : Fin N) c a, a ∈ inputs (kind k) (pub k) (word i.val) → + a ≠ (entry kind pub ref j l).address (pub j) c + writes : ∀ k j (i l : Fin N) c b, + (entry kind pub ref k i).address (pub k) c = (entry kind pub ref j l).address (pub j) b → + k = j ∧ i = l ∧ c = b + +variable (ref : Memory bits) + +/-- The memory agrees with the immutable input tables of every scan. -/ +def Reads (m : Memory bits) (N : ℕ) : Prop := + ∀ k (i : Fin N) a, a ∈ inputs (kind k) (pub k) (word i.val) → m a.val = ref a.val + +private theorem sameEntry {m : Memory bits} (h : Reads kind pub ref m N) (k : Fin d) (i : Fin N) : + entry kind pub m k i = entry kind pub ref k i := by + have ha := h k i + change row (kind k) (pub k) m (word i.val) = row (kind k) (pub k) ref (word i.val) + generalize hb : word (bits := bits) i.val = b at ha ⊢ + cases hk : kind k <;> simp [hk,inputs] at ha + · simp only [row,ha.1,ha.2] + · simp only [row,ha.1,ha.2.1,ha.2.2] + · rfl + +/-- Rows and frame of the visits for the listed slots. -/ +structure Completed (initial final : Memory bits) (ks : List (Fin d)) (N : ℕ) : Prop where + rows : ∀ k ∈ ks, ∀ (i : Fin N) c, + final ((entry kind pub ref k i).address (pub k) c).val = (entry kind pub ref k i).value c + frame : ∀ a, (∀ k ∈ ks, ∀ (i : Fin N) c, a ≠ ((entry kind pub ref k i).address (pub k) c).val) → + final a = initial a + +/-- Any list of local-slot passes, including repeated slots, executes against +one set of physical inputs and writes exactly the indicated rows. -/ +theorem runList (layout : Layout kind pub ref N) (ks : List (Fin d)) (m : Memory bits) + (read : Reads kind pub ref m N) : + ∃ rs, Runs kind pub N ks m rs ∧ Completed kind pub ref m (after m (eventLog rs)) ks N ∧ + RAMBuckets.cost Report.probes rs = (ks.map fun k => (1 + probeCount (kind k)) * N).sum := by + induction ks generalizing m with + | nil => exact ⟨[], .nil _, ⟨by simp, fun _ _ => rfl⟩, rfl⟩ + | cons k ks ih => + have same := sameEntry kind pub ref read + have localLayout : PassLayout (kind k) (pub k) m N := + ⟨fun i j c a ha he => layout.reads k k i j c a ha (he.trans (congrArg (fun s : Row bits => + s.address (pub k) c) (same k j))), + fun i j c b he => (layout.writes k k i j c b (by + change (entry kind pub m k i).address (pub k) c = (entry kind pub m k j).address (pub k) b at he + rwa [same,same] at he)).2⟩ + obtain ⟨rs,hr,hpre,_,cost⟩ := full_pass (kind k) (pub k) m localLayout + let next := after m (eventLog rs) + have frame (a : ℕ) (miss : ∀ (i : Fin N) c, a ≠ ((entry kind pub ref k i).address (pub k) c).val) : + next a = m a := by + apply hpre.frame + intro i _ c + change a ≠ ((entry kind pub m k i).address (pub k) c).val + rw [same] + exact miss i c + have readNext : Reads kind pub ref next N := fun j i a ha => + (frame a.val (fun l c eq => layout.reads j k i l c a ha (Fin.ext eq))).trans (read j i a ha) + obtain ⟨ts,ht,hcs,hct⟩ := ih next readNext + have append : after m (eventLog (rs ++ ts)) = after next (eventLog ts) := by + change List.foldl BurstRAM.update m ((rs ++ ts).flatMap Report.events) = _ + rw [List.flatMap_append,List.foldl_append] + rfl + refine ⟨rs ++ ts, .cons k hr ht, ?_, ?_⟩ + · rw [append] + constructor + · intro j hj i c + by_cases used : j ∈ ks + · exact hcs.rows j used i c + have eq := (List.mem_cons.mp hj).resolve_right used + subst j + rw [hcs.frame _ (fun l hl t b he => used ((layout.writes k l i t c b (Fin.ext he)).1 ▸ hl))] + have stored := hpre.rows i i.isLt c + change next ((entry kind pub m k i).address (pub k) c).val = (entry kind pub m k i).value c at stored + rwa [same] at stored + · intro a miss + rw [hcs.frame a (fun l hl => miss l (List.mem_cons_of_mem _ hl))] + exact frame a (miss k List.mem_cons_self) + · rw [RAMBuckets.cost_append,hct] + change RAMBuckets.cost Report.probes rs = _ at cost + simp [cost] + +end Sequence + +/-- Addresses of the five read-only tables used to write all refreshed arcs. -/ +structure Tables (bits : ℕ) where + /-- Base address of the table mapping each external bundle to its destination. -/ + target : W bits + /-- Base address of the total width of each external bundle. -/ + total : W bits + /-- Base address of the expander destination-port table, indexed by source port and local + expander slot. -/ + targetPort : W bits + /-- Base address of the corresponding reverse expander slot numbers at the destination ports. -/ + reverseSlot : W bits + /-- Base address of the internal widths selected for each site and expander slot. -/ + supply : W bits + +private def localCopy {dH d₀ : ℕ} : RefreshSlot dH d₀ → ℕ + | .inl _ => 0 + | .inr (.inl k) => k.val + | .inr (.inr k) => k.val + +/-- The physical output arrays are those of the incidence-directory interface. -/ +def words {dH d₀ : ℕ} (D r : ℕ) (I : Tables bits) (T : IncidenceDirectory bits) + (c : RefreshSlot dH d₀) : Public bits := + ![word D, word dH, word d₀, word r, word (localCopy c), I.target, I.total, + I.targetPort, I.reverseSlot, I.supply, T.actualOut, T.actualIn, T.width] + +/-- Select the outgoing mate, incoming mate, or width column from the actual incidence +directory. -/ +def columnBase (T : IncidenceDirectory bits) : Column → W bits + | .outgoing => T.actualOut + | .incoming => T.actualIn + | .width => T.width + +/-- Choose the destination slot for an incoming-column write and the source slot for +outgoing-mate and width writes. -/ +def rowIndex (s : Row bits) : Column → W bits + | .outgoing | .width => s.src + | .incoming => s.dst + +private theorem address_eq {dH d₀ : ℕ} (D r : ℕ) (I : Tables bits) (T : IncidenceDirectory bits) + (k : RefreshSlot dH d₀) (s : Row bits) (c : Column) : + s.address (words D r I T k) c = columnBase T c + rowIndex s c := by cases c <;> rfl + +/-- Every source operand lies outside the three output regions. -/ +def InputsApart (T : IncidenceDirectory bits) (kind : Fin d → Kind) (pub : Fin d → Public bits) (N : ℕ) : Prop := + ∀ k (i : Fin N) a, a ∈ inputs (kind k) (pub k) (word i.val) → + ∀ c (j : W bits), j.val < N*d → a ≠ columnBase T c + j + +/-- A memory address outside all three output regions. -/ +def Outside (T : IncidenceDirectory bits) (extent addr : ℕ) : Prop := + ∀ c (j : W bits), j.val < extent → addr ≠ (columnBase T c + j).val + +private def columnNumber : Column → Fin 6 + | .outgoing => 3 + | .incoming => 4 + | .width => 5 + +private theorem columnBase_eq (T : IncidenceDirectory bits) (c : Column) : + columnBase T c = T.column (columnNumber c) := by cases c <;> rfl + +private theorem columnNumber_injective : Function.Injective columnNumber := by + intro c d he + cases c <;> cases d <;> first | rfl | contradiction + +section Dyadic + +open SpectralGeometry MotifConversion + +variable {a g a₀ dH : ℕ} {K : Type*} [_root_.Field K] {c₁ c₂ : ℝ} + (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) + (hdH : 0 < dH) (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock K (expanderSupply E hdH conn) (2^a₀) c₁ c₂) + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (choice : DyadicRefreshChoice X E hdH conn F) + (I : Tables bits) (T : IncidenceDirectory bits) (ref : Memory bits) + +local notation "Nₛ" => Fintype.card X.Base * 2^a * 2^g +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "A" => arcs (D := 2^a) (d₀ := 2^a₀) X.baseIndex (bitWordFinEquiv g) +local notation "Y" => dyadicRefreshNext X E hdH conn F hD hd choice +local notation "Iₛ" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) E hdH conn F choice + +/-- This extent is the unchanged number of physical sites. -/ +theorem site_count : Nₛ = X.positions := by + rw [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv (a+g)), + Fintype.card_fin,pow_add,Nat.mul_assoc] + +/-- Contents of the inputs, including the selected motif's supply widths. -/ +structure SourceTables : Prop where + target : ∀ s, (ref (I.target + word (O s).val).val).val = (O (bundleTarget (splitSlots X) s)).val + total : ∀ s, (ref (I.total + word (O s).val).val).val = ∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) s j + targetPort : ∀ e : Fin (2^a) × Fin dH, (ref (I.targetPort + word (e.1.val*dH + e.2.val)).val).val = + (E.reverse e).1.val + reverseSlot : ∀ e : Fin (2^a) × Fin dH, (ref (I.reverseSlot + word (e.1.val*dH + e.2.val)).val).val = + (E.reverse e).2.val + supply : ∀ s (k : Fin dH), (ref (I.supply + word ((O s).val*dH+k.val)).val).val = Iₛ s.1 (s.2,k) + +/-- Use the final target and total of the native external segment pass. The +remaining inputs are the fixed expander table and the selected motif width +table. -/ +theorem SourceTables.ofExternal (q : Fin 8 → W bits) (data : RefreshRAM.Input bits) + (fit : Nₛ * 2^a ≤ 2^bits) (dir : Directory (splitSlots X) O (splitWidths X) q data fit) + (done : RefreshRAM.AtCursor q (Nₛ*2^a) data ref (Nₛ*2^a)) + (targetBase : I.target = q 2) (totalBase : I.total = q 4) + (totals : ∀ s, (RefreshRAM.cell q ref 4 (bundleWord O fit s)).val = + ∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) s j) + (targetPort : ∀ e : Fin (2^a) × Fin dH, (ref (I.targetPort + word (e.1.val*dH + e.2.val)).val).val = + (E.reverse e).1.val) + (reverseSlot : ∀ e : Fin (2^a) × Fin dH, (ref (I.reverseSlot + word (e.1.val*dH + e.2.val)).val).val = + (E.reverse e).2.val) + (supply : ∀ s (k : Fin dH), (ref (I.supply + word ((O s).val*dH+k.val)).val).val = Iₛ s.1 (s.2,k)) : + SourceTables X E hdH conn F choice I ref := by + have idx (s) : word (bits := bits) (O s).val = bundleWord O fit s := + Fin.ext (Nat.mod_eq_of_lt (bundleWord O fit s).isLt) + refine ⟨fun s => ?_,fun s => ?_,targetPort,reverseSlot,supply⟩ + · rw [targetBase,idx] + exact (congrArg Fin.val (done.target _ (bundleWord_live O q (fit := fit) dir.degree s))).trans (dir.target s) + · rw [totalBase,idx] + exact totals s + +/-- Word-size bounds for port count, residual lane count, refreshed degree, and all packed +actual slot identifiers. -/ +structure Fits (bits : ℕ) : Prop where + ports : 2^a < 2^bits + lanes : 2^g < 2^bits + degree : 2^a₀ < 2^bits + ids : Nₛ * 2^a₀ ≤ 2^bits + +local notation "classOf" => Equiv.symm (refreshSlots hd) +local notation "tables" => (fun k : Fin (2^a₀) => words (2^a) (2^g) I T (classOf k)) +local notation "routine" => (fun k : Fin (2^a₀) => kindOf (classOf k)) +local notation "rec" => (entry routine tables ref) + +private theorem record_at (input : SourceTables X E hdH conn F choice I ref) (fit : Fits (a₀ := a₀) X bits) + (i : Fin Nₛ) (c : RefreshSlot dH (2^a₀)) : + let pub := words (2^a) (2^g) I T c + Represents X.baseIndex (bitWordFinEquiv g) (expected (kindOf c) pub ref i) + (slotRecord (splitSlots X) (bitWordFinEquiv a) (splitWidths X) E.toSlotGraph hd Iₛ ((O).symm i) c) := by + let s := (O).symm i + let pub := words (2^a) (2^g) I T c + have dims : Dimensions pub (Fintype.card X.Base) (2^a) (2^g) dH (2^a₀) := + ⟨Nat.mod_eq_of_lt fit.ports, Nat.mod_eq_of_lt (by have := fit.degree; omega), + Nat.mod_eq_of_lt fit.degree,Nat.mod_eq_of_lt fit.lanes,fit.ids⟩ + have hi : i = O s := ((O).apply_symm_apply i).symm + change Represents _ _ (row _ pub ref (word i.val)) (slotRecord _ _ _ _ hd Iₛ s c) + rw [hi] + rcases c with k | k | k + · cases Subsingleton.elim k 0 + exact external_record X.baseIndex (bitWordFinEquiv g) hd dims (splitSlots X) (bitWordFinEquiv a) + (splitWidths X) E.toSlotGraph Iₛ s (input.target s) (input.total s) + · exact expander_record X.baseIndex (bitWordFinEquiv g) hd dims (splitSlots X) (bitWordFinEquiv a) + (splitWidths X) E.toSlotGraph Iₛ s k (Nat.mod_eq_of_lt (by change k.val < 2^bits; have := fit.degree; have := k.isLt; omega)) + (input.targetPort (s.2,k)) (input.reverseSlot (s.2,k)) (input.supply s k) + · exact padding_record X.baseIndex (bitWordFinEquiv g) hd dims (splitSlots X) (bitWordFinEquiv a) + (splitWidths X) E.toSlotGraph Iₛ s k (Nat.mod_eq_of_lt (by change k.val < 2^bits; have := fit.degree; have := k.isLt; omega)) + +/-- Recover the source arc from its two scan counters. -/ +def source (k : Fin (2^a₀)) (i : Fin Nₛ) : ActualArc X.Base (BitWord g) (2^a) (2^a₀) := + (promotedSites ((O).symm i),k) + +private theorem source_eq {k j : Fin (2^a₀)} {i l : Fin Nₛ} (h : source X k i = source X j l) : + k = j ∧ i = l := + ⟨congrArg Prod.snd h,(O).symm.injective (promotedSites.injective (congrArg Prod.fst h))⟩ + +private theorem source_covers (e : ActualArc X.Base (BitWord g) (2^a) (2^a₀)) : + ∃ k i, source X k i = e := + ⟨e.2,O (promotedSites.symm e.1),by simp [source]⟩ + +/-- The state-independent directory and the native slot writer use the same +port identifiers, even though the new base-index codomain is a cardinality cast. -/ +theorem actualPort_eq (e : ActualArc X.Base (BitWord g) (2^a) (2^a₀)) : + IncidenceDirectory.actualPort (w := bits) Y e = word (A e).val := by + rcases e with ⟨⟨⟨v,j⟩,l⟩,k⟩ + apply congrArg (word (bits := bits)) + change ((j.val + 2^a * (X.baseIndex v).val) * 2^g + (bitWordFinEquiv g l).val) * 2^a₀ + k.val = + k.val + 2^a₀ * ((bitWordFinEquiv g l).val + 2^g * (j.val + 2^a * (X.baseIndex v).val)) + ring + +private theorem ids (input : SourceTables X E hdH conn F choice I ref) (fit : Fits (a₀ := a₀) X bits) + (k : Fin (2^a₀)) (i : Fin Nₛ) : + (rec k i).src.val = (A (source X k i)).val ∧ + (rec k i).dst.val = (A ((Y).slots.actualGraph.target (source X k i))).val ∧ + (rec k i).width.val = (Y).width (((source X k i).1.1,(source X k i).2),(source X k i).1.2) := by + have r := record_at X E hdH conn F hd choice I T ref input fit i (classOf k) + have h := actual_record X.baseIndex (bitWordFinEquiv g) hD hd (splitSlots X) (bitWordFinEquiv a) + (splitWidths X) E.toSlotGraph Iₛ ((O).symm i) (classOf k) (rec k i) r + dsimp only at h + rw [Equiv.apply_symm_apply] at h + exact h + +include hD in +private theorem row_index_lt (input : SourceTables X E hdH conn F choice I ref) (fit : Fits (a₀ := a₀) X bits) + (k : Fin (2^a₀)) (i : Fin Nₛ) (c : Column) : + (rowIndex (rec k i) c).val < Nₛ*2^a₀ := by + obtain ⟨ho,hi,_⟩ := ids X E hdH conn F hD hd choice I T ref input fit k i + cases c with + | outgoing | width => exact ho ▸ (A (source X k i)).isLt + | incoming => exact hi ▸ (A ((Y).slots.actualGraph.target (source X k i))).isLt + +private theorem global_layout (input : SourceTables X E hdH conn F choice I ref) (fit : Fits (a₀ := a₀) X bits) + (phys : T.Layout Y) (apart : InputsApart T routine tables Nₛ) : Layout routine tables ref Nₛ := by + have bound := row_index_lt X E hdH conn F hD hd choice I T ref input fit + constructor + · intro k j i l c x hx + rw [address_eq] + exact apart k i x hx c _ (bound j l c) + · intro k j i l c b he + rw [address_eq,address_eq,columnBase_eq,columnBase_eq] at he + have count : Fintype.card (Y).Base = Fintype.card X.Base * 2^a := by + change Fintype.card (X.Base × Fin (2^a)) = _ + simp [Fintype.card_prod] + have key := (phys.apart _ _ _ _ (by rw [count]; exact bound k i c) + (by rw [count]; exact bound j l b)).mp (congrArg Fin.val he) + have hcb := columnNumber_injective key.1 + subst b + obtain ⟨ho,hi,_⟩ := ids X E hdH conn F hD hd choice I T ref input fit k i + obtain ⟨ho',hi',_⟩ := ids X E hdH conn F hD hd choice I T ref input fit j l + have hs : source X k i = source X j l := by + cases c with + | outgoing | width => + exact (A).injective (Fin.ext (ho.symm.trans ((congrArg Fin.val key.2).trans ho'))) + | incoming => + exact (Y).slots.actualGraph.target.injective ((A).injective + (Fin.ext (hi.symm.trans ((congrArg Fin.val key.2).trans hi')))) + obtain ⟨hk,hj⟩ := source_eq X hs + exact ⟨hk,hj,rfl⟩ + +private theorem asWord {v : W bits} {n : ℕ} (h : v.val = n) : v = word n := + Fin.ext (h.trans (Nat.mod_eq_of_lt (h ▸ v.isLt)).symm) + +private theorem terminal (input : SourceTables X E hdH conn F choice I ref) (fit : Fits (a₀ := a₀) X bits) + (m : Memory bits) (rows : Completed routine tables ref ref m (List.finRange (2^a₀)) Nₛ) : + T.ActualColumns Y m := by + have atSource (e : ActualArc X.Base (BitWord g) (2^a) (2^a₀)) : + let src := IncidenceDirectory.actualPort (w := bits) Y e + let dst := IncidenceDirectory.actualPort (w := bits) Y ((Y).slots.actualGraph.target e) + m (T.actualOut + src).val = dst ∧ m (T.actualIn + dst).val = src ∧ + m (T.width + src).val = CursorRAM.encode bits ((Y).width ((e.1.1,e.2),e.1.2)) := by + obtain ⟨k,i,rfl⟩ := source_covers X e + obtain ⟨hs,ht,hw⟩ := ids X E hdH conn F hD hd choice I T ref input fit k i + have src := (asWord hs).trans (actualPort_eq X E hdH conn F hD hd choice (source X k i)).symm + have dst := (asWord ht).trans (actualPort_eq X E hdH conn F hD hd choice + ((Y).slots.actualGraph.target (source X k i))).symm + have store := rows.rows k (List.mem_finRange k) i + have ho := store .outgoing + have hi := store .incoming + have hl := store .width + change m (T.actualOut + (rec k i).src).val = (rec k i).dst at ho + change m (T.actualIn + (rec k i).dst).val = (rec k i).src at hi + change m (T.width + (rec k i).src).val = (rec k i).width at hl + rw [src,dst] at ho hi + rw [src,asWord hw] at hl + exact ⟨ho,hi,hl⟩ + refine ⟨fun e => (atSource e).1, fun e => ?_, fun e => (atSource e).2.2⟩ + simpa only [Equiv.apply_symm_apply] using (atSource ((Y).slots.actualGraph.target.symm e)).2.1 + +/-- Starting with the concatenation directory, fixed expander and chosen supply +table, execute every slot scan and obtain all three actual fields of the +refreshed state's incidence directory. Every other memory cell is preserved. -/ +theorem all_slots (input : SourceTables X E hdH conn F choice I ref) (fit : Fits (a₀ := a₀) X bits) + (phys : T.Layout Y) (apart : InputsApart T routine tables Nₛ) : + ∃ rs, Runs routine tables Nₛ (List.finRange (2^a₀)) ref rs ∧ + T.ActualColumns Y (after ref (eventLog rs)) ∧ + (∀ addr, Outside T (Nₛ*2^a₀) addr → after ref (eventLog rs) addr = ref addr) ∧ + RAMBuckets.cost Report.probes rs = (6 + 7*dH + 4*(2^a₀-(dH+1))) * X.positions := by + have layout := global_layout X E hdH conn F hD hd choice I T ref input fit phys apart + obtain ⟨rs,hr,hc,cost⟩ := runList routine tables ref layout (List.finRange (2^a₀)) ref (fun _ _ _ _ => rfl) + refine ⟨rs,hr,terminal X E hdH conn F hD hd choice I T ref input fit _ hc,?_,?_⟩ + · intro addr outside + apply hc.frame + intro k _ i c + rw [address_eq] + exact outside c _ (row_index_lt X E hdH conn F hD hd choice I T ref input fit k i c) + · rw [cost,← List.ofFn_id,List.map_ofFn,List.sum_ofFn,← site_count X] + exact slot_cost hd Nₛ + +end Dyadic + +end CompressorRecords.PortRefresh.AllSlots + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshAllocation.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshAllocation.lean new file mode 100644 index 0000000000..367a41fbdb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshAllocation.lean @@ -0,0 +1,337 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshFinish + +/-! +# Packed allocation of one degree-refresh level + +Seven equal-capacity segment columns are followed by dense demands, strided terms, +selected expander supplies, the two fixed expander columns, and the next state's six +incidence columns. The one-past-the-end word count bounds the complete allocation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.Allocation + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh +open SpectralGeometry NewSlots + +/-- Dimensions and start address determining the packed segment, motif, expander, and refreshed +incidence arrays for one level. -/ +structure Plan where + /-- First address of the seven refresh segment columns. -/ + start : ℕ + /-- Number of promoted sites, counting the base vertex, promoted port, and residual lane. -/ + sites : ℕ + /-- Number of motif blocks, one for each old base vertex and residual lane. -/ + blocks : ℕ + /-- Number of old ports promoted into the new base. -/ + ports : ℕ + /-- Number of expander slots at each promoted port. -/ + expander : ℕ + /-- Restored number of slots at each output site. -/ + degree : ℕ + /-- Number of ordered demand entries in one block's dense demand vector. -/ + ties : ℕ + /-- Number of words reserved for each block's selected term record. -/ + stride : ℕ + +/-- Compute the refresh allocation dimensions from the old state, restored degree exponent, +expander degree, and record sizes. -/ +def plan {a g : ℕ} (X : State a (a+g)) (a₀ dH tieCount termStride start : ℕ) : Plan := + ⟨start,Fintype.card X.Base * 2^a * 2^g,Fintype.card X.Base * 2^g,2^a,dH,2^a₀,tieCount,termStride⟩ + +namespace Plan + +variable (P : Plan) + +/-- Number of segment entries in each scratch column, one per promoted site and old port. -/ +def segments := P.sites*P.ports +/-- Capacity of each output incidence column, one slot for each site and restored local slot +number. -/ +def capacity := P.sites*P.degree +/-- First demand-vector address, immediately after the seven segment columns. -/ +def demand := P.start+7*P.segments +/-- First term-record address, following all blocks' dense demand vectors. -/ +def term := P.demand+P.blocks*P.ties +/-- First selected-supply address, following the fixed-stride term records. -/ +def supply := P.term+P.blocks*P.stride +/-- First expander target-port address, following the selected per-site supplies. -/ +def targetPort := P.supply+P.sites*P.expander +/-- First expander reverse-slot address, following the target-port table. -/ +def reverseSlot := P.targetPort+P.ports*P.expander +/-- First address of the refreshed incidence columns, following both expander tables. -/ +def next := P.reverseSlot+P.ports*P.expander +/-- Exclusive end address of the allocation after the six output incidence columns. -/ +def stop := P.next+6*P.capacity + +/-- Public scratch operand zero gives the port count, and operands one through seven give the +segment-column addresses. -/ +def scratch (bits : ℕ) (c : Fin 8) : W bits := + if c = 0 then word P.ports else word (P.start+(c.val-1)*P.segments) + +/-- The bundle-target, total-width, expander-target, reverse-slot, and supply pointers passed +to the actual-slot scans. -/ +def inputs (bits : ℕ) : AllSlots.Tables bits := + ⟨P.scratch bits 2,P.scratch bits 4,word P.targetPort,word P.reverseSlot,word P.supply⟩ + +/-- The six output incidence pointers at consecutive column-capacity intervals starting at +`next`. -/ +def output (bits : ℕ) : IncidenceDirectory bits := + let col := fun k => word (P.next + k*P.capacity) + ⟨col 0,col 1,col 2,col 3,col 4,col 5⟩ + +theorem output_column (bits : ℕ) (c : Fin 6) : + (P.output bits).column c = word (P.next+c.val*P.capacity) := by fin_cases c <;> rfl + +/-- The scratch bases satisfy the external pass's common-capacity region convention. -/ +theorem scratch_regions {bits : ℕ} (room : P.stop ≤ 2^bits) (pos : 0 < P.capacity) : + RefreshRAM.Regions (P.scratch bits) P.segments := by + have upto : P.demand < 2^bits := by + dsimp only [stop,next,reverseSlot,targetPort,supply,term] at room; omega + apply RefreshRAM.Regions.packed (P.scratch bits) (base := P.start) (n := P.segments) upto.le + intro c hc + have hk : (c.val-1)*P.segments ≤ 7*P.segments := Nat.mul_le_mul_right _ (by have := c.isLt; omega) + rw [scratch,ite_eq_right hc] + exact Nat.mod_eq_of_lt (by dsimp only [demand] at upto; omega) + +private theorem address_val {bits head len : ℕ} (fit : head+len ≤ 2^bits) + (j : W bits) (hj : j.val < len) : (word head+j).val = head+j.val := by + rw [Fin.val_add,show (word (bits := bits) head).val = head from Nat.mod_eq_of_lt (by omega), + Nat.mod_eq_of_lt (by omega)] + +private theorem scratch_addr {bits : ℕ} (room : P.demand ≤ 2^bits) (c : Fin 8) (hc : c ≠ 0) + (j : W bits) (hj : j.val < P.segments) : (P.scratch bits c+j).val < P.demand := by + have h := Nat.mul_le_mul_right P.segments (show (c.val-1)+1 ≤ 7 by have := c.isLt; omega) + rw [Nat.add_mul,Nat.one_mul] at h + change P.start+7*P.segments ≤ 2^bits at room + rw [scratch,ite_eq_right hc,address_val (len := P.segments) (by omega) _ hj] + change _ < P.start+7*P.segments + omega + +private theorem column_addr {bits : ℕ} (room : P.stop ≤ 2^bits) (c : Fin 6) + (j : W bits) (hj : j.val < P.capacity) : P.next ≤ ((P.output bits).column c+j).val := by + have h := Nat.mul_le_mul_right P.capacity c.isLt + rw [Nat.succ_mul] at h + rw [output_column,address_val (len := P.capacity) (by dsimp only [stop] at room; omega) _ hj] + omega + +/-- Every actual or base output column lies inside the final six-column allocation. -/ +theorem column_interval {bits : ℕ} (room : P.stop ≤ 2^bits) (c : Fin 6) (j : W bits) + (hj : j.val < P.capacity) : + P.next ≤ ((P.output bits).column c+j).val ∧ ((P.output bits).column c+j).val < P.stop := by + have h := Nat.mul_le_mul_right P.capacity c.isLt + rw [Nat.succ_mul] at h + rw [output_column,address_val (len := P.capacity) (by dsimp only [stop] at room; omega) _ hj] + dsimp only [stop]; constructor <;> omega + +end Plan + +private theorem packed_lt {w N d : ℕ} (x y h : W w) (hx : x.val < N) (hy : y.val < d) (hh : h.val = d) : + (x*h+y).val < N*d := by + have bound := Nat.mul_le_mul_right d (Nat.succ_le_of_lt hx) + rw [Nat.succ_mul] at bound + rw [Fin.val_add,Fin.val_mul,hh] + exact (Nat.mod_le ..).trans_lt (by have := Nat.mod_le (x.val*d) (2^w); omega) + +private theorem read_before_next {bits D R dH d₀ N : ℕ} (P : Plan) (T : IncidenceDirectory bits) + (room : P.stop ≤ 2^bits) (ports : D = P.ports) (degree : dH = P.expander) + (sites : N = P.sites) (hports : D < 2^bits) (hh : dH < 2^bits) (hD : 0 < D) + (sbound : N ≤ P.segments) (i : Fin N) (k : RefreshSlot dH d₀) + (x : W bits) (used : x ∈ NewSlots.inputs (kindOf k) (AllSlots.words D R (P.inputs bits) T k) (word i.val)) : + x.val < P.next := by + let b : W bits := word i.val + have hb : b.val < N := (Nat.mod_le ..).trans_lt i.isLt + have hnext : P.next ≤ 2^bits := by dsimp only [Plan.stop] at room; omega + have ord₁ : P.demand ≤ P.supply := by dsimp only [Plan.supply,Plan.term]; omega + have ord₂ : P.supply+N*dH = P.targetPort := by rw [sites,degree]; rfl + have ord₃ : P.targetPort+D*dH = P.reverseSlot := by rw [ports,degree]; rfl + have ord₄ : P.reverseSlot+D*dH = P.next := by rw [ports,degree]; rfl + cases k with + | inl k => + change x ∈ [P.scratch bits 2+b,P.scratch bits 4+b] at used + rcases List.mem_cons.mp used with rfl | h + · have h := P.scratch_addr (by omega) 2 (by decide) b (hb.trans_le sbound); omega + · obtain rfl := List.mem_singleton.mp h + have h := P.scratch_addr (by omega) 4 (by decide) b (hb.trans_le sbound); omega + | inr k => + cases k with + | inr k => exact (List.not_mem_nil used).elim + | inl k => + let p := AllSlots.words D R (P.inputs bits) T (.inr (.inl k) : RefreshSlot dH d₀) + let v := BinaryOp.mod.eval (BinaryOp.div.eval b (p 3)) (p 0) + have hv : v.val < D := by + have he : (p 0).val = D := Nat.mod_eq_of_lt hports + change (_ % (p 0).val) % (2^bits) < D + rw [he]; exact (Nat.mod_le ..).trans_lt (Nat.mod_lt _ hD) + have h₁ : (p 1).val = dH := Nat.mod_eq_of_lt hh + have h₄ : (p 4).val < dH := (Nat.mod_le ..).trans_lt k.isLt + let e := v*p 1+p 4 + let y := b*p 1+p 4 + have he : e.val < D*dH := packed_lt v _ _ hv h₄ h₁ + have hy : y.val < N*dH := packed_lt b _ _ hb h₄ h₁ + change x ∈ [word P.targetPort+e,word P.reverseSlot+e,word P.supply+y] at used + rcases List.mem_cons.mp used with rfl | h + · rw [Plan.address_val (len := D*dH) (by omega) _ he]; omega + rcases List.mem_cons.mp h with rfl | h + · rw [Plan.address_val (len := D*dH) (by omega) _ he]; omega + obtain rfl := List.mem_singleton.mp h + rw [Plan.address_val (len := N*dH) (by omega) _ hy]; omega + +section Dyadic + +variable {bits a a₀ g dH : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (choice : DyadicRefreshChoice X E hdH conn F) + (tieCount termStride start : ℕ) + +local notation "P" => plan X a₀ dH tieCount termStride start +local notation "N" => Fintype.card X.Base * 2^a * 2^g +local notation "Y" => dyadicRefreshNext X E hdH conn F hD hd choice + +private theorem sites_pos : 0 < N := by positivity + +private theorem newBaseCount : Fintype.card (Y).Base = Fintype.card X.Base * 2^a := by + change Fintype.card (X.Base × Fin (2^a)) = _; simp + +/-- The packed address recipe meets every word-size and aliasing requirement for +post-term completion. No contents of the incoming memory enter the layout proof. -/ +theorem finish_layout (rowSize : 2+2^a*dH ≤ termStride) (room : (P).stop ≤ 2^bits) : + Finish.Layout X E hdH conn F hD hd choice ((P).scratch bits) (word (P).term) termStride ((P).inputs bits) ((P).output bits) := by + have capPos : 0 < (P).capacity := Nat.mul_pos (sites_pos X) (Nat.two_pow_pos a₀) + have nextLt : (P).next < 2^bits := by change (P).next+6*(P).capacity ≤ 2^bits at room; omega + have h₁ : (P).demand ≤ (P).term := Nat.le_add_right .. + have h₂ : (P).term + (Fintype.card X.Base * 2^g)*termStride = (P).supply := rfl + have h₃ : (P).supply+N*dH = (P).targetPort := rfl + have h₄ : (P).targetPort+2^a*dH = (P).reverseSlot := rfl + have h₅ : (P).reverseSlot+2^a*dH = (P).next := rfl + have h₆ : (P).start+7*(P).segments = (P).demand := rfl + have capLt : (P).capacity < 2^bits := by change (P).next+6*(P).capacity ≤ 2^bits at room; omega + have ncap : N ≤ (P).capacity := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a₀) + have nseg : N ≤ (P).segments := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a) + have dg : 2^a₀ < 2^bits := (Nat.le_mul_of_pos_left _ (sites_pos X)).trans_lt capLt + have dp : 2^a < 2^bits := by + have hs : 2^a ≤ (P).segments := Nat.le_mul_of_pos_left _ (sites_pos X); omega + have dr : 2^g < 2^bits := (Nat.le_mul_of_pos_left _ (Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos a))).trans_lt + (ncap.trans_lt capLt) + have eh : dH < 2^bits := by omega + have supDims : SupplyScan.Fits (dH := dH) X bits := + ⟨dp,dr,eh,(Nat.mul_le_mul_left N (by omega : dH ≤ 2^a₀)).trans capLt.le⟩ + have termVal : (word (bits := bits) (P).term).val = (P).term := Nat.mod_eq_of_lt (by omega) + have supplyVal : (((P).inputs bits).supply).val = (P).supply := Nat.mod_eq_of_lt (by omega) + have targetVal : (((P).inputs bits).targetPort).val = (P).targetPort := Nat.mod_eq_of_lt (by omega) + have reverseVal : (((P).inputs bits).reverseSlot).val = (P).reverseSlot := Nat.mod_eq_of_lt (by omega) + have rb : ExpanderROM.Regions ((P).inputs bits) (2^a*dH) := by + constructor + · rw [targetVal]; omega + · rw [reverseVal]; omega + · rw [targetVal,reverseVal]; exact Or.inl h₄.le + have sc (j : W bits) (hj : j.val < N*dH) : (((P).inputs bits).supply+j).val = (P).supply+j.val := + Plan.address_val (len := N*dH) (by omega) j hj + have readonly (addr : ℕ) (ha : addr < (P).targetPort) : Finish.ROMOutside ((P).inputs bits) (2^a*dH) addr := + ⟨Or.inl (targetVal ▸ ha),Or.inl (by rw [reverseVal]; omega)⟩ + have anext (c : Column) (j : W bits) (hj : j.val < (P).capacity) : + (P).next ≤ (AllSlots.columnBase ((P).output bits) c+j).val := by + cases c with + | outgoing => exact (P).column_addr room 3 _ hj + | incoming => exact (P).column_addr room 4 _ hj + | width => exact (P).column_addr room 5 _ hj + have yn := newBaseCount X E hdH conn F hD hd choice + refine ⟨rfl,rfl,⟨dp,dr,dg,capLt.le⟩,?_,rb,?_,?_,?_,?_⟩ + · apply SupplyScan.apart_of_intervals X E hdH conn F (word (P).term) termStride ((P).inputs bits).supply supDims rowSize + · rw [termVal]; omega + · rw [supplyVal]; omega + · rw [termVal,supplyVal]; exact Or.inl h₂.le + · intro j hj + exact readonly _ (by rw [sc _ hj]; omega) + · apply IncidenceDirectory.Layout.packed Y (P).next + · rw [yn]; exact room + · intro c + rw [yn,(P).output_column] + have h := Nat.mul_le_mul_right (P).capacity c.isLt + rw [Nat.succ_mul] at h + exact Nat.mod_eq_of_lt (show (P).next+c.val*(P).capacity < 2^bits by + change (P).next+6*(P).capacity ≤ 2^bits at room; omega) + · intro k i z used c j hj hz + have hread := read_before_next (R := 2^g) P ((P).output bits) room rfl rfl rfl dp eh (Nat.two_pow_pos a) + nseg i ((refreshSlots hd).symm k) z used + exact (Nat.not_le_of_lt hread) ((congrArg Fin.val hz).symm ▸ anext c j hj) + · intro c hc j hj + let addr := ((P).scratch bits c+j).val + have ha : addr < (P).demand := (P).scratch_addr (by omega) c hc j hj + refine ⟨?_,readonly addr (by omega),?_,?_⟩ + · intro i hi + have he := sc i hi + change addr ≠ (((P).inputs bits).supply+i).val; omega + · intro col i hi + have hh := anext col i hi + change addr ≠ (AllSlots.columnBase ((P).output bits) col+i).val; omega + · intro i hi + have hbase : BaseOutput.baseCount Y ≤ (P).capacity := by + rw [BaseOutput.baseCount,yn] + exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g)) + have hi' := hi.trans_le hbase + have h0 := (P).column_addr room 0 i hi' + have h1 := (P).column_addr room 1 i hi' + have h2 := (P).column_addr room 2 i hi' + change addr ≠ (((P).output bits).column 0+i).val ∧ addr ≠ (((P).output bits).column 1+i).val ∧ + addr ≠ (((P).output bits).column 2+i).val + exact ⟨by omega,by omega,by omega⟩ + +/-- The finish phase protects all earlier arrays, including the selected term headers, +and every address beyond the six next-state incidence columns. -/ +theorem outside_finish (room : (P).stop ≤ 2^bits) (addr : ℕ) + (outside : addr < (P).supply ∨ (P).stop ≤ addr) : + Finish.Outside X E hdH conn F hD hd choice (word (P).term) termStride ((P).inputs bits) ((P).output bits) addr := by + have capPos : 0 < (P).capacity := Nat.mul_pos (sites_pos X) (Nat.two_pow_pos a₀) + have s₁ : (P).supply+N*dH = (P).targetPort := rfl + have s₂ : (P).targetPort+2^a*dH = (P).reverseSlot := rfl + have s₃ : (P).reverseSlot+2^a*dH = (P).next := rfl + have s₄ : (P).next+6*(P).capacity = (P).stop := rfl + have hport : (((P).inputs bits).targetPort).val = (P).targetPort := + Nat.mod_eq_of_lt (show (P).targetPort < 2^bits by omega) + have hslot : (((P).inputs bits).reverseSlot).val = (P).reverseSlot := + Nat.mod_eq_of_lt (show (P).reverseSlot < 2^bits by omega) + have miss (c : Fin 6) (i : W bits) (hi : i.val < (P).capacity) : + addr ≠ (((P).output bits).column c+i).val := by + obtain ⟨hl,hu⟩ := (P).column_interval room c i hi + omega + constructor + · intro i hi + change addr ≠ (word (P).supply+i).val + rw [Plan.address_val (len := N*dH) (by omega) _ hi]; omega + · change (addr < (((P).inputs bits).targetPort).val ∨ _ ≤ addr) ∧ + (addr < (((P).inputs bits).reverseSlot).val ∨ _ ≤ addr) + rw [hport,hslot]; constructor <;> omega + · intro c i hi + cases c with + | outgoing => exact miss 3 i hi + | incoming => exact miss 4 i hi + | width => exact miss 5 i hi + · intro i hi + have hbase : BaseOutput.baseCount Y ≤ (P).capacity := by + rw [BaseOutput.baseCount,newBaseCount X E hdH conn F hD hd choice] + exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g)) + exact ⟨miss 0 _ (hi.trans_le hbase),miss 1 _ (hi.trans_le hbase),miss 2 _ (hi.trans_le hbase)⟩ + +theorem outside_finish_of_lt_supply (room : (P).stop ≤ 2^bits) (addr : ℕ) (ha : addr < (P).supply) : + Finish.Outside X E hdH conn F hD hd choice (word (P).term) termStride ((P).inputs bits) ((P).output bits) addr := + outside_finish X E hdH conn F hD hd choice tieCount termStride start room addr (.inl ha) + +theorem outside_finish_of_outside (room : (P).stop ≤ 2^bits) (addr : ℕ) + (ha : addr < start ∨ (P).stop ≤ addr) : + Finish.Outside X E hdH conn F hD hd choice (word (P).term) termStride ((P).inputs bits) ((P).output bits) addr := by + apply outside_finish X E hdH conn F hD hd choice tieCount termStride start room addr + have hs : start ≤ (P).supply := by + dsimp only [Plan.supply, Plan.term, Plan.demand]; change start ≤ start+_+_+_; omega + exact ha.imp (fun h => h.trans_le hs) id + +end Dyadic +end CompressorRecords.PortRefresh.Allocation + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshArgumentAddress.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshArgumentAddress.lean new file mode 100644 index 0000000000..b97cafefd5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshArgumentAddress.lean @@ -0,0 +1,267 @@ +import OAI.Computability.VPVNP.PairNodeArguments +import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +import Mathlib.Algebra.BigOperators.Fin + +/-! +# Compiled addresses of a node's independent slot arguments + +An argument buffer stores all outgoing fields followed by all incoming +fields. At an incoming port, the inverse incidence record identifies the +outgoing arc whose width must be counted. Static and runtime slot numbers +use the same ordering and the same width columns. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.ArgumentAddress + +open BurstRAM BurstRAM.PrivateRAM Compression PhaseRecipe +open PairSimulation.NodeArguments + +variable {a g w d : ℕ} + +/-- Dynamic bases, node and site operands of the address calculation. -/ +structure Input where + /-- Expression for the first address of the private node argument arena. -/ + arenaBase : Expr + /-- Expression for the number of words reserved for each node's argument frame. -/ + stride : Expr + /-- Expression for the node index selecting an argument frame. -/ + node : Expr + /-- Expression for the physical site ordinal used to index the incidence columns. -/ + siteOrd : Expr + /-- Expression for the base of the inverse actual-incidence column. -/ + actualIn : Expr + /-- Expression for the base of the widths indexed by outgoing actual slots. -/ + width : Expr + +/-- Compute a node's frame address from the arena base, node index, and frame stride. -/ +def Input.nodeBase (I : Input) := I.arenaBase.add (I.node.mul I.stride) + +/-- Pack the runtime site ordinal and a fixed local slot number into an actual-slot index. -/ +def Input.port (I : Input) (i : Fin d) := (I.siteOrd.mul (.lit d)).add (.lit i.val) + +/-- Load one slot's width, looking up its outgoing mate first when the slot is incoming. -/ +def Input.half (I : Input) (incoming : Bool) (i : Fin d) : Expr := + let port := I.port i + let src := if incoming then Expr.load (I.actualIn.add port) else port + .load (I.width.add src) + +/-- When the dynamic slot is `j`, the factor is one for `i < j` and zero +otherwise. The first division detects whether `j` reaches `i + 1`. -/ +def before (j : Expr) (i : Fin d) : Expr := + (Expr.lit 1).sub ((Expr.lit 1).div ((j.div (.lit (i.val+1))).add (.lit 1))) + +/-- Sum a list of word-valued address expressions, using zero for the empty list. -/ +def sum : List Expr → Expr + | [] => .lit 0 + | x::xs => x.add (sum xs) + +/-- Skip the outgoing fields when addressing the incoming half of a frame by summing all +outgoing widths. -/ +def outgoing (d : ℕ) (I : Input) (incoming : Bool) : Expr := + if incoming then sum ((List.finRange d).map (I.half false)) else .lit 0 + +/-- Dynamic slot address. The loop bound is the fixed graph degree. -/ +def field (d : ℕ) (I : Input) (incoming : Bool) (j : Expr) : Expr := + I.nodeBase.add ((outgoing d I incoming).add + (sum ((List.finRange d).map fun i => (before j i).mul (I.half incoming i)))) + +/-- Static-slot version, reading just the preceding fields on the selected side. -/ +def fieldStatic (I : Input) (incoming : Bool) (j : Fin d) : Expr := + I.nodeBase.add ((outgoing d I incoming).add + (sum (((List.finRange d).take j.val).map (I.half incoming)))) + +variable (pub : Fin 5 → Word w) (state : Word w) (mem : Memory w) +variable (I : Input) (X : State a g) (u : X.network.Site) (T : IncidenceDirectory w) + (A : Arena) (node : ℕ) + +/-- Number a site by its base vertex and binary lane, with the lane as the low-order field. -/ +def siteOrdinal : ℕ := (X.baseIndex u.1).val * 2^g + (bitWordFinEquiv g u.2).val + +/-- The published values and the node's own runtime ordinals. -/ +structure Represents : Prop where + arena : I.arenaBase.eval pub state mem = CursorRAM.encode w A.start + stride : I.stride.eval pub state mem = CursorRAM.encode w A.stride + node : I.node.eval pub state mem = CursorRAM.encode w node + site : I.siteOrd.eval pub state mem = CursorRAM.encode w (siteOrdinal X u) + actualIn : I.actualIn.eval pub state mem = T.actualIn + width : I.width.eval pub state mem = T.width + +private theorem encode_add (x y : ℕ) : + CursorRAM.encode w x + CursorRAM.encode w y = CursorRAM.encode w (x+y) := + Fin.ext (Nat.add_mod x y _).symm + +private theorem encode_mul (x y : ℕ) : + CursorRAM.encode w x * CursorRAM.encode w y = CursorRAM.encode w (x*y) := + Fin.ext (Nat.mul_mod x y _).symm + +variable {pub state mem I X u T A node} + +private theorem eval_nodeBase (h : Represents pub state mem I X u T A node) : + I.nodeBase.eval pub state mem = CursorRAM.encode w (A.base node) := by + change I.arenaBase.eval pub state mem + I.node.eval pub state mem * I.stride.eval pub state mem = _ + rw [h.arena,h.node,h.stride,encode_mul,encode_add] + rfl + +private theorem eval_port (h : Represents pub state mem I X u T A node) (j : Fin (2^a)) : + (I.port j).eval pub state mem = IncidenceDirectory.actualPort X (u,j) := by + change I.siteOrd.eval pub state mem * CursorRAM.encode w (2^a) + CursorRAM.encode w j.val = _ + rw [h.site,encode_mul,encode_add] + rfl + +theorem eval_half (h : Represents pub state mem I X u T A node) (cols : T.ActualColumns X mem) + (dir : Bool) (j : Fin (2^a)) : (I.half dir j).eval pub state mem = CursorRAM.encode w (X.halfWidth u dir j) := by + apply Eq.trans _ (WidthRead.value_actual X u T mem cols dir j) + cases dir with + | false => + change mem (I.width.eval pub state mem + (I.port j).eval pub state mem).val = _ + rw [h.width,eval_port h] + rfl + | true => + change mem (I.width.eval pub state mem + mem (I.actualIn.eval pub state mem + (I.port j).eval pub state mem).val).val = _ + rw [h.width,h.actualIn,eval_port h] + rfl + +private theorem eval_before (i j : Fin d) (slot : Expr) (fits : d < 2^w) + (hj : slot.eval pub state mem = CursorRAM.encode w j.val) : + (before slot i).eval pub state mem = if i.val < j.val then (1 : Word w) else 0 := by + have hjv : (slot.eval pub state mem).val = j.val := (congrArg Fin.val hj).trans + (Nat.mod_eq_of_lt (j.isLt.trans fits)) + have hinc : i.val+1 < 2^w := (Nat.succ_le_of_lt i.isLt).trans_lt fits + have hdiv : (slot.div (.lit (i.val+1))).eval pub state mem = CursorRAM.encode w (j.val/(i.val+1)) := by + change Fin.ofNat _ ((slot.eval pub state mem).val / (CursorRAM.encode w (i.val+1)).val) = _ + rw [hjv,show (CursorRAM.encode w (i.val+1)).val = i.val+1 from Nat.mod_eq_of_lt hinc] + have denom : j.val/(i.val+1)+1 < 2^w := by + have := Nat.div_le_self j.val (i.val+1) + have := j.isLt + omega + have one : (1 : Word w).val = 1 := by + change 1 % (2^w) = 1 + exact Nat.mod_eq_of_lt (by have := i.isLt; omega) + have hv : (((slot.div (.lit (i.val+1))).add (.lit 1)).eval pub state mem).val = j.val/(i.val+1)+1 := by + change ((slot.div (.lit (i.val+1))).eval pub state mem + CursorRAM.encode w 1).val = _ + rw [hdiv,encode_add] + exact Nat.mod_eq_of_lt denom + change 1 - Fin.ofNat _ ((1 : Word w).val / (((slot.div (.lit (i.val+1))).add (.lit 1)).eval pub state mem).val) = _ + rw [one,hv] + by_cases earlier : i.val < j.val + · have hq : 0 < j.val/(i.val+1) := Nat.div_pos earlier (by omega) + rw [ite_eq_left earlier,Nat.div_eq_of_lt (by omega)] + change (1 : Word w) - 0 = 1 + exact sub_zero _ + · rw [ite_eq_right earlier,Nat.div_eq_of_lt (by omega : j.val < i.val+1)] + change (1 : Word w) - 1 = 0 + exact sub_self _ + +private theorem eval_sum {J : Type*} (xs : List J) (expr : J → Expr) (vals : J → ℕ) + (eqn : ∀ j, (expr j).eval pub state mem = CursorRAM.encode w (vals j)) : + (sum (xs.map expr)).eval pub state mem = CursorRAM.encode w (xs.map vals).sum := by + induction xs with + | nil => rfl + | cons i is ih => + change (expr i).eval pub state mem + (sum (is.map expr)).eval pub state mem = _ + rw [eqn,ih,encode_add] + rfl + +private theorem sum_range (f : Fin d → ℕ) : ((List.finRange d).map f).sum = ∑ i, f i := by + rw [← List.ofFn_id,List.map_ofFn,List.sum_ofFn] + rfl + +private theorem eval_outgoing (h : Represents pub state mem I X u T A node) (cols : T.ActualColumns X mem) + (dir : Bool) : (outgoing (2^a) I dir).eval pub state mem = + CursorRAM.encode w (if dir then ∑ i, X.halfWidth u false i else 0) := by + cases dir with + | false => rfl + | true => + change (sum ((List.finRange _).map (I.half false))).eval pub state mem = CursorRAM.encode w (∑ i, _) + rw [eval_sum _ _ _ (eval_half h cols false),sum_range] + +theorem eval_field (h : Represents pub state mem I X u T A node) (cols : T.ActualColumns X mem) + (dir : Bool) (slot : Expr) (j : Fin (2^a)) (fits : 2^a < 2^w) + (hj : slot.eval pub state mem = CursorRAM.encode w j.val) : + (field (2^a) I dir slot).eval pub state mem = CursorRAM.encode w (A.fieldAddress X u node dir j) := by + let f := X.halfWidth u dir + have vals (i : Fin (2^a)) : ((before slot i).mul (I.half dir i)).eval pub state mem = + CursorRAM.encode w (if i.val simp [f] + change I.nodeBase.eval pub state mem + ((outgoing (2^a) I dir).eval pub state mem + + (sum ((List.finRange _).map _)).eval pub state mem) = _ + rw [eval_nodeBase h,eval_outgoing h cols,eval_sum _ _ _ vals,sum_range,encode_add,encode_add] + unfold Arena.fieldAddress offset + rw [List.sum_take_ofFn,Finset.sum_filter] + +theorem eval_fieldStatic (h : Represents pub state mem I X u T A node) (cols : T.ActualColumns X mem) + (dir : Bool) (j : Fin (2^a)) : + (fieldStatic I dir j).eval pub state mem = CursorRAM.encode w (A.fieldAddress X u node dir j) := by + change I.nodeBase.eval pub state mem + ((outgoing (2^a) I dir).eval pub state mem + + (sum (((List.finRange _).take j.val).map _)).eval pub state mem) = _ + rw [eval_nodeBase h,eval_outgoing h cols,eval_sum _ _ _ (eval_half h cols dir),encode_add,encode_add] + unfold Arena.fieldAddress offset + rw [List.map_take,← List.ofFn_id,List.map_ofFn] + rfl + +/-- Reads needed for one slot width, counting any computed pointer operands. -/ +def halfLoads (I : Input) (dir : Bool) : ℕ := + I.width.loads + I.siteOrd.loads + 1 + (if dir then I.actualIn.loads + 1 else 0) + +private theorem loads_half (I : Input) (dir : Bool) (i : Fin d) : + (I.half dir i).loads = halfLoads I dir := by + cases dir <;> simp [Input.half,Input.port,Expr.loads,Expr.add,Expr.mul,halfLoads] + omega + +private theorem sum_loads {α : Type*} (xs : List α) (f : α → Expr) (n : ℕ) + (h : ∀ i, (f i).loads = n) : (sum (xs.map f)).loads = xs.length*n := by + induction xs with + | nil => simp [sum,Expr.loads] + | cons i xs ih => + change (f i).loads + (sum (xs.map f)).loads = (xs.length+1)*n + rw [h,ih,Nat.succ_mul,Nat.add_comm] + +private theorem loads_outgoing (d : ℕ) (I : Input) (dir : Bool) : + (outgoing d I dir).loads = if dir then d*halfLoads I false else 0 := by + cases dir with + | false => rfl + | true => + change (sum ((List.finRange d).map _)).loads = d*halfLoads I false + rw [sum_loads _ _ _ (loads_half I false),List.length_finRange] + +/-- Actual reads in the compiled dynamic expression, independent of machine +width, network size and field widths. Dynamic pointer loads are counted on +every occurrence. -/ +theorem field_reads {r : ℕ} (d : ℕ) (I : Input) (dir : Bool) (j : Expr) + (regs : ℕ → Fin r) (start : ℕ) : + (((field d I dir j).compile regs start).map fun a => a.rhs.reads).sum = + I.arenaBase.loads + I.node.loads + I.stride.loads + (if dir then d*halfLoads I false else 0) + + d*(j.loads+halfLoads I dir) := by + rw [Expr.compile_reads] + have count (i : Fin d) : ((before j i).mul (I.half dir i)).loads = j.loads + halfLoads I dir := by + change (before j i).loads + (I.half dir i).loads = _ + simp [before,Expr.sub,Expr.div,Expr.add,Expr.loads,loads_half] + change (I.arenaBase.loads + (I.node.loads + I.stride.loads)) + + ((outgoing d I dir).loads + (sum ((List.finRange d).map _)).loads) = _ + rw [loads_outgoing,sum_loads _ _ _ count,List.length_finRange] + omega + +/-- Compiling a static address reads only its preceding slots, with a single +additional inverse lookup for each incoming width. -/ +theorem fieldStatic_reads {r : ℕ} (I : Input) (dir : Bool) (j : Fin d) + (regs : ℕ → Fin r) (start : ℕ) : + (((fieldStatic I dir j).compile regs start).map fun a => a.rhs.reads).sum = + I.arenaBase.loads + I.node.loads + I.stride.loads + (if dir then d*halfLoads I false else 0) + + j.val*halfLoads I dir := by + rw [Expr.compile_reads] + change (I.arenaBase.loads + (I.node.loads + I.stride.loads)) + + ((outgoing d I dir).loads + (sum (((List.finRange d).take j.val).map _)).loads) = _ + rw [loads_outgoing,sum_loads _ _ _ (loads_half I dir),List.length_take,List.length_finRange,min_eq_left j.isLt.le] + omega + +end CompressorRecords.PortRefresh.ArgumentAddress + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshArgumentSite.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshArgumentSite.lean new file mode 100644 index 0000000000..75aec2dcdd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshArgumentSite.lean @@ -0,0 +1,142 @@ +import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +import OAI.Computability.VPVNP.CompressorRefreshMapOperands +import OAI.Computability.VPVNP.CompressorRecordRefreshDemandScan + +/-! +# Word coordinates of a refresh argument site + +The promoted site has coordinates `(base, port, residual lane)`. The old lane stores the +same port as its high field, so promotion preserves the numerical site ordinal. The old +and new first slots multiply that ordinal by their respective degrees. The external +segment directory instead uses the old port as the segment index within the bundle. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.ArgumentSite + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh +open PhaseRecipe NewSlots +open scoped Fin.CommRing + +/-- The port of a promoted site, above the residual-lane field. -/ +def portIndex (D : ℕ) (z lanes : Expr) : Expr := (z.div lanes).mod (.lit D) + +/-- Block ordinal for the term table. Consecutive divisions recover the base vertex. -/ +def blockIndex (D : ℕ) (z lanes : Expr) : Expr := + (((z.div lanes).div (.lit D)).mul lanes).add (z.mod lanes) + +/-- Compute the first old slot of the site by multiplying its ordinal by the old degree. -/ +def oldFirst (D : ℕ) (z : Expr) : Expr := z.mul (.lit D) + +/-- Compute the first refreshed slot of the same physical site using the restored degree. -/ +def newFirst (d₀ : ℕ) (z : Expr) : Expr := z.mul (.lit d₀) + +/-- External segment in the current bundle's source-port order. -/ +def segment (D : ℕ) (z j : Expr) : Expr := (oldFirst D z).add j + +/-- Address the diagonal segment by using the site's own promoted port as the segment number. -/ +def diagonal (D : ℕ) (z lanes : Expr) : Expr := segment D z (portIndex D z lanes) + +variable {a g a₀ dH bits : ℕ} (X : State a (a+g)) (p : (X.Base × BitWord g) × Fin (2^a)) + (pub : Fin 5 → W bits) (state : W bits) (m : Memory bits) (z lanes : Expr) + +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "S" => Fintype.card X.Base * 2^a * 2^g * 2^a + +/-- Splitting the old binary word preserves the ordinal of the promoted physical site. -/ +theorem oldSite_number : + (X.baseIndex (RefreshMapOperands.oldSite X p).1).val * 2^(a+g) + + (bitWordFinEquiv (a+g) (RefreshMapOperands.oldSite X p).2).val = (O p).val := by + change (X.baseIndex p.1.1).val * 2^(a+g) + + (bitWordFinEquiv (a+g) ((splitBitWord a g).symm ((bitWordFinEquiv a).symm p.2,p.1.2))).val = _ + rw [splitBitWord_number,AddEquiv.apply_symm_apply,Equiv.apply_symm_apply,pow_add,sites_val] + ring + +private theorem first_word (n : ℕ) (hz : (z.eval pub state m).val = (O p).val) : + (z.mul (.lit n)).eval pub state m = word ((O p).val*n) := by + apply Fin.ext + change (z.eval pub state m * (n : W bits)).val = _ % _ + rw [Fin.val_mul,hz,Fin.val_natCast,Nat.mul_mod_mod] + +/-- The old outgoing or incoming field list starts at the first slot of the old site. -/ +theorem oldFirst_eval (hz : (z.eval pub state m).val = (O p).val) : + (oldFirst (2^a) z).eval pub state m = IncidenceDirectory.actualPort X (RefreshMapOperands.oldSite X p,0) := by + rw [oldFirst, first_word X p pub state m z _ hz] + change word _ = word (((X.baseIndex (RefreshMapOperands.oldSite X p).1).val*2^(a+g)+ + (bitWordFinEquiv (a+g) (RefreshMapOperands.oldSite X p).2).val)*2^a+0) + rw [oldSite_number,Nat.add_zero] + +/-- The new field list starts at the first slot of the promoted site in the selected state. -/ +theorem newFirst_eval (P : SlotGraph (Fin (2^a)) dH) (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) + (internal : X.Base × BitWord g → Fin (2^a) × Fin dH → ℕ) + (hz : (z.eval pub state m).val = (O p).val) : + (newFirst (2^a₀) z).eval pub state m = + IncidenceDirectory.actualPort (RefreshMapOperands.newState X P hD hd internal) (promotedSites p,0) := by + rw [newFirst,first_word X p pub state m z _ hz] + change word _ = word (((p.2.val + 2^a*(X.baseIndex p.1.1).val)*2^g+ + (bitWordFinEquiv g p.1.2).val)*2^a₀+0) + rw [sites_val,Nat.add_zero,Nat.mul_comm (2^a) _,Nat.add_comm p.2.val] + +private theorem unpack {x d : W bits} {hi lo : ℕ} (h : x.val = hi*d.val+lo) (hl : lo < d.val) : + (BinaryOp.div.eval x d).val = hi ∧ (BinaryOp.mod.eval x d).val = lo := by + have hd : 0 < d.val := Nat.zero_lt_of_lt hl + have hq : x.val / d.val = hi := by rw [h,Nat.mul_comm hi,Nat.mul_add_div hd,Nat.div_eq_of_lt hl,Nat.add_zero] + exact ⟨(Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)).trans hq, + (Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt)).trans (h ▸ Nat.mul_add_mod_of_lt hl)⟩ + +variable (hz : (z.eval pub state m).val = (sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) p).val) (hr : (lanes.eval pub state m).val = 2^g) + (hDfit : 2^a < 2^bits) + +include hz hr in +private theorem read_site : + ((z.div lanes).eval pub state m).val = (X.baseIndex p.1.1).val*2^a+p.2.val ∧ + ((z.mod lanes).eval pub state m).val = (bitWordFinEquiv g p.1.2).val := by + apply unpack (d := lanes.eval pub state m) (x := z.eval pub state m) + · rw [hz,sites_val,hr] + · rw [hr]; exact (bitWordFinEquiv g p.1.2).isLt + +include hz hr hDfit in +private theorem read_base : + (((z.div lanes).div (.lit (2^a))).eval pub state m).val = (X.baseIndex p.1.1).val ∧ + ((portIndex (2^a) z lanes).eval pub state m).val = p.2.val := by + have hword : ((2^a : ℕ) : W bits).val = 2^a := Nat.mod_eq_of_lt hDfit + apply unpack (d := ((2^a : ℕ) : W bits)) (x := (z.div lanes).eval pub state m) + · rw [hword]; exact (read_site X p pub state m z lanes hz hr).1 + · rw [hword]; exact p.2.isLt + +include hz hr hDfit in +theorem portIndex_eval : (portIndex (2^a) z lanes).eval pub state m = word p.2.val := by + apply Fin.ext + exact (read_base X p pub state m z lanes hz hr hDfit).2.trans + (Nat.mod_eq_of_lt (p.2.isLt.trans hDfit)).symm + +include hz hr hDfit in +theorem blockIndex_eval : (blockIndex (2^a) z lanes).eval pub state m = word (DemandScan.blocks X p.1).val := by + apply Fin.ext + change ((((z.div lanes).div (.lit (2^a))).eval pub state m)*(lanes.eval pub state m) + + (z.mod lanes).eval pub state m).val = _ % _ + rw [Fin.val_add,Fin.val_mul,(read_base X p pub state m z lanes hz hr hDfit).1,hr, + (read_site X p pub state m z lanes hz hr).2,Nat.mod_add_mod,DemandScan.blocks_val] + +include hz in +theorem segment_eval (jArg : Expr) (j : Fin (2^a)) (hj : (jArg.eval pub state m).val = j.val) + (fit : S ≤ 2^bits) : (segment (2^a) z jArg).eval pub state m = idWord O fit (p,j) := by + apply Fin.ext + change ((z.mul (.lit (2^a))).eval pub state m + jArg.eval pub state m).val = (numbered O (p,j)).val + rw [first_word X p pub state m z _ hz,Fin.val_add,Fin.val_ofNat,hj,Nat.mod_add_mod] + rw [← numbered_val] + exact Nat.mod_eq_of_lt ((numbered O (p,j)).isLt.trans_le fit) + +include hz hr hDfit in +theorem diagonal_eval (fit : S ≤ 2^bits) : + (diagonal (2^a) z lanes).eval pub state m = idWord O fit (p,p.2) := + segment_eval X p pub state m z hz _ _ (read_base X p pub state m z lanes hz hr hDfit).2 fit + +end CompressorRecords.PortRefresh.ArgumentSite + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshBaseOutput.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshBaseOutput.lean new file mode 100644 index 0000000000..e9529aca1a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshBaseOutput.lean @@ -0,0 +1,325 @@ +import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout +import OAI.Computability.VPVNP.RAMChain +import OAI.Computability.VPVNP.RAMBuckets + +/-! +# Reading the base slots at lane zero + +In a lifted slot graph the target of an outgoing slot at lane zero contains the destination +base vertex, its incoming slot, and the displacement. Appendix E uses one scan of these +slots to emit both base incidence tables and the displacement table of the next level. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BaseOutput + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression IncidenceDirectory +open CursorRAM (encode) + +variable {w a l : ℕ} (T : IncidenceDirectory w) (X : State a l) + +/-- Persistent state is the next base slot. The fixed public parameters give the two +radices and the addresses of the one input and three output columns. -/ +def params (T : IncidenceDirectory w) (a l : ℕ) : Fin 6 → Word w := + ![encode w (2^a), encode w (2^l), T.actualOut, T.baseOut, T.baseIn, T.shift] + +/-- Native visit that reads an actual mate at lane zero and emits its base mate, inverse mate, +and displacement. -/ +def visit : List (Op 8 6) := + [.stateWord 0, .publicWord 1 0, .publicWord 2 1, + .binary .div 3 0 1, .binary .mod 4 0 1, .binary .mul 3 3 2, .binary .mul 3 3 1, + .binary .add 3 3 4, .publicWord 5 2, .binary .add 5 5 3, .read 6 5, + .binary .mod 4 6 1, .binary .div 3 6 1, .binary .mod 6 3 2, .binary .div 3 3 2, + .binary .mul 3 3 1, .binary .add 3 3 4, .publicWord 5 3, .binary .add 5 5 0, + .write 5 3, .publicWord 5 4, .binary .add 5 5 3, .write 5 0, + .publicWord 5 5, .binary .add 5 5 0, .write 5 6, .constant 7 1, .binary .add 0 0 7] + +variable (p : Fin 6 → Word w) + +/-- Convert a packed base slot index into the actual slot index of that vertex and port at lane +zero. -/ +def source (i : Word w) := BinaryOp.div.eval i (p 0) * p 1 * p 0 + BinaryOp.mod.eval i (p 0) + +/-- Read the actual outgoing mate of a lane-zero source slot. -/ +def mate (m : Memory w) (i : Word w) := m (p 2 + source p i).val + +/-- Discard the lane from an actual mate index to recover its destination base slot. -/ +def destination (y : Word w) := + BinaryOp.div.eval (BinaryOp.div.eval y (p 0)) (p 1) * p 0 + BinaryOp.mod.eval y (p 0) + +/-- Extract the destination lane of a lane-zero arc, which equals its displacement. -/ +def displacement (y : Word w) := BinaryOp.mod.eval (BinaryOp.div.eval y (p 0)) (p 1) + +/-- Install the base mate, reverse mate, and displacement recovered from a single lane-zero +lookup. -/ +def update (m : Memory w) (i : Word w) : Memory w := + let j := destination p (mate p m i) + writeMemory (writeMemory (writeMemory m (p 3+i) j) (p 4+j) i) (p 5+i) (displacement p (mate p m i)) + +/-- The 28-event trace of one base-output visit, with one actual-mate read and three +base-column writes. -/ +def events (m : Memory w) (i : Word w) : List (Event w) := + let y := mate p m i + let j := destination p y + [.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.read (p 2 + source p i) y, + .tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.write (p 3+i) j, + .tick,.tick,.write (p 4+j) i,.tick,.tick,.write (p 5+i) (displacement p y),.tick,.tick] + +theorem events_work (m : Memory w) (i : Word w) : + (events p m i).length = 28 ∧ countProbes (events p m i) = 4 := ⟨rfl,rfl⟩ + +theorem events_after (m : Memory w) (i : Word w) : after m (events p m i) = update p m i := rfl + +private theorem visit_trace (m : Memory w) (i : Word w) (rs : Regs w 8) : + ∃ out, trace p i visit rs m = some (events p m i, out, update p m i) ∧ out 0 = i+1 := by + simp (config := {decide := true}) [visit, events, update, source, mate, destination, displacement, + trace, Op.effect, BinaryOp.eval, Function.update] + rfl + +theorem visit_native (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program 29 (M.program.start i) m [] = some ⟨events p m i, some (i+1)⟩ := by + obtain ⟨out, ht, hret⟩ := visit_trace p m i (fun _ => 0) + let M := (template visit 0).instantiate w p + change execute M.program (1 + visit.length) ⟨M.entry, i, fun _ => 0, fun _ => 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hret] + +/-- Number of base slots, counting every local port of each base vertex. -/ +abbrev baseCount := Fintype.card X.Base * 2^a + +/-- Number of actual slots, including all binary lanes at each base vertex and port. -/ +abbrev actualCount := Fintype.card X.Base * 2^l * 2^a + +private theorem counts : baseCount X ≤ actualCount X := + Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos l)) + +private theorem base_val (layout : T.Layout X) (e : X.Base × Fin (2^a)) : + (basePort (w := w) X e).val = (baseOrder X e).val := by + rw [basePort_number] + exact Nat.mod_eq_of_lt ((baseOrder X e).isLt.trans_le ((counts X).trans layout.fit)) + +private theorem actual_val (layout : T.Layout X) (e : (X.Base × BitWord l) × Fin (2^a)) : + (actualPort (w := w) X e).val = (actualOrder X e).val := by + rw [actualPort_number] + exact Nat.mod_eq_of_lt ((actualOrder X e).isLt.trans_le layout.fit) + +private theorem unpack {x d : Word w} {hi lo : ℕ} (h : x.val = hi * d.val + lo) (hl : lo < d.val) : + (BinaryOp.div.eval x d).val = hi ∧ (BinaryOp.mod.eval x d).val = lo := by + have hd : 0 < d.val := Nat.zero_lt_of_lt hl + have hq : x.val / d.val = hi := by + rw [h, Nat.mul_comm hi, Nat.mul_add_div hd, Nat.div_eq_of_lt hl, Nat.add_zero] + have hr : x.val % d.val = lo := by rw [h, Nat.mul_add_mod_of_lt hl] + exact ⟨(Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)).trans hq, + (Nat.mod_eq_of_lt ((Nat.mod_lt _ hd).trans d.isLt)).trans hr⟩ + +/-- The one actual read at lane zero decodes the base mate and its residual displacement. -/ +theorem read_row (layout : T.Layout X) (m : Memory w) (actual : T.ActualColumns X m) + (e : X.Base × Fin (2^a)) : + let p := params T a l + let y := mate p m (basePort X e) + destination p y = basePort X (X.slots.base.target e) ∧ + displacement p y = encode w (bitWordFinEquiv l (X.slots.displacement e)).val := by + let p := params T a l + have hc : 1 < Fintype.card X.Base := + Fintype.one_lt_card_iff.mpr ⟨_, _, X.slots.base.ends_ne e⟩ + have hR : 2^l < Fintype.card X.Base * 2^l := by + simpa using Nat.mul_lt_mul_of_pos_right hc (Nat.two_pow_pos l) + have hD : 2^a < actualCount X := by + have := Nat.mul_lt_mul_of_pos_right (show 1 < Fintype.card X.Base * 2^l by + have := Nat.two_pow_pos l; omega) (Nat.two_pow_pos a) + simpa using this + have hd : (p 0).val = 2^a := Nat.mod_eq_of_lt (hD.trans_le layout.fit) + have hl : (p 1).val = 2^l := + Nat.mod_eq_of_lt ((hR.trans_le (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a))).trans_le layout.fit) + have hu := unpack (hi := (X.baseIndex e.1).val) (lo := e.2.val) (x := basePort (w := w) X e) (d := p 0) + (by rw [base_val T X layout, baseOrder_val, hd]) (by rw [hd]; exact e.2.isLt) + have hz : (bitWordFinEquiv l 0).val = 0 := by simpa using bitWordFinEquiv_add_val (0 : BitWord l) 0 + have hs : source p (basePort X e) = actualPort X ((e.1,0),e.2) := by + apply Fin.ext + rw [source, Fin.val_add, Fin.val_mul, Fin.val_mul, hu.1, hu.2, hd, hl, actualPort_number] + change _ = (actualOrder X ((e.1,0),e.2)).val % _ + rw [actualOrder_val, hz, Nat.add_zero, Nat.mod_mul_mod, Nat.mod_add_mod] + let f := X.slots.base.target e + let s := X.slots.displacement e + let y := mate p m (basePort X e) + have hm : y = actualPort X ((f.1,s),f.2) := by + change m (T.actualOut + source p (basePort X e)).val = _ + rw [hs, actual.actualOut, LiftedSlots.actualGraph_target, zero_add] + have hyv : y.val = ((X.baseIndex f.1).val * (p 1).val + (bitWordFinEquiv l s).val) * (p 0).val + f.2.val := by + rw [hm, actual_val T X layout, actualOrder_val, hd, hl] + have hy := unpack hyv (by rw [hd]; exact f.2.isLt) + have hy' := unpack (d := p 1) hy.1 (by rw [hl]; exact (bitWordFinEquiv l s).isLt) + constructor + · apply Fin.ext + change (destination p y).val = (basePort (w := w) X f).val + rw [destination, Fin.val_add, Fin.val_mul, hy'.1, hy.2, hd, Nat.mod_add_mod, basePort_number] + change _ = (baseOrder X f).val % _ + rw [baseOrder_val] + · apply Fin.ext + change (BinaryOp.mod.eval (BinaryOp.div.eval y (p 0)) (p 1)).val = _ % _ + rw [hy'.2, Nat.mod_eq_of_lt ((bitWordFinEquiv l s).isLt.trans (hl ▸ (p 1).isLt))] + +private def writeBase (m : Memory w) (i j shift : Word w) : Memory w := + writeMemory (writeMemory (writeMemory m (T.baseOut+i) j) (T.baseIn+j) i) (T.shift+i) shift + +private theorem update_row (layout : T.Layout X) (m : Memory w) (actual : T.ActualColumns X m) + (e : X.Base × Fin (2^a)) : + update (params T a l) m (basePort X e) = writeBase T m (basePort X e) + (basePort X (X.slots.base.target e)) (encode w (bitWordFinEquiv l (X.slots.displacement e)).val) := by + obtain ⟨hd,hs⟩ := read_row T X layout m actual e + simp only [update, hd, hs, writeBase] + rfl + +private theorem cell_write (layout : T.Layout X) (m : Memory w) (i j shift : Word w) + (hi : i.val < actualCount X) (hj : j.val < actualCount X) (c : Fin 6) (x : Word w) + (hx : x.val < actualCount X) : + writeBase T m i j shift (T.column c + x).val = + if c = 2 ∧ x = i then shift else if c = 1 ∧ x = j then i + else if c = 0 ∧ x = i then j else m (T.column c + x).val := by + change writeMemory (writeMemory (writeMemory m (T.column 0+i) j) (T.column 1+j) i) + (T.column 2+i) shift (T.column c+x).val = _ + simp only [writeMemory, layout.apart c 2 x i hx hi, layout.apart c 1 x j hx hj, + layout.apart c 0 x i hx hi] + +/-- Slots already visited in the lane-zero pass, indexed by the source. +The inverse column is indexed by the matched destination. -/ +structure Prefix (m : Memory w) (k : ℕ) : Prop where + actual : T.ActualColumns X m + rows : ∀ e, (baseOrder X e).val < k → + m (T.baseOut + basePort X e).val = basePort X (X.slots.base.target e) ∧ + m (T.baseIn + basePort X (X.slots.base.target e)).val = basePort X e ∧ + m (T.shift + basePort X e).val = encode w (bitWordFinEquiv l (X.slots.displacement e)).val + +private theorem base_injective (layout : T.Layout X) : Function.Injective (basePort (w := w) X) := by + intro e f h + apply (baseOrder X).injective + exact Fin.ext ((base_val T X layout e).symm.trans ((congrArg Fin.val h).trans (base_val T X layout f))) + +private theorem step (layout : T.Layout X) (m : Memory w) (e : X.Base × Fin (2^a)) + (cur : Prefix T X m (baseOrder X e).val) : + Prefix T X (update (params T a l) m (basePort X e)) ((baseOrder X e).val+1) := by + rw [update_row T X layout m cur.actual] + have hb (b : X.Base × Fin (2^a)) : (basePort (w := w) X b).val < actualCount X := by + rw [base_val T X layout]; exact (baseOrder X b).isLt.trans_le (counts X) + have ha (b : (X.Base × BitWord l) × Fin (2^a)) : (actualPort (w := w) X b).val < actualCount X := by + rw [actual_val T X layout]; exact (actualOrder X b).isLt + let f := X.slots.base.target + let sh := encode w (bitWordFinEquiv l (X.slots.displacement e)).val + have cells := cell_write T X layout m (basePort X e) (basePort X (f e)) sh (hb e) (hb (f e)) + constructor + · constructor + · intro z + change writeBase T m _ _ _ (T.column 3 + actualPort X z).val = _ + rw [cells 3 _ (ha z)] + simp; exact cur.actual.actualOut z + · intro z + change writeBase T m _ _ _ (T.column 4 + actualPort X z).val = _ + rw [cells 4 _ (ha z)] + simp; exact cur.actual.actualIn z + · intro z + change writeBase T m _ _ _ (T.column 5 + actualPort X z).val = _ + rw [cells 5 _ (ha z)] + simp; exact cur.actual.width z + · intro z hz + change writeBase T m _ _ _ (T.column 0 + basePort X z).val = basePort X (f z) ∧ + writeBase T m _ _ _ (T.column 1 + basePort X (f z)).val = basePort X z ∧ + writeBase T m _ _ _ (T.column 2 + basePort X z).val = _ + rw [cells 0 _ (hb z), cells 1 _ (hb (f z)), cells 2 _ (hb z)] + by_cases he : z = e + · subst z; simp [sh] + · have hsrc : basePort (w := w) X z ≠ basePort X e := fun h => he (base_injective T X layout h) + have hdst : basePort (w := w) X (f z) ≠ basePort X (f e) := + fun h => he (f.injective (base_injective T X layout h)) + have hne : (baseOrder X z).val ≠ (baseOrder X e).val := + fun h => he ((baseOrder X).injective (Fin.ext h)) + simp [hsrc,hdst]; exact cur.rows z (by omega) + +/-- A memory address disjoint from all three written base columns. -/ +def Outside (addr : ℕ) : Prop := + ∀ j : Word w, j.val < baseCount X → + addr ≠ (T.baseOut+j).val ∧ addr ≠ (T.baseIn+j).val ∧ addr ≠ (T.shift+j).val + +/-- All lane-zero calls through the given cursor, with unchanged memory outside the output +columns. Neither the inverse actual column nor the width column is read by these calls. -/ +theorem scan_run (layout : T.Layout X) (m : Memory w) (k calls : ℕ) + (cur : Prefix T X m k) (room : k + calls ≤ baseCount X) : + let M := (template visit 0).instantiate w (params T a l) + ∃ rs, runSegment M.program 29 (some (Fin.ofNat (2^w) k)) m (List.replicate calls []) = some rs ∧ + Prefix T X (after m (eventLog rs)) (k + calls) ∧ + (∀ addr, Outside T X addr → after m (eventLog rs) addr = m addr) ∧ + rs.length = calls ∧ ∀ r ∈ rs, r.events.length = 28 ∧ countProbes r.events = 4 := by + let p := params T a l + let M := (template visit 0).instantiate w p + induction calls generalizing k m with + | zero => exact ⟨[],rfl,cur,fun _ _ => rfl,rfl,by simp⟩ + | succ s ih => + have hk : k < baseCount X := by omega + let e := (baseOrder X).symm ⟨k,hk⟩ + let i := basePort (w := w) X e + have he : (baseOrder X e).val = k := by simp [e] + have hi : i.val = k := (base_val T X layout e).trans he + have hiw : Fin.ofNat (2^w) k = i := by apply Fin.ext; rw [← hi]; exact Nat.mod_eq_of_lt i.isLt + have hn := step T X layout m e (he ▸ cur) + have hnext : i + 1 = Fin.ofNat (2^w) (k+1) := by + apply Fin.ext + rw [Fin.val_add, Fin.val_one', hi, Nat.add_mod_mod]; rfl + let r : Report w := ⟨events p m i, some (i+1)⟩ + obtain ⟨rs,run,rows,frame,hl,hw⟩ := ih (update p m i) (k+1) (he ▸ hn) (by omega) + have hm : after m (eventLog (r :: rs)) = after (update p m i) (eventLog rs) := by + change List.foldl BurstRAM.update m (events p m i ++ eventLog rs) = _ + rw [List.foldl_append]; rfl + refine ⟨r :: rs, ?_, ?_, ?_, by simp [hl], ?_⟩ + · change runSegment M.program 29 (some (Fin.ofNat (2^w) k)) m (List.replicate (s+1) []) = _ + rw [hiw, List.replicate_succ, runSegment, visit_native p m i] + change runSegment M.program 29 (some (Fin.ofNat (2^w) (k+1))) (update p m i) (List.replicate s []) = some rs at run + simp only [r, events_after, hnext, run, Option.map_some] + · simpa [hm, Nat.add_assoc, Nat.add_comm 1 s] using rows + · intro addr outside + rw [hm, frame addr outside] + change update (params T a l) m (basePort X e) addr = _ + rw [update_row T X layout m cur.actual] + have hs := outside i (hi ▸ hk) + have hd := outside (basePort X (X.slots.base.target e)) + (by rw [base_val T X layout]; exact (baseOrder X _).isLt) + change writeBase T m i (basePort X (X.slots.base.target e)) _ addr = _ + simp [writeBase, writeMemory, hs.1, hs.2.2, hd.2.1] + · intro q hq + rcases List.mem_cons.mp hq with rfl | hq + · exact events_work p m i + · exact hw q hq + +private theorem pass_cost {rs : List (Report w)} (hw : ∀ r ∈ rs, countProbes r.events = 4) : + RAMBuckets.cost (fun r : Report w => countProbes r.events) rs = 5 * rs.length := by + induction rs with + | nil => simp [RAMBuckets.cost] + | cons r rs ih => + rw [RAMBuckets.cost, hw r (List.mem_cons_self ..), ih (fun q h => hw q (List.mem_cons_of_mem _ h)), + List.length_cons, Nat.mul_succ] + omega + +/-- One call for each base slot recovers the entire base matching, its inverse, and its +displacement. Together with the actual columns these give the complete level directory. -/ +theorem base_pass (m : Memory w) (layout : T.Layout X) (actual : T.ActualColumns X m) : + let M := (template visit 0).instantiate w (params T a l) + ∃ rs, runSegment M.program 29 (some 0) m (List.replicate (baseCount X) []) = some rs ∧ + T.Represents X (after m (eventLog rs)) ∧ + (∀ addr, Outside T X addr → after m (eventLog rs) addr = m addr) ∧ + RAMBuckets.cost (fun r : Report w => countProbes r.events) rs = 5 * baseCount X ∧ + rs.length = baseCount X ∧ ∀ r ∈ rs, r.events.length = 28 ∧ countProbes r.events = 4 := by + have init : Prefix T X m 0 := ⟨actual, fun _ h => (Nat.not_lt_zero _ h).elim⟩ + obtain ⟨rs,run,rows,frame,hl,hw⟩ := scan_run T X layout m 0 (baseCount X) init (by simp) + have full (e) := rows.rows e (by simpa only [Nat.zero_add] using (baseOrder X e).isLt) + refine ⟨rs,run,?_,frame,(pass_cost (fun r h => (hw r h).2)).trans (by rw [hl]),hl,hw⟩ + refine ⟨fun e => (full e).1, fun e => ?_, fun e => (full e).2.2, + rows.actual.actualOut, rows.actual.actualIn, rows.actual.width⟩ + simpa only [Equiv.apply_symm_apply] using (full (X.slots.base.target.symm e)).2.1 + +end CompressorRecords.BaseOutput + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshBuild.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshBuild.lean new file mode 100644 index 0000000000..02b5f33918 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshBuild.lean @@ -0,0 +1,221 @@ +import OAI.Computability.VPVNP.CompressionHistory +import OAI.Computability.VPVNP.CompressorRecordRefreshPrepareAllocation +import OAI.Computability.VPVNP.CompressorRecordRefreshAdmitted + +/-! +# Native construction of a complete degree-refresh level + +The sole data input is a represented old incidence directory. On each legal branch, the +program prepares both segment endpoints, reads the block demands, chooses admitted terms, +installs their supply widths and builds the next six incidence columns. All arrays use +the packed allocation, with a single end-address bound. The same final memory retains the +individual demands, selected grid rows, repetition counts and payload coordinates used by +the local history tests. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.Build + +open BurstRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry MotifConversion +open NewSlots RefreshRAM Allocation + +variable {bits a a₀ g dH t : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (choice : DyadicRefreshChoice X E hdH conn F) + (ties : Fin t ≃ Tie (2^a)) (T : IncidenceDirectory bits) (start stride : ℕ) + +local notation "P" => plan X a₀ dH t stride start +local notation "Q" => Plan.scratch P bits +local notation "Iₛ" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) E hdH conn F choice +local notation "Y" => dyadicRefreshNext X E hdH conn F hD hd choice +local notation "N" => Fintype.card X.Base * 2^a * 2^g +local notation "B" => Fintype.card X.Base * 2^g +local notation "S" => N*2^a +local notation "sourceBase" => word (bits := bits) (Plan.demand P) +local notation "termBase" => word (bits := bits) (Plan.term P) +local notation "demand" => blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) +local notation "frame" => PrepareLayout X T a₀ dH t stride start + +private theorem append_memory (m : Memory bits) (x y : List (Report bits)) : + after m (eventLog (x++y)) = after (after m (eventLog x)) (eventLog y) := by + change List.foldl BurstRAM.update m ((x++y).flatMap Report.events) = _ + rw [List.flatMap_append,List.foldl_append]; rfl + +private theorem prepare_memory {q : Fin 8 → W bits} {base lanes : W bits} {fit : S ≤ 2^bits} + {m m' : Memory bits} {rs : List (Report bits)} (run : PrepareRun X T q base ties lanes fit m m' rs) : + m' = after m (eventLog rs) := by + rcases run with ⟨rg,rd,re,ds,_,_,rfl,rfl⟩ + simp only [append_memory] + +/-- One full execution, segmented at its preparation, term selection and output stages. +The term bits belong to the selected mathematical branch in physical block order. -/ +def Run (cap : ℕ) (L : frame) (m : Memory bits) (rs : List (Report bits)) : Prop := + ∃ pre terms post, + let m₁ := after m (eventLog pre) + let m₂ := after m₁ (eventLog terms) + rs = (pre ++ terms) ++ post ∧ + PrepareRun X T Q sourceBase ties (word (2^g)) L.regions.fits m m₁ pre ∧ + termRun E hdH conn F ties X sourceBase termBase stride cap (blockTapes E hdH conn F X choice bits) m₁ = some terms ∧ + Finish.Run X E hdH conn F hD hd choice termBase stride ((P).inputs bits) ((P).output bits) m₂ post + +/-- All local input fields that the subsequent history traversal can read from this level. -/ +structure Stored (fit : S ≤ 2^bits) (m : Memory bits) : Prop where + segments : SegmentFields X Q fit m + demands : ∀ s, DemandPreparation.demandAt ties (DemandScan.rowBase X t sourceBase s) m = demand s + terms : SupplyScan.TermFields X E hdH conn F choice termBase stride m + readback : ∀ s, TermRecordScan.Fields F finProdFinEquiv.symm (fun _ => zero_lt_one) + (demand s) (choice s).val (SupplyScan.recordBase X termBase stride s) m + +/-- The report count plus all RAM probes. Only the fixed expander ROM is independent of +the old graph's position and block counts. -/ +noncomputable def charge : ℕ := 6*N + 12*S + 3*B*t + B*(1+TermRecordScan.probesPerRow F t (2^a*dH)) + + (4*(N*dH) + 3*(2^a*dH) + ((6+7*dH+4*(2^a₀-(dH+1)))*X.positions + 5*BaseOutput.baseCount Y)) + +/-- A coefficient depending only on the fixed refresh motif and degrees. -/ +noncomputable def chargeFactor (tiesCount : ℕ) := 6 + 12*2^a + 3*tiesCount + + (1+TermRecordScan.probesPerRow F tiesCount (2^a*dH)) + 4*dH + 3*dH + + (6+7*dH+4*(2^a₀-(dH+1))) + 5*2^a₀ + +/-- In particular, the actual phase reports have a uniform linear charge in the number +of positions, independently of the old or selected wire widths. -/ +theorem charge_le_positions : + charge (t := t) X E hdH conn F hD hd choice ≤ chargeFactor E hdH conn F t * X.positions := by + have pos : N = X.positions := bundleCount_positions X (IncidenceDirectory.baseOrder X) + have blocks : B ≤ N := by + exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)) + have ports : 2^a ≤ N := (Nat.le_mul_of_pos_left _ Fintype.card_pos).trans + (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g)) + have sites : Fintype.card X.Base * 2^a ≤ N := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g) + have baseCount : BaseOutput.baseCount Y = (Fintype.card X.Base * 2^a)*2^a₀ := by + change Fintype.card (X.Base × Fin (2^a)) * _ = _ + simp only [Fintype.card_prod,Fintype.card_fin] + have c₁ := Nat.mul_le_mul_right (3*t) blocks + have c₂ := Nat.mul_le_mul_right (1+TermRecordScan.probesPerRow F t (2^a*dH)) blocks + have c₃ := Nat.mul_le_mul_right (3*dH) ports + have c₄ := Nat.mul_le_mul_right (5*2^a₀) sites + unfold charge chargeFactor + rw [baseCount,← pos] + simp only [Nat.add_mul] + linarith only [c₁,c₂,c₃,c₄] + +private theorem bounds (nextWidth : (Y).maxWireWidth < 2^bits) : + (∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j) < 2^bits) ∧ + (∀ (b : (X.Base × BitWord g) × Fin (2^a)) (i : Fin dH), Iₛ b.1 (b.2,i) < 2^bits) := by + have h (b : (X.Base × BitWord g) × Fin (2^a)) (slot : RefreshSlot dH (2^a₀)) := + ((Y).width_le_maxWireWidth (refreshedCoordinates.symm (b, refreshSlots hd slot))).trans_lt nextWidth + change ∀ b slot, newWidths hd _ Iₛ (refreshedCoordinates (refreshedCoordinates.symm _)).1 + (refreshedCoordinates (refreshedCoordinates.symm (b, refreshSlots hd slot))).2 < 2^bits at h + simp only [Equiv.apply_symm_apply,newWidths,Equiv.symm_apply_apply] at h + exact ⟨fun b => h b (.inl 0),fun b i => h b (.inr (.inl i))⟩ + +private theorem demand_bound (s : X.Base × BitWord g) (e : Tie (2^a)) : demand s e ≤ X.maxWireWidth := by + unfold blockDemandWidths internalWidth + split <;> exact X.width_le_maxWireWidth _ + +/-- The packed level produces the directory of the actual selected next state, retains +all fields needed by the local history, and writes only to its reserved interval. -/ +theorem build (m : Memory bits) (old : T.Represents X m) + (before : ∀ c : Fin 6, (T.column c).val + S ≤ start) + (wide : 2+2^a*dH ≤ stride) (room : (P).stop < 2^bits) + (termBits : termConstant E hdH conn F ties + 4*Nat.clog 2 (X.maxWireWidth+1) ≤ bits) + (nextWidth : (Y).maxWireWidth < 2^bits) + (cap : ℕ) (capFit : TermWorker.budget F t (2^a*dH) bits X.maxWireWidth ≤ cap) : + let L := prepare_layout X T a₀ dH t stride start before room + ∃ rs, Run X E hdH conn F hD hd choice ties T start stride cap L m rs ∧ + ((P).output bits).Represents Y (after m (eventLog rs)) ∧ + Stored X E hdH conn F choice ties start stride L.regions.fits (after m (eventLog rs)) ∧ + (∀ addr, addr < start ∨ (P).stop ≤ addr → after m (eventLog rs) addr = m addr) ∧ + RAMBuckets.cost Report.probes rs ≤ charge (t := t) X E hdH conn F hD hd choice := by + let L := prepare_layout X T a₀ dH t stride start before room + obtain ⟨external,internal⟩ := bounds X E hdH conn F hD hd choice nextWidth + obtain ⟨pre,m₁,prun,seg₁,demands,preFrame,pcost⟩ := + prepare_demands X T Q sourceBase ties m old (word (2^g)) L.degree L.lanes L.regions L.directory L.gather + L.baseApart external L.demandRoom L.demandApart + have pm := prepare_memory X ties T prun + obtain ⟨terms,trun,term₂,readback₂,termFrame,tcost,_⟩ := term_pass E hdH conn F ties X sourceBase termBase + stride wide L.demandTerm L.termRoom m₁ X.maxWireWidth termBits (demand_bound X) demands cap capFit choice + let m₂ := after m₁ (eventLog terms) + change ∀ addr, addr < (termBase).val ∨ (termBase).val+B*stride ≤ addr → m₂ addr = m₁ addr at termFrame + have h₀ : start+7*S = (P).demand := rfl + have h₁ : (P).demand+B*t = (P).term := rfl + have h₂ : (P).term+B*stride = (P).supply := rfl + have h₃ : (P).supply ≤ (P).stop := by dsimp only [Plan.stop,Plan.next,Plan.reverseSlot,Plan.targetPort]; omega + have w₁ : (sourceBase).val = (P).demand := Nat.mod_eq_of_lt (by omega) + have w₂ : (termBase).val = (P).term := Nat.mod_eq_of_lt (by omega) + have seg₂ : SegmentFields X Q L.regions.fits m₂ := + seg₁.transfer X Q fun c hc i hi => termFrame _ (Or.inl (by rw [w₂]; have := ((P).scratch_interval (by omega) c hc i hi).2; omega)) + obtain ⟨post,frun,next,seg₃,postFrame,fcost⟩ := Finish.finish X E hdH conn F hD hd choice Q termBase stride + ((P).inputs bits) ((P).output bits) m₂ L.regions.fits seg₂ term₂ + (finish_layout X E hdH conn F hD hd choice t stride start wide room.le) internal + let rs := (pre ++ terms) ++ post + let m₃ := after m₂ (eventLog post) + change ∀ addr, Finish.Outside X E hdH conn F hD hd choice termBase stride ((P).inputs bits) ((P).output bits) addr → m₃ addr = m₂ addr at postFrame + have fm : after m (eventLog rs) = m₃ := by simp only [rs,m₃,m₂,pm,append_memory] + have low (j : ℕ) (hj : j < (P).supply) : m₃ j = m₂ j := + postFrame j (outside_finish_of_lt_supply X E hdH conn F hD hd choice t stride start room.le j hj) + have daddr (s : X.Base × BitWord g) (i : Fin t) : (DemandScan.rowBase X t sourceBase s).val + i.val < (P).term := by + have h := Nat.mul_le_mul_right t (DemandScan.blocks X s).isLt + rw [Nat.succ_mul] at h + rw [DemandScan.rowBase,Fin.val_add,w₁] + have hmod := Nat.mod_le ((DemandScan.blocks X s).val*t) (2^bits) + have hmod' := Nat.mod_le ((P).demand + ((DemandScan.blocks X s).val*t) % (2^bits)) (2^bits) + change ((P).demand + ((DemandScan.blocks X s).val*t) % (2^bits)) % (2^bits) + i.val < _ + have := i.isLt; omega + have demand₃ (s) : DemandPreparation.demandAt ties (DemandScan.rowBase X t sourceBase s) m₃ = demand s := by + funext e + obtain ⟨i,rfl⟩ := ties.surjective e + have h := DemandPreparation.demandAt_address ties (DemandScan.rowBase X t sourceBase s) m₃ + (DemandScan.rowBase_fits X sourceBase L.demandRoom s) i + have h' := DemandPreparation.demandAt_address ties (DemandScan.rowBase X t sourceBase s) m₁ + (DemandScan.rowBase_fits X sourceBase L.demandRoom s) i + have bound := daddr s i + rw [h,low _ (by omega),termFrame _ (Or.inl (by rw [w₂]; exact bound)),← h',demands] + have termAddr (s : X.Base × BitWord g) : + (SupplyScan.recordBase X termBase stride s).val + stride ≤ (P).supply := by + let i := (DemandScan.blocks X s).val + have h := Nat.mul_le_mul_right stride (DemandScan.blocks X s).isLt + rw [Nat.succ_mul] at h + rw [SupplyScan.recordBase,← DemandScan.blocks_val,Fin.val_add,Fin.val_mul,w₂] + change ((P).term + (((i % 2^bits) * (stride % 2^bits)) % 2^bits)) % 2^bits + stride ≤ _ + rw [Nat.mul_mod_mod,Nat.mod_mul_mod,Nat.add_mod_mod] + have hr : (P).term + i*stride < 2^bits := by dsimp only [i]; omega + rw [Nat.mod_eq_of_lt hr] + dsimp only [i]; omega + have fields₃ : SupplyScan.TermFields X E hdH conn F choice termBase stride m₃ := by + refine ⟨term₂.fits,fun s => ?_,fun s e => ?_⟩ + · rw [low]; exact term₂.repetitions s + have := termAddr s; omega + · rw [low]; exact term₂.payload s e + have h := Nat.mul_le_mul_right dH e.1.isLt + rw [Nat.succ_mul] at h + have := e.2.isLt; have := termAddr s; omega + have stored : Stored X E hdH conn F choice ties start stride L.regions.fits m₃ := by + refine ⟨seg₃,demand₃,fields₃,fun s => ?_⟩ + have h := termAddr s + refine ⟨?_,?_,fun i => ?_⟩ + · rw [low _ (by omega)]; exact (readback₂ s).1 + · rw [low _ (by omega)]; exact (readback₂ s).2.1 + · rw [low _ (by have := i.isLt; omega)]; exact (readback₂ s).2.2 i + refine ⟨rs,⟨pre,terms,post,rfl,pm ▸ prun,pm ▸ trun,pm ▸ frun⟩,fm ▸ next,fm ▸ stored,fun addr outside => ?_,?_⟩ + · rw [fm,postFrame _ (outside_finish_of_outside X E hdH conn F hD hd choice t stride start room.le _ outside)] + rw [termFrame _ (by rw [w₂]; omega)] + apply preFrame + · intro c hc i hi + have hh := (P).scratch_interval (by omega) c hc i hi + change start ≤ _ ∧ _ < (P).demand at hh + omega + · rw [w₁]; omega + · rw [show rs = (pre++terms)++post from rfl,RAMBuckets.cost_append,RAMBuckets.cost_append,pcost,fcost] + unfold charge + omega + +end CompressorRecords.PortRefresh.Build + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshDemandScan.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshDemandScan.lean new file mode 100644 index 0000000000..61ea527020 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshDemandScan.lean @@ -0,0 +1,383 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshNewSlots +import OAI.Computability.VPVNP.DegreeRefreshPass +import OAI.Computability.VPVNP.CompressorChoicePreparation + +/-! +# Dense demand vectors for the degree-refresh term reader + +For each ordered tie, one native pass visits the old base vertex and residual +lane of every block. The selected segment column supplies the outgoing or +incoming width at that tie's local half-slot. The resulting contiguous array +is the input used by the motif term verifier. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.DemandScan + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM NewSlots +open Compression Compression.Refresh Compression.DegreeRefresh + +variable {w N t : ℕ} +/-- Eight public words that specify a tie's ports, the block dimensions, the selected width +column, and the dense demand destination. -/ +abbrev Params (w : ℕ) := Fin 8 → W w + +/-- Public words are the residual lane count, port count, target port, source +port, tie count, tie index, selected width-column base and dense output base. -/ +def visit : List (Op 9 8) := + [.stateWord 0, .publicWord 1 0, .binary .div 2 0 1, .binary .mod 3 0 1, + .publicWord 4 1, .binary .mul 2 2 4, .publicWord 5 2, .binary .add 2 2 5, + .binary .mul 2 2 1, .binary .add 2 2 3, .binary .mul 2 2 4, + .publicWord 5 3, .binary .add 2 2 5, .publicWord 6 6, .binary .add 2 6 2, .read 7 2, + .publicWord 4 4, .binary .mul 3 0 4, .publicWord 5 5, .binary .add 3 3 5, + .publicWord 6 7, .binary .add 3 6 3, .write 3 7, .constant 8 1, .binary .add 0 0 8] + +/-- Address of the selected segment width for the block and ordered tie being scanned. -/ +def inputAddr (p : Params w) (i : W w) : W w := + let v := BinaryOp.div.eval i (p 0) + let l := BinaryOp.mod.eval i (p 0) + p 6 + (((v * p 1 + p 2) * p 0 + l) * p 1 + p 3) + +/-- Address of one demand entry, indexed first by block ordinal and then by tie ordinal. -/ +def outputAddr (p : Params w) (i : W w) : W w := p 7 + (i * p 4 + p 5) + +/-- The 25 events that read a selected width and write it into the block's dense demand vector. -/ +def events (p : Params w) (m : Memory w) (i : W w) : List (Event w) := + let v := m (inputAddr p i).val + List.replicate 15 .tick ++ [.read (inputAddr p i) v] ++ List.replicate 6 .tick ++ + [.write (outputAddr p i) v, .tick, .tick] + +theorem work (p : Params w) (m : Memory w) (i : W w) : + (events p m i).length = 25 ∧ countProbes (events p m i) = 2 := by simp [events,countProbes] + +theorem after_events (p : Params w) (m : Memory w) (i : W w) : + after m (events p m i) = writeMemory m (outputAddr p i) (m (inputAddr p i).val) := rfl + +set_option maxRecDepth 4096 in +private theorem visit_trace (p : Params w) (m : Memory w) (i : W w) (r : Regs w 9) : + ∃ s, trace p i visit r m = some (events p m i, s, writeMemory m (outputAddr p i) (m (inputAddr p i).val)) ∧ + s 0 = i+1 := by + simp (config := {decide := true}) [visit,events,inputAddr,outputAddr,trace,Op.effect,BinaryOp.eval,Function.update] + rfl + +theorem native (p : Params w) (m : Memory w) (i : W w) : + let M := (template visit 0).instantiate w p + execute M.program 26 (M.program.start i) m [] = some ⟨events p m i,some (i+1)⟩ := by + obtain ⟨rs,ht,hr⟩ := visit_trace p m i (fun _ => 0) + let M := (template visit 0).instantiate w p + change execute M.program (1+visit.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ m [] = _ + rw [execute_template,run_eq_trace,ht] + simp [hr] + +/-- The actual lists of native calls, in tie order and then block order. -/ +inductive Runs (p : Fin t → Params w) (N : ℕ) : List (Fin t) → Memory w → List (Report w) → Prop where + | nil (m) : Runs p N [] m [] + | cons (k : Fin t) {ks m rs ts} + (head : let M := (template visit 0).instantiate w (p k) + runSegment M.program 26 (some 0) m (List.replicate N []) = some rs) + (tail : Runs p N ks (after m (eventLog rs)) ts) : Runs p N (k :: ks) m (rs ++ ts) + +variable (p : Fin t → Params w) (ref : Memory w) + +/-- Source width address for one tie pass and one finite block index. -/ +def src (k : Fin t) (i : Fin N) := inputAddr (p k) (word i.val) +/-- Destination demand address for the same tie pass and block index. -/ +def dst (k : Fin t) (i : Fin N) := outputAddr (p k) (word i.val) + +/-- Source widths avoid every demand write, and the destination address determines the tie and +block uniquely. -/ +structure Layout (N : ℕ) : Prop where + reads : ∀ k j (i l : Fin N), src p k i ≠ dst p j l + writes : ∀ k j (i l : Fin N), dst p k i = dst p j l → k = j ∧ i = l + +/-- Completed cells for the passes preceding the current tie and the visited +block prefix of the current tie. Outside this set the initial memory is intact. -/ +structure Saved (ref m : Memory w) (done : Fin t → Fin N → Prop) : Prop where + rows : ∀ k i, done k i → m (dst p k i).val = ref (src p k i).val + frame : ∀ addr, (∀ k i, done k i → addr ≠ (dst p k i).val) → m addr = ref addr + +private theorem one_step (layout : Layout p N) (m : Memory w) {done : Fin t → Fin N → Prop} + (prev : Saved p ref m done) (j : Fin t) (l : Fin N) : + Saved p ref (after m (events (p j) m (word l.val))) (fun k i => done k i ∨ k = j ∧ i = l) := by + rw [after_events] + have live : m (src p j l).val = ref (src p j l).val := + prev.frame _ (fun k i _ he => layout.reads j k l i (Fin.ext he)) + constructor + · intro k i hk + change writeMemory m (dst p j l) (m (src p j l).val) (dst p k i).val = _ + by_cases he : dst p k i = dst p j l + · obtain ⟨rfl,rfl⟩ := layout.writes k j i l he + simpa [writeMemory] using live + · have hn := Fin.val_ne_of_ne he + simp only [writeMemory,ite_eq_right hn] + exact prev.rows k i (hk.resolve_right (fun ⟨h,h'⟩ => he (h ▸ h' ▸ rfl))) + · intro addr outside + change writeMemory m (dst p j l) _ addr = _ + rw [writeMemory,ite_eq_right (outside j l (.inr ⟨rfl,rfl⟩))] + exact prev.frame addr (fun k i h => outside k i (.inl h)) + +private theorem saved_congr {m : Memory w} {f g : Fin t → Fin N → Prop} + (h : Saved p ref m f) (eq : ∀ k i, f k i ↔ g k i) : Saved p ref m g := + ⟨fun k i hi => h.rows k i ((eq k i).mpr hi), fun addr ha => h.frame addr (fun k i hi => ha k i ((eq k i).mp hi))⟩ + +/-- One tie's scan, retaining all earlier writes and every unvisited cell. -/ +theorem scan_run (layout : Layout p N) (done : Fin t → Fin N → Prop) (j : Fin t) + (m : Memory w) (k calls : ℕ) (room : k+calls ≤ N) + (prev : Saved p ref m (fun u i => done u i ∨ u = j ∧ i.val < k)) : + let M := (template visit 0).instantiate w (p j) + ∃ rs, runSegment M.program 26 (some (word k)) m (List.replicate calls []) = some rs ∧ + Saved p ref (after m (eventLog rs)) (fun u i => done u i ∨ u = j ∧ i.val < k+calls) ∧ + RAMBuckets.cost Report.probes rs = 3*calls := by + let M := (template visit 0).instantiate w (p j) + induction calls generalizing m k with + | zero => exact ⟨[],rfl,prev,rfl⟩ + | succ n ih => + let l : Fin N := ⟨k,by omega⟩ + let b := word (bits := w) k + let r : Report w := ⟨events (p j) m b,some (b+1)⟩ + let next := after m r.events + have hprev : Saved p ref next (fun u i => done u i ∨ u=j ∧ i.val done k i ∨ k ∈ ks) ∧ + RAMBuckets.cost Report.probes rs = 3*N*ks.length := by + induction ks generalizing m done with + | nil => exact ⟨[],.nil _,saved_congr p ref prev (by simp),by simp [RAMBuckets.cost]⟩ + | cons j ks ih => + have start : Saved p ref m (fun u i => done u i ∨ u = j ∧ i.val < 0) := + saved_congr p ref prev (by simp) + obtain ⟨rs,hr,hs,hc⟩ := scan_run p ref layout done j m 0 N (by simp) start + let mid := after m (eventLog rs) + have saved : Saved p ref mid (fun u i => done u i ∨ u=j) := saved_congr p ref hs (by simp) + obtain ⟨ts,ht,hf,hw⟩ := ih mid _ saved + have hm : after m (eventLog (rs++ts)) = after mid (eventLog ts) := by + change List.foldl BurstRAM.update m ((rs++ts).flatMap Report.events) = _ + rw [List.flatMap_append,List.foldl_append]; rfl + have zero : word (bits := w) 0 = 0 := Fin.ext (by simp [word]) + rw [zero] at hr + refine ⟨rs++ts,.cons j hr ht,?_,?_⟩ + · rw [hm]; exact saved_congr p ref hf (by simp [or_assoc]) + · rw [RAMBuckets.cost_append,hc,hw,List.length_cons,Nat.mul_succ]; omega + +/-- One public table for each fixed role of the motif. -/ +def words {D r t : ℕ} (ties : Fin t ≃ Tie D) (q : Fin 8 → W w) (out : W w) + (k : Fin t) : Params w := + ![word r, word D, word (tieTarget (ties k)).val, word (tieSource (ties k)).val, + word t, word k.val, if (ties k).1 then q 1 else q 7, out] + +private theorem pack_lt {q Q i d : ℕ} (hq : q (Fintype.card X.Base * 2^g) +local notation "S" => (Fintype.card X.Base * 2^a * 2^g * 2^a) +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "P" => words (r := 2^g) ties q out + +/-- Enumerate blocks by old base vertex and residual lane, with the residual lane varying +fastest. -/ +def blocks : X.Base × BitWord g ≃ Fin B := + (X.baseIndex.prodCongr (bitWordFinEquiv g)).trans finProdFinEquiv + +theorem blocks_val (s : X.Base × BitWord g) : + (blocks X s).val = (X.baseIndex s.1).val * 2^g + (bitWordFinEquiv g s.2).val := by + change (bitWordFinEquiv g s.2).val + 2^g * (X.baseIndex s.1).val = _ + ring + +private def halfSlot (s : X.Base × BitWord g) (e : Tie (2^a)) : DyadicArc X.Base (BitWord g) a := + ((s,tieTarget e),tieSource e) + +private theorem source_key (s : X.Base × BitWord g) (e : Tie (2^a)) : + (numbered O (halfSlot X s e)).val = + (((X.baseIndex s.1).val * 2^a + (tieTarget e).val) * 2^g + + (bitWordFinEquiv g s.2).val) * 2^a + (tieSource e).val := by + rw [halfSlot,numbered_val,sites_val] + +private theorem src_eq (fit : S ≤ 2^w) (laneFit : 2^g < 2^w) (k : Fin t) (s : X.Base × BitWord g) : + src P k (blocks X s) = + (if (ties k).1 then q 1 else q 7) + idWord O fit (halfSlot X s (ties k)) := by + have boundB : B ≤ S := by + calc B ≤ B * (2^a * 2^a) := Nat.le_mul_of_pos_right _ (by positivity) + _ = S := by ring + have hval : (word (bits := w) (blocks X s).val).val = + (X.baseIndex s.1).val * 2^g + (bitWordFinEquiv g s.2).val := + (Nat.mod_eq_of_lt ((blocks X s).isLt.trans_le (boundB.trans fit))).trans (blocks_val X s) + have hr : (word (bits := w) (2^g)).val = 2^g := Nat.mod_eq_of_lt laneFit + have hv : BinaryOp.div.eval (word (bits := w) (blocks X s).val) (word (2^g)) = word (X.baseIndex s.1).val := by + apply Fin.ext + change ((_ : W w).val / (_ : W w).val) % _ = _ % _ + rw [hval,hr,Nat.mul_comm (X.baseIndex s.1).val,Nat.mul_add_div (Nat.two_pow_pos _), + Nat.div_eq_of_lt (bitWordFinEquiv g s.2).isLt,Nat.add_zero] + have hl : BinaryOp.mod.eval (word (bits := w) (blocks X s).val) (word (2^g)) = word (bitWordFinEquiv g s.2).val := by + apply Fin.ext + change ((_ : W w).val % (_ : W w).val) % _ = _ % _ + rw [hval,hr,Nat.mul_add_mod_of_lt (bitWordFinEquiv g s.2).isLt] + change (if (ties k).1 then q 1 else q 7) + (((BinaryOp.div.eval _ (word (2^g)) * word (2^a) + word (tieTarget (ties k)).val) * word (2^g) + + BinaryOp.mod.eval _ (word (2^g))) * word (2^a) + word (tieSource (ties k)).val) = _ + rw [hv,hl,mul_word,add_word,mul_word,add_word,mul_word,add_word,← source_key X s (ties k)] + congr 1 + exact Fin.ext (Nat.mod_eq_of_lt (idWord O fit (halfSlot X s (ties k))).isLt) + +private theorem dst_eq (i : Fin B) (k : Fin t) : dst P k i = out + word (i.val*t+k.val) := by + change out + (word i.val * word t + word k.val) = _ + rw [mul_word,add_word] + +private theorem dst_val (room : out.val+B*t ≤ 2^w) (i : Fin B) (k : Fin t) : + (dst P k i).val = out.val + i.val*t + k.val := by + rw [dst_eq X ties q out i k,Fin.val_add] + have h := pack_lt i.isLt k.isLt + change (out.val + ((i.val*t+k.val) % (2^w))) % (2^w) = _ + rw [Nat.mod_eq_of_lt (by omega : i.val*t+k.val < 2^w),Nat.mod_eq_of_lt (by omega),Nat.add_assoc] + +/-- The source columns are disjoint from the dense output interval. -/ +def Apart : Prop := + ∀ c : Fin 8, c = 1 ∨ c = 7 → ∀ i : W w, i.val < S → + (q c+i).val < out.val ∨ out.val+B*t ≤ (q c+i).val + +private theorem layout (fit : S ≤ 2^w) (laneFit : 2^g < 2^w) + (room : out.val+B*t ≤ 2^w) (apart : Apart (t := t) X q out) : Layout P B := by + constructor + · intro k j i l he + let s := (blocks X).symm i + have hi : i = blocks X s := ((blocks X).apply_symm_apply i).symm + have hsrc := src_eq X ties q out fit laneFit k s + rw [← hi] at hsrc + have hrange := dst_val X ties q out room l j + let z := idWord O fit (halfSlot X s (ties k)) + have hz : z.val < S := (numbered O (halfSlot X s (ties k))).isLt + have choose : (src P k i).val < out.val ∨ out.val+B*t ≤ (src P k i).val := by + rw [hsrc] + cases h : (ties k).1 with + | false => exact apart 7 (.inr rfl) z hz + | true => exact apart 1 (.inl rfl) z hz + rw [he,hrange] at choose + have := pack_lt l.isLt j.isLt + omega + · intro k j i l he + have h := congrArg Fin.val he + rw [dst_val X ties q out room i k,dst_val X ties q out room l j] at h + have key : i.val*t+k.val = l.val*t+j.val := by omega + have hkj : k=j := Fin.ext ((Nat.mul_add_mod_of_lt k.isLt).symm.trans + ((congrArg (· % t) key).trans (Nat.mul_add_mod_of_lt j.isLt))) + subst j + exact ⟨rfl,Fin.ext (Nat.eq_of_mul_eq_mul_right (Nat.zero_lt_of_lt k.isLt) (Nat.add_right_cancel key))⟩ + +/-- Recover the exact tie width from the completed external segment pass. At an +incoming half-slot, its own destination identifier is the incoming-width key. -/ +theorem read_demand (fit : S ≤ 2^w) (laneFit : 2^g < 2^w) + (data : RefreshRAM.Input w) (dir : Directory (splitSlots X) O (splitWidths X) q data fit) + (done : RefreshRAM.AtCursor q S data ref S) + (inc : ∀ e : DyadicArc X.Base (BitWord g) a, + (RefreshRAM.cell q ref 7 (idWord O fit (oldPortMatching (splitSlots X) (bitWordFinEquiv a) e))).val = + (outgoingRecord (splitSlots X) (bitWordFinEquiv a) (splitWidths X) e).width) + (k : Fin t) (s : X.Base × BitWord g) : + (ref (src P k (blocks X s)).val).val = + blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) s (ties k) := by + rw [src_eq X ties q out fit laneFit k s] + let e := halfSlot X s (ties k) + let perm := oldPortMatching (splitSlots X) (bitWordFinEquiv a) + change (ref ((if (ties k).1 then q 1 else q 7) + idWord O fit e).val).val = + internalWidth perm (groupedWidths (bitWordFinEquiv a) (splitWidths X)) s (ties k) + cases h : (ties k).1 with + | true => + simp [h,internalWidth] + exact (congrArg Fin.val (done.old (idWord O fit e) (numbered O e).isLt)).trans (dir.old e) + | false => + have hr := inc (perm.symm e) + change (RefreshRAM.cell q ref 7 (idWord O fit (perm (perm.symm e)))).val = _ at hr + rw [Equiv.apply_symm_apply] at hr + simp [h,internalWidth] + exact hr + +/-- Base address handed to the term verifier for this block. -/ +def rowBase (t : ℕ) (out : W w) (s : X.Base × BitWord g) : W w := + out + word ((blocks X s).val*t) + +theorem rowBase_fits (room : out.val+B*t ≤ 2^w) (s : X.Base × BitWord g) : + (rowBase X t out s).val + t ≤ 2^w := by + have h : ((blocks X s).val+1)*t ≤ B*t := Nat.mul_le_mul_right _ (blocks X s).isLt + rw [Nat.succ_mul] at h + rw [rowBase,Fin.val_add] + change (out.val + ((blocks X s).val*t) % 2^w) % 2^w + t ≤ _ + have := Nat.mod_le ((blocks X s).val*t) (2^w) + have := Nat.mod_le (out.val + ((blocks X s).val*t) % 2^w) (2^w) + omega + +/-- Execute all fixed tie scans from the terminal segment directory. The +motif verifier reads exactly the graph's demand function at each row base. +The cost is three calls-plus-probes per pair of a block and a tie. -/ +theorem demand_table (fit : S ≤ 2^w) (laneFit : 2^g < 2^w) (room : out.val+B*t ≤ 2^w) + (apart : Apart (t := t) X q out) + (data : RefreshRAM.Input w) (dir : Directory (splitSlots X) O (splitWidths X) q data fit) + (done : RefreshRAM.AtCursor q S data ref S) + (inc : ∀ e : DyadicArc X.Base (BitWord g) a, + (RefreshRAM.cell q ref 7 (idWord O fit (oldPortMatching (splitSlots X) (bitWordFinEquiv a) e))).val = + (outgoingRecord (splitSlots X) (bitWordFinEquiv a) (splitWidths X) e).width) : + ∃ rs, Runs P B (List.finRange t) ref rs ∧ + (∀ s, DemandPreparation.demandAt ties (rowBase X t out s) (after ref (eventLog rs)) = + blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) s) ∧ + (∀ addr, addr < out.val ∨ out.val+B*t ≤ addr → after ref (eventLog rs) addr = ref addr) ∧ + RAMBuckets.cost Report.probes rs = 3*B*t := by + have lay := layout X ties q out fit laneFit room apart + obtain ⟨rs,run,saved,cost⟩ := scans P ref lay (List.finRange t) ref (fun _ _ => False) + ⟨fun _ _ h => h.elim, fun _ _ => rfl⟩ + refine ⟨rs,run,?_,?_,by simpa using cost⟩ + · intro s + funext e + obtain ⟨k,rfl⟩ := ties.surjective e + have hrow := saved.rows k (blocks X s) (.inr (List.mem_finRange k)) + have val := (congrArg Fin.val hrow).trans (read_demand ref X ties q out fit laneFit data dir done inc k s) + rw [dst_eq X ties q out (blocks X s) k] at val + change ((after ref (eventLog rs)) ((out + word ((blocks X s).val*t)) + + word (ties.symm (ties k)).val).val).val = _ + rw [Equiv.symm_apply_apply,add_assoc,add_word] + exact val + · intro addr outside + apply saved.frame + intro k i _ + rw [dst_val X ties q out room i k] + have := pack_lt i.isLt k.isLt + omega + +end Graph + +end CompressorRecords.PortRefresh.DemandScan + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshDeterminism.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshDeterminism.lean new file mode 100644 index 0000000000..ad8fa22fe2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshDeterminism.lean @@ -0,0 +1,98 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshBuild + +/-! +# Uniqueness of a native degree-refresh execution + +The initial memory and the selected branch tapes determine all reports. The two +ordered scans run a deterministic table at each tie or slot and thread its memory +into the next table. Thus splitting a full execution into native phases does not +introduce additional computational paths. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh + +open BurstRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry NewSlots + +variable {bits a a₀ g dH t n : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} + +/-- A fixed sequence of demand scans has one report list. -/ +theorem DemandScan.Runs.deterministic {p : Fin t → DemandScan.Params bits} {order : List (Fin t)} + {m : Memory bits} {rs ss : List (Report bits)} + (left : DemandScan.Runs p n order m rs) (right : DemandScan.Runs p n order m ss) : rs = ss := by + induction left generalizing ss with + | nil => cases right; rfl + | cons j head tail ih => + cases right with + | cons _ head' tail' => + obtain rfl := Option.some.inj (head.symm.trans head') + exact congrArg (_ ++ ·) (ih tail') + +/-- A fixed sequence of local-slot scans has one report list. -/ +theorem AllSlots.Runs.deterministic {kind : Fin t → Kind} {pub : Fin t → Public bits} + {order : List (Fin t)} {m : Memory bits} {rs ss : List (Report bits)} + (left : AllSlots.Runs kind pub n order m rs) (right : AllSlots.Runs kind pub n order m ss) : rs = ss := by + induction left generalizing ss with + | nil => cases right; rfl + | cons j head tail ih => + cases right with + | cons _ head' tail' => + obtain rfl := Option.some.inj (head.symm.trans head') + exact congrArg (_ ++ ·) (ih tail') + +variable {X : State a (a+g)} {E : RegularArcGraph (Fin (2^a)) dH} {hdH : 0 < dH} + {conn : (arcSupportGraph E.multiplicity).Connected} + {F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K'} + {hD : 1 < 2^a} {hd : dH+1 ≤ 2^a₀} {choice : DyadicRefreshChoice X E hdH conn F} + {q : Fin 8 → W bits} {ties : Fin t ≃ Tie (2^a)} {I : AllSlots.Tables bits} + {T : IncidenceDirectory bits} {termBase out lanes : W bits} {start stride cap : ℕ} {m : Memory bits} + {rs ss : List (Report bits)} + +local notation "S" => Fintype.card X.Base * 2^a * 2^g * 2^a + +/-- The gather, directory, external segment and demand tables determine both the +reports and the final memory of the preparation phase. -/ +theorem PrepareRun.deterministic {fit : S ≤ 2^bits} {u v : Memory bits} + (left : PrepareRun X T q out ties lanes fit m u rs) + (right : PrepareRun X T q out ties lanes fit m v ss) : rs = ss ∧ u = v := by + obtain ⟨rg,rd,re,ds,⟨hg,hd',he,_⟩,run,rfl,rfl⟩ := left + obtain ⟨rg',rd',re',ds',⟨hg',hd'',he',_⟩,run',rfl,rfl⟩ := right + obtain rfl := Option.some.inj (hg.symm.trans hg') + obtain rfl := Option.some.inj (hd'.symm.trans hd'') + obtain rfl := Option.some.inj (he.symm.trans he') + obtain rfl := DemandScan.Runs.deterministic run run' + exact ⟨rfl,rfl⟩ + +/-- The selected-width table, expander ROM, actual-slot scans and lane-zero table +determine the terminal report list of the selected state. -/ +theorem Finish.Run.deterministic + (left : Finish.Run X E hdH conn F hD hd choice termBase stride I T m rs) + (right : Finish.Run X E hdH conn F hD hd choice termBase stride I T m ss) : rs = ss := by + obtain ⟨s,e,o,b,rfl,hs,he,ho,hb⟩ := left + obtain ⟨s',e',o',b',rfl,hs',he',ho',hb'⟩ := right + obtain rfl := Option.some.inj (hs.symm.trans hs') + obtain rfl := Option.some.inj (he.symm.trans he') + obtain rfl := AllSlots.Runs.deterministic ho ho' + obtain rfl := Option.some.inj (hb.symm.trans hb') + rfl + +/-- A fixed branch choice and initial incidence memory admit at most one complete +list of native refresh reports, for any capacity and packed preparation layout. -/ +theorem Build.Run.deterministic {L : Allocation.PrepareLayout X T a₀ dH t stride start} + (left : Build.Run X E hdH conn F hD hd choice ties T start stride cap L m rs) + (right : Build.Run X E hdH conn F hD hd choice ties T start stride cap L m ss) : rs = ss := by + obtain ⟨p,t',f,rfl,hp,ht,hf⟩ := left + obtain ⟨p',t'',f',rfl,hp',ht',hf'⟩ := right + obtain rfl := (PrepareRun.deterministic hp hp').1 + obtain rfl := Option.some.inj (ht.symm.trans ht') + obtain rfl := Finish.Run.deterministic hf hf' + rfl + +end CompressorRecords.PortRefresh + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshDirectory.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshDirectory.lean new file mode 100644 index 0000000000..e222f9acbb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshDirectory.lean @@ -0,0 +1,335 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshOldWidths +import OAI.Computability.VPVNP.LaneReindex + +/-! +# Constructing the degree-refresh bundle directory + +The degree refresh in Appendix E enumerates bundles by base arc and residual lane. +The base slot table contains the destination arc and the old binary displacement. +One native call unpacks these words, translates the lane, and writes the destination +bundle number, the port shift and the initial concatenation offset. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh + +open Compression BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {V : Type} {a g n bits : ℕ} + +/-- Enumerate each base arc's bundles in increasing order of the remaining lane. -/ +def bundleOrder (g : ℕ) (base : V × Fin (2^a) ≃ Fin n) : + (V × BitWord g) × Fin (2^a) ≃ Fin (n * 2^g) := + let perm : (V × BitWord g) × Fin (2^a) ≃ (V × Fin (2^a)) × BitWord g := + ⟨fun ((x,l),j) => ((x,j),l), fun ((x,j),l) => ((x,l),j), fun _ => rfl, fun _ => rfl⟩ + perm.trans ((base.prodCongr (bitWordFinEquiv g)).trans finProdFinEquiv) + +theorem bundleOrder_val (g : ℕ) (base : V × Fin (2^a) ≃ Fin n) + (b : (V × BitWord g) × Fin (2^a)) : + (bundleOrder g base b).val = (base (b.1.1,b.2)).val * 2^g + (bitWordFinEquiv g b.1.2).val := by + change (bitWordFinEquiv g b.1.2).val + 2^g * (base (b.1.1,b.2)).val = _ + rw [Nat.mul_comm, Nat.add_comm] + +namespace BundleDirectory + +variable (X : LiftedSlots V (2^a) (BitWord a × BitWord g)) (base : V × Fin (2^a) ≃ Fin n) + (p : Fin 8 → Word bits) + +/-- Parameter zero is the lane count. Tables one and five are the old base target and +displacement. Tables two, three and four are the output columns shared with the segment scan. -/ +def visit : List (Op 9 8) := + [.stateWord 0, .publicWord 1 0, .binary .div 2 0 1, .binary .mod 3 0 1, + .publicWord 4 1, .binary .add 4 4 2, .read 5 4, + .publicWord 4 5, .binary .add 4 4 2, .read 6 4, + .binary .div 7 6 1, .binary .mod 6 6 1, .binary .bitXor 3 3 6, + .binary .mul 5 5 1, .binary .add 5 5 3, + .publicWord 4 2, .binary .add 4 4 0, .write 4 5, + .publicWord 4 3, .binary .add 4 4 0, .write 4 7, + .constant 6 0, .publicWord 4 4, .binary .add 4 4 0, .write 4 6, + .constant 8 1, .binary .add 0 0 8] + +/-- Read a word at the indexed offset from a refresh column's public base address. -/ +abbrev cell := @RefreshRAM.cell + +/-- Decode a bundle ordinal to its old base arc by dividing out the residual lanes. -/ +def sourceArc (i : Word bits) := BinaryOp.div.eval i (p 0) + +/-- Read the old base arc's packed binary displacement from the shift column. -/ +def shiftWord (m : Memory bits) (i : Word bits) := cell p m 5 (sourceArc p i) + +/-- Extract the high-order port shift from the packed displacement by dividing by the residual +lane count. -/ +def portShift (m : Memory bits) (i : Word bits) := BinaryOp.div.eval (shiftWord p m i) (p 0) + +/-- Encode the destination bundle from the old base mate and the residual lane translated by +XOR. -/ +def targetWord (m : Memory bits) (i : Word bits) := + cell p m 1 (sourceArc p i) * p 0 + BinaryOp.bitXor.eval (BinaryOp.mod.eval i (p 0)) + (BinaryOp.mod.eval (shiftWord p m i) (p 0)) + +/-- Write the translated bundle number and port shift, and initialize the bundle's running +width total to zero. -/ +def update (m : Memory bits) (i : Word bits) : Memory bits := + writeMemory (writeMemory (writeMemory m (p 2 + i) (targetWord p m i)) + (p 3 + i) (portShift p m i)) (p 4 + i) 0 + +/-- The 27-event directory visit reads the old mate and shift and writes the target, port +shift, and zero total. -/ +def events (m : Memory bits) (i : Word bits) : List (Event bits) := + let e := sourceArc p i + [.tick, .tick, .tick, .tick, .tick, .tick, .read (p 1 + e) (cell p m 1 e), + .tick, .tick, .read (p 5 + e) (cell p m 5 e), .tick, .tick, .tick, .tick, .tick, + .tick, .tick, .write (p 2 + i) (targetWord p m i), + .tick, .tick, .write (p 3 + i) (portShift p m i), + .tick, .tick, .tick, .write (p 4 + i) 0, .tick, .tick] + +theorem events_work (m : Memory bits) (i : Word bits) : + (events p m i).length = 27 ∧ countProbes (events p m i) = 5 := ⟨rfl,rfl⟩ + +theorem events_after (m : Memory bits) (i : Word bits) : after m (events p m i) = update p m i := rfl + +set_option maxRecDepth 4096 in +private theorem visit_trace (m : Memory bits) (i : Word bits) (rs : Regs bits 9) : + ∃ out, trace p i visit rs m = some (events p m i, out, update p m i) ∧ out 0 = i + 1 := by + simp (config := {decide := true}) [visit, events, update, sourceArc, shiftWord, portShift, + targetWord, cell, RefreshRAM.cell, trace, Op.effect, BinaryOp.eval, Function.update] + rfl + +/-- The actual table executes from its normal entry and advances the persistent bundle cursor. -/ +theorem visit_native (m : Memory bits) (i : Word bits) : + let M := (template visit 0).instantiate bits p + execute M.program 28 (M.program.start i) m [] = some ⟨events p m i, some (i + 1)⟩ := by + obtain ⟨out, ht, hret⟩ := visit_trace p m i (fun _ => 0) + let M := (template visit 0).instantiate bits p + change execute M.program (1 + visit.length) ⟨M.entry, i, fun _ => 0, fun _ => 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hret] + +/-- The base displacement is stored as a port in the high bits and a residual-lane shift +in the low bits. These columns are shared by all the lanes of a base arc. -/ +structure BaseTables (m : Memory bits) : Prop where + lanes : (p 0).val = 2^g + target : ∀ e, (cell p m 1 (Fin.ofNat _ (base e).val)).val = (base (X.base.target e)).val + displacement : ∀ e, (cell p m 5 (Fin.ofNat _ (base e).val)).val = + (bitWordFinEquiv a (X.displacement e).1).val * 2^g + (bitWordFinEquiv g (X.displacement e).2).val + +/-- The old graph's ordinary binary displacement cell supplies the packed displacement +required by the directory, after splitting the old lane into port and residual coordinates. -/ +theorem BaseTables.ofOld (G : LiftedSlots V (2^a) (BitWord (a+g))) (m : Memory bits) + (hl : (p 0).val = 2^g) + (ht : ∀ e, (cell p m 1 (Fin.ofNat _ (base e).val)).val = (base (G.base.target e)).val) + (hs : ∀ e, (cell p m 5 (Fin.ofNat _ (base e).val)).val = + (bitWordFinEquiv (a+g) (G.displacement e)).val) : + BaseTables (relane G (splitBitWord a g)) base p m := + ⟨hl, ht, fun e => (hs e).trans (splitBitWord_number a g (G.displacement e))⟩ + +private theorem unpack {x d : Word bits} {hi lo : ℕ} (h : x.val = hi * d.val + lo) (hl : lo < d.val) : + (BinaryOp.div.eval x d).val = hi ∧ (BinaryOp.mod.eval x d).val = lo := by + have hd : 0 < d.val := Nat.zero_lt_of_lt hl + have hq : x.val / d.val = hi := by + rw [h, Nat.mul_comm hi, Nat.mul_add_div hd, Nat.div_eq_of_lt hl, Nat.add_zero] + have hr : x.val % d.val = lo := by rw [h, Nat.mul_add_mod_of_lt hl] + exact ⟨(Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)).trans hq, + (Nat.mod_eq_of_lt ((Nat.mod_lt _ hd).trans d.isLt)).trans hr⟩ + +/-- Decoding an actual source bundle yields precisely its translated target and port shift. -/ +theorem translated_row (m : Memory bits) (rep : BaseTables X base p m) (fit : n * 2^g ≤ 2^bits) + (b : (V × BitWord g) × Fin (2^a)) (i : Word bits) (hi : i.val = (bundleOrder g base b).val) : + (targetWord p m i).val = (bundleOrder g base (bundleTarget X b)).val ∧ + (portShift p m i).val = (bitWordFinEquiv a (X.displacement (b.1.1,b.2)).1).val := by + obtain ⟨⟨x,l⟩,j⟩ := b + let e := (x,j) + have hs := unpack (d := p 0) (x := i) (by simpa only [rep.lanes, bundleOrder_val] using hi) + (by simpa only [rep.lanes] using (bitWordFinEquiv g l).isLt) + have he : sourceArc p i = Fin.ofNat _ (base e).val := by + apply Fin.ext + exact hs.1.trans (Nat.mod_eq_of_lt (hs.1 ▸ (sourceArc p i).isLt)).symm + have sh : (shiftWord p m i).val = + (bitWordFinEquiv a (X.displacement e).1).val * (p 0).val + + (bitWordFinEquiv g (X.displacement e).2).val := by + rw [shiftWord, he, rep.displacement, rep.lanes] + have ds := unpack sh (by simpa only [rep.lanes] using (bitWordFinEquiv g (X.displacement e).2).isLt) + refine ⟨?_,ds.1⟩ + have hx (u v : Word bits) : (BinaryOp.bitXor.eval u v).val = u.val ^^^ v.val := + Nat.mod_eq_of_lt (Nat.xor_lt_two_pow u.isLt v.isLt) + have ht := (bundleOrder g base (bundleTarget X ((x,l),j))).isLt.trans_le fit + rw [bundleTarget_apply, bundleOrder_val, bitWordFinEquiv_add_val] at ht ⊢ + rw [targetWord, Fin.val_add, Fin.val_mul, he, rep.target, hx, hs.2, ds.2, rep.lanes, + Nat.mod_add_mod, Nat.mod_eq_of_lt ht] + +/-- The two base columns have one entry per old base arc. Each output column has +one entry per bundle. Only overlaps involving a write need to be ruled out. -/ +structure Layout (p : Fin 8 → Word bits) (n lanes : ℕ) : Prop where + fits : n * lanes ≤ 2^bits + apart : ∀ (t u : Fin 8) (x i : Word bits), 1 ≤ t.val → t.val ≤ 5 → 2 ≤ u.val → u.val ≤ 4 → + x.val < (if t = 1 ∨ t = 5 then n else n * lanes) → i.val < n * lanes → + ((p t + x).val = (p u + i).val ↔ t = u ∧ x = i) + +/-- Equal-capacity regions in the existing refresh layout satisfy the weaker +bounds for the two read-only base tables. -/ +theorem Layout.ofRegions (h : RefreshRAM.Regions p (n * 2^g)) : Layout p n (2^g) := by + refine ⟨h.fits, fun t u x i ht _ hu _ hx hi => ?_⟩ + apply h.apart t u (by rintro rfl; simp at ht) (by rintro rfl; simp at hu) x i _ hi + split at hx + · exact hx.trans_le (Nat.le_mul_of_pos_right n (Nat.two_pow_pos g)) + · exact hx + +/-- Addresses outside the output columns through a given cursor. -/ +def Outside (k addr : ℕ) : Prop := + ∀ i : Word bits, i.val < k → + addr ≠ (p 2 + i).val ∧ addr ≠ (p 3 + i).val ∧ addr ≠ (p 4 + i).val + +/-- The constructed rows through the cursor, together with the surviving base tables. -/ +structure Prefix (m : Memory bits) (k : ℕ) : Prop where + inputs : BaseTables X base p m + rows : ∀ b, (bundleOrder g base b).val < k → + let i : Word bits := Fin.ofNat _ (bundleOrder g base b).val + (cell p m 2 i).val = (bundleOrder g base (bundleTarget X b)).val ∧ + (cell p m 3 i).val = (bitWordFinEquiv a (X.displacement (b.1.1,b.2)).1).val ∧ cell p m 4 i = 0 + +private theorem cell_update {lanes : ℕ} (layout : Layout p n lanes) (m : Memory bits) + (i : Word bits) (hi : i.val < n * lanes) (t : Fin 8) (x : Word bits) + (ht₁ : 1 ≤ t.val) (ht₅ : t.val ≤ 5) (hx : x.val < (if t = 1 ∨ t = 5 then n else n * lanes)) : + cell p (update p m i) t x = + if t = 4 ∧ x = i then 0 else if t = 3 ∧ x = i then portShift p m i + else if t = 2 ∧ x = i then targetWord p m i else cell p m t x := by + simp only [update, cell, RefreshRAM.cell, writeMemory, + layout.apart t 4 x i ht₁ ht₅ (by decide) (by decide) hx hi, + layout.apart t 3 x i ht₁ ht₅ (by decide) (by decide) hx hi, + layout.apart t 2 x i ht₁ ht₅ (by decide) (by decide) hx hi] + +private theorem step (layout : Layout p n (2^g)) (m : Memory bits) (i : Word bits) + (hi : i.val < n * 2^g) (cur : Prefix X base p m i.val) : + Prefix X base p (update p m i) (i.val+1) := by + have cellEq := cell_update p layout m i hi + have hbase (e : V × Fin (2^a)) : (Fin.ofNat (2^bits) (base e).val).val < n := + (Nat.mod_le ..).trans_lt (base e).isLt + constructor + · refine ⟨cur.inputs.lanes, fun e => ?_, fun e => ?_⟩ + · rw [cellEq 1 _ (by decide) (by decide) (by simpa using hbase e)] + simpa using cur.inputs.target e + · rw [cellEq 5 _ (by decide) (by decide) (by simpa using hbase e)] + simpa using cur.inputs.displacement e + · intro b hb + let j := Fin.ofNat (2^bits) (bundleOrder g base b).val + have hj : j.val = (bundleOrder g base b).val := Nat.mod_eq_of_lt ((bundleOrder g base b).isLt.trans_le layout.fits) + have hjn : j.val < n * 2^g := hj ▸ (bundleOrder g base b).isLt + change (cell p _ 2 j).val = _ ∧ (cell p _ 3 j).val = _ ∧ cell p _ 4 j = 0 + rw [cellEq 2 j (by decide) (by decide) (by simpa using hjn), + cellEq 3 j (by decide) (by decide) (by simpa using hjn), + cellEq 4 j (by decide) (by decide) (by simpa using hjn)] + by_cases hji : j = i + · have correct := translated_row X base p m cur.inputs layout.fits b i (hji ▸ hj) + simpa [hji] using correct + · have hne : j.val ≠ i.val := Fin.val_ne_of_ne hji + simp [hji]; exact cur.rows b (by omega) + +/-- The native scan from an arbitrary prefix extends that prefix by its call count. +Memory outside the output rows through the final cursor keeps its incoming value. -/ +theorem scan_run (layout : Layout p n (2^g)) (m : Memory bits) (k calls : ℕ) + (cur : Prefix X base p m k) (room : k + calls ≤ n * 2^g) : + let M := (template visit 0).instantiate bits p + ∃ rs, runSegment M.program 28 (some (Fin.ofNat (2^bits) k)) m (List.replicate calls []) = some rs ∧ + Prefix X base p (after m (eventLog rs)) (k + calls) ∧ + (∀ z, Outside p (k + calls) z → after m (eventLog rs) z = m z) ∧ + rs.length = calls ∧ ∀ r ∈ rs, r.events.length = 27 ∧ countProbes r.events = 5 := by + let M := (template visit 0).instantiate bits p + induction calls generalizing m k with + | zero => exact ⟨[], rfl, cur, fun _ _ => rfl, rfl, by simp⟩ + | succ s ih => + let i := Fin.ofNat (2^bits) k + have hv : i.val = k := Nat.mod_eq_of_lt (by have := layout.fits; omega) + have hi : i.val < n * 2^g := by omega + have next := step X base p layout m i hi (hv ▸ cur) + have hnext : i + 1 = Fin.ofNat (2^bits) (k+1) := by + apply Fin.ext + rw [Fin.val_add, Fin.val_one', hv, Nat.add_mod_mod] + rfl + let r : Report bits := ⟨events p m i, some (i+1)⟩ + obtain ⟨rs,run,rows,frame,hl,hw⟩ := ih (update p m i) (k+1) (hv ▸ next) (by omega) + have hm : after m (eventLog (r :: rs)) = after (update p m i) (eventLog rs) := by + change List.foldl BurstRAM.update m (events p m i ++ eventLog rs) = _ + rw [List.foldl_append]; rfl + refine ⟨r :: rs, ?_, ?_, ?_, by simp [hl], ?_⟩ + · change runSegment M.program 28 (some i) m (List.replicate (s+1) []) = _ + rw [List.replicate_succ, runSegment, visit_native p m i] + simp only [M, r, events_after, hnext, run, Option.map_some] + · simpa [hm, Nat.add_assoc, Nat.add_comm 1 s] using rows + · intro z hz + rw [hm, frame z (by simpa only [Nat.add_assoc, Nat.add_comm 1 s] using hz)] + obtain ⟨h₂,h₃,h₄⟩ := hz i (by omega) + simp [update, writeMemory, h₂, h₃, h₄] + · intro q hq + rcases List.mem_cons.mp hq with rfl | hq + · exact events_work p m i + · exact hw q hq + +private theorem pass_cost {rs : List (Report bits)} (hw : ∀ r ∈ rs, countProbes r.events = 5) : + RAMBuckets.cost (fun r : Report bits => countProbes r.events) rs = 6 * rs.length := by + induction rs with + | nil => simp [RAMBuckets.cost] + | cons r rs ih => + rw [RAMBuckets.cost, hw r (List.mem_cons_self ..), ih (fun q h => hw q (List.mem_cons_of_mem _ h)), + List.length_cons, Nat.mul_succ] + omega + +/-- Complete directory initialization from the old base slot tables. It costs six calls +plus probes per bundle and writes only the target, shift and total arrays. -/ +theorem directory_pass (layout : Layout p n (2^g)) (m : Memory bits) (old : BaseTables X base p m) : + let M := (template visit 0).instantiate bits p + ∃ rs, runSegment M.program 28 (some 0) m (List.replicate (n * 2^g) []) = some rs ∧ + Prefix X base p (after m (eventLog rs)) (n * 2^g) ∧ + (∀ z, Outside p (n * 2^g) z → after m (eventLog rs) z = m z) ∧ + RAMBuckets.cost (fun r : Report bits => countProbes r.events) rs = 6 * (n * 2^g) ∧ + rs.length = n * 2^g ∧ ∀ r ∈ rs, r.events.length = 27 ∧ countProbes r.events = 5 := by + have init : Prefix X base p m 0 := ⟨old, fun b h => ((bundleOrder g base b).val.not_lt_zero h).elim⟩ + obtain ⟨rs,run,rows,frame,hl,hw⟩ := scan_run X base p layout m 0 (n * 2^g) init (by simp) + exact ⟨rs,run,by simpa using rows,by simpa using frame, + (pass_cost (fun r h => (hw r h).2)).trans (by rw [hl]),hl,hw⟩ + +/-- Every bundle read by a live source segment is inside the constructed directory. -/ +theorem liveBundle_lt (q : Fin 8 → Word bits) (hd : (q 0).val = 2^a) {b : Word bits} + (live : RefreshRAM.LiveBundle q (n * 2^g * 2^a) b) : b.val < n * 2^g := by + obtain ⟨i,hi,rfl⟩ := live + change (i.val / (q 0).val) % (2^bits) < n * 2^g + exact (Nat.mod_le ..).trans_lt (hd ▸ (Nat.div_lt_iff_lt_mul (Nat.two_pow_pos a)).mpr hi) + +/-- The constructed directory and gathered widths give exactly the initial state of the +external segment scan. Only totals at live bundle numbers need initialization. -/ +theorem Prefix.external_start (q : Fin 8 → Word bits) (m : Memory bits) + (w : (V × Fin (2^a)) × (BitWord a × BitWord g) → ℕ) + (done : Prefix X base p m (n * 2^g)) (hd : (q 0).val = 2^a) + (targetBase : q 2 = p 2) (shiftBase : q 3 = p 3) (totalBase : q 4 = p 4) + (old : ∀ i : Word bits, i.val < n * 2^g * 2^a → + cell q m 1 i = (graphInput X (bundleOrder g base) w).width i) : + RefreshRAM.AtCursor q (n * 2^g * 2^a) (graphInput X (bundleOrder g base) w) m 0 := by + let ord := bundleOrder g base + have rows (i : Word bits) (live : RefreshRAM.LiveBundle q (n * 2^g * 2^a) i) : + cell q m 2 i = (graphInput X ord w).target i ∧ + cell q m 3 i = (graphInput X ord w).shift i ∧ cell q m 4 i = 0 := by + have hi := liveBundle_lt q hd live + let b := ord.symm ⟨i.val,hi⟩ + have hid : (ord b).val = i.val := congrArg Fin.val (ord.apply_symm_apply ⟨i.val,hi⟩) + have hiw : Fin.ofNat (2^bits) (ord b).val = i := by rw [hid]; exact Fin.ext (Nat.mod_eq_of_lt i.isLt) + obtain ⟨target, shift, total⟩ := done.rows b (ord b).isLt + change (cell p m 2 (Fin.ofNat _ (ord b).val)).val = (ord (bundleTarget X b)).val at target + change (cell p m 3 (Fin.ofNat _ (ord b).val)).val = _ at shift + change cell p m 4 (Fin.ofNat _ (ord b).val) = 0 at total + rw [hiw] at target shift total + change m (q 2+i).val = _ ∧ m (q 3+i).val = _ ∧ m (q 4+i).val = 0 + rw [targetBase, shiftBase, totalBase] + simp only [graphInput, dite_eq_left hi] + exact ⟨Fin.ext (target.trans ((Nat.mod_eq_of_lt (target ▸ (cell p m 2 i).isLt)).symm)), + Fin.ext (shift.trans ((Nat.mod_eq_of_lt (shift ▸ (cell p m 3 i).isLt)).symm)), total⟩ + exact RefreshRAM.AtCursor.start old (fun i live => (rows i live).1) (fun i live => (rows i live).2.1) + (fun i live => (rows i live).2.2) + +end BundleDirectory +end CompressorRecords.PortRefresh + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshExpanderROM.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshExpanderROM.lean new file mode 100644 index 0000000000..b23a48bbef --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshExpanderROM.lean @@ -0,0 +1,229 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshAllSlots + +/-! +# Initializing the fixed expander incidence table + +The fixed expander supplies one finite schedule row per outgoing port and +local slot. Each row carries the port and local slot of its reverse edge as +public words. A native call writes the two columns read by the degree-refresh +slot writer. These public values depend only on the expander. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.ExpanderROM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM NewSlots SpectralGeometry + +variable {w D dH : ℕ} + +/-- Public words are row ID, reverse port, reverse slot, port column base, and +slot column base. The call returns the successor row ID. -/ +def put : List (Op 6 5) := + [.publicWord 0 0, .publicWord 1 3, .binary .add 1 1 0, .publicWord 2 1, .write 1 2, + .publicWord 3 4, .binary .add 3 3 0, .publicWord 4 2, .write 3 4, + .constant 5 1, .binary .add 0 0 5] + +/-- The 11 events that publish an expander edge's destination port and reverse slot at its +fixed ordinal. -/ +def events (p : Fin 5 → W w) : List (Event w) := + [.tick,.tick,.tick,.tick,.write (p 3+p 0) (p 1),.tick,.tick,.tick,.write (p 4+p 0) (p 2),.tick,.tick] + +theorem events_work (p : Fin 5 → W w) : (events p).length = 11 ∧ countProbes (events p) = 2 := + ⟨rfl,rfl⟩ + +theorem events_after (p : Fin 5 → W w) (m : Memory w) : + after m (events p) = writeMemory (writeMemory m (p 3+p 0) (p 1)) (p 4+p 0) (p 2) := rfl + +private theorem put_trace (p : Fin 5 → W w) (state : W w) (m : Memory w) (regs : Regs w 6) : + ∃ rs, trace p state put regs m = some (events p,rs,after m (events p)) ∧ rs 0 = p 0+1 := by + simp (config := {decide := true}) [put,events,trace,Op.effect,BinaryOp.eval,Function.update] + exact ⟨rfl,rfl⟩ + +theorem native (p : Fin 5 → W w) (state : W w) (m : Memory w) : + let M := (template put 0).instantiate w p + execute M.program 12 (M.program.start state) m [] = some ⟨events p,some (p 0+1)⟩ := by + obtain ⟨rs,hr,hret⟩ := put_trace p state m (fun _ => 0) + let M := (template put 0).instantiate w p + change execute M.program (1 + put.length) ⟨M.entry,state,fun _ => 0,fun _ => 0⟩ m [] = _ + rw [execute_template,run_eq_trace,hr] + simp [hret] + +variable (E : RegularArcGraph (Fin D) dH) (I : AllSlots.Tables w) + +/-- Public schedule data for the edge with row-major ID `i`. -/ +def words (i : Fin (D*dH)) : Fin 5 → W w := + let target := E.reverse (finProdFinEquiv.symm i) + ![word i.val,word target.1.val,word target.2.val,I.targetPort,I.reverseSlot] + +/-- The report of one fixed expander row, including its two writes and the next edge ordinal. -/ +def report (i : Fin (D*dH)) : Report w := + ⟨events (words E I i),some (word i.val + 1)⟩ + +/-- Execute each hardwired row from the state and memory returned by the +previous call, collecting the actual reports. -/ +def runRows : Option (W w) → Memory w → List (Fin (D*dH)) → Option (List (Report w)) + | _, _, [] => some [] + | none, _, _::_ => none + | some state, m, i::is => + let M := (template put 0).instantiate w (words E I i) + match execute M.program 12 (M.program.start state) m [] with + | none => none + | some r => (runRows r.result (after m r.events) is).map (r :: ·) + +theorem schedule_run (state : W w) (m : Memory w) (is : List (Fin (D*dH))) : + runRows E I (some state) m is = some (is.map (report E I)) := by + induction is generalizing m state with + | nil => rfl + | cons i is ih => + rw [runRows,native] + change (runRows E I (some (word i.val+1)) (after m (events (words E I i))) is).map (report E I i :: ·) = _ + rw [ih] + rfl + +/-- Both output regions fit, and their intervals are disjoint. -/ +structure Regions (I : AllSlots.Tables w) (n : ℕ) : Prop where + ports : I.targetPort.val+n ≤ 2^w + slots : I.reverseSlot.val+n ≤ 2^w + apart : I.targetPort.val+n ≤ I.reverseSlot.val ∨ I.reverseSlot.val+n ≤ I.targetPort.val + +private def address (port : Bool) (i : Fin (D*dH)) : W w := + (if port then I.targetPort else I.reverseSlot) + word i.val + +private def value (port : Bool) (i : Fin (D*dH)) : W w := + let dst := E.reverse (finProdFinEquiv.symm i) + if port then word dst.1.val else word dst.2.val + +private theorem address_val (reg : Regions I (D*dH)) (c : Bool) (i : Fin (D*dH)) : + (address I c i).val = (if c then I.targetPort.val else I.reverseSlot.val) + i.val := by + have fit : (if c then I.targetPort.val else I.reverseSlot.val) + D*dH ≤ 2^w := by + cases c <;> first | exact reg.ports | exact reg.slots + have hi := i.isLt + have haddr : (if c then I.targetPort.val else I.reverseSlot.val) + i.val < 2^w := by omega + rw [address,Fin.val_add] + have hb : (if c then I.targetPort else I.reverseSlot).val = (if c then I.targetPort.val else I.reverseSlot.val) := + by cases c <;> rfl + rw [hb,show (word (bits := w) i.val).val = i.val from Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt haddr] + +private theorem address_inj (reg : Regions I (D*dH)) {c b : Bool} {i j : Fin (D*dH)} + (he : address I c i = address I b j) : c=b ∧ i=j := by + have h := congrArg Fin.val he + rw [address_val I reg,address_val I reg] at h + have hi := i.isLt + have hj := j.isLt + have ha := reg.apart + cases c <;> cases b + all_goals first | exact ⟨rfl,Fin.ext (Nat.add_left_cancel h)⟩ | simp at h; omega + +private theorem written (reg : Regions I (D*dH)) (i : Fin (D*dH)) (m : Memory w) (c : Bool) : + after m (report E I i).events (address I c i).val = value (w := w) E c i := by + have ne : (address I true i).val ≠ (address I false i).val := + fun h => Bool.noConfusion (address_inj I reg (Fin.ext h)).1 + change (I.targetPort+word i.val).val ≠ (I.reverseSlot+word i.val).val at ne + change writeMemory (writeMemory m (I.targetPort+word i.val) (value E true i)) + (I.reverseSlot+word i.val) (value E false i) (address I c i).val = _ + cases c with + | false => exact ite_eq_left rfl + | true => + change (if (I.targetPort+word i.val).val = (I.reverseSlot+word i.val).val then _ else _) = _ + rw [ite_eq_right ne] + exact ite_eq_left rfl + +private theorem frame (i : Fin (D*dH)) (m : Memory w) (addr : ℕ) + (miss : ∀ c, addr ≠ (address I c i).val) : after m (report E I i).events addr = m addr := by + have hp := miss true + have hs := miss false + change addr ≠ (I.targetPort + word i.val).val at hp + change addr ≠ (I.reverseSlot + word i.val).val at hs + change writeMemory (writeMemory m (I.targetPort+word i.val) (value E true i)) + (I.reverseSlot+word i.val) (value E false i) addr = _ + rw [writeMemory,ite_eq_right hs,writeMemory,ite_eq_right hp] + +private theorem rows (reg : Regions I (D*dH)) (is : List (Fin (D*dH))) (m : Memory w) : + let final := after m (eventLog (is.map (report E I))) + (∀ i ∈ is, ∀ c, final (address I c i).val = value E c i) ∧ + ∀ addr, (∀ i ∈ is, ∀ c, addr ≠ (address I c i).val) → final addr = m addr := by + induction is generalizing m with + | nil => exact ⟨by simp,fun _ _ => rfl⟩ + | cons i is ih => + let mid := after m (report E I i).events + have hm : after m (eventLog ((i::is).map (report E I))) = after mid (eventLog (is.map (report E I))) := by + change List.foldl BurstRAM.update m ((report E I i).events ++ eventLog _) = _ + rw [List.foldl_append]; rfl + obtain ⟨ht,hf⟩ := ih mid + dsimp only + rw [hm] + constructor + · intro j hj c + by_cases already : j ∈ is + · exact ht j already c + have eq := (List.mem_cons.mp hj).resolve_right already + subst j + rw [hf _ (fun j hj b he => already ((address_inj I reg (c := c) (b := b) (i := i) (j := j) (Fin.ext he)).2.symm ▸ hj))] + exact written E I reg i m c + · intro addr outside + rw [hf addr (fun j hj => outside j (List.mem_cons_of_mem _ hj))] + exact frame E I i m addr (outside i List.mem_cons_self) + +private theorem cost (is : List (Fin (D*dH))) : + RAMBuckets.cost Report.probes (is.map (report E I)) = 3*is.length := by + induction is with + | nil => rfl + | cons i is ih => + have h : (report E I i).probes = 2 := (events_work _).2 + rw [List.map_cons,RAMBuckets.cost,h,ih,List.length_cons,Nat.mul_succ] + omega + +private theorem numbered_edge (e : Fin D × Fin dH) : + (finProdFinEquiv e).val = e.1.val*dH+e.2.val := by + change e.2.val + dH*e.1.val = _ + ring + +/-- The values in the two cells are the actual port and slot of the reverse +edge, at exactly the addresses used by the slot writer. -/ +structure Ready (m : Memory w) : Prop where + targetPort : ∀ e : Fin D × Fin dH, (m (I.targetPort + word (e.1.val*dH+e.2.val)).val).val = (E.reverse e).1.val + reverseSlot : ∀ e : Fin D × Fin dH, (m (I.reverseSlot + word (e.1.val*dH+e.2.val)).val).val = (E.reverse e).2.val + +/-- Initialize the fixed expander from arbitrary incoming memory. The finite +schedule makes one call with two writes per edge, preserving all addresses +outside the two reserved intervals. -/ +theorem initialize_expander (reg : Regions I (D*dH)) (m : Memory w) : + let order := List.finRange (D*dH) + let rs := order.map (report E I) + let final := after m (eventLog rs) + runRows E I (some 0) m order = some rs ∧ Ready E I final ∧ + (∀ addr, (addr < I.targetPort.val ∨ I.targetPort.val+D*dH ≤ addr) → + (addr < I.reverseSlot.val ∨ I.reverseSlot.val+D*dH ≤ addr) → final addr = m addr) ∧ + RAMBuckets.cost Report.probes rs = 3*(D*dH) := by + intro order rs final + obtain ⟨values,preserve⟩ := rows E I reg order m + have hfit : D*dH ≤ 2^w := by have := reg.ports; omega + refine ⟨schedule_run E I 0 m order, ?_, ?_, by simpa [rs,order] using cost E I order⟩ + · constructor <;> intro e + · have h := congrArg Fin.val (values (finProdFinEquiv e) (List.mem_finRange _) true) + change (final (I.targetPort+word (finProdFinEquiv e).val).val).val = + (word (bits := w) (E.reverse (finProdFinEquiv.symm (finProdFinEquiv e))).1.val).val at h + rw [numbered_edge,Equiv.symm_apply_apply] at h + exact h.trans (Nat.mod_eq_of_lt ((E.reverse e).1.isLt.trans_le + ((Nat.le_mul_of_pos_right D (Nat.zero_lt_of_lt e.2.isLt)).trans hfit))) + · have h := congrArg Fin.val (values (finProdFinEquiv e) (List.mem_finRange _) false) + change (final (I.reverseSlot+word (finProdFinEquiv e).val).val).val = + (word (bits := w) (E.reverse (finProdFinEquiv.symm (finProdFinEquiv e))).2.val).val at h + rw [numbered_edge,Equiv.symm_apply_apply] at h + exact h.trans (Nat.mod_eq_of_lt ((E.reverse e).2.isLt.trans_le + ((Nat.le_mul_of_pos_left dH (Nat.zero_lt_of_lt e.1.isLt)).trans hfit))) + · intro addr op os + apply preserve + intro i _ c + rw [address_val I reg] + have := i.isLt + cases c <;> simp <;> omega + +end CompressorRecords.PortRefresh.ExpanderROM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshExternal.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshExternal.lean new file mode 100644 index 0000000000..4e79e882bc --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshExternal.lean @@ -0,0 +1,221 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshScan + +/-! +# External segment arrays on the actual dyadic refresh graph + +Starting with the old widths and the translated bundle directory in memory, the native +pass constructs both ends of every external segment. Its row count is the old degree times +the position count. Its offsets agree with the concatenation used by the kernel even when +widths vary arbitrarily between lanes of the same bundle. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh + +open Compression Compression.Refresh Compression.DegreeRefresh RefreshRAM +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {V L : Type} [AddCommGroup L] {a n bits : ℕ} +variable (X : LiftedSlots V (2 ^ a) (BitWord a × L)) + (ord : (V × L) × Fin (2 ^ a) ≃ Fin n) + (w : (V × Fin (2 ^ a)) × (BitWord a × L) → ℕ) + (p : Fin 8 → BurstRAM.Word bits) (A : Input bits) + +/-- A numbered external segment of a dyadic refresh, indexed by its base vertex, lane, bundle +port, and segment port. -/ +abbrev DyadicArc (V L : Type) (a : ℕ) := Refresh.Arc (V × L) (2 ^ a) + +/-- The numerical source identifier used as the persistent scan cursor. -/ +def idWord (fit : n * 2 ^ a ≤ 2 ^ bits) (e : DyadicArc V L a) : BurstRAM.Word bits := + Fin.castLE fit (numbered ord e) + +/-- The bundle identifier used in the target, shift and running-total arrays. -/ +def bundleWord (fit : n * 2 ^ a ≤ 2 ^ bits) (b : (V × L) × Fin (2 ^ a)) : BurstRAM.Word bits := + Fin.castLE ((Nat.le_mul_of_pos_right n (Nat.two_pow_pos a)).trans fit) (ord b) + +/-- Contents required in the old width table and in the two fixed-width columns of the +directory. The initial values at unused addresses are immaterial. -/ +structure Directory (fit : n * 2 ^ a ≤ 2 ^ bits) : Prop where + degree : (p 0).val = 2 ^ a + old : ∀ e, (A.width (idWord ord fit e)).val = groupedWidths (bitWordFinEquiv a) w e + target : ∀ b, (A.target (bundleWord ord fit b)).val = (ord (bundleTarget X b)).val + shift : ∀ b, (A.shift (bundleWord ord fit b)).val = (bitWordFinEquiv a (X.displacement (b.1.1,b.2)).1).val + +variable {fit : n * 2 ^ a ≤ 2 ^ bits} + +/-- Decode each numbered row directly to the old width, destination bundle or port shift. +Blank padding past the three table extents is assigned zero. -/ +def graphInput : Input bits where + width i := if h : i.val < n * 2 ^ a then Fin.ofNat _ + (groupedWidths (bitWordFinEquiv a) w ((numbered ord).symm ⟨i.val,h⟩)) else 0 + target b := if h : b.val < n then Fin.ofNat _ (ord (bundleTarget X (ord.symm ⟨b.val,h⟩))).val else 0 + shift b := if h : b.val < n then + let old := ord.symm ⟨b.val,h⟩ + Fin.ofNat _ (bitWordFinEquiv a (X.displacement (old.1.1,old.2)).1).val else 0 + +/-- The explicitly decoded table gives a valid directory with room for each concatenation. -/ +theorem graphInput_directory (degree : (p 0).val = 2 ^ a) + (room : ∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) w b j) < 2 ^ bits) : + Directory X ord w p (graphInput X ord w) fit := by + constructor + · exact degree + · intro e + have hfit : groupedWidths (bitWordFinEquiv a) w e < 2 ^ bits := + (Finset.single_le_sum (s := Finset.univ) (fun _ _ => Nat.zero_le _) + (Finset.mem_univ e.2) (f := bundleWidths (bitWordFinEquiv a) w e.1)).trans_lt (room e.1) + simp [graphInput, idWord, Nat.mod_eq_of_lt hfit] + · intro b + have hlt : (ord (bundleTarget X b)).val < 2 ^ bits := (bundleWord ord fit (bundleTarget X b)).isLt + simp [graphInput, bundleWord, Nat.mod_eq_of_lt hlt] + · intro b + have hlt := (bitWordFinEquiv a (X.displacement (b.1.1,b.2)).1).isLt.trans (degree ▸ (p 0).isLt) + simp [graphInput, bundleWord, Nat.mod_eq_of_lt hlt] + +omit [AddCommGroup L] in +private theorem idWord_surj (i : BurstRAM.Word bits) (hi : i.val < n * 2 ^ a) : + ∃ e, i = idWord ord fit e := by + refine ⟨(numbered ord).symm ⟨i.val,hi⟩, Fin.ext ?_⟩ + simp [idWord] + +omit [AddCommGroup L] in +private theorem idWord_bundle (hd : (p 0).val = 2 ^ a) (e : DyadicArc V L a) : + bundle p (idWord ord fit e) = bundleWord ord fit e.1 := by + apply Fin.ext + change ((numbered ord e).val / (p 0).val) % _ = _ + rcases e with ⟨b,j⟩ + rw [numbered_val, hd, Nat.mul_comm (ord b).val, Nat.mul_add_div (Nat.two_pow_pos a), + Nat.div_eq_of_lt j.isLt, Nat.add_zero] + exact Nat.mod_eq_of_lt (bundleWord ord fit b).isLt + +omit [AddCommGroup L] in +/-- Each bundle number names a reachable directory row. Its source segment at port zero +is an actual cursor value in the pass. -/ +theorem bundleWord_live (hd : (p 0).val = 2^a) (b : (V × L) × Fin (2^a)) : + LiveBundle p (n * 2^a) (bundleWord ord fit b) := by + let j : Fin (2^a) := ⟨0,Nat.two_pow_pos a⟩ + exact ⟨idWord ord fit (b,j), (numbered ord (b,j)).isLt, idWord_bundle ord p hd (b,j)⟩ + +private theorem idWord_dest (T : Directory X ord w p A fit) (e : DyadicArc V L a) : + A.dest p (idWord ord fit e) = idWord ord fit (oldPortMatching X (bitWordFinEquiv a) e) := by + rcases e with ⟨b,j⟩ + apply Fin.ext + unfold Input.dest + rw [idWord_bundle ord p T.degree] + exact translated_index X ord _ _ _ b j _ rfl T.degree (T.target b) (T.shift b) fit + +/-- A bundle accumulator sums exactly its own previously visited source ports. -/ +theorem prefixTotal_eq (T : Directory X ord w p A fit) (b : (V × L) × Fin (2 ^ a)) + (k : ℕ) (hk : k ≤ n * 2 ^ a) : + prefixTotal p A k (bundleWord ord fit b) = ∑ j : Fin (2 ^ a), + if (numbered ord (b,j)).val < k then groupedWidths (bitWordFinEquiv a) w (b,j) else 0 := by + classical + induction k with + | zero => simp [prefixTotal] + | succ k ih => + have hkn : k < n * 2 ^ a := hk + let e := (numbered ord).symm ⟨k,hkn⟩ + have he : (numbered ord e).val = k := by simp [e] + have hword : Fin.ofNat (2^bits) k = idWord ord fit e := by + apply Fin.ext + change k % 2 ^ bits = (numbered ord e).val + rw [he, Nat.mod_eq_of_lt (hkn.trans_le fit)] + have hbij (j : Fin (2^a)) : (numbered ord (b,j)).val = k ↔ (b,j) = e := by + rw [← he, Fin.val_inj, Equiv.apply_eq_iff_eq] + have hstep (j : Fin (2^a)) : + (if (numbered ord (b,j)).val < k+1 then groupedWidths (bitWordFinEquiv a) w (b,j) else 0) = + (if (numbered ord (b,j)).val < k then groupedWidths (bitWordFinEquiv a) w (b,j) else 0) + + (if (b,j) = e then groupedWidths (bitWordFinEquiv a) w (b,j) else 0) := by + simp only [← hbij j]; split_ifs <;> omega + simp_rw [hstep] + rw [Finset.sum_add_distrib, prefixTotal, ih (by omega), hword, idWord_bundle ord p T.degree, T.old] + congr 1 + have hb : bundleWord ord fit e.1 = bundleWord ord fit b ↔ e.1 = b := by + change Fin.castLE _ (ord e.1) = Fin.castLE _ (ord b) ↔ _ + rw [(Fin.castLE_injective _).eq_iff, ord.injective.eq_iff] + simp only [hb] + rcases he' : e with ⟨u,i⟩ + by_cases h : u = b + · subst u; simp + · simp [h, Ne.symm h] + +private theorem truncated_sum {D : ℕ} (f : Fin D → ℕ) (j : Fin D) : + (∑ t : Fin D, if t.val < j.val then f t else 0) = ∑ t : Fin j, f (Fin.castLE j.isLt.le t) := by + rw [← Finset.sum_filter] + apply Finset.sum_bij' (fun t ht => (⟨t.val, (Finset.mem_filter.mp ht).2⟩ : Fin j)) + (fun t _ => Fin.castLE j.isLt.le t) + all_goals first | intros; rfl | solve | simp | intro t _; exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, t.isLt⟩ + +/-- The running total at the source segment number equals the exact kernel offset. -/ +theorem prefixTotal_offset (T : Directory X ord w p A fit) (e : DyadicArc V L a) : + prefixTotal p A (idWord ord fit e).val (bundle p (idWord ord fit e)) = + (outgoingRecord X (bitWordFinEquiv a) w e).offset := by + rw [idWord_bundle ord p T.degree] + change prefixTotal p A (numbered ord e).val _ = _ + rw [prefixTotal_eq X ord w p A T _ _ (numbered ord e).isLt.le] + rcases e with ⟨b,j⟩ + change (∑ t : Fin (2^a), if (numbered ord (b,t)).val < (numbered ord (b,j)).val then _ else 0) = _ + simp_rw [numbered_val, Nat.add_lt_add_iff_left] + exact truncated_sum _ j + +/-- For the actual graph the translated rows are injective. The only numerical width +requirement is that the full concatenation of each bundle fits in a word. -/ +theorem directory_legal (T : Directory X ord w p A fit) + (room : ∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) w b j) < 2 ^ bits) : + Legal p (n * 2 ^ a) A := by + constructor + · intro i hi + obtain ⟨e,rfl⟩ := idWord_surj ord (fit := fit) i hi + rw [idWord_dest X ord w p A T] + exact (numbered ord _).isLt + · intro i j hi hj h + obtain ⟨e,rfl⟩ := idWord_surj ord (fit := fit) i hi + obtain ⟨f,rfl⟩ := idWord_surj ord (fit := fit) j hj + rw [idWord_dest X ord w p A T, idWord_dest X ord w p A T] at h + have h' := (numbered ord).injective (Fin.castLE_injective _ h) + exact congrArg (idWord ord fit) ((oldPortMatching X (bitWordFinEquiv a)).injective h') + · intro i hi + obtain ⟨e,rfl⟩ := idWord_surj ord (fit := fit) i hi + rw [T.old, prefixTotal_offset X ord w p A T] + exact (segment_fits X (bitWordFinEquiv a) w e).trans_lt (room e.1) + +/-- The complete native external pass writes the source and destination records of every +actual old arc, at cost nine per segment including call boundaries. -/ +theorem external_pass (T : Directory X ord w p A fit) (regions : Regions p (n * 2 ^ a)) + (room : ∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) w b j) < 2 ^ bits) + (m : Memory bits) (init : AtCursor p (n * 2 ^ a) A m 0) : + let M := (template visit 0).instantiate bits p + ∃ rs, runSegment M.program 33 (some 0) m (List.replicate (n * 2 ^ a) []) = some rs ∧ + RAMBuckets.cost (fun r : Report bits => countProbes r.events) rs = 9 * (n * 2 ^ a) ∧ + AtCursor p (n * 2^a) A (after m (eventLog rs)) (n * 2^a) ∧ + (∀ addr, outsideScan p (n * 2^a) addr → after m (eventLog rs) addr = m addr) ∧ + (∀ b, (cell p (after m (eventLog rs)) 4 (bundleWord ord fit b)).val = + ∑ j, bundleWidths (bitWordFinEquiv a) w b j) ∧ + ∀ e : DyadicArc V L a, + let m' := after m (eventLog rs) + let i := idWord ord fit e + let j := idWord ord fit (oldPortMatching X (bitWordFinEquiv a) e) + let r := outgoingRecord X (bitWordFinEquiv a) w e + (cell p m' 5 i).val = r.offset ∧ (cell p m' 6 j).val = r.offset ∧ + (cell p m' 7 j).val = r.width := by + have legal := directory_legal X ord w p A T room + obtain ⟨rs,hr,hc,frame,hl,hwork⟩ := scan_run regions legal init + (n * 2 ^ a) (by simp) + refine ⟨rs, hr, (scan_cost (fun r h => (hwork r h).2)).trans (by rw [hl]), by simpa only [Nat.zero_add] using hc, frame, ?_, ?_⟩ + · intro b + have hbn := bundleWord_live ord p (fit := fit) T.degree b + rw [hc.totals _ hbn, Nat.zero_add, prefixTotal_eq X ord w p A T _ _ le_rfl] + simp only [Fin.is_lt, ite_true, Fin.val_ofNat] + exact Nat.mod_eq_of_lt (room b) + intro e + have h := hc.exact legal (by simp) (idWord ord fit e) (by simp [idWord]) + rw [idWord_dest X ord w p A T, prefixTotal_offset X ord w p A T] at h + exact ⟨h.1, h.2.1, (congrArg Fin.val h.2.2).trans (T.old e)⟩ + +end CompressorRecords.PortRefresh + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshFinish.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshFinish.lean new file mode 100644 index 0000000000..4449ba3756 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshFinish.lean @@ -0,0 +1,165 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshPrepare +import OAI.Computability.VPVNP.CompressorRecordRefreshExpanderROM +import OAI.Computability.VPVNP.CompressorRecordRefreshSupplyScan +import OAI.Computability.VPVNP.CompressorRecordRefreshIncidence + +/-! +# Completing a degree refresh from its selected term records + +The selected payloads and repetition headers determine all expander widths. The fixed +expander table then gives their endpoint slots. The actual incidence scans consume those +fields and the retained external bundle directory, and the lane-zero scan recovers the base +slots of the chosen next state. Each stage receives the preceding stage's physical memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.Finish + +open BurstRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry NewSlots + +variable {bits a a₀ g dH : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (choice : DyadicRefreshChoice X E hdH conn F) + (q : Fin 8 → W bits) (termBase : W bits) (stride : ℕ) (I : AllSlots.Tables bits) + (T : IncidenceDirectory bits) + +local notation "Y" => dyadicRefreshNext X E hdH conn F hD hd choice +local notation "N" => Fintype.card X.Base * 2^a * 2^g +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "Iₛ" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) E hdH conn F choice +local notation "kind" => (fun k : Fin (2^a₀) => kindOf (Equiv.symm (refreshSlots hd) k)) +local notation "pub" => (fun k : Fin (2^a₀) => AllSlots.words (2^a) (2^g) I T (Equiv.symm (refreshSlots hd) k)) +local notation "supplyPub" => SupplyScan.params (2^a) (2^g) dH termBase stride F.selectorBits I.supply + +/-- The two fixed expander output intervals, in the representation used by its ROM pass. -/ +def ROMOutside (n addr : ℕ) : Prop := + (addr < I.targetPort.val ∨ I.targetPort.val+n ≤ addr) ∧ + (addr < I.reverseSlot.val ∨ I.reverseSlot.val+n ≤ addr) + +/-- An address outside the supply, expander, actual incidence and base incidence writes. -/ +structure Outside (addr : ℕ) : Prop where + supply : SupplyScan.Outside supplyPub (N*dH) addr + rom : ROMOutside I (2^a*dH) addr + actual : AllSlots.Outside T (N*2^a₀) addr + base : BaseOutput.Outside T Y addr + +/-- The segment and supply input columns survive until consumed, and the seven +segment columns remain accessible for the refresh kernel after all writes. -/ +structure Layout : Prop where + targetBase : I.target = q 2 + totalBase : I.total = q 4 + dims : AllSlots.Fits (a₀ := a₀) X bits + supplyApart : SupplyScan.Apart supplyPub (N*dH) + romRegions : ExpanderROM.Regions I (2^a*dH) + romSupply : ∀ j : W bits, j.val < N*dH → ROMOutside I (2^a*dH) (I.supply+j).val + incidence : T.Layout Y + slotReads : AllSlots.InputsApart T kind pub N + segments : ∀ c : Fin 8, c ≠ 0 → ∀ j : W bits, j.val < N*2^a → + Outside X E hdH conn F hD hd choice termBase stride I T (q c+j).val + +/-- The four stages' individual executions, together with their order in the common +report list. The ROM report is indexed by the fixed outgoing expander edge. -/ +def Run (initial : Memory bits) (reports : List (Report bits)) : Prop := + ∃ ss es os bs, + let m₁ := after initial (eventLog ss) + let m₂ := after m₁ (eventLog es) + let m₃ := after m₂ (eventLog os) + reports = ss ++ es ++ (os ++ bs) ∧ + runSegment ((template SupplyScan.visit 0).instantiate bits supplyPub).program 34 + (some 0) initial (List.replicate (N*dH) []) = some ss ∧ + ExpanderROM.runRows E I (some 0) m₁ (List.finRange (2^a*dH)) = some es ∧ + AllSlots.Runs kind pub N (List.finRange (2^a₀)) m₂ os ∧ + runSegment ((template BaseOutput.visit 0).instantiate bits (BaseOutput.params T a₀ g)).program + 29 (some 0) m₃ (List.replicate (BaseOutput.baseCount Y) []) = some bs + +private theorem append_memory (m : Memory bits) (x y : List (Report bits)) : + after m (eventLog (x++y)) = after (after m (eventLog x)) (eventLog y) := by + change List.foldl BurstRAM.update m ((x++y).flatMap Report.events) = _ + rw [List.flatMap_append,List.foldl_append]; rfl + +/-- The supply pass and fixed expander ROM produce exactly the inputs read +by the subsequent slot workers, in their actual shared memory. -/ +theorem supply_and_rom (m : Memory bits) (fit : N*2^a ≤ 2^bits) (segments : SegmentFields X q fit m) + (terms : SupplyScan.TermFields X E hdH conn F choice termBase stride m) + (layout : Layout X E hdH conn F hD hd choice q termBase stride I T) + (widthFit : ∀ (s : (X.Base × BitWord g) × Fin (2^a)) (k : Fin dH), Iₛ s.1 (s.2,k) < 2^bits) : + ∃ ss es, + let m₁ := after m (eventLog ss) + let m₂ := after m₁ (eventLog es) + runSegment ((template SupplyScan.visit 0).instantiate bits supplyPub).program 34 + (some 0) m (List.replicate (N*dH) []) = some ss ∧ + ExpanderROM.runRows E I (some 0) m₁ (List.finRange (2^a*dH)) = some es ∧ + AllSlots.SourceTables X E hdH conn F choice I m₂ ∧ + (∀ addr, Outside X E hdH conn F hD hd choice termBase stride I T addr → m₂ addr = m addr) ∧ + RAMBuckets.cost Report.probes ss = 4*(N*dH) ∧ RAMBuckets.cost Report.probes es = 3*(2^a*dH) := by + have dims : SupplyScan.Fits (dH := dH) X bits := + ⟨layout.dims.ports,layout.dims.lanes,lt_of_lt_of_le (by omega : dH < 2^a₀) layout.dims.degree.le, + (Nat.mul_le_mul_left _ (by omega : dH ≤ 2^a₀)).trans layout.dims.ids⟩ + obtain ⟨ss,srun,swidth,sframe,scost,_,_⟩ := SupplyScan.supply_pass X E hdH conn F choice + termBase stride I.supply m terms dims layout.supplyApart widthFit + let m₁ := after m (eventLog ss) + let es := (List.finRange (2^a*dH)).map (ExpanderROM.report E I) + let m₂ := after m₁ (eventLog es) + obtain ⟨erun,rom,rframe,rcost⟩ := ExpanderROM.initialize_expander E I layout.romRegions m₁ + have preFrame (addr : ℕ) (ho : Outside X E hdH conn F hD hd choice termBase stride I T addr) : + m₂ addr = m addr := (rframe addr ho.rom.1 ho.rom.2).trans (sframe addr ho.supply) + have seg₂ : SegmentFields X q fit m₂ := + segments.transfer X q (fun c hc j hj => preFrame _ (layout.segments c hc j hj)) + have index (s : (X.Base × BitWord g) × Fin (2^a)) : word (bits := bits) (O s).val = bundleWord O fit s := + Fin.ext (Nat.mod_eq_of_lt (bundleWord O fit s).isLt) + have src : AllSlots.SourceTables X E hdH conn F choice I m₂ := by + constructor + · intro b; rw [layout.targetBase,index]; exact seg₂.target b + · intro b; rw [layout.totalBase,index]; exact seg₂.total b + · exact rom.targetPort + · exact rom.reverseSlot + · intro s k + let i : W bits := word ((O s).val*dH+k.val) + have num : (finProdFinEquiv (O s,k)).val = (O s).val*dH+k.val := by change k.val+dH*(O s).val = _; ring + have hi : i.val < N*dH := (Nat.mod_le ..).trans_lt (num ▸ (finProdFinEquiv (O s,k)).isLt) + have ho := layout.romSupply i hi + change (m₂ (I.supply+i).val).val = _ + rw [show m₂ (I.supply+i).val = m₁ (I.supply+i).val from rframe _ ho.1 ho.2] + exact swidth s k + exact ⟨ss,es,srun,erun,src,preFrame,scost,rcost⟩ + +/-- From selected term records and the old segment fields, the post-term phase produces +the six-column incidence directory of the chosen dyadic state. The final memory retains +the segment offsets and preserves every address outside the reserved output columns. -/ +theorem finish (m : Memory bits) (fit : N*2^a ≤ 2^bits) (segments : SegmentFields X q fit m) + (terms : SupplyScan.TermFields X E hdH conn F choice termBase stride m) + (layout : Layout X E hdH conn F hD hd choice q termBase stride I T) + (widthFit : ∀ (s : (X.Base × BitWord g) × Fin (2^a)) (k : Fin dH), Iₛ s.1 (s.2,k) < 2^bits) : + ∃ rs, Run X E hdH conn F hD hd choice termBase stride I T m rs ∧ + T.Represents Y (after m (eventLog rs)) ∧ SegmentFields X q fit (after m (eventLog rs)) ∧ + (∀ addr, Outside X E hdH conn F hD hd choice termBase stride I T addr → after m (eventLog rs) addr = m addr) ∧ + RAMBuckets.cost Report.probes rs = + 4*(N*dH) + 3*(2^a*dH) + ((6+7*dH+4*(2^a₀-(dH+1)))*X.positions + 5*BaseOutput.baseCount Y) := by + obtain ⟨ss,es,srun,erun,src,preFrame,scost,rcost⟩ := + supply_and_rom X E hdH conn F hD hd choice q termBase stride I T m fit segments terms layout widthFit + let m₁ := after m (eventLog ss) + let m₂ := after m₁ (eventLog es) + obtain ⟨os,bs,orun,brun,rep,iframe,icost⟩ := + incidence_output X E hdH conn F hD hd choice I T m₂ src layout.dims layout.incidence layout.slotReads + let rs := ss ++ es ++ (os ++ bs) + have finalMem : after m (eventLog rs) = after (after m₂ (eventLog os)) (eventLog bs) := by + simp only [rs,m₂,m₁,append_memory] + have frame (addr) (ho : Outside X E hdH conn F hD hd choice termBase stride I T addr) : + after m (eventLog rs) addr = m addr := by + rw [finalMem] + exact (iframe addr ho.actual ho.base).trans (preFrame addr ho) + refine ⟨rs,⟨ss,es,os,bs,rfl,srun,erun,orun,brun⟩,finalMem ▸ rep, + segments.transfer X q (fun c hc i hi => frame _ (layout.segments c hc i hi)),frame,?_⟩ + change RAMBuckets.cost Report.probes ((ss++es)++(os++bs)) = _ + rw [RAMBuckets.cost_append,RAMBuckets.cost_append,scost,rcost,icost] + +end CompressorRecords.PortRefresh.Finish + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshIncidence.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshIncidence.lean new file mode 100644 index 0000000000..7a6460e6e9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshIncidence.lean @@ -0,0 +1,58 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshAllSlots +import OAI.Computability.VPVNP.CompressorRecordRefreshBaseOutput +import OAI.Computability.VPVNP.CompressorRecordRefreshInputs + +/-! +# The six incidence columns after degree refresh + +The selected supply widths and completed external bundles feed every numbered actual slot +writer. A final pass reads the outgoing arcs on lane zero and recovers the base permutation, +its inverse and its residual-lane shifts. The output is the common directory expected by the +next shrinking pass, at the precise state selected by this term of the refresh. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh + +open BurstRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry + +variable {bits a a₀ g dH : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (choice : DyadicRefreshChoice X E hdH conn F) + (I : AllSlots.Tables bits) (T : IncidenceDirectory bits) (mem : Memory bits) + +local notation "Y" => dyadicRefreshNext X E hdH conn F hD hd choice +local notation "N" => Fintype.card X.Base * 2^a * 2^g +local notation "kind" => (fun k : Fin (2^a₀) => NewSlots.kindOf (Equiv.symm (refreshSlots hd) k)) +local notation "pub" => (fun k : Fin (2^a₀) => AllSlots.words (2^a) (2^g) I T (Equiv.symm (refreshSlots hd) k)) + +/-- All actual slot passes and the base-output pass, in their execution order. Both levels +of incidence and all actual widths are available by direct addressing in the final memory. -/ +theorem incidence_output (src : AllSlots.SourceTables X E hdH conn F choice I mem) + (fit : AllSlots.Fits (a₀ := a₀) X bits) (layout : T.Layout Y) + (apart : AllSlots.InputsApart T kind pub N) : + let M := (template BaseOutput.visit 0).instantiate bits (BaseOutput.params T a₀ g) + ∃ slotReports baseReports, + let m₁ := after mem (eventLog slotReports) + let m₂ := after m₁ (eventLog baseReports) + AllSlots.Runs kind pub N (List.finRange (2^a₀)) mem slotReports ∧ + runSegment M.program 29 (some 0) m₁ (List.replicate (BaseOutput.baseCount Y) []) = some baseReports ∧ + T.Represents Y m₂ ∧ + (∀ addr, AllSlots.Outside T (N * 2^a₀) addr → BaseOutput.Outside T Y addr → m₂ addr = mem addr) ∧ + RAMBuckets.cost Report.probes (slotReports ++ baseReports) = + (6 + 7*dH + 4*(2^a₀-(dH+1))) * X.positions + 5 * BaseOutput.baseCount Y := by + obtain ⟨s,hs,actual,fs,cs⟩ := AllSlots.all_slots X E hdH conn F hD hd choice I T mem src fit layout apart + obtain ⟨b,hb,rep,fb,cb,_,_⟩ := BaseOutput.base_pass T Y (after mem (eventLog s)) layout actual + refine ⟨s,b,hs,hb,rep,fun addr ho ht => (fb addr ht).trans (fs addr ho), ?_⟩ + exact (RAMBuckets.cost_append Report.probes s b).trans (congrArg₂ (· + ·) cs cb) + +end CompressorRecords.PortRefresh + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshInputs.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshInputs.lean new file mode 100644 index 0000000000..0ec86fc190 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshInputs.lean @@ -0,0 +1,90 @@ +import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout +import OAI.Computability.VPVNP.CompressorRecordRefreshPhases + +/-! +# Reading the common incidence directory at a degree refresh + +The external pass obtains its gathered width directly from the site's outgoing width column. +The outgoing base mate and the packed old displacement are the two base inputs of the bundle +pass. Both are already present in a represented cursor, shrink or refresh state. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.IncidenceDirectory + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PortRefresh + +variable {bits a g : ℕ} (X : State a (a+g)) (T : IncidenceDirectory bits) (m : Memory bits) + +private theorem base_parts (b : X.Base × Fin (2^a)) : + (baseOrder X b).val / 2^a = (X.baseIndex b.1).val ∧ (baseOrder X b).val % 2^a = b.2.val := by + rw [baseOrder_val] + refine ⟨?_,Nat.mul_add_mod_of_lt b.2.isLt⟩ + rw [Nat.mul_comm, Nat.mul_add_div (Nat.two_pow_pos a), Nat.div_eq_of_lt b.2.isLt, Nat.add_zero] + +/-- Read a natural width directly from the directory's actual width column. -/ +theorem Represents.refresh_widths (rep : T.Represents X m) (q : Fin 4 → BurstRAM.Word bits) + (old : q 2 = T.width) (room : ∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j) < 2^bits) : + RefreshGather.HasOldWidths X (baseOrder X) q m := by + intro b l + let parts := splitBitWord a g l + let s := ((b.1,parts.2),b.2) + let j := bitWordFinEquiv a parts.1 + have width : bundleWidths (bitWordFinEquiv a) (splitWidths X) s j = X.width (b,l) := by + change X.width ((b.1,b.2),(splitBitWord a g).symm ((bitWordFinEquiv a).symm j,parts.2)) = _ + simp [j,parts] + have bound := (Finset.single_le_sum (s := Finset.univ) (fun _ _ => Nat.zero_le _) + (Finset.mem_univ j) (f := bundleWidths (bitWordFinEquiv a) (splitWidths X) s)).trans_lt (room s) + rw [width] at bound + simp only [old, (base_parts X b).1, (base_parts X b).2] + change (m (T.width + actualPort X ((b.1,l),b.2)).val).val = _ + rw [rep.width] + exact Nat.mod_eq_of_lt bound + +/-- The directory's outgoing base mate and old displacement supply the bundle initializer. -/ +theorem Represents.refresh_base (rep : T.Represents X m) (q : Fin 8 → BurstRAM.Word bits) + (lanes : (q 0).val = 2^g) (mate : q 1 = T.baseOut) (disp : q 5 = T.shift) + (room : Fintype.card X.Base * 2^a ≤ 2^bits) (wide : 2^(a+g) ≤ 2^bits) : + BundleDirectory.BaseTables (splitSlots X) (baseOrder X) q m := by + apply BundleDirectory.BaseTables.ofOld (baseOrder X) q X.slots m lanes + · intro b + change (m (q 1 + CursorRAM.encode bits (baseOrder X b).val).val).val = _ + rw [mate, ← basePort_number, rep.baseOut, basePort_number] + exact Nat.mod_eq_of_lt ((baseOrder X _).isLt.trans_le room) + · intro b + change (m (q 5 + CursorRAM.encode bits (baseOrder X b).val).val).val = _ + rw [disp, ← basePort_number, rep.shift] + exact Nat.mod_eq_of_lt ((bitWordFinEquiv (a+g) _).isLt.trans_le wide) + +/-- From an arbitrary represented old state, the native external construction produces +all refreshed bundle targets, widths and both endpoint segment tables in shared memory. -/ +theorem Represents.external_execution (rep : T.Represents X m) (p : Fin 8 → BurstRAM.Word bits) + (lanes : BurstRAM.Word bits) (degree : (p 0).val = 2^a) (residual : lanes.val = 2^g) + (regions : RefreshRAM.Regions p (Fintype.card X.Base * 2^a * 2^g * 2^a)) + (dirLayout : BundleDirectory.Layout (directoryWords p lanes T.baseOut T.shift) + (Fintype.card X.Base * 2^a) (2^g)) + (wireApart : RefreshGather.SourcesDisjoint (gatherWords p lanes T.width) (Fintype.card X.Base * 2^a * 2^g * 2^a)) + (baseApart : baseOutsideGather X (baseOrder X) p T.baseOut T.shift) + (room : ∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j) < 2^bits) : + ExternalExecution X (baseOrder X) p lanes T.width T.baseOut T.shift m regions.fits := by + have ha := Nat.two_pow_pos a + have hg := Nat.two_pow_pos g + let V := Fintype.card X.Base + have hv : 0 < V := Fintype.card_pos + have bound : V * 2^a * 2^g ≤ 2^bits := (Nat.le_mul_of_pos_right _ ha).trans regions.fits + have hbase := (Nat.le_mul_of_pos_right (V * 2^a) hg).trans bound + have hlanes : 2^(a+g) ≤ 2^bits := by + rw [pow_add, Nat.mul_assoc] at * + exact (Nat.le_mul_of_pos_left _ hv).trans bound + apply external_phases X (baseOrder X) p lanes T.width T.baseOut T.shift degree residual regions dirLayout m + (rep.refresh_widths X T m _ rfl room) _ wireApart baseApart room + exact rep.refresh_base X T m _ residual rfl rfl hbase hlanes + +end CompressorRecords.IncidenceDirectory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshLifetime.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshLifetime.lean new file mode 100644 index 0000000000..3a5a6ffb88 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshLifetime.lean @@ -0,0 +1,99 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshBuild + +/-! +# Retaining an earlier refresh level for the history traversal + +The old segment columns, dense demands and selected term descriptors occupy the interval +from the allocation start up to the selected-supply column. Agreement on this interval +transfers every refresh field required by a later depth-first traversal. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.Build + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry +open NewSlots RefreshRAM Allocation + +variable {bits a a₀ g dH t : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} + {X : State a (a+g)} {E : RegularArcGraph (Fin (2^a)) dH} {hdH : 0 < dH} + {conn : (arcSupportGraph E.multiplicity).Connected} + {F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K'} + {choice : DyadicRefreshChoice X E hdH conn F} + {ties : Fin t ≃ Tie (2^a)} {start stride : ℕ} {m m' : Memory bits} + +local notation "P" => plan X a₀ dH t stride start +local notation "Q" => Plan.scratch P bits +local notation "B" => Fintype.card X.Base * 2^g +local notation "S" => Fintype.card X.Base * 2^a * 2^g * 2^a +local notation "demandBase" => word (bits := bits) (Plan.demand P) +local notation "termBase" => word (bits := bits) (Plan.term P) + +/-- A later memory contains the same segment rows, demands, grid and repetition +headers, and payload coordinates whenever it agrees on their allocated interval. -/ +theorem Stored.transfer {fit : S ≤ 2^bits} (data : Stored X E hdH conn F choice ties start stride fit m) + (wide : 2+2^a*dH ≤ stride) (room : (P).stop ≤ 2^bits) + (same : ∀ addr, start ≤ addr → addr < (P).supply → m' addr = m addr) : + Stored X E hdH conn F choice ties start stride fit m' := by + have capPos : 0 < (P).capacity := by change 0 < Fintype.card X.Base*2^a*2^g*2^a₀; positivity + have upto : (P).supply < 2^bits := by + dsimp only [Plan.stop,Plan.next,Plan.reverseSlot,Plan.targetPort] at room; omega + have h₀ : start ≤ (P).demand := Nat.le_add_right .. + have h₁ : (P).demand+B*t = (P).term := rfl + have h₂ : (P).term+B*stride = (P).supply := rfl + have db : (demandBase).val = (P).demand := Nat.mod_eq_of_lt (by omega) + have tb : (termBase).val = (P).term := Nat.mod_eq_of_lt (by omega) + have terms (s : X.Base × BitWord g) : + start ≤ (SupplyScan.recordBase X termBase stride s).val ∧ + (SupplyScan.recordBase X termBase stride s).val+stride ≤ (P).supply := by + let i := (DemandScan.blocks X s).val + have step := Nat.mul_le_mul_right stride (Nat.succ_le_of_lt (DemandScan.blocks X s).isLt) + rw [Nat.succ_mul] at step + have inside : (P).term+i*stride < 2^bits := by dsimp only [i]; omega + have head : (SupplyScan.recordBase X termBase stride s).val = (P).term+i*stride := by + rw [SupplyScan.recordBase,← DemandScan.blocks_val,Fin.val_add,Fin.val_mul,tb] + change ((P).term + ((i % 2^bits * (stride % 2^bits)) % 2^bits)) % 2^bits = _ + rw [Nat.mod_mul_mod,Nat.mul_mod_mod,Nat.add_mod_mod,Nat.mod_eq_of_lt inside] + rw [head]; dsimp only [i]; constructor <;> omega + constructor + · apply SegmentFields.transfer X Q data.segments + intro c hc i hi + obtain ⟨lower,upper⟩ := (P).scratch_interval (by omega : (P).demand ≤ 2^bits) c hc i hi + exact same _ lower (by omega) + · intro s + funext e + let i := (DemandScan.blocks X s).val + have step := Nat.mul_le_mul_right t (Nat.succ_le_of_lt (DemandScan.blocks X s).isLt) + rw [Nat.succ_mul] at step + have inside : (P).demand+i*t < 2^bits := by dsimp only [i]; omega + have head : (DemandScan.rowBase X t demandBase s).val = (P).demand+i*t := by + rw [DemandScan.rowBase,Fin.val_add,db,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt inside] + obtain ⟨j,rfl⟩ := ties.surjective e + have fits := DemandScan.rowBase_fits X demandBase (by rw [db]; omega : (demandBase).val+B*t ≤ 2^bits) s + have cell := DemandPreparation.demandAt_address ties (DemandScan.rowBase X t demandBase s) m fits j + have cell' := DemandPreparation.demandAt_address ties (DemandScan.rowBase X t demandBase s) m' fits j + rw [cell',same _ (by rw [head]; omega) (by rw [head]; dsimp only [i]; have := j.isLt; omega),← cell,data.demands] + · refine ⟨data.terms.fits,fun s => ?_,fun s e => ?_⟩ + · obtain ⟨lo,hi⟩ := terms s + rw [same _ (by omega) (by omega)] + exact data.terms.repetitions s + · obtain ⟨lo,hi⟩ := terms s + have h := Nat.mul_le_mul_right dH e.1.isLt + rw [Nat.succ_mul] at h + have hk := e.2.isLt + rw [same _ (by omega) (by omega)] + exact data.terms.payload s e + · intro s + obtain ⟨lo,hi⟩ := terms s + refine ⟨?_,?_,fun j => ?_⟩ + · rw [same _ lo (by omega)]; exact (data.readback s).1 + · rw [same _ (by omega) (by omega)]; exact (data.readback s).2.1 + · rw [same _ (by omega) (by have := j.isLt; omega)]; exact (data.readback s).2.2 j + +end CompressorRecords.PortRefresh.Build + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshNewSlots.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshNewSlots.lean new file mode 100644 index 0000000000..7145022a70 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshNewSlots.lean @@ -0,0 +1,634 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshDirectory +import OAI.Computability.VPVNP.CompressorRecordRefreshTerms + +/-! +# Native writes of the refreshed endpoint and width tables + +Each visit takes a bundle (new site) number as its persistent cursor. The bundle +order is old base vertex, port, residual lane. At a fixed local slot, one call +writes the translated incoming identifier, the inverse link and the actual +width. The expander's two fixed columns are indexed by port and expander slot. +The selected supply widths are indexed by the full site and expander slot. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.NewSlots + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open Compression Compression.Refresh Compression.DegreeRefresh + +variable {bits : ℕ} + +/-- The fixed-width machine word used for refreshed slot addresses and widths. -/ +abbrev W (bits : ℕ) := BurstRAM.Word bits +/-- The thirteen public words supplying dimensions, a local slot index, and the input and +output column heads. -/ +abbrev Public (bits : ℕ) := Fin 13 → W bits + +/-- The local index is zero for the external slot, an expander-edge number +for an internal slot, and a padding-copy number for a padding slot. -/ +inductive Kind where | external | expander | padding + +/-- Columns 10 and 11 map an outgoing identifier to its incoming identifier +and vice versa. Column 12 stores the width at the outgoing identifier. -/ +structure Row (bits : ℕ) where + /-- Packed outgoing slot identifier for this incidence row. -/ + src : W bits + /-- Packed incoming slot identifier at the opposite end of this incidence row. -/ + dst : W bits + /-- The word encoding the number of bits carried by the arc. -/ + width : W bits + +/-- Write the two directed mate links and the outgoing width for the row. -/ +def Row.update (p : Public bits) (m : Memory bits) (s : Row bits) : Memory bits := + writeMemory (writeMemory (writeMemory m (p 10 + s.src) s.dst) (p 11 + s.dst) s.src) + (p 12 + s.src) s.width + +/-- Read the dimensions, target/total arrays, fixed expander and selected supply +tables. Arithmetic is word arithmetic, including the cyclic padding rotation. -/ +def row (kind : Kind) (p : Public bits) (m : Memory bits) (b : W bits) : Row bits := + let base := BinaryOp.div.eval b (p 3) + let j := BinaryOp.mod.eval base (p 0) + let vertex := BinaryOp.div.eval base (p 0) + let lane := BinaryOp.mod.eval b (p 3) + let site := fun t => (vertex * p 0 + t) * p 3 + lane + match kind with + | .external => ⟨b * p 2, m (p 5 + b).val * p 2, m (p 6 + b).val⟩ + | .expander => + let e := j * p 1 + p 4 + let t := m (p 7 + e).val + let h := m (p 8 + e).val + ⟨b * p 2 + (p 4 + 1), site t * p 2 + (h + 1), m (p 9 + (b * p 1 + p 4)).val⟩ + | .padding => + let k := p 1 + p 4 + 1 + ⟨b * p 2 + k, site (BinaryOp.mod.eval (j + 1) (p 0)) * p 2 + k, 0⟩ + +/-- Load the base vertex (register 4), port (5), and lane (6) from the site cursor. -/ +private def decode : List (Op 12 13) := + [.stateWord 0, .publicWord 7 3, .binary .div 4 0 7, .binary .mod 6 0 7, + .publicWord 8 0, .binary .mod 5 4 8, .binary .div 4 4 8, .binary .mul 4 4 8] + +/-- Register 5 now carries the target port. Restore the target site (register 2) +while preserving the lane. -/ +private def restore : List (Op 12 13) := + [.binary .add 2 4 5, .binary .mul 2 2 7, .binary .add 2 2 6] + +private def prepare : Kind → List (Op 12 13) + | .external => + [.stateWord 0, .publicWord 4 5, .binary .add 4 4 0, .read 2 4, + .publicWord 4 6, .binary .add 4 4 0, .read 3 4, .publicWord 4 2, + .binary .mul 1 0 4, .binary .mul 2 2 4] + | .expander => + decode ++ [.publicWord 9 1, .publicWord 10 4, .binary .mul 11 5 9, + .binary .add 11 11 10, .publicWord 3 7, .binary .add 3 3 11, .read 5 3, + .publicWord 3 8, .binary .add 3 3 11, .read 11 3] ++ restore ++ + [.binary .mul 3 0 9, .binary .add 3 3 10, .publicWord 4 9, .binary .add 4 4 3, + .read 3 4, .constant 6 1, .binary .add 10 10 6, .binary .add 11 11 6, + .publicWord 4 2, .binary .mul 1 0 4, .binary .add 1 1 10, + .binary .mul 2 2 4, .binary .add 2 2 11] + | .padding => + decode ++ [.constant 9 1, .binary .add 5 5 9, .binary .mod 5 5 8] ++ restore ++ + [.publicWord 10 1, .publicWord 11 4, .binary .add 10 10 11, .binary .add 10 10 9, + .publicWord 4 2, .binary .mul 1 0 4, .binary .add 1 1 10, + .binary .mul 2 2 4, .binary .add 2 2 10, .constant 3 0] + +/-- Fixed tables of instructions. Public words 0–4 give the port count, +expander degree, new degree, residual lane count and the local copy index. +Words 5–9 give bases of the external target, external total, expander target +port, expander reverse slot and selected supply width arrays. Words 10–12 +locate the forward link, inverse link and width arrays. -/ +def code (kind : Kind) : List (Op 12 13) := + prepare kind ++ [.publicWord 4 10, .binary .add 4 4 1, .write 4 2, + .publicWord 4 11, .binary .add 4 4 2, .write 4 1, + .publicWord 4 12, .binary .add 4 4 1, .write 4 3, .constant 4 1, .binary .add 0 0 4] + +private def ticks (n : ℕ) : List (Event bits) := List.replicate n .tick + +/-- The native read and write events for one external, expander, or padding slot at the current +site. -/ +def events (kind : Kind) (p : Public bits) (m : Memory bits) (b : W bits) : List (Event bits) := + let read := fun a : W bits => Event.read a (m a.val) + let before := match kind with + | .external => ticks 3 ++ [read (p 5 + b)] ++ ticks 2 ++ [read (p 6 + b)] ++ ticks 3 + | .expander => + let j := BinaryOp.mod.eval (BinaryOp.div.eval b (p 3)) (p 0) + let e := j * p 1 + p 4 + ticks 14 ++ [read (p 7 + e)] ++ ticks 2 ++ [read (p 8 + e)] ++ ticks 7 ++ + [read (p 9 + (b * p 1 + p 4))] ++ ticks 8 + | .padding => ticks 24 + let s := row kind p m b + before ++ ticks 2 ++ [.write (p 10 + s.src) s.dst] ++ ticks 2 ++ + [.write (p 11 + s.dst) s.src] ++ ticks 2 ++ [.write (p 12 + s.src) s.width] ++ ticks 2 + +theorem events_work (kind : Kind) (p : Public bits) (m : Memory bits) (b : W bits) : + (events kind p m b).length = (match kind with | .external => 21 | .expander => 45 | .padding => 35) ∧ + countProbes (events kind p m b) = (match kind with | .external => 5 | .expander => 6 | .padding => 3) := by + cases kind <;> simp [events, countProbes, ticks] + +theorem events_after (kind : Kind) (p : Public bits) (m : Memory bits) (b : W bits) : + after m (events kind p m b) = (row kind p m b).update p m := by + cases kind <;> rfl + +set_option maxRecDepth 8192 in +private theorem code_trace (kind : Kind) (p : Public bits) (m : Memory bits) + (b : W bits) (regs : Regs bits 12) : + ∃ rs, trace p b (code kind) regs m = + some (events kind p m b, rs, (row kind p m b).update p m) ∧ rs 0 = b + 1 := by + cases kind <;> + simp (config := {decide := true}) [code, prepare, decode, restore, trace, Op.effect, + row, Row.update, events, ticks, BinaryOp.eval, Function.update] <;> repeat' constructor + +/-- One native call from fresh private memory, including its full event sequence. -/ +theorem native (kind : Kind) (p : Public bits) (m : Memory bits) (b : W bits) : + let M := (template (code kind) 0).instantiate bits p + execute M.program (1 + (code kind).length) (M.program.start b) m [] = + some ⟨events kind p m b, some (b + 1)⟩ := by + obtain ⟨rs, ht, hr⟩ := code_trace kind p m b (fun _ => 0) + let M := (template (code kind) 0).instantiate bits p + change execute M.program (1 + (code kind).length) ⟨M.entry,b,fun _ => 0,fun _ => 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hr] + +/-- Read back the two endpoint links and the width after this native call. +The inequalities separate the three actual output cells, including at loops +of the numerical permutation. -/ +theorem written (kind : Kind) (p : Public bits) (m : Memory bits) (b : W bits) + (oi : p 10 + (row kind p m b).src ≠ p 11 + (row kind p m b).dst) + (ow : p 10 + (row kind p m b).src ≠ p 12 + (row kind p m b).src) + (iw : p 11 + (row kind p m b).dst ≠ p 12 + (row kind p m b).src) : + let s := row kind p m b + let m' := after m (events kind p m b) + m' (p 10 + s.src).val = s.dst ∧ m' (p 11 + s.dst).val = s.src ∧ m' (p 12 + s.src).val = s.width := by + dsimp only + rw [events_after] + simp [Row.update, writeMemory, Fin.val_inj, oi, ow, iw] + +section Graph + +variable {V H L : Type} {n r D dH d₀ : ℕ} +variable (vertices : V ≃ Fin n) (lanes : L ≃ Fin r) + +/-- The external directory enumerates the base arc before the residual lane. -/ +def sites : (V × L) × Fin D ≃ Fin (n * D * r) := + let base := (vertices.prodCongr (Equiv.refl (Fin D))).trans finProdFinEquiv + promotedSites.trans ((base.prodCongr lanes).trans finProdFinEquiv) + +/-- The endpoint identifiers range bijectively over the refreshed half-slots. -/ +def arcs : ActualArc V L D d₀ ≃ Fin (n * D * r * d₀) := + let site := promotedSites.symm.trans (sites (D := D) vertices lanes) + (site.prodCongr (Equiv.refl _)).trans finProdFinEquiv + +theorem sites_val (s : (V × L) × Fin D) : + (sites vertices lanes s).val = + ((vertices s.1.1).val * D + s.2.val) * r + (lanes s.1.2).val := by + change (lanes s.1.2).val + r * (s.2.val + D * (vertices s.1.1).val) = _ + ring + +theorem arcs_val (s : (V × L) × Fin D) (k : Fin d₀) : + (arcs vertices lanes (promotedSites s,k)).val = (sites vertices lanes s).val * d₀ + k.val := by + change k.val + d₀ * (sites vertices lanes s).val = _ + ring + +/-- Embed a numerical array index into a word. -/ +abbrev word (a : ℕ) : W bits := Fin.ofNat _ a + +/-- With product-order base slots, the binary directory and new slots have +identical site numbers. -/ +theorem bundleOrder_sites (a g : ℕ) : + bundleOrder g ((vertices.prodCongr (Equiv.refl (Fin (2^a)))).trans finProdFinEquiv) = + sites vertices (bitWordFinEquiv g) := by + ext x + rfl + +private theorem add_word (a b : ℕ) : word a + word b = word (bits := bits) (a+b) := + Fin.ext (Nat.add_mod a b (2 ^ bits)).symm + +private theorem mul_word (a b : ℕ) : word a * word b = word (bits := bits) (a*b) := + Fin.ext (Nat.mul_mod a b (2 ^ bits)).symm + +private theorem unit_word (a : ℕ) : word a + 1 = word (bits := bits) (a+1) := add_word a 1 + +private theorem asWord (x : W bits) : x = word x.val := + Fin.ext (Nat.mod_eq_of_lt x.isLt).symm + +private theorem div_mod_pack (x stride : W bits) {q d u : ℕ} + (h : x.val = q * d + u) (hs : stride.val = d) (hu : u < d) : + BinaryOp.div.eval x stride = word q ∧ BinaryOp.mod.eval x stride = word u := by + have hd : 0 < d := Nat.zero_lt_of_lt hu + constructor <;> apply Fin.ext + · change (x.val / stride.val) % _ = q % _ + rw [h, hs, Nat.mul_comm q, Nat.mul_add_div hd, Nat.div_eq_of_lt hu, Nat.add_zero] + · change (x.val % stride.val) % _ = u % _ + rw [h, hs, Nat.mul_add_mod_of_lt hu] + +/-- Public constants common to the three scans. The whole interval of output +half-slot identifiers fits in the address word. -/ +structure Dimensions (p : Public bits) (n D r dH d₀ : ℕ) : Prop where + ports : (p 0).val = D + expander : (p 1).val = dH + degree : (p 2).val = d₀ + lanes : (p 3).val = r + fits : n * D * r * d₀ ≤ 2 ^ bits + +variable {p : Public bits} {m : Memory bits} +variable (hD : 1 < D) (hd : dH + 1 ≤ d₀) (dim : Dimensions p n D r dH d₀) + +include hd dim in +private theorem decode_exact (s : (V × L) × Fin D) : + let b := word (bits := bits) (sites vertices lanes s).val + let base := BinaryOp.div.eval b (p 3) + BinaryOp.div.eval base (p 0) = word (vertices s.1.1).val ∧ + BinaryOp.mod.eval base (p 0) = word s.2.val ∧ + BinaryOp.mod.eval b (p 3) = word (lanes s.1.2).val := by + let v := (vertices s.1.1).val + let l := (lanes s.1.2).val + have hl : l < r := (lanes s.1.2).isLt + have hfit := (sites vertices lanes s).isLt.trans_le + ((Nat.le_mul_of_pos_right (n*D*r) (by omega : 0 < d₀)).trans dim.fits) + have hq : v * D + s.2.val < 2 ^ bits := by + have hle := Nat.le_mul_of_pos_right (v * D + s.2.val) (Nat.zero_lt_of_lt hl) + rw [sites_val] at hfit + dsimp [v] at hle ⊢ + omega + have hval : (word (bits := bits) (sites vertices lanes s).val).val = (v * D + s.2.val) * r + l := + (Nat.mod_eq_of_lt hfit).trans (sites_val vertices lanes s) + obtain ⟨hb,hlane⟩ := div_mod_pack _ _ hval dim.lanes hl + obtain ⟨hv,hj⟩ := div_mod_pack (word (bits := bits) (v * D + s.2.val)) (p 0) + (Nat.mod_eq_of_lt hq) dim.ports s.2.isLt + exact ⟨hb ▸ hv, hb ▸ hj, hlane⟩ + +private theorem extNumber (hd : dH + 1 ≤ d₀) : + (refreshSlots hd (.inl 0)).val = 0 := rfl + +private theorem expNumber (hd : dH + 1 ≤ d₀) (k : Fin dH) : + (refreshSlots hd (.inr (.inl k))).val = k.val + 1 := by + change 1 + k.val = k.val + 1 + omega + +private theorem padNumber (hd : dH + 1 ≤ d₀) (k : Fin (d₀-(dH+1))) : + (refreshSlots hd (.inr (.inr k))).val = dH + k.val + 1 := by + change 1 + (dH + k.val) = _ + omega + +private theorem rotate_word (j : Fin D) (degree : W bits) (hdeg : degree.val = D) : + BinaryOp.mod.eval (word j.val + 1) degree = word (finRotate D j).val := by + have room := hdeg ▸ degree.isLt + have hj : j.val + 1 < 2 ^ bits := (Nat.succ_le_of_lt j.isLt).trans_lt room + let := j.neZero + apply Fin.ext + change ((word j.val + 1 : W bits).val % degree.val) % _ = (finRotate D j).val % _ + rw [unit_word, show (word (bits := bits) (j.val+1)).val = j.val+1 from Nat.mod_eq_of_lt hj, hdeg, + finRotate_apply, Fin.val_add, Fin.val_one', Nat.add_mod_mod] + +/-- Equality with the numbered graph record before writing the three cells. -/ +def Represents (s : Row bits) (record : NewSlot V L D d₀) : Prop := + s.src.val = (arcs vertices lanes record.src).val ∧ + s.dst.val = (arcs vertices lanes record.dst).val ∧ s.width.val = record.width + +private theorem represents_of_words {s : Row bits} {record : NewSlot V L D d₀} + (src : s.src = word (arcs vertices lanes record.src).val) + (dst : s.dst = word (arcs vertices lanes record.dst).val) (width : s.width.val = record.width) + (fit : n * D * r * d₀ ≤ 2 ^ bits) : Represents vertices lanes s record := by + rw [Represents,src,dst] + exact ⟨Nat.mod_eq_of_lt ((arcs vertices lanes record.src).isLt.trans_le fit), + Nat.mod_eq_of_lt ((arcs vertices lanes record.dst).isLt.trans_le fit), width⟩ + +variable [AddCommGroup L] (G : LiftedSlots V D (H × L)) (port : H ≃ Fin D) + (width : (V × Fin D) × (H × L) → ℕ) (P : SlotGraph (Fin D) dH) + (internal : V × L → Fin D × Fin dH → ℕ) + +include dim + +/-- The translated target directory and the computed prefix total are the two +input words of the external-slot visit. -/ +theorem external_record (s : (V × L) × Fin D) + (target : (m (p 5 + word (sites vertices lanes s).val).val).val = (sites vertices lanes (bundleTarget G s)).val) + (total : (m (p 6 + word (sites vertices lanes s).val).val).val = ∑ j, bundleWidths port width s j) : + Represents vertices lanes (row .external p m (word (sites vertices lanes s).val)) + (slotRecord G port width P hd internal s (.inl 0)) := by + have hg := (asWord (p 2)).trans (congrArg word dim.degree) + have ht := (asWord (m (p 5 + word (sites vertices lanes s).val).val)).trans (congrArg word target) + apply represents_of_words vertices lanes _ _ total dim.fits + · simp only [row,slotRecord,arcs_val,extNumber,Nat.add_zero,hg,mul_word] + · simp only [row,slotRecord,arcs_val,extNumber,Nat.add_zero,ht,hg,mul_word] + +/-- A RAM visit reads the matching reverse port and reverse slot from the fixed +expander, and the selected width from the current term's supply table. -/ +theorem expander_record (s : (V × L) × Fin D) (k : Fin dH) (hk : (p 4).val = k.val) + (t : (m (p 7 + word (s.2.val * dH + k.val)).val).val = (P.target (s.2,k)).1.val) + (u : (m (p 8 + word (s.2.val * dH + k.val)).val).val = (P.target (s.2,k)).2.val) + (supply : (m (p 9 + word ((sites vertices lanes s).val * dH + k.val)).val).val = internal s.1 (s.2,k)) : + Represents vertices lanes (row .expander p m (word (sites vertices lanes s).val)) + (slotRecord G port width P hd internal s (.inr (.inl k))) := by + obtain ⟨hv,hj,hl⟩ := decode_exact vertices lanes hd dim s + have h0 := (asWord (p 0)).trans (congrArg word dim.ports) + have h1 := (asWord (p 1)).trans (congrArg word dim.expander) + have h2 := (asWord (p 2)).trans (congrArg word dim.degree) + have h3 := (asWord (p 3)).trans (congrArg word dim.lanes) + have h4 := (asWord (p 4)).trans (congrArg word hk) + have ht := (asWord (m (p 7 + word (s.2.val * dH + k.val)).val)).trans (congrArg word t) + have hu := (asWord (m (p 8 + word (s.2.val * dH + k.val)).val)).trans (congrArg word u) + apply represents_of_words vertices lanes _ _ _ dim.fits + · simp only [row,slotRecord,arcs_val,expNumber,h2,h4,unit_word,mul_word,add_word] + · simp only [row,slotRecord,arcs_val,expNumber,hv,hj,hl] + simp only [h0,h1,h2,h3,h4,mul_word,add_word,ht,hu,unit_word,sites_val] + · simpa only [row,slotRecord,h1,h4,mul_word,add_word] using supply + +/-- Padding preserves the local copy number, advances the port modulo the old +degree at the same vertex and lane, and emits the zero-width row. -/ +theorem padding_record (s : (V × L) × Fin D) (k : Fin (d₀-(dH+1))) (hk : (p 4).val = k.val) : + Represents vertices lanes (row .padding p m (word (sites vertices lanes s).val)) + (slotRecord G port width P hd internal s (.inr (.inr k))) := by + obtain ⟨hv,hj,hl⟩ := decode_exact vertices lanes hd dim s + have h0 := (asWord (p 0)).trans (congrArg word dim.ports) + have h1 := (asWord (p 1)).trans (congrArg word dim.expander) + have h2 := (asWord (p 2)).trans (congrArg word dim.degree) + have h3 := (asWord (p 3)).trans (congrArg word dim.lanes) + have h4 := (asWord (p 4)).trans (congrArg word hk) + have hrot := rotate_word s.2 (p 0) dim.ports + apply represents_of_words vertices lanes _ _ rfl dim.fits + · simp only [row,slotRecord,arcs_val,padNumber,h1,h2,h4,mul_word,add_word,unit_word] + · simp only [row,slotRecord,arcs_val,padNumber,hv,hj,hl,hrot] + simp only [h0,h1,h2,h3,h4,mul_word,add_word,unit_word,sites_val] + +omit dim + +/-- The identifiers stored by any of the three verified visits give precisely +the actual matching and width, including the incoming slot number. -/ +theorem actual_record (s : (V × L) × Fin D) (k : RefreshSlot dH d₀) (out : Row bits) + (ok : Represents vertices lanes out (slotRecord G port width P hd internal s k)) : + let src := (promotedSites s, refreshSlots hd k) + out.src.val = (arcs vertices lanes src).val ∧ + out.dst.val = (arcs vertices lanes ((degreeRefresh G P hD hd).actualGraph.target src)).val ∧ + out.width.val = actualWidths hd port width internal ((src.1.1,src.2),src.1.2) := by + obtain ⟨hs,ht,hw⟩ := slotRecord_spec G port width P hD hd internal s k + obtain ⟨ha,hb,hc⟩ := ok + rw [hs] at ha ht hw + exact ⟨ha,hb.trans (congrArg (fun x => (arcs vertices lanes x).val) ht.symm),hc.trans hw.symm⟩ + +open MotifGrid MotifBlocks MotifConversion SpectralGeometry + +variable [AddCommGroup H] {K : Type*} [_root_.Field K] {c₁ c₂ : ℝ} + (E : RegularArcGraph (Fin D) dH) (hdH : 0 < dH) (conn : (arcSupportGraph E.multiplicity).Connected) + (F : FixedBlock K tieSource tieTarget (expanderSupply E hdH conn) + (realWidths tieMass) (realWidths (expanderMass d₀)) c₁ c₂) + +include dim in +/-- The expander visit applies also to the explicit supply lengths of a +term admitted by the block reader, including its selector fields. -/ +theorem chosen_expander_record (c : BlockChoices G port width E hdH conn F) + (s : (V × L) × Fin D) (k : Fin dH) (hk : (p 4).val = k.val) + (t : (m (p 7 + word (s.2.val * dH + k.val)).val).val = (E.reverse (s.2,k)).1.val) + (u : (m (p 8 + word (s.2.val * dH + k.val)).val).val = (E.reverse (s.2,k)).2.val) + (supply : (m (p 9 + word ((sites vertices lanes s).val * dH + k.val)).val).val = + supplyWidths F (fun t => (demandRecord G port width s.1 t).width) (c s.1).val (s.2,k)) : + Represents vertices lanes (row .expander p m (word (sites vertices lanes s).val)) + (slotRecord G port width E.toSlotGraph hd (blockSupplyWidths G port width E hdH conn F c) + s (.inr (.inl k))) := by + apply expander_record vertices lanes hd dim G port width E.toSlotGraph _ s k hk t u + exact supply.trans (chosen_supply_record G port width E hdH conn F hd c s.1 (s.2,k)).2.2.symm + +omit [AddCommGroup H] in +/-- The two input words of the external-slot writer come directly from the +terminal memory of the external segment pass. -/ +theorem external_terminal_record {a : ℕ} (X : LiftedSlots V (2^a) (BitWord a × L)) + (w : (V × Fin (2^a)) × (BitWord a × L) → ℕ) (E : SlotGraph (Fin (2^a)) dH) + (int : V × L → Fin (2^a) × Fin dH → ℕ) (q : Fin 8 → W bits) (A : RefreshRAM.Input bits) + (fit : n * 2^a * r * 2^a ≤ 2^bits) (sizes : Dimensions p n (2^a) r dH d₀) + (dir : Directory X (sites vertices lanes) w q A fit) + (done : RefreshRAM.AtCursor q (n * 2^a * r * 2^a) A m (n * 2^a * r * 2^a)) + (targetBase : p 5 = q 2) (totalBase : p 6 = q 4) + (s : (V × L) × Fin (2^a)) + (total : (RefreshRAM.cell q m 4 (bundleWord (sites vertices lanes) fit s)).val = + ∑ j, bundleWidths (bitWordFinEquiv a) w s j) : + Represents vertices lanes (row .external p m (word (sites vertices lanes s).val)) + (slotRecord X (bitWordFinEquiv a) w E hd int s (.inl 0)) := by + let ord := sites (D := 2^a) vertices lanes + have idx : word (bits := bits) (ord s).val = bundleWord ord fit s := + (asWord (bundleWord ord fit s)).symm + have ht := (congrArg Fin.val (done.target _ (bundleWord_live ord q (fit := fit) dir.degree s))).trans (dir.target s) + apply external_record vertices lanes hd sizes X (bitWordFinEquiv a) w E int s + · change (m (p 5 + word (ord s).val).val).val = _ + rw [idx,targetBase] + exact ht + · change (m (p 6 + word (ord s).val).val).val = _ + rw [idx,totalBase] + exact total + +end Graph + + +/-- The three output words of a visit. -/ +inductive Column where | outgoing | incoming | width + +/-- Select a row's write address, indexing the incoming column by destination and the other two +by source. -/ +def Row.address (s : Row bits) (p : Public bits) : Column → W bits + | .outgoing => p 10 + s.src + | .incoming => p 11 + s.dst + | .width => p 12 + s.src + +/-- Select the row value to store in the outgoing-mate, incoming-mate, or width column. -/ +def Row.value (s : Row bits) : Column → W bits + | .outgoing => s.dst + | .incoming => s.src + | .width => s.width + +/-- All read addresses are determined by the cursor and the public words. -/ +def inputs (kind : Kind) (p : Public bits) (b : W bits) : List (W bits) := + match kind with + | .external => [p 5 + b, p 6 + b] + | .expander => + let j := BinaryOp.mod.eval (BinaryOp.div.eval b (p 3)) (p 0) + let e := j * p 1 + p 4 + [p 7 + e, p 8 + e, p 9 + (b * p 1 + p 4)] + | .padding => [] + +private theorem row_congr (kind : Kind) (p : Public bits) (b : W bits) {m ref : Memory bits} + (reads : ∀ a ∈ inputs kind p b, m a.val = ref a.val) : row kind p m b = row kind p ref b := by + cases kind <;> simp [inputs] at reads + · simp only [row,reads.1,reads.2] + · simp only [row,reads.1,reads.2.1,reads.2.2] + · rfl + +private theorem update_miss (s : Row bits) (p : Public bits) (m : Memory bits) (a : ℕ) + (miss : ∀ c, a ≠ (s.address p c).val) : s.update p m a = m a := by + have ho := miss .outgoing + have hi := miss .incoming + have hw := miss .width + simp only [Row.address] at ho hi hw + simp [Row.update,writeMemory,ho,hi,hw] + +private theorem update_hit (s : Row bits) (p : Public bits) (m : Memory bits) + (inj : Function.Injective (s.address p)) (c : Column) : + s.update p m (s.address p c).val = s.value c := by + have oi : s.address p .outgoing ≠ s.address p .incoming := fun h => Column.noConfusion (inj h) + have ow : s.address p .outgoing ≠ s.address p .width := fun h => Column.noConfusion (inj h) + have iw : s.address p .incoming ≠ s.address p .width := fun h => Column.noConfusion (inj h) + simp only [Row.address] at oi ow iw + cases c <;> simp [Row.address,Row.value,Row.update,writeMemory,Fin.val_inj,oi,ow,iw] + +section Pass + +variable {N : ℕ} (kind : Kind) (p : Public bits) (ref : Memory bits) + +/-- Expected record at a source site, calculated in the input memory. -/ +abbrev expected (i : Fin N) : Row bits := row kind p ref (word i.val) + +/-- Output words of different rows and columns have distinct addresses. They +are disjoint from all inputs of the pass. -/ +structure PassLayout (N : ℕ) : Prop where + reads : ∀ (i j : Fin N) c a, a ∈ inputs kind p (word i.val) → + a ≠ (expected kind p ref j).address p c + writes : ∀ (i j : Fin N) c d, + (expected kind p ref i).address p c = (expected kind p ref j).address p d → i = j ∧ c = d + +/-- Every visited row is complete. Every memory word outside the visited +output cells has its original value, including words beyond the RAM range. -/ +structure Prefix (N : ℕ) (m : Memory bits) (k : ℕ) : Prop where + rows : ∀ (i : Fin N), i.val < k → ∀ c, + m ((expected kind p ref i).address p c).val = (expected kind p ref i).value c + frame : ∀ a, (∀ (i : Fin N), i.val < k → ∀ c, a ≠ ((expected kind p ref i).address p c).val) → m a = ref a + +private theorem prefix_step (L : PassLayout kind p ref N) {m : Memory bits} {k : ℕ} + (cur : Prefix kind p ref N m k) (hk : k < N) : + Prefix kind p ref N ((row kind p m (word k)).update p m) (k+1) := by + let j : Fin N := ⟨k,hk⟩ + have same : row kind p m (word k) = expected kind p ref j := by + apply row_congr + intro a ha + exact cur.frame a.val (fun i _ c he => L.reads j i c a ha (Fin.ext he)) + rw [same] + constructor + · intro i hi c + by_cases eq : i = j + · subst i + exact update_hit _ p m (fun c d h => (L.writes j j c d h).2) c + · have ne : i.val ≠ k := fun h => eq (Fin.ext h) + rw [update_miss _ p m _ (fun d h => eq (L.writes i j c d (Fin.ext h)).1)] + exact cur.rows i (by omega) c + · intro a ha + rw [update_miss _ p m _ (ha j (Nat.lt_succ_self k))] + exact cur.frame a (fun i hi => ha i (hi.trans (Nat.lt_succ_self k))) + +/-- Probe count of a native visit, before adding its call boundary. -/ +def probeCount : Kind → ℕ + | .external => 5 + | .expander => 6 + | .padding => 3 + +/-- Choose the native table for each slot class. -/ +def kindOf {dH d₀ : ℕ} : RefreshSlot dH d₀ → Kind + | .inl _ => .external + | .inr (.inl _) => .expander + | .inr (.inr _) => .padding + +/-- Summing the full-pass costs over the numbered local slots counts each +expander and each padding copy separately. -/ +theorem slot_cost {dH d₀ : ℕ} (hd : dH+1 ≤ d₀) (N : ℕ) : + ∑ k : Fin d₀, (1 + probeCount (kindOf ((refreshSlots hd).symm k))) * N = + (6 + 7*dH + 4*(d₀-(dH+1))) * N := by + rw [← (refreshSlots hd).sum_comp] + simp only [Equiv.symm_apply_apply,Fintype.sum_sum_type,kindOf,probeCount,Finset.sum_const, + Finset.card_univ,Fintype.card_fin,smul_eq_mul] + ring + +/-- All calls for one fixed local slot, starting at any already completed prefix. -/ +theorem scan_run (layout : PassLayout kind p ref N) (m : Memory bits) (k calls : ℕ) + (cur : Prefix kind p ref N m k) (room : k + calls ≤ N) : + let M := (template (code kind) 0).instantiate bits p + ∃ rs, runSegment M.program (1 + (code kind).length) (some (word k)) m (List.replicate calls []) = some rs ∧ + Prefix kind p ref N (after m (eventLog rs)) (k + calls) ∧ rs.length = calls ∧ + RAMBuckets.cost (fun r : Report bits => countProbes r.events) rs = (1 + probeCount kind) * calls := by + let M := (template (code kind) 0).instantiate bits p + induction calls generalizing k m with + | zero => exact ⟨[],rfl,cur,rfl,by simp [RAMBuckets.cost]⟩ + | succ t ih => + let i := word (bits := bits) k + let r : Report bits := ⟨events kind p m i, some (i+1)⟩ + have next := prefix_step kind p ref layout cur (by omega) + obtain ⟨rs,hr,hc,hl,hw⟩ := ih _ (k+1) next (by omega) + have hm : after m (eventLog (r :: rs)) = after ((row kind p m i).update p m) (eventLog rs) := by + change List.foldl BurstRAM.update m (events kind p m i ++ eventLog rs) = _ + rw [List.foldl_append] + change after (after m (events kind p m i)) (eventLog rs) = _ + rw [events_after] + refine ⟨r :: rs, ?_, ?_, by simp [hl], ?_⟩ + · change runSegment M.program _ (some i) m (List.replicate (t+1) []) = _ + rw [List.replicate_succ,runSegment,native] + simp only [M,r,i,events_after,unit_word,hr,Option.map_some] + · simpa only [hm,Nat.add_assoc,Nat.add_comm 1 t] using hc + · have hprobe : countProbes r.events = probeCount kind := (events_work kind p m i).2 + rw [RAMBuckets.cost,hprobe,hw,Nat.mul_succ,Nat.add_comm] + +/-- From arbitrary initial memory, one complete native pass produces all +forward and inverse links and widths for its slot and preserves every other +cell. This costs six, seven or four per site, according to the slot class. -/ +theorem full_pass (layout : PassLayout kind p ref N) : + let M := (template (code kind) 0).instantiate bits p + ∃ rs, runSegment M.program (1 + (code kind).length) (some 0) ref (List.replicate N []) = some rs ∧ + Prefix kind p ref N (after ref (eventLog rs)) N ∧ rs.length = N ∧ + RAMBuckets.cost (fun r : Report bits => countProbes r.events) rs = (1 + probeCount kind) * N := by + have zero : word (bits := bits) 0 = 0 := Fin.ext (by simp [word]) + simpa only [Nat.zero_add,zero] using scan_run kind p ref layout ref 0 N + ⟨fun _ h => (Nat.not_lt_zero _ h).elim, fun _ _ => rfl⟩ (by simp) + +end Pass + + +section ActualPass + +variable {V H L : Type} {n r D dH d₀ : ℕ} [AddCommGroup L] +variable (vertices : V ≃ Fin n) (lanes : L ≃ Fin r) +variable (G : LiftedSlots V D (H × L)) (port : H ≃ Fin D) + (width : (V × Fin D) × (H × L) → ℕ) (P : SlotGraph (Fin D) dH) + (internal : V × L → Fin D × Fin dH → ℕ) (hD : 1 < D) (hd : dH + 1 ≤ d₀) + (kind : Kind) (p : Public bits) (ref : Memory bits) + +include hD in +/-- For a fixed local slot, injectivity within each physical column follows +from the permutation of actual lifted half-slots. This also covers parallel +expander edges. Only the separation of input and output arrays and of distinct +output columns needs to be supplied by the address layout. -/ +theorem PassLayout.ofActual (k : RefreshSlot dH d₀) + (rows : ∀ i : Fin (n * D * r), Represents vertices lanes (expected kind p ref i) + (slotRecord G port width P hd internal ((sites vertices lanes).symm i) k)) + (reads : ∀ (i j : Fin (n * D * r)) c a, a ∈ inputs kind p (word i.val) → + a ≠ (expected kind p ref j).address p c) + (columns : ∀ (i j : Fin (n * D * r)) c d, c ≠ d → + (expected kind p ref i).address p c ≠ (expected kind p ref j).address p d) : + PassLayout kind p ref (n * D * r) := by + let src := fun i : Fin (n * D * r) => (promotedSites ((sites vertices lanes).symm i),refreshSlots hd k) + have si : Function.Injective src := fun _ _ h => + (sites vertices lanes).symm.injective (promotedSites.injective (congrArg Prod.fst h)) + have ids := fun i => actual_record vertices lanes hD hd G port width P internal + ((sites vertices lanes).symm i) k (expected kind p ref i) (rows i) + have outgoing : Function.Injective (fun i : Fin (n*D*r) => (expected kind p ref i).src) := by + intro i j he + apply si + apply (arcs vertices lanes).injective + exact Fin.ext ((ids i).1.symm.trans ((congrArg Fin.val he).trans (ids j).1)) + have incoming : Function.Injective (fun i : Fin (n*D*r) => (expected kind p ref i).dst) := by + intro i j he + apply si + apply (degreeRefresh G P hD hd).actualGraph.target.injective + apply (arcs vertices lanes).injective + exact Fin.ext ((ids i).2.1.symm.trans ((congrArg Fin.val he).trans (ids j).2.1)) + refine ⟨reads,fun i j c d he => ?_⟩ + have hcd : c = d := by_contra fun h => columns i j c d h he + subst d + refine ⟨?_,rfl⟩ + cases c with + | outgoing | width => exact outgoing (add_left_cancel he) + | incoming => exact incoming (add_left_cancel he) + +end ActualPass + +end CompressorRecords.PortRefresh.NewSlots + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshOldWidths.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshOldWidths.lean new file mode 100644 index 0000000000..210005cac4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshOldWidths.lean @@ -0,0 +1,238 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshExternal +import OAI.Computability.VPVNP.DegreeRefreshPass + +/-! +# Gathering the old actual widths in source-port order + +The old directory stores widths by site and outgoing slot. The degree refresh consumes +a port prefix of the old lane. A scan decodes the bundle, residual lane and port fields, +reads each old slot’s width directly and writes it in source-port order. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace Compression + +private def digits : List (ZMod 2) → ℕ + | [] => 0 + | b :: bs => b.val * 2 ^ bs.length + digits bs + +private theorem digits_append (u v : List (ZMod 2)) : + digits (u ++ v) = digits u * 2 ^ v.length + digits v := by + induction u with + | nil => simp [digits] + | cons b u ih => simp only [List.cons_append, digits, List.length_append, pow_add, ih]; ring + +private theorem digits_ofFn {n : ℕ} (x : BitWord n) : digits (List.ofFn x) = (bitWordFinEquiv n x).val := by + induction n with + | zero => rfl + | succ n ih => + rw [List.ofFn_succ, digits, List.length_ofFn, bitWordFinEquiv_val, ← ih (Fin.tail x)] + change _ * _ + digits (List.ofFn (Fin.tail x)) = _ + rw [Nat.mul_comm, Nat.add_comm] + +/-- The port is the high field of the old lane number and the residual lane its low field. -/ +theorem splitBitWord_number (a g : ℕ) (x : BitWord (a+g)) : + (bitWordFinEquiv (a+g) x).val = + (bitWordFinEquiv a ((splitBitWord a g x).1)).val * 2 ^ g + (bitWordFinEquiv g ((splitBitWord a g x).2)).val := by + rw [← digits_ofFn, List.ofFn_add, digits_append, List.length_ofFn, digits_ofFn, digits_ofFn] + rfl + +end Compression + +namespace CompressorRecords.RefreshGather + +open Compression BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- Source order is `(base arc, residual lane, port)`. The old width column uses +`(base vertex, port, residual lane, slot)`. -/ +def oldIndex (D R i : Word w) : Word w := + let b := BinaryOp.div.eval i D + let port := BinaryOp.mod.eval i D + let arc := BinaryOp.div.eval b R + ((BinaryOp.div.eval arc D * D + port) * R + BinaryOp.mod.eval b R) * D + BinaryOp.mod.eval arc D + +theorem oldIndex_val (D R i : Word w) {x j g : ℕ} (hj : j < D.val) (hg : g < R.val) + (hi : i.val = (x * R.val + g) * D.val + j) : + (oldIndex D R i).val = (((x / D.val * D.val + j) * R.val + g) * D.val + x % D.val) % 2^w := by + have divVal (a b : Word w) : (BinaryOp.div.eval a b).val = a.val / b.val := + Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt a.isLt) + have modVal (a b : Word w) : (BinaryOp.mod.eval a b).val = a.val % b.val := + Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt a.isLt) + have hd : 0 < D.val := (Nat.zero_le j).trans_lt hj + have hr : 0 < R.val := (Nat.zero_le g).trans_lt hg + have hrow : i.val % D.val = j := hi ▸ Nat.mul_add_mod_of_lt hj + have hb : i.val / D.val = x * R.val + g := by + rw [hi, Nat.mul_comm _ D.val, Nat.mul_add_div hd, Nat.div_eq_of_lt hj, Nat.add_zero] + have hbase : (x * R.val + g) / R.val = x := by + rw [Nat.mul_comm x, Nat.mul_add_div hr, Nat.div_eq_of_lt hg, Nat.add_zero] + simp only [oldIndex, Fin.val_add, Fin.val_mul, divVal, modVal, hb, hbase, hrow, + Nat.mul_add_mod_of_lt hg, Nat.mod_add_mod, Nat.mod_mul_mod ] + +/-- Public fields are port count, residual-lane count, old actual-width base and new +width-array base. Persistent state is the source-ordered segment index. -/ +def gather : List (Op 9 4) := + [.stateWord 0, .publicWord 1 0, .publicWord 2 1, .binary .div 3 0 1, .binary .mod 4 0 1, + .binary .div 5 3 2, .binary .mod 6 3 2, .binary .mod 7 5 1, .binary .div 5 5 1, + .binary .mul 5 5 1, .binary .add 5 5 4, .binary .mul 5 5 2, .binary .add 5 5 6, + .binary .mul 5 5 1, .binary .add 5 5 7, .publicWord 7 2, .binary .add 7 7 5, + .read 6 7, .publicWord 7 3, .binary .add 7 7 0, .write 7 6, + .constant 8 1, .binary .add 0 0 8] + +/-- Locate an old actual width by converting a source-ordered segment ordinal to its old +outgoing-slot index. -/ +def widthAddress (p : Fin 4 → Word w) (i : Word w) := p 2 + oldIndex (p 0) (p 1) i + +/-- Read the old actual width selected by a segment ordinal. -/ +def readWidth (p : Fin 4 → Word w) (m : Memory w) (i : Word w) := m (widthAddress p i).val + +/-- The 23-event gather visit reads the old slot width and writes it at the source-ordered +segment index. -/ +def events (p : Fin 4 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + let a := widthAddress p i + [.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick, + .read a (m a.val),.tick,.tick,.write (p 3 + i) (m a.val),.tick,.tick] + +theorem gather_work (p : Fin 4 → Word w) (m : Memory w) (i : Word w) : + (events p m i).length = 23 ∧ countProbes (events p m i) = 2 := ⟨rfl,rfl⟩ + +theorem gather_after (p : Fin 4 → Word w) (m : Memory w) (i : Word w) : + after m (events p m i) = writeMemory m (p 3 + i) (readWidth p m i) := rfl + +private theorem gather_trace (p : Fin 4 → Word w) (m : Memory w) (i : Word w) (regs : Regs w 9) : + ∃ rs, trace p i gather regs m = some (events p m i, rs, writeMemory m (p 3+i) (readWidth p m i)) ∧ + rs 0 = i + 1 := by + simp (config := {decide := true}) [gather, trace, Op.effect, BinaryOp.eval, Function.update, events, + widthAddress, readWidth, oldIndex] + rfl + +/-- A complete native call fetches the named old width, writes the source-ordered width +and returns the next segment number. -/ +theorem gather_native (p : Fin 4 → Word w) (m : Memory w) (i : Word w) : + let M := (template gather 0).instantiate w p + execute M.program 24 (M.program.start i) m [] = some ⟨events p m i, some (i+1)⟩ := by + obtain ⟨rs, ht, hr⟩ := gather_trace p m i (fun _ => 0) + let M := (template gather 0).instantiate w p + change execute M.program (1 + gather.length) ⟨M.entry, i, fun _ => 0, fun _ => 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht]; simp [hr] + +/-- The old and new width columns occupy distinct cells. -/ +def SourcesDisjoint (p : Fin 4 → Word w) (n : ℕ) : Prop := + ∀ (i j : Word w), i.val < n → j.val < n → + (widthAddress p i).val ≠ (p 3 + j).val + +/-- Completed rows and the exact frame after `k` gather calls. -/ +structure Gathered (p : Fin 4 → Word w) (old m : Memory w) (k : ℕ) : Prop where + rows : ∀ i : Word w, i.val < k → m (p 3 + i).val = readWidth p old i + frame : ∀ addr : ℕ, (∀ i : Word w, i.val < k → addr ≠ (p 3 + i).val) → m addr = old addr + +private theorem gather_step {p : Fin 4 → Word w} {n : ℕ} {old m : Memory w} + (apart : SourcesDisjoint p n) (i : Word w) (hi : i.val < n) (h : Gathered p old m i.val) : + Gathered p old (writeMemory m (p 3 + i) (readWidth p m i)) (i.val+1) := by + have hr : readWidth p m i = readWidth p old i := + h.frame _ (fun j hj => apart i j hi (hj.trans hi)) + constructor + · intro j hj + by_cases he : i = j + · subst j; simpa [writeMemory] using hr + · have hne : (p 3 + j).val ≠ (p 3 + i).val := fun hv => he (add_left_cancel (Fin.ext hv)).symm + rw [writeMemory, ite_eq_right hne] + exact h.rows j (by have := Fin.val_ne_of_ne he; omega) + · intro addr outside + rw [writeMemory, ite_eq_right (outside i (Nat.lt_succ_self _))] + exact h.frame addr (fun j hj => outside j (Nat.lt_succ_of_lt hj)) + +/-- The full native gather pass copies every width and changes only completed output rows. -/ +theorem gather_run {p : Fin 4 → Word w} {n k : ℕ} {old m : Memory w} + (fit : n ≤ 2^w) (apart : SourcesDisjoint p n) (h : Gathered p old m k) + (steps : ℕ) (hk : k + steps ≤ n) : + let M := (template gather 0).instantiate w p + ∃ rs, runSegment M.program 24 (some (Fin.ofNat (2^w) k)) m (List.replicate steps []) = some rs ∧ + Gathered p old (after m (eventLog rs)) (k + steps) ∧ rs.length = steps ∧ + ∀ r ∈ rs, r.events.length = 23 ∧ countProbes r.events = 2 := by + let M := (template gather 0).instantiate w p + induction steps generalizing k m with + | zero => exact ⟨[], rfl, h, rfl, by simp⟩ + | succ s ih => + let i := Fin.ofNat (2^w) k + have hv : i.val = k := Nat.mod_eq_of_lt (by omega) + have next := gather_step apart i (by omega) (hv ▸ h) + have hn : i + 1 = Fin.ofNat (2^w) (k+1) := by + apply Fin.ext + rw [Fin.val_add, Fin.val_one', hv, Nat.add_mod_mod]; rfl + let r : Report w := ⟨events p m i, some (i+1)⟩ + obtain ⟨rs,hr,hc,hl,hw⟩ := ih (k := k+1) (hv ▸ next) (by omega) + refine ⟨r :: rs, ?_, ?_, by simp [hl], ?_⟩ + · change runSegment M.program 24 (some i) m (List.replicate (s+1) []) = _ + rw [List.replicate_succ, runSegment, gather_native p m i] + simp only [M, r, gather_after, hn, hr, Option.map_some] + · have he : after m (eventLog (r :: rs)) = + after (writeMemory m (p 3 + i) (readWidth p m i)) (eventLog rs) := by + change List.foldl BurstRAM.update m (events p m i ++ eventLog rs) = _ + rw [List.foldl_append]; rfl + simpa [he, Nat.add_assoc, Nat.add_comm 1 s] using hc + · intro rep hrep + rcases List.mem_cons.mp hrep with rfl | hr + · exact gather_work p m i + · exact hw rep hr + +/-- A segment read reaches the exact old outgoing slot in the unsplit lane numbering. -/ +theorem original_lane_index {a g : ℕ} (p : Fin 4 → Word w) (i : Word w) (arc : ℕ) + (oldLane : BitWord (a+g)) (hd : (p 0).val = 2^a) (hg : (p 1).val = 2^g) + (hi : i.val = (arc * 2^g + (bitWordFinEquiv g ((splitBitWord a g oldLane).2)).val) * 2^a + + (bitWordFinEquiv a ((splitBitWord a g oldLane).1)).val) + : oldIndex (p 0) (p 1) i = Fin.ofNat _ + ((arc / 2^a * 2^(a+g) + (bitWordFinEquiv (a+g) oldLane).val) * 2^a + arc % 2^a) := by + apply Fin.ext + rw [splitBitWord_number, pow_add] + have key := oldIndex_val (p 0) (p 1) i (x := arc) + (j := (bitWordFinEquiv a ((splitBitWord a g oldLane).1)).val) + (g := (bitWordFinEquiv g ((splitBitWord a g oldLane).2)).val) + (by rw [hd]; exact (bitWordFinEquiv a _).isLt) (by rw [hg]; exact (bitWordFinEquiv g _).isLt) + (by simpa only [hd,hg] using hi) + rw [key,hd,hg] + congr 1 + ring + +open Refresh (groupedWidths splitWidths) +open PortRefresh + +/-- Widths at the directly addressed old sites and outgoing slots. -/ +def HasOldWidths {a g n : ℕ} (X : State a (a+g)) (base : X.Base × Fin (2^a) ≃ Fin n) + (p : Fin 4 → Word w) (m : Memory w) : Prop := + ∀ (b : X.Base × Fin (2^a)) (l : BitWord (a+g)), + let oldArc := (base b).val + let key := (oldArc / 2^a * 2^(a+g) + (bitWordFinEquiv (a+g) l).val) * 2^a + oldArc % 2^a + (m (p 2 + Fin.ofNat (2^w) key).val).val = X.width (b,l) + +/-- The physical width read by the gather call is precisely the source-port field of the +actual dyadic compression state in the common incidence-directory format. -/ +theorem read_state_width {a g n : ℕ} (X : State a (a+g)) (base : X.Base × Fin (2^a) ≃ Fin n) + (ord : (X.Base × BitWord g) × Fin (2^a) ≃ Fin (n*2^g)) + (ho : ∀ b, (ord b).val = (base (b.1.1,b.2)).val * 2^g + (bitWordFinEquiv g b.1.2).val) + (p : Fin 4 → Word w) (m : Memory w) (old : HasOldWidths X base p m) + (hd : (p 0).val = 2^a) (hg : (p 1).val = 2^g) (fit : n*2^g*2^a ≤ 2^w) + (e : DyadicArc X.Base (BitWord g) a) : + (readWidth p m (idWord ord fit e)).val = groupedWidths (bitWordFinEquiv a) (splitWidths X) e := by + obtain ⟨⟨⟨v,g'⟩,s⟩,j⟩ := e + let lane := (splitBitWord a g).symm ((bitWordFinEquiv a).symm j,g') + let b := ((v,g'),s) + let i := idWord ord fit (b,j) + have hi : i.val = ((base (v,s)).val * 2^g + (bitWordFinEquiv g g').val) * 2^a + j.val := by + change (numbered ord (b,j)).val = _ + rw [numbered_val, ho] + have hold := original_lane_index p i (base (v,s)).val lane hd hg + (by simpa [lane] using hi) + change (m (p 2 + oldIndex (p 0) (p 1) i).val).val = X.width ((v,s),lane) + rw [hold] + exact old (v,s) lane + +end CompressorRecords.RefreshGather + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshPhases.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshPhases.lean new file mode 100644 index 0000000000..54cdae557a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshPhases.lean @@ -0,0 +1,186 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshDirectory +import OAI.Computability.VPVNP.CompressorRecordRefreshNewSlots + +/-! +# Native external descriptor construction from an old compressor state + +The old outgoing slots index the width column directly. The old base table supplies a target +and a binary lane displacement per arc. Three scans with shared external memory gather the +actual widths, translate the base table into a bundle directory and write the two endpoint +segment tables. The resulting totals and segment rows refer to the same old state and the +same kernel intervals. The resource count includes all three scans. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh + +open Compression Compression.Refresh Compression.DegreeRefresh BurstRAM PrimedStackRAM RefreshRAM + +variable {a g n bits : ℕ} (X : State a (a+g)) (base : X.Base × Fin (2^a) ≃ Fin n) + +/-- The gather and directory tables use the array bases of the ensuing external pass. -/ +def gatherWords (p : Fin 8 → BurstRAM.Word bits) (lanes oldWidth : BurstRAM.Word bits) : Fin 4 → BurstRAM.Word bits := + ![p 0, lanes, oldWidth, p 1] + +/-- Assemble the bundle-directory operands from the residual lane count, old base columns, and +three scratch destinations. -/ +def directoryWords (p : Fin 8 → BurstRAM.Word bits) (lanes target shift : BurstRAM.Word bits) : + Fin 8 → BurstRAM.Word bits := ![lanes,target,p 2,p 3,p 4,shift,0,0] + +variable (p : Fin 8 → BurstRAM.Word bits) (lanes oldWidth target shift : BurstRAM.Word bits) + +/-- The old base columns also remain live through the gather's width writes. -/ +def baseOutsideGather : Prop := + ∀ e (j : BurstRAM.Word bits), j.val < n * 2^g * 2^a → + (target + Fin.ofNat (2^bits) (base e).val).val ≠ (p 1 + j).val ∧ + (shift + Fin.ofNat (2^bits) (base e).val).val ≠ (p 1 + j).val + +private theorem gather_cost {rs : List (Report bits)} (h : ∀ r ∈ rs, countProbes r.events = 2) : + RAMBuckets.cost Report.probes rs = 3 * rs.length := by + induction rs with + | nil => simp [RAMBuckets.cost] + | cons r rs ih => + rw [RAMBuckets.cost, Report.probes, h r (List.mem_cons_self ..), ih (fun q hq => h q (List.mem_cons_of_mem _ hq)), + List.length_cons, Nat.mul_succ] + omega + +/-- A physical address outside all seven arrays at this level. -/ +def outsideLevel (p : Fin 8 → BurstRAM.Word bits) (S addr : ℕ) : Prop := + ∀ t : Fin 8, t ≠ 0 → ∀ i : BurstRAM.Word bits, i.val < S → addr ≠ (p t + i).val + +include base in +/-- The source-bundle count is the physical position count of the input state. -/ +theorem bundleCount_positions : n * 2^g = X.positions := by + have hbase := Fintype.card_congr base + rw [Fintype.card_prod, Fintype.card_fin, Fintype.card_fin] at hbase + rw [State.positions, Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv (a+g)), Fintype.card_fin, ← hbase, pow_add] + exact Nat.mul_assoc .. + +/-- Native reports, memory and geometric rows produced by the three external passes. -/ +def ExternalReports (m : Memory bits) (fit : n * 2^g * 2^a ≤ 2^bits) + (rg rd re : List (Report bits)) : Prop := + let B := n * 2^g + let S := B * 2^a + let ord := bundleOrder g base + let gM := (template RefreshGather.gather 0).instantiate bits (gatherWords p lanes oldWidth) + let dM := (template BundleDirectory.visit 0).instantiate bits (directoryWords p lanes target shift) + let eM := (template RefreshRAM.visit 0).instantiate bits p + let m₁ := after m (eventLog rg) + let m₂ := after m₁ (eventLog rd) + let m₃ := after m₂ (eventLog re) + runSegment gM.program 24 (some 0) m (List.replicate S []) = some rg ∧ + runSegment dM.program 28 (some 0) m₁ (List.replicate B []) = some rd ∧ + runSegment eM.program 33 (some 0) m₂ (List.replicate S []) = some re ∧ + RAMBuckets.cost Report.probes (rg ++ rd ++ re) = 6 * B + 12 * S ∧ + AtCursor p S (graphInput (splitSlots X) ord (splitWidths X)) m₃ S ∧ + (∀ addr, outsideLevel p S addr → m₃ addr = m addr) ∧ + (∀ b, (cell p m₃ 4 (bundleWord ord fit b)).val = + ∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j) ∧ + ∀ e : DyadicArc X.Base (BitWord g) a, + let i := idWord ord fit e + let j := idWord ord fit (oldPortMatching (splitSlots X) (bitWordFinEquiv a) e) + let r := outgoingRecord (splitSlots X) (bitWordFinEquiv a) (splitWidths X) e + (cell p m₃ 5 i).val = r.offset ∧ (cell p m₃ 6 j).val = r.offset ∧ (cell p m₃ 7 j).val = r.width + +/-- Existence of a complete deterministic external construction. -/ +def ExternalExecution (m : Memory bits) (fit : n * 2^g * 2^a ≤ 2^bits) : Prop := + ∃ rg rd re, ExternalReports X base p lanes oldWidth target shift m fit rg rd re + +/-- Execute the three native phase tables in succession from the old physical slot records. +For `B` bundles and `S` segments the exact cost is `6B + 12S` calls plus external probes. -/ +theorem external_phases_stages (degree : (p 0).val = 2^a) (residual : lanes.val = 2^g) + (regions : Regions p (n*2^g*2^a)) + (dirLayout : BundleDirectory.Layout (directoryWords p lanes target shift) n (2^g)) + (m : Memory bits) + (widths : RefreshGather.HasOldWidths X base (gatherWords p lanes oldWidth) m) + (baseTable : BundleDirectory.BaseTables (splitSlots X) base (directoryWords p lanes target shift) m) + (wireApart : RefreshGather.SourcesDisjoint (gatherWords p lanes oldWidth) (n*2^g*2^a)) + (baseApart : baseOutsideGather (g := g) X base p target shift) + (room : ∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j) < 2^bits) : + ∃ rg rd re, ExternalReports X base p lanes oldWidth target shift m regions.fits rg rd re ∧ + BundleDirectory.BaseTables (splitSlots X) base (directoryWords p lanes target shift) (after m (eventLog rg)) ∧ + AtCursor p (n*2^g*2^a) (graphInput (splitSlots X) (bundleOrder g base) (splitWidths X)) + (after (after m (eventLog rg)) (eventLog rd)) 0 := by + let B := n * 2^g + let S := B * 2^a + let q := gatherWords p lanes oldWidth + let d := directoryWords p lanes target shift + let ord := bundleOrder g base + let data : Input bits := graphInput (splitSlots X) ord (splitWidths X) + have T : Directory (splitSlots X) ord (splitWidths X) p data regions.fits := + graphInput_directory (splitSlots X) ord (splitWidths X) p degree room + have start : RefreshGather.Gathered q m m 0 := + ⟨fun _ hi => (Nat.not_lt_zero _ hi).elim, fun _ _ => rfl⟩ + obtain ⟨rg,hg,done,ng,wg⟩ := RefreshGather.gather_run regions.fits wireApart start S (by simp [S,B]) + let m₁ := after m (eventLog rg) + have old : BundleDirectory.BaseTables (splitSlots X) base d m₁ := by + refine ⟨baseTable.lanes, fun e => ?_, fun e => ?_⟩ + · have h := done.frame (target + Fin.ofNat (2^bits) (base e).val).val + (fun j hj => (baseApart e j (by simpa only [Nat.zero_add] using hj)).1) + exact (congrArg Fin.val h).trans (baseTable.target e) + · have h := done.frame (shift + Fin.ofNat (2^bits) (base e).val).val + (fun j hj => (baseApart e j (by simpa only [Nat.zero_add] using hj)).2) + exact (congrArg Fin.val h).trans (baseTable.displacement e) + obtain ⟨rd,hd,ready,frame,cd,_,_⟩ := BundleDirectory.directory_pass (splitSlots X) base d dirLayout m₁ old + let m₂ := after m₁ (eventLog rd) + have init := BundleDirectory.Prefix.external_start (splitSlots X) base d p m₂ (splitWidths X) ready degree rfl rfl rfl (by + intro i hi + let e := (numbered ord).symm ⟨i.val,hi⟩ + have he : idWord ord regions.fits e = i := by + apply Fin.ext + change (numbered ord e).val = i.val + simp [e] + have hframe := frame (p 1+i).val (by + intro j hj + have hs : j.val < S := hj.trans_le (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)) + exact ⟨fun h => (by decide : (1 : Fin 8) ≠ 2) ((regions.apart 1 2 (by decide) (by decide) i j hi hs).mp h).1, + fun h => (by decide : (1 : Fin 8) ≠ 3) ((regions.apart 1 3 (by decide) (by decide) i j hi hs).mp h).1, + fun h => (by decide : (1 : Fin 8) ≠ 4) ((regions.apart 1 4 (by decide) (by decide) i j hi hs).mp h).1⟩) + change after m₁ (eventLog rd) (p 1+i).val = data.width i + rw [hframe] + have copy := done.rows i (by simpa only [Nat.zero_add] using hi) + change m₁ (p 1+i).val = _ at copy + rw [copy, ← he] + apply Fin.ext + exact (RefreshGather.read_state_width X base ord (bundleOrder_val g base) q m widths degree residual regions.fits e).trans + (T.old e).symm) + obtain ⟨re,he,ce,atEnd,frameEnd,total,rows⟩ := external_pass (splitSlots X) ord (splitWidths X) p data T regions room m₂ init + have finalFrame (addr : ℕ) (outside : outsideLevel p S addr) : + after m₂ (eventLog re) addr = m addr := by + have he' := frameEnd addr (fun t ht => outside t (by rintro rfl; simp at ht)) + have hd' := frame addr (fun i hi => + let hs := hi.trans_le (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)) + ⟨outside 2 (by decide) i hs, outside 3 (by decide) i hs, outside 4 (by decide) i hs⟩) + have hg' := done.frame addr (fun i hi => outside 1 (by decide) i (by simpa only [Nat.zero_add] using hi)) + exact he'.trans (hd'.trans hg') + refine ⟨rg,rd,re,⟨hg,hd,he,?_,atEnd,finalFrame,total,rows⟩,old,init⟩ + have cg := gather_cost (fun r h => (wg r h).2) + rw [ng] at cg + change RAMBuckets.cost Report.probes re = 9 * S at ce + change RAMBuckets.cost Report.probes rd = 6 * B at cd + simp only [RAMBuckets.cost_append, cg, cd, ce, S, B] + ring + +/-- A complete execution of the three native refresh prepasses. -/ +theorem external_phases (degree : (p 0).val = 2^a) (residual : lanes.val = 2^g) + (regions : Regions p (n*2^g*2^a)) + (dirLayout : BundleDirectory.Layout (directoryWords p lanes target shift) n (2^g)) + (m : Memory bits) + (widths : RefreshGather.HasOldWidths X base (gatherWords p lanes oldWidth) m) + (baseTable : BundleDirectory.BaseTables (splitSlots X) base (directoryWords p lanes target shift) m) + (wireApart : RefreshGather.SourcesDisjoint (gatherWords p lanes oldWidth) (n*2^g*2^a)) + (baseApart : baseOutsideGather (g := g) X base p target shift) + (room : ∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j) < 2^bits) : + ExternalExecution X base p lanes oldWidth target shift m regions.fits := by + obtain ⟨rg,rd,re,h,_,_⟩ := external_phases_stages X base p lanes oldWidth target shift degree residual + regions dirLayout m widths baseTable wireApart baseApart room + exact ⟨rg,rd,re,h⟩ + +end CompressorRecords.PortRefresh + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshPrepare.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshPrepare.lean new file mode 100644 index 0000000000..c850bec8dc --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshPrepare.lean @@ -0,0 +1,110 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshDemandScan +import OAI.Computability.VPVNP.CompressorRecordRefreshInputs + +/-! +# Preparing the external fields and internal demands of a refresh + +The initial state is the shared six-column incidence directory. The three external passes +produce both ends of every segment. The fixed ordered ties then copy the appropriate +outgoing or incoming width into a contiguous demand record at each port block. No term +selection or payload assignment precedes this construction. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh + +open BurstRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh RefreshRAM NewSlots + +variable {a g bits t : ℕ} (X : State a (a+g)) (T : IncidenceDirectory bits) + (q : Fin 8 → BurstRAM.Word bits) (out : BurstRAM.Word bits) (ties : Fin t ≃ Tie (2^a)) + +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "V" => Fintype.card X.Base +local notation "B" => V * 2^g +local notation "N" => V * 2^a * 2^g +local notation "S" => N * 2^a + +/-- The directory fields needed after the demand scan, including both physical endpoints +of every segment and the individual old width at each end. -/ +structure SegmentFields (fit : S ≤ 2^bits) (m : Memory bits) : Prop where + target : ∀ b, (cell q m 2 (bundleWord O fit b)).val = (O (bundleTarget (splitSlots X) b)).val + total : ∀ b, (cell q m 4 (bundleWord O fit b)).val = ∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j + segments : ∀ e : DyadicArc X.Base (BitWord g) a, + let i := idWord O fit e + let j := idWord O fit (oldPortMatching (splitSlots X) (bitWordFinEquiv a) e) + let r := outgoingRecord (splitSlots X) (bitWordFinEquiv a) (splitWidths X) e + (cell q m 1 i).val = r.width ∧ (cell q m 5 i).val = r.offset ∧ + (cell q m 6 j).val = r.offset ∧ (cell q m 7 j).val = r.width + +/-- Preserve the segment data across writes in other level arrays. -/ +theorem SegmentFields.transfer {fit : S ≤ 2^bits} {m m' : Memory bits} (data : SegmentFields X q fit m) + (frame : ∀ c : Fin 8, c ≠ 0 → ∀ i : BurstRAM.Word bits, i.val < S → cell q m' c i = cell q m c i) : + SegmentFields X q fit m' := by + have bn (b : (X.Base × BitWord g) × Fin (2^a)) : (bundleWord O fit b).val < S := + (O b).isLt.trans_le (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)) + constructor + · intro b; rw [frame 2 (by decide) _ (bn b)]; exact data.target b + · intro b; rw [frame 4 (by decide) _ (bn b)]; exact data.total b + · intro e + dsimp only + have h (c : Fin 8) (hc : c ≠ 0) (a) := frame c hc (idWord O fit a) (numbered O a).isLt + simp only [h 1 (by decide), h 5 (by decide), h 6 (by decide), h 7 (by decide)] + exact data.segments e + +/-- A demand row lies outside the seven segment arrays so all segment descriptors remain +available for the local kernel, even after copying the dense internal demand vector. -/ +def demandApart : Prop := ∀ c : Fin 8, c ≠ 0 → ∀ i : BurstRAM.Word bits, i.val < S → + (q c + i).val < out.val ∨ out.val+B*t ≤ (q c+i).val + +/-- Four native passes in their shared-memory execution order. -/ +def PrepareRun (lanes : BurstRAM.Word bits) (fit : S ≤ 2^bits) + (m m' : Memory bits) (reports : List (Report bits)) : Prop := + ∃ rg rd re ds, + ExternalReports X (IncidenceDirectory.baseOrder X) q lanes T.width T.baseOut T.shift m fit rg rd re ∧ + let ext := after (after (after m (eventLog rg)) (eventLog rd)) (eventLog re) + DemandScan.Runs (DemandScan.words (r := 2^g) ties q out) B (List.finRange t) ext ds ∧ + m' = after ext (eventLog ds) ∧ reports = (rg ++ rd ++ re) ++ ds + +/-- From an existing incidence directory to all numerical inputs of the block term tests. +The same output memory also retains all external widths, endpoint offsets and bundle targets. -/ +theorem prepare_demands (m : Memory bits) (rep : T.Represents X m) (lanes : BurstRAM.Word bits) + (degree : (q 0).val = 2^a) (residual : lanes.val = 2^g) (regions : Regions q S) + (dirLayout : BundleDirectory.Layout (directoryWords q lanes T.baseOut T.shift) (V*2^a) (2^g)) + (wireApart : RefreshGather.SourcesDisjoint (gatherWords q lanes T.width) S) + (baseApart : baseOutsideGather X (IncidenceDirectory.baseOrder X) q T.baseOut T.shift) + (widthRoom : ∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j) < 2^bits) + (demandRoom : out.val+B*t ≤ 2^bits) (apart : demandApart (t := t) X q out) : + ∃ rs m', PrepareRun X T q out ties lanes regions.fits m m' rs ∧ SegmentFields X q regions.fits m' ∧ + (∀ s, DemandPreparation.demandAt ties (DemandScan.rowBase X t out s) m' = + blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) s) ∧ + (∀ addr, outsideLevel q S addr → (addr < out.val ∨ out.val+B*t ≤ addr) → m' addr = m addr) ∧ + RAMBuckets.cost Report.probes rs = 6*N + 12*S + 3*B*t := by + obtain ⟨rg,rd,re,extReports⟩ := IncidenceDirectory.Represents.external_execution X T m rep q lanes degree residual + regions dirLayout wireApart baseApart widthRoom + have ⟨_,_,_,cost,done,frame,totals,rows⟩ := extReports + let ext := after (after (after m (eventLog rg)) (eventLog rd)) (eventLog re) + let A := graphInput (bits := bits) (splitSlots X) O (splitWidths X) + have T' : Directory (splitSlots X) O (splitWidths X) q A regions.fits := + graphInput_directory (splitSlots X) O (splitWidths X) q degree widthRoom + have atEnd : AtCursor q S A ext S := done + have extData : SegmentFields X q regions.fits ext := by + refine ⟨fun b => ?_,totals,fun e => ?_⟩ + · exact (congrArg Fin.val (atEnd.target _ (bundleWord_live O q (fit := regions.fits) degree b))).trans (T'.target b) + · exact ⟨(congrArg Fin.val (atEnd.old _ (numbered O e).isLt)).trans (T'.old e), rows e⟩ + have ap : DemandScan.Apart (t := t) X q out := fun c hc => apart c (by rcases hc with rfl | rfl <;> decide) + obtain ⟨ds,runD,demand,frameD,costD⟩ := DemandScan.demand_table ext X ties q out regions.fits + (residual ▸ lanes.isLt) demandRoom ap A T' atEnd (fun e => (rows e).2.2) + let m' := after ext (eventLog ds) + refine ⟨(rg ++ rd ++ re) ++ ds, m', ⟨rg,rd,re,ds,extReports,runD,rfl,rfl⟩, + extData.transfer X q (fun c hc i hi => frameD _ (apart c hc i hi)), demand, + fun addr he hd => (frameD addr hd).trans (frame addr he), ?_⟩ + exact (RAMBuckets.cost_append Report.probes _ _).trans (congrArg₂ (· + ·) cost costD) + +end CompressorRecords.PortRefresh + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshPrepareAllocation.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshPrepareAllocation.lean new file mode 100644 index 0000000000..649cb12ce6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshPrepareAllocation.lean @@ -0,0 +1,164 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshAllocation + +/-! +# Preparing a refresh in its packed allocation + +The six old incidence columns end before the seven new scratch columns. The gather reads +a permutation of the old actual slots and the directory reads the two old base columns. +The demand table and every strided term record begin after the last scratch column. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.Allocation + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh +open NewSlots + +variable {bits a g : ℕ} + +private theorem packed_lt {x j n d : ℕ} (hx : x < n) (hj : j < d) : x*d+j < n*d := by + have h := Nat.mul_le_mul_right d (Nat.succ_le_of_lt hx) + rw [Nat.succ_mul] at h; omega + +/-- Transposing port and residual lane in the gather index stays inside the old +site-major width table, including when the dimensions are powers of two of size one. -/ +theorem gather_index_lt (D R i : W bits) (v : ℕ) (hd : 0 < D.val) (hr : 0 < R.val) + (hi : i.val < v*D.val*R.val*D.val) : + (RefreshGather.oldIndex D R i).val < v*D.val*R.val*D.val := by + let b := i.val/D.val + let j := i.val%D.val + let x := b/R.val + let l := b%R.val + have hb : b < v*D.val*R.val := (Nat.div_lt_iff_lt_mul hd).mpr hi + have hx : x < v*D.val := (Nat.div_lt_iff_lt_mul hr).mpr hb + have hj : j < D.val := Nat.mod_lt _ hd + have hl : l < R.val := Nat.mod_lt _ hr + have outer : i.val = b*D.val+j := (Nat.div_add_mod' ..).symm + have inner : b = x*R.val+l := (Nat.div_add_mod' ..).symm + have key := RefreshGather.oldIndex_val D R i hj hl (inner ▸ outer) + rw [key] + exact (Nat.mod_le ..).trans_lt (packed_lt (packed_lt (packed_lt ((Nat.div_lt_iff_lt_mul hd).mpr hx) hj) hl) + (Nat.mod_lt _ hd)) + +theorem Plan.scratch_interval (P : Plan) (room : P.demand ≤ 2^bits) (c : Fin 8) (hc : c ≠ 0) + (j : W bits) (hj : j.val < P.segments) : P.start ≤ (P.scratch bits c+j).val ∧ (P.scratch bits c+j).val < P.demand := by + have h := Nat.mul_le_mul_right P.segments (show (c.val-1)+1 ≤ 7 by have := c.isLt; omega) + rw [Nat.add_mul,Nat.one_mul] at h + change P.start+7*P.segments ≤ 2^bits at room + have baseFits : P.start+(c.val-1)*P.segments < 2^bits := by omega + have cellFits : P.start+(c.val-1)*P.segments+j.val < 2^bits := by omega + rw [Plan.scratch,ite_eq_right hc,Fin.val_add, + show (word (bits := bits) (P.start+(c.val-1)*P.segments)).val = _ from Nat.mod_eq_of_lt baseFits, + Nat.mod_eq_of_lt cellFits] + change P.start ≤ _ ∧ _ < P.start+7*P.segments + constructor <;> omega + +variable (X : State a (a+g)) (T : IncidenceDirectory bits) (a₀ dH t stride start : ℕ) + +local notation "P" => plan X a₀ dH t stride start +local notation "Q" => Plan.scratch P bits +local notation "L" => (word (bits := bits) (2^g)) +local notation "V" => Fintype.card X.Base +local notation "B" => V*2^g +local notation "N" => V*2^a*2^g +local notation "S" => N*2^a + +/-- The exact inputs for `prepare_demands` and the term reader. The term row intervals +are disjoint from all segment descriptors, so their native writes preserve the endpoints. -/ +structure PrepareLayout : Prop where + degree : (Q 0).val = 2^a + lanes : (L).val = 2^g + regions : RefreshRAM.Regions Q S + directory : BundleDirectory.Layout (directoryWords Q L T.baseOut T.shift) (V*2^a) (2^g) + gather : RefreshGather.SourcesDisjoint (gatherWords Q L T.width) S + baseApart : baseOutsideGather X (IncidenceDirectory.baseOrder X) Q T.baseOut T.shift + demandRoom : (word (bits := bits) (P).demand).val+B*t ≤ 2^bits + demandApart : demandApart (t := t) X Q (word (P).demand) + demandTerm : (word (bits := bits) (P).demand).val+B*t ≤ (word (bits := bits) (P).term).val + termRoom : (word (bits := bits) (P).term).val+B*stride < 2^bits + termApart : ∀ c : Fin 8, c ≠ 0 → ∀ j : W bits, j.val < S → ∀ b : Fin B, + (Q c+j).val < (word (bits := bits) ((P).term+b.val*stride)).val + +private theorem directory_layout (before : ∀ c : Fin 6, (T.column c).val+S ≤ start) + (regions : RefreshRAM.Regions Q S) (droom : (P).demand ≤ 2^bits) : + BundleDirectory.Layout (directoryWords Q L T.baseOut T.shift) (V*2^a) (2^g) := by + let p := directoryWords Q L T.baseOut T.shift + have ns : N ≤ S := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a) + have bn : V*2^a ≤ N := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g) + have fixed (i : Fin 8) (h₂ : 2 ≤ i.val) (h₄ : i.val ≤ 4) : p i = Q i := by + fin_cases i <;> first | rfl | simp at h₂ h₄ + refine ⟨ns.trans regions.fits,fun c u x y hc₁ hc₅ hu₂ hu₄ hx hy => ?_⟩ + have hu₀ : u ≠ 0 := by rintro rfl; simp at hu₂ + change (p c+x).val = (p u+y).val ↔ c=u ∧ x=y + rw [fixed u hu₂ hu₄] + have hafter := ((P).scratch_interval droom u hu₀ y (hy.trans_le ns)).1 + change start ≤ (Q u+y).val at hafter + by_cases hread : c=1 ∨ c=5 + · rw [ite_eq_left hread] at hx + have hbefore (i : Fin 6) : (T.column i+x).val < start := + (Nat.mod_le ((T.column i).val+x.val) _).trans_lt (by have := before i; have := hx.trans_le (bn.trans ns); omega) + have hne : c ≠ u := by rcases hread with rfl | rfl <;> rintro rfl <;> simp at hu₂ hu₄ + have he : (p c+x).val ≠ (Q u+y).val := by + rcases hread with rfl | rfl + · exact Nat.ne_of_lt ((hbefore 0).trans_le hafter) + · exact Nat.ne_of_lt ((hbefore 2).trans_le hafter) + simp [he,hne] + · rw [ite_eq_right hread] at hx + have hn₁ : c.val ≠ 1 := fun h => hread (Or.inl (Fin.ext h)) + have hn₅ : c.val ≠ 5 := fun h => hread (Or.inr (Fin.ext h)) + rw [fixed c (by omega) (by omega)] + exact regions.apart c u (by rintro rfl; simp at hc₁) hu₀ x y (hx.trans_le ns) (hy.trans_le ns) + +/-- Packed prepass allocation. The six scalar end bounds on the old columns and one +total allocation bound replace all the per-cell separation conditions of the native scans. -/ +theorem prepare_layout (before : ∀ c : Fin 6, (T.column c).val+S ≤ start) (room : (P).stop < 2^bits) : + PrepareLayout X T a₀ dH t stride start := by + have spos : 0 < N := by positivity + have capPos : 0 < (P).capacity := Nat.mul_pos spos (Nat.two_pow_pos a₀) + have regions := (P).scratch_regions room.le capPos + have hs : 2^a ≤ (P).segments := Nat.le_mul_of_pos_left _ spos + have hR : 2^g ≤ N := Nat.le_mul_of_pos_left _ (Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos a)) + have ns : N ≤ S := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a) + have bn : V*2^a ≤ N := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g) + have stopRoom : (P).supply < 2^bits := by + dsimp only [Plan.stop,Plan.next,Plan.reverseSlot,Plan.targetPort] at room; omega + have hsrc : start+7*S = (P).demand := rfl + have hterm : (P).demand+B*t = (P).term := rfl + have hsup : (P).term+B*stride = (P).supply := rfl + change 2^a ≤ S at hs + have hd : (Q 0).val = 2^a := by change (word (bits := bits) (2^a)).val = _; exact Nat.mod_eq_of_lt (by omega) + have hr : (L).val = 2^g := Nat.mod_eq_of_lt (show 2^g < 2^bits by omega) + have hm : (word (bits := bits) (P).demand).val = (P).demand := Nat.mod_eq_of_lt (by omega) + have ht : (word (bits := bits) (P).term).val = (P).term := Nat.mod_eq_of_lt (by omega) + have dir := directory_layout X T a₀ dH t stride start before regions (by omega) + have low (c : Fin 6) (i : W bits) (hi : i.val < S) : (T.column c+i).val < start := + (Nat.mod_le ((T.column c).val+i.val) _).trans_lt (by have := before c; omega) + have scratch (c : Fin 8) (hc : c ≠ 0) (j : W bits) (hj : j.val < S) := + (P).scratch_interval (by omega : (P).demand ≤ 2^bits) c hc j hj + refine ⟨hd,hr,regions,dir,?_,?_,by rw [hm]; omega,?_,by rw [hm,ht]; omega,by rw [ht]; omega,?_⟩ + · intro i j hi hj + have h := gather_index_lt (Q 0) L i V (by rw [hd]; exact Nat.two_pow_pos a) (by rw [hr]; exact Nat.two_pow_pos g) + (by simpa only [hd,hr] using hi) + rw [hd,hr] at h + exact Nat.ne_of_lt ((low 5 _ h).trans_le (scratch 1 (by decide) j hj).1) + · intro e j hj + have he : (Fin.ofNat (2^bits) (IncidenceDirectory.baseOrder X e).val).val < S := + (Nat.mod_le ..).trans_lt ((IncidenceDirectory.baseOrder X e).isLt.trans_le (bn.trans ns)) + have ha := (scratch 1 (by decide) j hj).1 + exact ⟨Nat.ne_of_lt ((low 0 _ he).trans_le ha),Nat.ne_of_lt ((low 2 _ he).trans_le ha)⟩ + · intro c hc i hi + exact Or.inl (by rw [hm]; exact (scratch c hc i hi).2) + · intro c hc j hj b + have upper := Nat.mul_le_mul_right stride b.isLt.le + have hb : (P).term+b.val*stride < 2^bits := by omega + rw [show (word (bits := bits) ((P).term+b.val*stride)).val = _ from Nat.mod_eq_of_lt hb] + have ha := (scratch c hc j hj).2; omega + +end CompressorRecords.PortRefresh.Allocation + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshRAM.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshRAM.lean new file mode 100644 index 0000000000..85a2b9c8fe --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshRAM.lean @@ -0,0 +1,104 @@ +import OAI.Computability.VPVNP.CompressorRecordTable + +/-! +# Writing external segment records during a degree refresh + +Appendix E visits the source ports of each bundle consecutively. The directory stores the +translated destination bundle and the port displacement for each source bundle. Each visit +reads the old width and the running total. It writes the offset at both ends, the incoming +width at the translated port, and the new total. The outgoing width remains directly +available in the old-width array. All addresses below are word addresses. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- Public words, in order, are the degree, old widths, bundle targets, port shifts, +bundle totals, outgoing offsets, incoming offsets and incoming widths. The persistent +state is the source segment number in bundle-major order. -/ +def visit : List (Op 12 8) := + [.stateWord 0, .publicWord 1 0, .binary .div 2 0 1, .binary .mod 3 0 1, + .publicWord 4 2, .binary .add 4 4 2, .read 5 4, + .publicWord 4 3, .binary .add 4 4 2, .read 6 4, + .binary .bitXor 6 3 6, .binary .mul 5 5 1, .binary .add 5 5 6, + .publicWord 4 1, .binary .add 4 4 0, .read 7 4, + .publicWord 8 4, .binary .add 8 8 2, .read 9 8, + .publicWord 4 5, .binary .add 4 4 0, .write 4 9, + .publicWord 4 6, .binary .add 4 4 5, .write 4 9, + .publicWord 4 7, .binary .add 4 4 5, .write 4 7, + .binary .add 9 9 7, .write 8 9, .constant 10 1, .binary .add 0 0 10] + +/-- Recover the source bundle from a segment ordinal by dividing by the port count. -/ +def bundle (p : Fin 8 → Word w) (i : Word w) : Word w := BinaryOp.div.eval i (p 0) + +/-- Find the incoming segment ordinal using the stored target bundle and the source port +translated by the bundle's XOR shift. -/ +def destination (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : Word w := + let b := bundle p i + let j := BinaryOp.mod.eval i (p 0) + let t := m (p 2 + b).val + let shift := m (p 3 + b).val + t * p 0 + BinaryOp.bitXor.eval j shift + +/-- Physical update, including the two offset records in the same source-port order. -/ +def update (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : Memory w := + let b := bundle p i + let j := destination p m i + let width := m (p 1 + i).val + let offset := m (p 4 + b).val + let out := writeMemory m (p 5 + i) offset + let inc := writeMemory (writeMemory out (p 6 + j) offset) (p 7 + j) width + writeMemory inc (p 4 + b) (offset + width) + +/-- External accesses and local word steps in scan order. -/ +def events (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + let b := bundle p i + let j := destination p m i + let width := m (p 1 + i).val + let offset := m (p 4 + b).val + [.tick, .tick, .tick, .tick, .tick, .tick, .read (p 2 + b) (m (p 2 + b).val), + .tick, .tick, .read (p 3 + b) (m (p 3 + b).val), .tick, .tick, .tick, + .tick, .tick, .read (p 1 + i) width, .tick, .tick, .read (p 4 + b) offset, + .tick, .tick, .write (p 5 + i) offset, .tick, .tick, .write (p 6 + j) offset, + .tick, .tick, .write (p 7 + j) width, .tick, .write (p 4 + b) (offset + width), .tick, .tick] + +theorem events_work (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : + (events p m i).length = 32 ∧ countProbes (events p m i) = 8 := ⟨rfl, rfl⟩ + +theorem events_after (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : + after m (events p m i) = update p m i := rfl + +set_option maxRecDepth 4096 in +private theorem visit_trace (p : Fin 8 → Word w) (m : Memory w) (i : Word w) (r : Regs w 12) : + ∃ rs, trace p i visit r m = some (events p m i, rs, update p m i) ∧ rs 0 = i + 1 := by + simp (config := {decide := true}) [visit, events, update, bundle, destination, trace, Op.effect, + BinaryOp.eval, Function.update] + rfl + +/-- From zeroed call-local memory the fixed table returns the next source identifier. +Its eight probes cover both ends even for a zero-width wire. -/ +theorem visit_native (p : Fin 8 → Word w) (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program 33 (M.program.start i) m [] = some ⟨events p m i, some (i + 1)⟩ := by + obtain ⟨rs, ht, hr⟩ := visit_trace p m i (fun _ => 0) + let M := (template visit 0).instantiate w p + change execute M.program (1 + visit.length) ⟨M.entry, i, fun _ => 0, fun _ => 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hr] + +/-- The updated total is the exact right endpoint whenever the bundle fits in one word. -/ +theorem prefix_exact (x y : Word w) (h : x.val + y.val < 2 ^ w) : + (x + y).val = x.val + y.val := by rw [Fin.val_add, Nat.mod_eq_of_lt h] + +end CompressorRecords.RefreshRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshReadback.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshReadback.lean new file mode 100644 index 0000000000..d07bcb3188 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshReadback.lean @@ -0,0 +1,157 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshBuild +import OAI.Computability.VPVNP.DegreeRefreshEntries + +/-! +# Reading the port-local coefficient from a constructed refresh + +At the local port, both segment lookups use the same site/port index. The incoming table +already contains the source ordering's offset. Reading the two independent half-words at +these stored intervals supplies the diagonal tests and all external halves of the two +ordered families of ties. The dense demand and selected payload rows determine the +arguments of the scalar-index map for the actual kernel. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.Readback + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry +open NetworkKernel WireTensor MotifConversion NewSlots RefreshRAM + +variable {bits a a₀ g dH t : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (q : Fin 8 → W bits) (m : Memory bits) + +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "D" => 2^a +local notation "S" => Fintype.card X.Base * D * 2^g * D +local notation "G" => splitSlots X +local notation "port" => bitWordFinEquiv a +local notation "w₀" => splitWidths X +local notation "ws" => groupedWidths port w₀ +local notation "perm" => oldPortMatching G port +local notation "dst" => bundleTarget G + +/-- Numerical width and offset of one incident external segment. The direction is local +to the port, so the incoming read needs no inverse translation. -/ +def interval (fit : S ≤ 2^bits) (outgoing : Bool) (e : DyadicArc X.Base (BitWord g) a) : ℕ × ℕ := + let i := idWord O fit e + if outgoing then ((cell q m 1 i).val,(cell q m 5 i).val) + else ((cell q m 7 i).val,(cell q m 6 i).val) + +/-- The width and offset in each physical half of the table describe the corresponding +source-ordered segment of the incident external word. -/ +theorem interval_spec {fit : S ≤ 2^bits} (data : SegmentFields X q fit m) (e : DyadicArc X.Base (BitWord g) a) : + interval X q m fit true e = (ws e,(outgoingRecord G port w₀ e).offset) ∧ + interval X q m fit false e = (ws ((perm).symm e),(incomingRecord G port w₀ e).offset) := by + obtain ⟨width,offset,_⟩ := data.segments e + have dest := (data.segments ((perm).symm e)).2.2 + simp only [Equiv.apply_symm_apply] at dest + exact ⟨Prod.ext width offset,Prod.ext dest.2 (dest.1.trans (congrArg SegmentRecord.offset + (incomingRecord_matching G port w₀ e).symm))⟩ + +/-- Read one bit using the stored length and offset. Empty segments have no readable bits. -/ +def bit {n : ℕ} (field : ℕ × ℕ) (wire : Refresh.Word n) (i : ℕ) : Option Bool := + if i < field.1 then if h : field.2+i < n then some (wire ⟨field.2+i,h⟩) else none else none + +private theorem bit_eq {n : ℕ} {field : ℕ × ℕ} (wire : Refresh.Word n) (i : Fin field.1) (j : Fin n) + (pos : j.val = field.2+i.val) : bit field wire i.val = some (wire j) := by + simp only [bit,ite_eq_left i.isLt,dite_eq_left (pos ▸ j.isLt)] + exact congrArg (fun v => some (wire v)) (Fin.ext pos.symm) + +/-- The two lists of segment words produced from physical endpoint records. -/ +def segments (fit : S ≤ 2^bits) (p : (X.Base × BitWord g) × Fin D) + (outWord : Refresh.Word (∑ j, ws (p,j))) (inWord : Refresh.Word (∑ j, ws ((dst).symm p,j))) : + PortSegments perm ws p.1 p.2 := + (fun j i => (bit (interval X q m fit true (p,j)) outWord i.val).getD false, + fun j i => (bit (interval X q m fit false (p,j)) inWord i.val).getD false) + +/-- Physical offsets and widths recover the same bit lists as the exact kernel for +arbitrary independently chosen incoming and outgoing payloads. -/ +theorem segments_eq {fit : S ≤ 2^bits} (data : SegmentFields X q fit m) (p : (X.Base × BitWord g) × Fin D) + (outWord : Refresh.Word (∑ j, ws (p,j))) (inWord : Refresh.Word (∑ j, ws ((dst).symm p,j))) : + segments X q m fit p outWord inWord = incidentPortSegments perm dst (oldPortMatching_bundle G port) ws p outWord inWord := by + apply Prod.ext + · funext j i + obtain ⟨u,pos,h⟩ := (local_bit_reads G port w₀ p j outWord inWord).1 i + change (bit (interval X q m fit true (p,j)) outWord i.val).getD false = _ + rw [(interval_spec X q m data (p,j)).1,bit_eq (field := (ws (p,j),(outgoingRecord G port w₀ (p,j)).offset)) outWord i u pos,h] + rfl + · funext j i + obtain ⟨u,pos,h⟩ := (local_bit_reads G port w₀ p j outWord inWord).2 i + change (bit (interval X q m fit false (p,j)) inWord i.val).getD false = _ + rw [(interval_spec X q m data (p,j)).2,bit_eq (field := (ws ((perm).symm (p,j)),(incomingRecord G port w₀ (p,j)).offset)) inWord i u pos,h] + rfl + +variable (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) + (choice : DyadicRefreshChoice X E hdH conn F) (ties : Fin t ≃ Tie (2^a)) (start stride : ℕ) + +local notation "P" => Allocation.plan X a₀ dH t stride start +local notation "Q" => Allocation.Plan.scratch P bits +local notation "demand" => blockDemandWidths G port w₀ +local notation "Y" => expanderBranchGraph G port w₀ E hdH conn F hD hd choice +local notation "outBase" => word (bits := bits) (Allocation.Plan.term P) +local notation "inBase" => word (bits := bits) (Allocation.Plan.demand P) + +/-- Read the selected payload vector without any search through a finite enumeration. -/ +def payload (base : W bits) (s : X.Base × BitWord g) (e : Fin D × Fin dH) : ℕ := + (m ((SupplyScan.recordBase X base stride s).val + 2 + (finProdFinEquiv e).val)).val + +theorem payload_eq {fit : S ≤ 2^bits} (stored : Build.Stored X E hdH conn F choice ties start stride fit m) + (s : X.Base × BitWord g) : payload X m stride outBase s = (choice s).val := by + funext e + simpa only [payload,Equiv.symm_apply_apply] using (stored.readback s).2.2 (finProdFinEquiv e) + +private noncomputable def loadedEntry (d d' : Tie D → ℕ) (v v' : Fin D × Fin dH → ℕ) + (hd : d' = d) (hv : v' = v) (j : Fin D) (x : MotifDemandPadding.HalfBits tieSource tieTarget d j) + (y : MotifSelector.Half (expanderSupply E hdH conn) (fun e => Fin (2^(supplyWidths F d v e))) j) : + Option (Fin (repetitions F d) → (parameterData F).Entry) := + let x' : MotifDemandPadding.HalfBits tieSource tieTarget d' j := hd.symm ▸ x + let y' : MotifSelector.Half (expanderSupply E hdH conn) (fun e => Fin (2^(supplyWidths F d' v' e))) j := + hd.symm ▸ hv.symm ▸ y + hd ▸ entry F (fun _ => zero_lt_one) d' v' j x' y' + +private theorem loadedEntry_eq (d d' : Tie D → ℕ) (v v' : Fin D × Fin dH → ℕ) + (hw : d' = d) (hv : v' = v) (j x y) : + loadedEntry E hdH conn F d d' v v' hw hv j x y = entry F (fun _ => zero_lt_one) d v j x y := by + subst d' v'; rfl + +/-- Port-local scalar indices using the constructed records for segment reads, demand +widths and the admitted supply profile. The ordinary incident half-wires remain inputs. -/ +noncomputable def indices {fit : S ≤ 2^bits} (stored : Build.Stored X E hdH conn F choice ties start stride fit m) + (p : (X.Base × BitWord g) × Fin D) + (before : Placed (refreshPositions port) (actualWireGraph G w₀).Half (promotedSites p)) + (after : (Y).Half (promotedSites p)) : + Option (Fin (repetitions F (demand p.1)) → (parameterData F).Entry) := by + classical + let n := blockSupplyWidths G port w₀ E hdH conn F choice + let A := fun s e => Fin (2^n s e) + let x := (originalIso G port w₀).pullHalf p (before (originalSites port p) (by simp [promotedSites,originalSites,refreshPositions])) + let u := (promotedIso G port w₀ E.toSlotGraph hD hd A n (fun s e => (wordIndex (n s e)).symm)).pullHalf p after + let z := segments X Q m fit p (u.1 (.inl p) rfl) (u.2 (.inl ((dst).symm p)) ((dst).apply_symm_apply p).symm) + let y := supplyHalf (R := ℤ) dst ws Prod.fst (fun e => (E.reverse e).1) A (2^a₀-(dH+1)) p u + exact if x.1 ((p.1,p.2),p.2) rfl = z.1 p.2 ∧ z.2 p.2 = incomingHalf (R := ℤ) perm ws p.1 p.2 p.2 x then + loadedEntry E hdH conn F (demand p.1) (DemandPreparation.demandAt ties (DemandScan.rowBase X t inBase p.1) m) + (choice p.1).val (payload X m stride outBase p.1) (stored.demands p.1) + (payload_eq X m E hdH conn F choice ties start stride stored p.1) p.2 (portInput (R := ℤ) perm ws p.1 p.2 x z) y + else none + +/-- The labels obtained from the physical records are exactly the common parameter +indices of the port kernel, including the failure cases of its diagonal and selector tests. -/ +theorem indices_eq {fit : S ≤ 2^bits} (stored : Build.Stored X E hdH conn F choice ties start stride fit m) + (p : (X.Base × BitWord g) × Fin D) + (before : Placed (refreshPositions port) (actualWireGraph G w₀).Half (promotedSites p)) + (after : (Y).Half (promotedSites p)) : + indices X m E hdH conn F hD hd choice ties start stride stored p before after = + refreshEntryIndices G port w₀ E hdH conn F hD hd choice p before after := by + unfold indices refreshEntryIndices + dsimp only + erw [segments_eq X Q m stored.segments,loadedEntry_eq] + +end CompressorRecords.PortRefresh.Readback + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshResult.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshResult.lean new file mode 100644 index 0000000000..45e8d8edc4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshResult.lean @@ -0,0 +1,102 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshDeterminism + +/-! +# Correctness of all native degree-refresh branches + +Determinism transfers the verified memory contents and resource bound to every complete +execution. Starting from the old incidence directory, an arbitrary family of block tapes +passes the physical preparation and term checks exactly when it encodes a unique admitted +branch that extends to a complete native refresh. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.Build + +open BurstRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry +open MotifConversion NewSlots RefreshRAM Allocation + +variable {bits a a₀ g dH t : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (choice : DyadicRefreshChoice X E hdH conn F) + (ties : Fin t ≃ Tie (2^a)) (T : IncidenceDirectory bits) (start stride : ℕ) + +local notation "P" => plan X a₀ dH t stride start +local notation "Q" => Plan.scratch P bits +local notation "N" => Fintype.card X.Base * 2^a * 2^g +local notation "B" => Fintype.card X.Base * 2^g +local notation "S" => N*2^a +local notation "sourceBase" => word (bits := bits) (Plan.demand P) +local notation "termBase" => word (bits := bits) (Plan.term P) +local notation "demand" => blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) +local notation "Y" => dyadicRefreshNext X E hdH conn F hD hd choice + +/-- Every successful full execution has the selected incidence columns, local-history +fields, interval frame and a linear bound on its total calls plus probes. -/ +theorem Run.result {L : PrepareLayout X T a₀ dH t stride start} {m : Memory bits} {rs : List (Report bits)} {cap : ℕ} + (execution : Run X E hdH conn F hD hd choice ties T start stride cap L m rs) + (old : T.Represents X m) (before : ∀ c : Fin 6, (T.column c).val+S ≤ start) + (wide : 2+2^a*dH ≤ stride) (room : (P).stop < 2^bits) + (termBits : termConstant E hdH conn F ties + 4*Nat.clog 2 (X.maxWireWidth+1) ≤ bits) + (nextWidth : (Y).maxWireWidth < 2^bits) + (capFit : TermWorker.budget F t (2^a*dH) bits X.maxWireWidth ≤ cap) : + ((P).output bits).Represents Y (after m (eventLog rs)) ∧ + Stored X E hdH conn F choice ties start stride L.regions.fits (after m (eventLog rs)) ∧ + (∀ addr, addr < start ∨ (P).stop ≤ addr → after m (eventLog rs) addr = m addr) ∧ + RAMBuckets.cost Report.probes rs ≤ chargeFactor E hdH conn F t * X.positions := by + obtain ⟨checked,run,rep,stored,frame,cost⟩ := build X E hdH conn F hD hd choice ties T start stride m old + before wide room termBits nextWidth cap capFit + obtain rfl := Run.deterministic execution run + exact ⟨rep,stored,frame,cost.trans (charge_le_positions X E hdH conn F hD hd choice)⟩ + +/-- Each bundle contains one old width for every port, even when several widths vanish. -/ +theorem bundle_total_le_max (b : (X.Base × BitWord g) × Fin (2^a)) : + (∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j) ≤ 2^a*X.maxWireWidth := by + calc + _ ≤ ∑ _j : Fin (2^a), X.maxWireWidth := Finset.sum_le_sum fun _ _ => X.width_le_maxWireWidth _ + _ = _ := by simp + +/-- Equivalence between acceptance of arbitrary physical block tapes and unique complete +branch realizability. The prepared demand memory is generated by executing the prefix. -/ +theorem branches_iff (m : Memory bits) (old : T.Represents X m) + (before : ∀ c : Fin 6, (T.column c).val+S ≤ start) (wide : 2+2^a*dH ≤ stride) (room : (P).stop < 2^bits) + (totalFit : 2^a*X.maxWireWidth < 2^bits) + (termBits : termConstant E hdH conn F ties + 4*Nat.clog 2 (X.maxWireWidth+1) ≤ bits) + (nextWidth : ∀ c, (dyadicRefreshNext X E hdH conn F hD hd c).maxWireWidth < 2^bits) + (cap : ℕ) (capFit : TermWorker.budget F t (2^a*dH) bits X.maxWireWidth ≤ cap) (tapes : Fin B → List Bool) : + let L := prepare_layout X T a₀ dH t stride start before room + (∃ pre m₁ terms, PrepareRun X T Q sourceBase ties (word (2^g)) L.regions.fits m m₁ pre ∧ + termRun E hdH conn F ties X sourceBase termBase stride cap tapes m₁ = some terms) ↔ + ∃! c : DyadicRefreshChoice X E hdH conn F, tapes = blockTapes E hdH conn F X c bits ∧ + ∃ rs, Run X E hdH conn F hD hd c ties T start stride cap L m rs := by + let L := prepare_layout X T a₀ dH t stride start before room + constructor + · rintro ⟨pre,prepared,terms,hr,ht⟩ + obtain ⟨_,canonical,hc,_,demands,_,_⟩ := prepare_demands X T Q sourceBase ties m old (word (2^g)) + L.degree L.lanes L.regions L.directory L.gather L.baseApart + (fun b => (bundle_total_le_max X b).trans_lt totalFit) L.demandRoom L.demandApart + have same := (PrepareRun.deterministic hr hc).2 + subst prepared + have hw (s) (e) : demand s e ≤ X.maxWireWidth := by + unfold blockDemandWidths internalWidth + split <;> exact X.width_le_maxWireWidth _ + have stream := term_stream_iff E hdH conn F ties X sourceBase termBase stride wide L.demandTerm L.termRoom + canonical X.maxWireWidth termBits hw demands cap capFit tapes + obtain ⟨c,encoded,unique⟩ := stream.mp (by rw [ht]; rfl) + obtain ⟨rs,run,_⟩ := build X E hdH conn F hD hd c ties T start stride m old before wide room termBits + (nextWidth c) cap capFit + exact ⟨c,⟨encoded,rs,run⟩,fun c' h => unique c' h.1⟩ + · rintro ⟨c,⟨encoded,rs,run⟩,_⟩ + obtain ⟨pre,terms,_,_,hr,ht,_⟩ := run + refine ⟨pre,after m (eventLog pre),terms,hr,?_⟩ + rw [encoded]; exact ht + +end CompressorRecords.PortRefresh.Build + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshScan.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshScan.lean new file mode 100644 index 0000000000..d6c8ffa48d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshScan.lean @@ -0,0 +1,242 @@ +import OAI.Computability.VPVNP.CompressorRecordRefresh +import OAI.Computability.VPVNP.RAMChain +import OAI.Computability.VPVNP.RAMBuckets + +/-! +# Complete external-bundle pass of Appendix E + +The segment scan visits all old actual arc numbers in increasing order. Each bundle's +accumulator is independent. Both endpoint arrays receive the prefix in source order and +the incoming array receives the source's width, including at an empty segment. The scan +runs from zeroed bundle totals and preserves the read-only directory and old widths. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- Directory and old wire lengths, in the word format used by `visit`. -/ +structure Input (w : ℕ) where + /-- The old outgoing width at each source-ordered segment ordinal. -/ + width : Word w → Word w + /-- The translated destination bundle number at each source bundle ordinal. -/ + target : Word w → Word w + /-- The binary port displacement associated with each source bundle. -/ + shift : Word w → Word w + +/-- Compute the destination segment ordinal from the immutable bundle target and port-shift +functions. -/ +def Input.dest (A : Input w) (p : Fin 8 → Word w) (i : Word w) : Word w := + let b := bundle p i + A.target b * p 0 + BinaryOp.bitXor.eval (BinaryOp.mod.eval i (p 0)) (A.shift b) + +/-- Width accumulated in a given bundle in the first `k` visits. -/ +def prefixTotal (p : Fin 8 → Word w) (A : Input w) : ℕ → Word w → ℕ + | 0, _ => 0 + | k+1, b => prefixTotal p A k b + + if bundle p (Fin.ofNat (2^w) k) = b then (A.width (Fin.ofNat (2^w) k)).val else 0 + +/-- Read the indexed word of the table whose base is the selected public operand. -/ +def cell (p : Fin 8 → Word w) (m : Memory w) (t : Fin 8) (i : Word w) : Word w := m (p t + i).val + +/-- The nonzero public indices name the seven arrays. All array indices are below `n`. -/ +structure Regions (p : Fin 8 → Word w) (n : ℕ) : Prop where + fits : n ≤ 2 ^ w + apart : ∀ (t u : Fin 8), t ≠ 0 → u ≠ 0 → ∀ (i j : Word w), i.val < n → j.val < n → + ((p t + i).val = (p u + j).val ↔ t = u ∧ i = j) + +/-- Seven consecutive arrays of the same capacity satisfy the address condition. -/ +theorem Regions.packed (p : Fin 8 → Word w) {base n : ℕ} (hfit : base + 7 * n ≤ 2 ^ w) + (haddr : ∀ t : Fin 8, t ≠ 0 → (p t).val = base + (t.val - 1) * n) : Regions p n := by + constructor + · omega + · intro t u ht hu i j hi hj + have addr (c : Fin 8) (hc : c ≠ 0) (x : Word w) (hx : x.val < n) : + (p c + x).val = base + (c.val - 1) * n + x.val := by + have hl : (c.val - 1 + 1) * n ≤ 7 * n := Nat.mul_le_mul_right _ (by have := c.isLt; omega) + rw [Nat.add_mul, Nat.one_mul] at hl + rw [Fin.val_add, haddr _ hc, Nat.mod_eq_of_lt (by omega)] + rw [addr _ ht _ hi, addr _ hu _ hj] + constructor + · intro he + have ha : (t.val - 1) * n + i.val = (u.val - 1) * n + j.val := by omega + have hi' := Nat.mul_add_mod_of_lt hi (a := t.val-1) + have hj' := Nat.mul_add_mod_of_lt hj (a := u.val-1) + have hij : i = j := Fin.ext (hi'.symm.trans ((congrArg (· % n) ha).trans hj')) + subst j + have htu := Nat.eq_of_mul_eq_mul_right (by omega : 0 < n) (Nat.add_right_cancel ha) + have tpos : t.val ≠ 0 := fun h => ht (Fin.ext h) + have upos : u.val ≠ 0 := fun h => hu (Fin.ext h) + exact ⟨Fin.ext (by omega), rfl⟩ + · rintro ⟨rfl,rfl⟩; rfl + +/-- `dest` permutes the scanned interval and all computed bundle totals fit in a word. -/ +structure Legal (p : Fin 8 → Word w) (n : ℕ) (A : Input w) : Prop where + dst_lt : ∀ i : Word w, i.val < n → (A.dest p i).val < n + dst_inj : ∀ i j : Word w, i.val < n → j.val < n → A.dest p i = A.dest p j → i = j + total_lt : ∀ i : Word w, i.val < n → prefixTotal p A i.val (bundle p i) + (A.width i).val < 2^w + +/-- Exactly the directory entries reached by old outgoing slot identifiers. -/ +def LiveBundle (p : Fin 8 → Word w) (n : ℕ) (b : Word w) : Prop := + ∃ i : Word w, i.val < n ∧ bundle p i = b + +private theorem LiveBundle.lt {p : Fin 8 → Word w} {n : ℕ} {b : Word w} (h : LiveBundle p n b) : b.val < n := by + obtain ⟨i,hi,rfl⟩ := h + exact ((Nat.mod_le _ _).trans (Nat.div_le_self ..)).trans_lt hi + +/-- Physical contents at the scan cursor. Unvisited output entries may contain arbitrary +words. Every incoming entry below the cursor is keyed by the translated destination. -/ +structure AtCursor (p : Fin 8 → Word w) (n : ℕ) (A : Input w) (m : Memory w) (k : ℕ) : Prop where + old : ∀ i : Word w, i.val < n → cell p m 1 i = A.width i + target : ∀ b : Word w, LiveBundle p n b → cell p m 2 b = A.target b + shift : ∀ b : Word w, LiveBundle p n b → cell p m 3 b = A.shift b + totals : ∀ b : Word w, LiveBundle p n b → cell p m 4 b = Fin.ofNat _ (prefixTotal p A k b) + done : ∀ i : Word w, i.val < k → + cell p m 5 i = Fin.ofNat _ (prefixTotal p A i.val (bundle p i)) ∧ + cell p m 6 (A.dest p i) = Fin.ofNat _ (prefixTotal p A i.val (bundle p i)) ∧ + cell p m 7 (A.dest p i) = A.width i + +/-- At cursor zero only the old tables and zeroed bundle totals need initialization. -/ +theorem AtCursor.start {p : Fin 8 → Word w} {n : ℕ} {A : Input w} {m : Memory w} + (old : ∀ i : Word w, i.val < n → cell p m 1 i = A.width i) + (target : ∀ b : Word w, LiveBundle p n b → cell p m 2 b = A.target b) + (shift : ∀ b : Word w, LiveBundle p n b → cell p m 3 b = A.shift b) + (totals : ∀ b : Word w, LiveBundle p n b → cell p m 4 b = 0) : AtCursor p n A m 0 := + ⟨old, target, shift, totals, fun _ hi => (Nat.not_lt_zero _ hi).elim⟩ + +/-- Under the one-word width bound the two offset cells carry the exact natural prefix. -/ +theorem AtCursor.exact {p : Fin 8 → Word w} {n k : ℕ} {A : Input w} {m : Memory w} + (h : AtCursor p n A m k) (legal : Legal p n A) (hk : k ≤ n) (i : Word w) (hi : i.val < k) : + (cell p m 5 i).val = prefixTotal p A i.val (bundle p i) ∧ + (cell p m 6 (A.dest p i)).val = prefixTotal p A i.val (bundle p i) ∧ + cell p m 7 (A.dest p i) = A.width i := by + obtain ⟨out,inc,len⟩ := h.done i hi + have fit := (Nat.le_add_right _ _).trans_lt (legal.total_lt i (hi.trans_le hk)) + exact ⟨(congrArg Fin.val out).trans (Nat.mod_eq_of_lt fit), + (congrArg Fin.val inc).trans (Nat.mod_eq_of_lt fit), len⟩ + +private theorem bundle_le (p : Fin 8 → Word w) (i : Word w) : (bundle p i).val ≤ i.val := + (Nat.mod_le _ _).trans (Nat.div_le_self ..) + +private theorem destination_at {p : Fin 8 → Word w} {A : Input w} {n k : ℕ} {m : Memory w} + (h : AtCursor p n A m k) (i : Word w) (hi : i.val < n) : destination p m i = A.dest p i := by + have hb : LiveBundle p n (bundle p i) := ⟨i,hi,rfl⟩ + change cell p m 2 (bundle p i) * _ + BinaryOp.bitXor.eval _ (cell p m 3 (bundle p i)) = _ + rw [h.target _ hb, h.shift _ hb] + rfl + +private theorem cell_update {p : Fin 8 → Word w} {A : Input w} {n : ℕ} {m : Memory w} + (reg : Regions p n) (legal : Legal p n A) (i : Word w) (hi : i.val < n) + (h : AtCursor p n A m i.val) (t : Fin 8) (ht : t ≠ 0) (x : Word w) (hx : x.val < n) : + let b := bundle p i + let off : Word w := Fin.ofNat _ (prefixTotal p A i.val b) + cell p (update p m i) t x = + if t = 4 ∧ x = b then off + A.width i + else if t = 7 ∧ x = A.dest p i then A.width i + else if t = 6 ∧ x = A.dest p i then off + else if t = 5 ∧ x = i then off else cell p m t x := by + have hb := (bundle_le p i).trans_lt hi + have hd := legal.dst_lt i hi + have hd' := destination_at h i hi + have h₁ := h.old i hi + have h₄ := h.totals _ ⟨i,hi,rfl⟩ + dsimp only [cell] at h₁ h₄ ⊢ + simp only [update, hd', h₁, h₄, writeMemory, reg.apart t 4 ht (by decide) x _ hx hb, + reg.apart t 7 ht (by decide) x _ hx hd, reg.apart t 6 ht (by decide) x _ hx hd, + reg.apart t 5 ht (by decide) x i hx hi] + +/-- A native segment visit preserves the scan invariant. -/ +theorem cursor_step {p : Fin 8 → Word w} {A : Input w} {n : ℕ} {m : Memory w} + (reg : Regions p n) (legal : Legal p n A) (i : Word w) (hi : i.val < n) + (h : AtCursor p n A m i.val) : AtCursor p n A (update p m i) (i.val+1) := by + have step := cell_update reg legal i hi h + have castI : Fin.ofNat (2^w) i.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt) + constructor + · intro j hj; simpa using (step 1 (by decide) j hj).trans (by simpa using h.old j hj) + · intro j hj; simpa using (step 2 (by decide) j hj.lt).trans (by simpa using h.target j hj) + · intro j hj; simpa using (step 3 (by decide) j hj.lt).trans (by simpa using h.shift j hj) + · intro b hb + rw [step 4 (by decide) b hb.lt] + by_cases he : b = bundle p i + · subst b + simp only [prefixTotal, castI, true_and, ite_true] + apply Fin.ext + simp [Fin.val_add, Fin.ofNat, Nat.mod_add_mod] + · simpa [prefixTotal, castI, he, Ne.symm he] using h.totals b hb + · intro j hj + have hjn : j.val < n := by omega + have hd := legal.dst_lt j hjn + rw [step 5 (by decide) j hjn, step 6 (by decide) (A.dest p j) hd, step 7 (by decide) (A.dest p j) hd] + by_cases he : j = i + · subst j; simp + · have hn : A.dest p j ≠ A.dest p i := fun hh => he (legal.dst_inj j i hjn hi hh) + have hlt : j.val < i.val := by have := Fin.val_ne_of_ne he; omega + simpa [he, hn] using h.done j hlt + +/-- The external pass writes the total and three segment columns, indexed below `n`. -/ +def outsideScan (p : Fin 8 → Word w) (n addr : ℕ) : Prop := + ∀ t : Fin 8, 4 ≤ t.val → ∀ i : Word w, i.val < n → addr ≠ (p t + i).val + +/-- All native calls of the external scan and all records through the resulting cursor. -/ +theorem scan_run {p : Fin 8 → Word w} {A : Input w} {n k : ℕ} {m : Memory w} + (reg : Regions p n) (legal : Legal p n A) (h : AtCursor p n A m k) + (steps : ℕ) (hb : k + steps ≤ n) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 33 (some (Fin.ofNat (2^w) k)) m (List.replicate steps []) = some rs ∧ + AtCursor p n A (after m (eventLog rs)) (k + steps) ∧ + (∀ addr, outsideScan p n addr → after m (eventLog rs) addr = m addr) ∧ rs.length = steps ∧ + ∀ r ∈ rs, r.events.length = 32 ∧ countProbes r.events = 8 := by + let M := (template visit 0).instantiate w p + induction steps generalizing k m with + | zero => exact ⟨[], rfl, h, fun _ _ => rfl, rfl, by simp⟩ + | succ s ih => + let i := Fin.ofNat (2^w) k + have hv : i.val = k := Nat.mod_eq_of_lt (by have := reg.fits; omega) + have hi : i.val < n := by omega + have hn := cursor_step reg legal i hi (hv ▸ h) + have hn' : i + 1 = Fin.ofNat (2^w) (k+1) := by + apply Fin.ext + rw [Fin.val_add, Fin.val_one', hv, Nat.add_mod_mod] + rfl + let r : Report w := ⟨events p m i, some (i+1)⟩ + obtain ⟨rs,hr,hc,frame,hlen,hw⟩ := ih (k := k+1) (hv ▸ hn) (by omega) + have hm : after m (eventLog (r :: rs)) = after (update p m i) (eventLog rs) := by + change List.foldl BurstRAM.update m (events p m i ++ eventLog rs) = _ + rw [List.foldl_append]; rfl + refine ⟨r :: rs, ?_, ?_, ?_, by simp [hlen], ?_⟩ + · change runSegment M.program 33 (some i) m (List.replicate (s+1) []) = _ + rw [List.replicate_succ, runSegment, visit_native p m i] + simp only [M, r, events_after, hn', hr, Option.map_some] + · simpa [hm, Nat.add_assoc, Nat.add_comm 1 s] using hc + · intro addr outside + rw [hm, frame addr outside] + have hd : (destination p m i).val < n := (destination_at (hv ▸ h) i hi) ▸ legal.dst_lt i hi + simp only [update, writeMemory, ite_eq_right (outside 4 (by decide) _ ((bundle_le p i).trans_lt hi)), + ite_eq_right (outside 7 (by decide) _ hd), ite_eq_right (outside 6 (by decide) _ hd), + ite_eq_right (outside 5 (by decide) _ hi)] + · intro q hq + rcases List.mem_cons.mp hq with rfl | hq + · exact events_work p m i + · exact hw q hq + +/-- The exact call-plus-probe cost through all visited segments. -/ +theorem scan_cost {rs : List (Report w)} (h : ∀ r ∈ rs, countProbes r.events = 8) : + RAMBuckets.cost (fun r : Report w => countProbes r.events) rs = 9 * rs.length := by + induction rs with + | nil => simp [RAMBuckets.cost] + | cons r rs ih => + rw [RAMBuckets.cost, h r (List.mem_cons_self ..), ih (fun q hq => h q (List.mem_cons_of_mem _ hq)), + List.length_cons, Nat.mul_succ] + omega + +end CompressorRecords.RefreshRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshSupplyScan.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshSupplyScan.lean new file mode 100644 index 0000000000..f12c23085f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshSupplyScan.lean @@ -0,0 +1,381 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshNewSlots +import OAI.Computability.VPVNP.DegreeRefreshPass +import OAI.Computability.VPVNP.CompressorTermRecord + +/-! +# Reading the chosen supply widths of every refresh block + +A term record stores its grid row, repetition count, and integer payload widths in +port/expander-slot order. The internal arcs in the degree refresh have additional selector +fields, one per repetition. This pass reads the chosen term at the source's block and +writes the total width to the supply column in the site order used by the slot emitter. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.SupplyScan + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open Compression Compression.Refresh Compression.DegreeRefresh NewSlots +open scoped Fin.CommRing + +variable {bits : ℕ} + +/-- The seven supply-scan operands give port and lane counts, expander degree, term base and +stride, selector width, and supply base. -/ +def params (D R h : ℕ) (termBase : BurstRAM.Word bits) (stride selectors : ℕ) + (supplyBase : BurstRAM.Word bits) : Fin 7 → BurstRAM.Word bits := + ![word D,word R,word h,termBase,word stride,word selectors,supplyBase] + +/-- The cursor ranges over all site/expander-slot pairs in supply-table order. -/ +def visit : List (Op 8 7) := + [.stateWord 0, .publicWord 1 0, .publicWord 2 1, .publicWord 3 2, + .binary .div 4 0 3, .binary .mod 5 0 3, .binary .div 6 4 2, .binary .mod 4 4 2, + .binary .mod 7 6 1, .binary .div 6 6 1, .binary .mul 6 6 2, .binary .add 6 6 4, + .publicWord 4 4, .binary .mul 6 6 4, .publicWord 4 3, .binary .add 6 4 6, + .constant 4 1, .binary .add 4 6 4, .read 4 4, .publicWord 2 5, .binary .mul 4 4 2, + .binary .mul 7 7 3, .binary .add 7 7 5, .constant 2 2, .binary .add 7 7 2, + .binary .add 7 6 7, .read 7 7, .binary .add 4 7 4, .publicWord 6 6, + .binary .add 6 6 0, .write 6 4, .constant 7 1, .binary .add 0 0 7] + +variable (p : Fin 7 → BurstRAM.Word bits) + +/-- Recover the promoted site from a supply cursor by dividing out the expander slot. -/ +def site (i : BurstRAM.Word bits) := BinaryOp.div.eval i (p 2) +/-- Recover the packed old vertex and promoted port by dividing out the residual lane. -/ +def vertexPort (i : BurstRAM.Word bits) := BinaryOp.div.eval (site p i) (p 1) +/-- Compute the selected term's block ordinal from the old vertex and residual lane, discarding +the promoted port. -/ +def block (i : BurstRAM.Word bits) := + BinaryOp.div.eval (vertexPort p i) (p 0) * p 1 + BinaryOp.mod.eval (site p i) (p 1) +/-- Index the selected payload coordinate by promoted port and local expander slot. -/ +def coordinate (i : BurstRAM.Word bits) := + BinaryOp.mod.eval (vertexPort p i) (p 0) * p 2 + BinaryOp.mod.eval i (p 2) +/-- First word of the fixed-stride term record for the cursor's block. -/ +def header (i : BurstRAM.Word bits) := p 3 + block p i * p 4 +/-- Address of the selected port-and-slot payload width after the term record's two header +words. -/ +def payload (i : BurstRAM.Word bits) := header p i + (coordinate p i + 2) +/-- Compute the internal width as the stored payload width plus the repetition count times the +selector width. -/ +def value (m : Memory bits) (i : BurstRAM.Word bits) := + m (payload p i).val + m (header p i+1).val * p 5 + +/-- The 33-event visit reads the repetition count and payload width and publishes the resulting +internal width. -/ +def events (m : Memory bits) (i : BurstRAM.Word bits) : List (Event bits) := + [.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick, + .tick,.tick,.tick,.tick,.read (header p i+1) (m (header p i+1).val),.tick,.tick,.tick, + .tick,.tick,.tick,.tick,.read (payload p i) (m (payload p i).val),.tick,.tick,.tick, + .write (p 6+i) (value p m i),.tick,.tick] + +theorem events_work (m : Memory bits) (i : BurstRAM.Word bits) : + (events p m i).length = 33 ∧ countProbes (events p m i) = 3 := ⟨rfl,rfl⟩ + +theorem events_after (m : Memory bits) (i : BurstRAM.Word bits) : + after m (events p m i) = writeMemory m (p 6+i) (value p m i) := rfl + +set_option maxRecDepth 4096 in +private theorem visit_trace (m : Memory bits) (i : BurstRAM.Word bits) (rs : Regs bits 8) : + ∃ out, trace p i visit rs m = some (events p m i,out,writeMemory m (p 6+i) (value p m i)) ∧ + out 0 = i+1 := by + simp (config := {decide := true}) [visit, events, value, header, payload, block, coordinate, + site, vertexPort, trace, Op.effect, BinaryOp.eval, Function.update] + +theorem visit_native (m : Memory bits) (i : BurstRAM.Word bits) : + let M := (template visit 0).instantiate bits p + execute M.program 34 (M.program.start i) m [] = some ⟨events p m i,some (i+1)⟩ := by + obtain ⟨out, ht, hret⟩ := visit_trace p m i (fun _ => 0) + let M := (template visit 0).instantiate bits p + change execute M.program (1 + visit.length) ⟨M.entry, i, fun _ => 0, fun _ => 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht]; simp [hret] + +/-- The term fields used by the pass lie outside the output column. -/ +def Apart (n : ℕ) : Prop := + ∀ i j : BurstRAM.Word bits, i.val < n → j.val < n → + (header p i+1).val ≠ (p 6+j).val ∧ (payload p i).val ≠ (p 6+j).val + +/-- The address is outside every supply destination whose cursor is less than the specified +count. -/ +def Outside (n addr : ℕ) : Prop := + ∀ j : BurstRAM.Word bits, j.val < n → addr ≠ (p 6+j).val + +/-- Materialized width rows and the memory frame through the given cursor. -/ +structure Prefix (initial m : Memory bits) (k : ℕ) : Prop where + rows : ∀ i : BurstRAM.Word bits, i.val < k → m (p 6+i).val = value p initial i + frame : ∀ addr, Outside p k addr → m addr = initial addr + +private theorem step (initial m : Memory bits) {n : ℕ} (apart : Apart p n) (i : BurstRAM.Word bits) + (hi : i.val < n) (cur : Prefix p initial m i.val) : + Prefix p initial (writeMemory m (p 6+i) (value p m i)) (i.val+1) := by + have same : value p m i = value p initial i := by + rw [value, cur.frame _ (fun j hj => (apart i j hi (hj.trans hi)).2), + cur.frame _ (fun j hj => (apart i j hi (hj.trans hi)).1)] + rfl + constructor + · intro j hj + by_cases eq : j = i + · subst j; simpa [writeMemory] using same + · have neq : (p 6+j).val ≠ (p 6+i).val := fun h => eq (add_left_cancel (Fin.ext h)) + rw [writeMemory, ite_eq_right neq] + exact cur.rows j (by have := Fin.val_ne_of_ne eq; omega) + · intro addr outside + rw [writeMemory, ite_eq_right (outside i (by omega))] + exact cur.frame addr (fun j hj => outside j (Nat.lt_succ_of_lt hj)) + +/-- Native visits extend any prefix in order, preserving all term records. -/ +theorem scan_run (initial m : Memory bits) (n k calls : ℕ) (fit : n ≤ 2^bits) + (apart : Apart p n) (cur : Prefix p initial m k) (room : k+calls ≤ n) : + let M := (template visit 0).instantiate bits p + ∃ rs, runSegment M.program 34 (some (Fin.ofNat (2^bits) k)) m (List.replicate calls []) = some rs ∧ + Prefix p initial (after m (eventLog rs)) (k+calls) ∧ rs.length = calls ∧ + ∀ r ∈ rs, r.events.length = 33 ∧ countProbes r.events = 3 := by + let M := (template visit 0).instantiate bits p + induction calls generalizing k m with + | zero => exact ⟨[],rfl,cur,rfl,by simp⟩ + | succ s ih => + let i := Fin.ofNat (2^bits) k + have hv : i.val = k := Nat.mod_eq_of_lt (by omega) + have next := step p initial m apart i (by omega) (hv ▸ cur) + have hnext : i+1 = Fin.ofNat (2^bits) (k+1) := by + apply Fin.ext; rw [Fin.val_add, Fin.val_one', hv, Nat.add_mod_mod]; rfl + let r : Report bits := ⟨events p m i,some (i+1)⟩ + obtain ⟨rs,run,rows,hl,hw⟩ := ih (writeMemory m (p 6+i) (value p m i)) (k+1) (hv ▸ next) (by omega) + have hm : after m (eventLog (r :: rs)) = after (writeMemory m (p 6+i) (value p m i)) (eventLog rs) := by + change List.foldl BurstRAM.update m (events p m i ++ eventLog rs) = _ + rw [List.foldl_append]; rfl + refine ⟨r :: rs, ?_, ?_, by simp [hl], ?_⟩ + · change runSegment M.program 34 (some i) m (List.replicate (s+1) []) = _ + rw [List.replicate_succ, runSegment, visit_native p m i] + simp only [M,r,events_after,hnext,run,Option.map_some] + · simpa [hm, Nat.add_assoc, Nat.add_comm 1 s] using rows + · intro q hq + rcases List.mem_cons.mp hq with rfl | hq + · exact events_work p m i + · exact hw q hq + +private theorem scan_cost {rs : List (Report bits)} (hw : ∀ r ∈ rs, countProbes r.events = 3) : + RAMBuckets.cost Report.probes rs = 4*rs.length := by + induction rs with + | nil => simp [RAMBuckets.cost] + | cons r rs ih => + change (1+countProbes r.events)+RAMBuckets.cost Report.probes rs = _ + rw [hw r (List.mem_cons_self ..), ih (fun q h => hw q (List.mem_cons_of_mem _ h)), + List.length_cons, Nat.mul_succ] + omega + +section Dyadic + +open SpectralGeometry MotifConversion + +variable {a g a₀ dH : ℕ} {K : Type*} [_root_.Field K] {c₁ c₂ : ℝ} + (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock K (expanderSupply E hdH conn) (2^a₀) c₁ c₂) + (choice : DyadicRefreshChoice X E hdH conn F) + (termBase : BurstRAM.Word bits) (stride : ℕ) (supplyBase : BurstRAM.Word bits) + +local notation "Nₛ" => Fintype.card X.Base * 2^a * 2^g +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "Iₛ" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) E hdH conn F choice +local notation "demand" => blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) +local notation "pub" => params (2^a) (2^g) dH termBase stride F.selectorBits supplyBase + +/-- Term records are indexed by base vertex and residual lane. -/ +def recordBase (s : X.Base × BitWord g) : BurstRAM.Word bits := + termBase + word ((X.baseIndex s.1).val * 2^g + (bitWordFinEquiv g s.2).val) * word stride + +/-- The two physical fields consumed from each selected term. The outer vector uses +the port/expander-slot order of the term writer. -/ +structure TermFields (m : Memory bits) : Prop where + fits : ∀ s, (recordBase X termBase stride s).val + 2 + 2^a * dH < 2^bits + repetitions : ∀ s, m ((recordBase X termBase stride s).val+1) = word (MotifConversion.repetitions F (demand s)) + payload : ∀ s (e : Fin (2^a) × Fin dH), + m ((recordBase X termBase stride s).val+2+e.1.val*dH+e.2.val) = word ((choice s).val e) + +private theorem finPair_val {n m : ℕ} (i : Fin n) (j : Fin m) : + (finProdFinEquiv (i,j)).val = i.val*m + j.val := by + change j.val+m*i.val = _; ring + +/-- The natural-number fields of the batch term reader, in its supply-coordinate order, +suffice to construct the word-valued inputs of this scan. -/ +theorem TermFields.ofValues (m : Memory bits) + (fit : ∀ s, (recordBase X termBase stride s).val+2+2^a*dH < 2^bits) + (rep : ∀ s, (m ((recordBase X termBase stride s).val+1)).val = MotifConversion.repetitions F (demand s)) + (vec : ∀ s (i : Fin (2^a*dH)), (m ((recordBase X termBase stride s).val+2+i.val)).val = + (choice s).val (finProdFinEquiv.symm i)) : TermFields X E hdH conn F choice termBase stride m := by + have toWord (x : BurstRAM.Word bits) (v : ℕ) (h : x.val = v) : x = word v := + Fin.ext (h.trans (Nat.mod_eq_of_lt (h ▸ x.isLt)).symm) + refine ⟨fit,fun s => toWord _ _ (rep s),fun s e => toWord _ _ ?_⟩ + have h := vec s (finProdFinEquiv e) + rw [Equiv.symm_apply_apply] at h + rw [show (finProdFinEquiv e).val = e.1.val*dH+e.2.val from finPair_val e.1 e.2] at h + simpa only [Nat.add_assoc] using h + +/-- Read the two fields from a physical table of the actual native term memory images. +Each block can have a different input memory, row, and selected repetition count. -/ +theorem TermFields.ofRecordMemory (m : Memory bits) (prior : X.Base × BitWord g → Memory bits) + (row u : X.Base × BitWord g → BurstRAM.Word bits) + (fit : ∀ s, (recordBase X termBase stride s).val+2+2^a*dH < 2^bits) + (rep : ∀ s, (u s).val = MotifConversion.repetitions F (demand s)) + (record : ∀ s addr, let b := recordBase X termBase stride s + b.val ≤ addr → addr < b.val+2+2^a*dH → + m addr = TermRecord.recordMemory (prior s) b (row s) (u s) finProdFinEquiv.symm (choice s).val addr) : + TermFields X E hdH conn F choice termBase stride m := by + have fields (s) := TermRecord.recordMemory_fields (prior s) (recordBase X termBase stride s) + (row s) (u s) finProdFinEquiv.symm (choice s).val (fit s) + constructor + · exact fit + · intro s + rw [record s _ (by omega) (by omega), (fields s).2.1, ← rep s] + exact Fin.ext (Nat.mod_eq_of_lt (u s).isLt).symm + · intro s e + let i := finProdFinEquiv e + have hi : i.val = e.1.val*dH + e.2.val := finPair_val e.1 e.2 + have idx : (recordBase X termBase stride s).val+2+e.1.val*dH+e.2.val = + (recordBase X termBase stride s).val+2+i.val := by omega + rw [idx, record s _ (by omega) (by have := i.isLt; omega), (fields s).2.2.1 i] + simp [i] + +/-- Dimension and output-index bounds for the sweep. -/ +structure Fits (bits : ℕ) : Prop where + ports : 2^a < 2^bits + lanes : 2^g < 2^bits + degree : dH < 2^bits + rows : Nₛ*dH ≤ 2^bits + +private theorem unpack {x d : BurstRAM.Word bits} {hi lo : ℕ} (h : x.val = hi*d.val+lo) (hl : lo < d.val) : + (BinaryOp.div.eval x d).val = hi ∧ (BinaryOp.mod.eval x d).val = lo := by + have hd : 0 < d.val := Nat.zero_lt_of_lt hl + have hq : x.val / d.val = hi := by rw [h, Nat.mul_comm hi, Nat.mul_add_div hd, Nat.div_eq_of_lt hl, Nat.add_zero] + exact ⟨(Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt)).trans hq, + (Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt)).trans (h ▸ Nat.mul_add_mod_of_lt hl)⟩ + +/-- The runtime quotient/remainder operations recover the block number and payload +coordinate from the site/slot cursor. -/ +private theorem addresses (dims : Fits (dH := dH) X bits) + (s : (X.Base × BitWord g) × Fin (2^a)) (k : Fin dH) : + let i : BurstRAM.Word bits := word ((O s).val*dH+k.val) + header pub i = recordBase X termBase stride s.1 ∧ coordinate pub i = word (s.2.val*dH+k.val) := by + let i : BurstRAM.Word bits := word ((O s).val*dH+k.val) + have hlt : (O s).val*dH+k.val < Nₛ*dH := finPair_val (O s) k ▸ (finProdFinEquiv (O s,k)).isLt + have hv : i.val = (O s).val*dH+k.val := Nat.mod_eq_of_lt (hlt.trans_le dims.rows) + have h₀ : (pub 0).val = 2^a := Nat.mod_eq_of_lt dims.ports + have h₁ : (pub 1).val = 2^g := Nat.mod_eq_of_lt dims.lanes + have h₂ : (pub 2).val = dH := Nat.mod_eq_of_lt dims.degree + have hk := unpack (d := pub 2) (by simpa only [h₂] using hv) (by rw [h₂]; exact k.isLt) + have hs : (site pub i).val = ((X.baseIndex s.1.1).val * 2^a + s.2.val)*(pub 1).val + + (bitWordFinEquiv g s.1.2).val := by rw [site, hk.1, sites_val, h₁] + have hl := unpack hs (by rw [h₁]; exact (bitWordFinEquiv g s.1.2).isLt) + have hb := unpack (d := pub 0) (by simpa only [h₀] using hl.1) (by rw [h₀]; exact s.2.isLt) + have block_eq : block pub i = word ((X.baseIndex s.1.1).val*2^g + (bitWordFinEquiv g s.1.2).val) := by + apply Fin.ext + rw [block, vertexPort, Fin.val_add, Fin.val_mul, hb.1, hl.2, h₁, Nat.mod_add_mod] + rfl + refine ⟨?_,?_⟩ + · change pub 3 + block pub i * pub 4 = _ + rw [block_eq]; rfl + · apply Fin.ext + change (coordinate pub i).val = _ % _ + rw [coordinate, vertexPort, Fin.val_add, Fin.val_mul, hb.2, hk.2, h₂, Nat.mod_add_mod] + +private theorem physical_addresses (dims : Fits (dH := dH) X bits) + (s : (X.Base × BitWord g) × Fin (2^a)) (k : Fin dH) + (fit : (recordBase X termBase stride s.1).val+2+2^a*dH < 2^bits) : + let i : BurstRAM.Word bits := word ((O s).val*dH+k.val) + (header pub i+1).val = (recordBase X termBase stride s.1).val+1 ∧ + (payload pub i).val = (recordBase X termBase stride s.1).val+2+s.2.val*dH+k.val := by + let i : BurstRAM.Word bits := word ((O s).val*dH+k.val) + let b := recordBase X termBase stride s.1 + change b.val+2+2^a*dH < 2^bits at fit + have hk : s.2.val*dH+k.val < 2^a*dH := finPair_val s.2 k ▸ (finProdFinEquiv (s.2,k)).isLt + have h : (b+1).val = b.val+1 := by + rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (show 1 < 2^bits by omega), Nat.mod_eq_of_lt (by omega)] + have hp : (b + (word (s.2.val*dH+k.val) + 2)).val = b.val+2+s.2.val*dH+k.val := by + have htwo : (2 : BurstRAM.Word bits).val = 2 := Nat.mod_eq_of_lt (show 2 < 2^bits by omega) + have hidx : s.2.val*dH+k.val < 2^bits := by omega + have hidx' : s.2.val*dH+k.val+2 < 2^bits := by omega + have haddr : b.val+(s.2.val*dH+k.val+2) < 2^bits := by omega + rw [Fin.val_add, Fin.val_add, Fin.val_ofNat, htwo, Nat.mod_eq_of_lt hidx, + Nat.mod_eq_of_lt hidx', Nat.mod_eq_of_lt haddr] + omega + obtain ⟨hblock,hcoord⟩ := addresses X E hdH conn F termBase stride supplyBase dims s k + change (header pub i+1).val = _ ∧ (header pub i+(coordinate pub i+2)).val = _ + rw [hblock, hcoord] + exact ⟨h,hp⟩ + +/-- A strided term region and a disjoint contiguous supply region satisfy the separation +needed by the physical sweep. Either order of the two regions is allowed. -/ +theorem apart_of_intervals (dims : Fits (dH := dH) X bits) (rowFits : 2+2^a*dH ≤ stride) + (termFit : termBase.val + (Fintype.card X.Base * 2^g)*stride < 2^bits) + (outFit : supplyBase.val + Nₛ*dH ≤ 2^bits) + (sep : termBase.val + (Fintype.card X.Base * 2^g)*stride ≤ supplyBase.val ∨ + supplyBase.val + Nₛ*dH ≤ termBase.val) : Apart pub (Nₛ*dH) := by + intro i j hi hj + let pos := (finProdFinEquiv (m := Nₛ) (n := dH)).symm ⟨i.val,hi⟩ + let s := (O).symm pos.1 + let k := pos.2 + let key := (X.baseIndex s.1.1).val*2^g + (bitWordFinEquiv g s.1.2).val + have hkey : key < Fintype.card X.Base * 2^g := by + simpa only [key, finPair_val] using (finProdFinEquiv (X.baseIndex s.1.1,bitWordFinEquiv g s.1.2)).isLt + have hroom := Nat.mul_le_mul_right stride (Nat.succ_le_of_lt hkey) + rw [Nat.succ_mul] at hroom + have hb : (recordBase X termBase stride s.1).val = termBase.val + key*stride := by + change (termBase.val + ((key % 2^bits)*(stride % 2^bits)) % 2^bits) % 2^bits = _ + rw [Nat.mod_mul_mod, Nat.mul_mod_mod, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)] + have idx : (O s).val*dH+k.val = i.val := by + have hh : (finProdFinEquiv pos).val = i.val := congrArg Fin.val (finProdFinEquiv.apply_symm_apply ⟨i.val,hi⟩) + rw [show (finProdFinEquiv pos).val = pos.1.val*dH+pos.2.val from finPair_val ..] at hh + simpa only [s,k,Equiv.apply_symm_apply] using hh + have hid : word ((O s).val*dH+k.val) = i := by rw [idx]; exact Fin.ext (Nat.mod_eq_of_lt i.isLt) + have hout : (pub 6 + j).val = supplyBase.val+j.val := + Nat.mod_eq_of_lt (show supplyBase.val + j.val < 2^bits by omega) + have hrow : (recordBase X termBase stride s.1).val+2+2^a*dH < 2^bits := by omega + have hk : s.2.val*dH+k.val < 2^a*dH := finPair_val s.2 k ▸ (finProdFinEquiv (s.2,k)).isLt + obtain ⟨hrep,hpay⟩ := physical_addresses X E hdH conn F termBase stride supplyBase dims s k hrow + rw [hid] at hrep hpay + rw [hrep,hpay,hout,hb] + constructor <;> omega + +/-- Each computed value is the actual selected supply width including selector bits. -/ +theorem read_supply (m : Memory bits) (terms : TermFields X E hdH conn F choice termBase stride m) + (dims : Fits (dH := dH) X bits) (s : (X.Base × BitWord g) × Fin (2^a)) (k : Fin dH) : + value pub m (word ((O s).val*dH+k.val)) = word (Iₛ s.1 (s.2,k)) := by + obtain ⟨hrep,hpay⟩ := physical_addresses X E hdH conn F termBase stride supplyBase dims s k (terms.fits s.1) + rw [value,hrep,hpay,terms.payload s.1 (s.2,k),terms.repetitions] + apply Fin.ext + change ((word ((choice s.1).val (s.2,k)) : BurstRAM.Word bits) + word (repetitions F (demand s.1)) * + word F.selectorBits).val = (((choice s.1).val (s.2,k)) + repetitions F (demand s.1)*F.selectorBits) % _ + simp [Fin.val_add, Fin.val_mul, word, Nat.mod_add_mod, Nat.mod_mul_mod] + +/-- Full table for the expander slots of the selected branch, with one native call and +three probes per row, and the exact frame for the shared memory. -/ +theorem supply_pass (m : Memory bits) (terms : TermFields X E hdH conn F choice termBase stride m) + (dims : Fits (dH := dH) X bits) (apart : Apart pub (Nₛ*dH)) + (widthFit : ∀ (s : (X.Base × BitWord g) × Fin (2^a)) (k : Fin dH), Iₛ s.1 (s.2,k) < 2^bits) : + let M := (template visit 0).instantiate bits pub + ∃ rs, runSegment M.program 34 (some 0) m (List.replicate (Nₛ*dH) []) = some rs ∧ + (∀ s (k : Fin dH), ((after m (eventLog rs)) (supplyBase + word ((O s).val*dH+k.val)).val).val = Iₛ s.1 (s.2,k)) ∧ + (∀ addr, Outside pub (Nₛ*dH) addr → after m (eventLog rs) addr = m addr) ∧ + RAMBuckets.cost Report.probes rs = 4*(Nₛ*dH) ∧ rs.length = Nₛ*dH ∧ + ∀ r ∈ rs, r.events.length = 33 ∧ countProbes r.events = 3 := by + have init : Prefix pub m m 0 := ⟨fun _ h => (Nat.not_lt_zero _ h).elim, fun _ _ => rfl⟩ + obtain ⟨rs,run,done,hl,hw⟩ := scan_run pub m m (Nₛ*dH) 0 (Nₛ*dH) dims.rows apart init (by simp) + refine ⟨rs,run,?_,by simpa using done.frame,(scan_cost (fun r h => (hw r h).2)).trans (by rw [hl]),hl,hw⟩ + intro s k + let i : BurstRAM.Word bits := word ((O s).val*dH+k.val) + have hk : (O s).val*dH+k.val < Nₛ*dH := finPair_val (O s) k ▸ (finProdFinEquiv (O s,k)).isLt + have hi : i.val < Nₛ*dH := (Nat.mod_le ..).trans_lt hk + have stored := done.rows i (by simpa only [Nat.zero_add] using hi) + change ((after m (eventLog rs)) (pub 6+i).val).val = _ + rw [stored, read_supply X E hdH conn F choice termBase stride supplyBase m terms dims s k] + exact Nat.mod_eq_of_lt (widthFit s k) + +end Dyadic +end CompressorRecords.PortRefresh.SupplyScan + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRefreshTerms.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshTerms.lean new file mode 100644 index 0000000000..103bdab424 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRefreshTerms.lean @@ -0,0 +1,65 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshExternal +import OAI.Computability.VPVNP.CompressorRecordChoices +import OAI.Computability.VPVNP.DegreeRefreshConversion + +/-! +# Selecting and recording one expander-motif term per port block + +The term reader uses the widths of the two copies of the ordered ties, including an +incoming width at its translated source address. Every accepted encoding selects exactly +one family of terms of the actual refresh. The internal arcs in the numbered output rows +carry the selected supply widths, including the selector fields required by the motif map. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh + +open Compression Compression.Refresh Compression.DegreeRefresh +open MotifGrid MotifBlocks MotifConversion SpectralGeometry + +variable {V E L : Type} {D dH d₀ n bits : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable [AddCommGroup E] [AddCommGroup L] (G : LiftedSlots V D (E × L)) + (port : E ≃ Fin D) (w : (V × Fin D) × (E × L) → ℕ) + (P : RegularArcGraph (Fin D) dH) (hdH : 0 < dH) (conn : (arcSupportGraph P.multiplicity).Connected) + (F : FixedBlock k tieSource tieTarget (expanderSupply P hdH conn) + (realWidths tieMass) (realWidths (expanderMass d₀)) K K') + +/-- The demand vector used by the reader is available from the two endpoint record tables. -/ +theorem demand_vector (s : V × L) : + (fun e => (demandRecord G port w s e).width) = blockDemandWidths G port w s := + funext (demandRecord_width G port w s) + +variable (hD : 1 < D) (hd : dH + 1 ≤ d₀) + (blocks : Fin n ≃ V × L) (fit : ∀ s, outerCap F (blockDemandWidths G port w s) < 2 ^ bits) + +include hD hd in +private theorem supplyMassPos (e : Fin D × Fin dH) : 0 < expanderMass d₀ e := + div_pos (Nat.cast_pos.mpr (by omega)) (Nat.cast_pos.mpr (by omega)) + +/-- Complete choice prefixes biject with the internal terms in the exact degree refresh. -/ +noncomputable def termReader : ChoiceReader (BlockChoices G port w P hdH conn F) := + motifPassReader F blocks finProdFinEquiv.symm (supplyMassPos hD hd) (blockDemandWidths G port w) bits fit + +theorem termReader_bits (c : BlockChoices G port w P hdH conn F) : + ((termReader G port w P hdH conn F hD hd blocks fit).encode c).length ≤ n * ((D * dH) * bits) := + motifPass_bits_le F blocks finProdFinEquiv.symm (supplyMassPos hD hd) (blockDemandWidths G port w) bits fit c + +/-- The stored expander slot number identifies the supply role, the matching incoming slot +and the exact payload-plus-selector width of this branch. -/ +theorem chosen_supply_record (c : BlockChoices G port w P hdH conn F) (s : V × L) (e : Fin D × Fin dH) : + let internal := blockSupplyWidths G port w P hdH conn F c + let r := slotRecord G port w P.toSlotGraph hd internal (s,e.1) (.inr (.inl e.2)) + r.src = (promotedSites (s,e.1), refreshSlots hd (.inr (.inl e.2))) ∧ + r.dst = (promotedSites (s,(P.reverse e).1), refreshSlots hd (.inr (.inl (P.reverse e).2))) ∧ + r.width = supplyWidths F (fun t => (demandRecord G port w s t).width) (c s).val e := by + rw [demand_vector] + exact ⟨rfl, rfl, rfl⟩ + +end CompressorRecords.PortRefresh + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordRegisterSetup.lean b/lean/OAI/Computability/VPVNP/CompressorRecordRegisterSetup.lean new file mode 100644 index 0000000000..65961a2d9f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordRegisterSetup.lean @@ -0,0 +1,213 @@ +import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +import OAI.Computability.VPVNP.PairSimulationPrivateSlices + +/-! +# Loading a finite family of operand expressions into live registers + +The six input registers provide the five expression operands and the state operand. +Each expression is evaluated using the existing straight-line compiler in the same +scratch bank. Its result is copied to its own output register. All loads use the +current external memory. Neither memory changes and no branch bits are consumed. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RegisterSetup + +open BurstRAM BurstRAM.PrivateRAM PhaseRecipe RowRecipe +open PrimedStackRAM (Regs) +open scoped Fin.CommRing +open private eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe +open private run run_append run_single compile_keep compile_value from OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +open private ReadPrefix ReadPrefix.nil ReadPrefix.tick ReadPrefix.read ReadPrefix.execute + from OAI.Computability.VPVNP.PairSimulationPrivateSlices + +variable {n v w p r k : ℕ} (f : Fin n → Expr) + +/-- Maximum number of temporary slots needed by any expression in the operand bank. -/ +def scratchCount := Finset.univ.sup fun i => (f i).slots +/-- Register count for the output bank, shared expression scratch, and one final fallback +register. -/ +def regCount := n + scratchCount f + 1 + +/-- The dedicated register holding the value of the expression at this index. -/ +def output (i : Fin n) : Fin (regCount f) := ⟨i.val, by unfold regCount; have := i.isLt; omega⟩ +/-- Select a register after the outputs for an in-range scratch index, or the last register +otherwise. -/ +def scratch (j : ℕ) : Fin (regCount f) := + if h : j < scratchCount f then ⟨n+j, by unfold regCount; omega⟩ + else Fin.last (n+scratchCount f) + +private theorem room (i : Fin n) : (f i).slots ≤ scratchCount f := Finset.le_sup (f := fun j => (f j).slots) (Finset.mem_univ i) + +private theorem scratch_val {j : ℕ} (hj : j < scratchCount f) : (scratch f j).val = n+j := by + simp [scratch,hj] + +/-- Compile one operand expression into shared scratch and copy its value to its dedicated +output register. -/ +def emit (i : Fin n) : List (Assign (regCount f) 5) := + (f i).compile (scratch f) 0 ++ [⟨output f i,.copy (scratch f 0)⟩] + +/-- Concatenate the expression evaluations and output copies in increasing operand-index order. -/ +def lines := (List.finRange n).flatMap (emit f) + +private theorem emit_output (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (rs : Regs w (regCount f)) (i j : Fin n) : + run pub s m (emit f i) rs (output f j) = if i = j then (f i).eval pub s m else rs (output f j) := by + rw [emit,run_append,run_single] + by_cases h : i=j + · subst j + simp only [Function.update_self,RHS.value] + apply compile_value _ _ _ _ _ (scratchCount f) _ _ (by simpa using room f i) + intro j hj k hk he + have eq := congrArg Fin.val he + rw [scratch_val f hj,scratch_val f hk] at eq + omega + · have ne : output f j ≠ output f i := by intro e; exact h (Fin.ext (congrArg Fin.val e).symm) + rw [ite_eq_right h,Function.update_of_ne ne] + apply compile_keep + intro u _ hu eq + have eq' := congrArg Fin.val eq + rw [scratch_val f (by have := room f i; omega)] at eq' + change j.val = n+u at eq'; have := j.isLt; omega + +private theorem emit_list (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) (is : List (Fin n)) + (rs : Regs w (regCount f)) (j : Fin n) : + run pub s m (is.flatMap (emit f)) rs (output f j) = if j ∈ is then (f j).eval pub s m else rs (output f j) := by + induction is generalizing rs with + | nil => rfl + | cons i is ih => + rw [List.flatMap_cons,run_append,ih,emit_output] + by_cases hi : i=j + · subst i; simp + · simp [hi,Ne.symm hi] + +variable (bank : Fin v ↪ Fin r) (inputs : Fin 6 → Fin r) + +/-- Lower a recipe assignment to a private-machine instruction using the designated work +registers, input registers, and successor address. -/ +def instruction (a : Assign v 5) (next : Fin p) : Instr w p r k := match a.rhs with + | .literal x => .constant (bank a.dst) (Fin.ofNat _ x.val) next + | .publicWord j => .copy (bank a.dst) (inputs j.castSucc) next + | .state => .copy (bank a.dst) (inputs (Fin.last 5)) next + | .copy j => .copy (bank a.dst) (bank j) next + | .binary op j l => .binary op (bank a.dst) (bank j) (bank l) next + | .read j => .readExternal (bank a.dst) (bank j) next + +theorem resize_instruction (a : Assign v 5) (next : Fin p) : + (instruction (w := 2) (k := k) bank inputs a next).resize w = instruction bank inputs a next := by + obtain ⟨i,h⟩ := a + cases h <;> simp only [instruction,Instr.resize,Fin.ofNat_val_eq_self] + +/-- Every program address in the assignment list contains the specified lowered instruction +linked to the next address. -/ +def Linked (M : Machine w p r k) (pc : ℕ → Fin p) (ls : List (Assign v 5)) : Prop := + ∀ i : Fin ls.length, M.code (pc i.val) = instruction bank inputs ls[i.val] (pc (i.val+1)) + +private theorem execute_lines (M : Machine w p r k) (m : Memory w) (ls : List (Assign v 5)) + (safe : ∀ i j, bank i ≠ inputs j) (pub : Fin 5 → Word w) (state : Word w) + (rs : Regs w v) (pc : ℕ → Fin p) (link : Linked bank inputs M pc ls) (c : Config w p r) + (atStart : c.pc = pc 0) (hp : ∀ i : Fin 5, c.reg (inputs i.castSucc) = pub i) + (hs : c.reg (inputs (Fin.last 5)) = state) (hv : ∀ i, c.reg (bank i) = rs i) : + let ev := evaluate pub state m ls rs + ∃ d, ReadPrefix M m c ev.1 d ∧ d.pc = pc ls.length ∧ d.privateMem = c.privateMem ∧ + d.persistent = c.persistent ∧ (∀ i, d.reg (bank i) = ev.2 i) ∧ + ∀ j, (∀ i, j ≠ bank i) → d.reg j = c.reg j := by + induction ls generalizing pc c rs with + | nil => exact ⟨c,ReadPrefix.nil _,atStart,rfl,rfl,hv,fun _ _ => rfl⟩ + | cons a ls ih => + let value := a.rhs.value pub state m rs + let c' := c.put (pc 1) (bank a.dst) value + let rs' := Function.update rs a.dst value + have hstep : M.program.step c = (instruction bank inputs a (pc 1)).run M.publicData c := by + have h := link ⟨0,by simp⟩ + simp only [Machine.program,atStart] + rw [h]; rfl + have keep (j : Fin r) (h : j ≠ bank a.dst) : c'.reg j = c.reg j := Function.update_of_ne h .. + have hv' (i) : c'.reg (bank i) = rs' i := by + by_cases he : i=a.dst + · subst i; simp [c',rs',Config.put] + · rw [keep _ (bank.injective.ne he)]; exact (hv i).trans (Function.update_of_ne he ..).symm + have tail : Linked bank inputs M (fun i => pc (i+1)) ls := fun i => link ⟨i.val+1,by simp [i.isLt]⟩ + obtain ⟨d,ht,hd,hm,hp',hr,hf⟩ := ih rs' _ tail c' rfl + (fun j => (keep _ (safe _ _).symm).trans (hp j)) ((keep _ (safe _ _).symm).trans hs) hv' + refine ⟨d,?_,hd,hm,hp',hr,fun j h => (hf j h).trans (keep _ (h _))⟩ + cases a with | mk dest rhs => + cases rhs with + | literal v => exact ReadPrefix.tick hstep ht + | publicWord j => + apply ReadPrefix.tick _ ht + rw [hstep]; simp only [instruction,Instr.run,hp]; rfl + | state => + apply ReadPrefix.tick _ ht + rw [hstep]; simp only [instruction,Instr.run,hs]; rfl + | copy j | binary _ j _ => + apply ReadPrefix.tick _ ht + rw [hstep]; simp only [instruction,Instr.run,hv]; rfl + | read j => + apply @ReadPrefix.read _ _ _ _ M m c (fun u => c.put (pc 1) (bank dest) u) d _ (rs j) _ ht + rw [hstep]; simp only [instruction,Instr.run,hv] + +private theorem lines_probes (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) (rs : Regs w (regCount f)) : + countProbes (evaluate pub state m (lines f) rs).1 = ∑ i, (f i).loads := by + rw [(eval_cost pub state m (lines f) rs).2] + have cost (is : List (Fin n)) : + ((is.flatMap (emit f)).map fun a => a.rhs.reads).sum = (is.map fun i => (f i).loads).sum := by + induction is with + | nil => rfl + | cons i is ih => + simp only [List.flatMap_cons,List.map_append,List.sum_append,ih,emit,Expr.compile_reads,List.map_cons,List.sum_cons] + rfl + rw [lines,cost,← List.ofFn_id,List.map_ofFn,List.sum_ofFn]; rfl + +private theorem no_choices (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) (ls : List (Assign v 5)) (rs : Regs w v) : + choiceBits (evaluate pub state m ls rs).1 = [] := by + induction ls generalizing rs with + | nil => rfl + | cons a ls ih => + obtain ⟨dest,rhs⟩ := a + cases rhs <;> simp only [evaluate,RHS.event,choiceBits,ih] + +variable (vm : Fin (regCount f) ↪ Fin r) + +/-- Execute the linked read-only setup on arbitrary live input registers. The static +code length bounds every probe and private step, independently of the field widths. -/ +theorem execute_setup_trace (M : Machine w p r k) (m : Memory w) (pc : ℕ → Fin p) + (link : Linked vm inputs M pc (lines f)) (safe : ∀ i j, vm i ≠ inputs j) (c : Config w p r) (hpc : c.pc = pc 0) : + let pub := fun i : Fin 5 => c.reg (inputs i.castSucc) + let state := c.reg (inputs (Fin.last 5)) + ∃ events d, events.length = (lines f).length ∧ countProbes events = ∑ i, (f i).loads ∧ choiceBits events = [] ∧ + d.pc = pc (lines f).length ∧ + d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧ + (∀ i, d.reg (vm (output f i)) = (f i).eval pub state m) ∧ (∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j) ∧ + ∀ fuel bs, execute M.program (fuel+events.length) c m bs = + (execute M.program fuel d m bs).map (fun rep => ⟨events++rep.events,rep.result⟩) := by + let pub := fun i : Fin 5 => c.reg (inputs i.castSucc) + let state := c.reg (inputs (Fin.last 5)) + let rs := fun i => c.reg (vm i) + let ev := (evaluate pub state m (lines f) rs).1 + obtain ⟨d,hd,endPC,mem,pers,vals,frame⟩ := execute_lines vm inputs M m (lines f) safe pub state rs pc link c hpc + (fun _ => rfl) rfl (fun _ => rfl) + refine ⟨ev,d,(eval_cost pub state m (lines f) rs).1,lines_probes f ..,no_choices ..,endPC,mem,pers,fun i => ?_,frame,ReadPrefix.execute hd⟩ + exact (vals _).trans ((emit_list f pub state m (List.finRange n) rs i).trans (ite_eq_left (List.mem_finRange i))) + +/-- Register and continuation postconditions of the native setup. -/ +theorem execute_setup (M : Machine w p r k) (m : Memory w) (pc : ℕ → Fin p) + (link : Linked vm inputs M pc (lines f)) (safe : ∀ i j, vm i ≠ inputs j) (c : Config w p r) (hpc : c.pc = pc 0) : + let pub := fun i : Fin 5 => c.reg (inputs i.castSucc) + let state := c.reg (inputs (Fin.last 5)) + ∃ events d, events.length = (lines f).length ∧ d.pc = pc (lines f).length ∧ + d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧ + (∀ i, d.reg (vm (output f i)) = (f i).eval pub state m) ∧ (∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j) ∧ + ∀ fuel bs, execute M.program (fuel+events.length) c m bs = + (execute M.program fuel d m bs).map (fun rep => ⟨events++rep.events,rep.result⟩) := by + obtain ⟨events,d,len,_,_,post⟩ := execute_setup_trace f inputs vm M m pc link safe c hpc + exact ⟨events,d,len,post⟩ + +end CompressorRecords.RegisterSetup + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordScores.lean b/lean/OAI/Computability/VPVNP/CompressorRecordScores.lean new file mode 100644 index 0000000000..93d92dcd51 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordScores.lean @@ -0,0 +1,105 @@ +import OAI.Computability.VPVNP.CompressorRecordTable +import OAI.Computability.VPVNP.MotifAdmission +import OAI.Computability.VPVNP.ShrinkEnergy + +/-! +# Computing the common layout from two word counters + +In the second descriptor scan of Appendix E, each term contributes its squared supply +widths to two totals. Clearing the fixed denominators yields nonnegative integers, and +the common positive arc mass cancels. One native word block accumulates an edge's +contribution with two probes. One comparison of the two counters picks the same layout +as the real energy comparison of §7.2, including the tie case. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression.ShrinkEnergy + +variable {M T : Type*} [Fintype M] [Fintype T] + +/-- Integral score accumulated for the selected payloads in one layout. -/ +def layoutScore (q : T → ℚ) (width : M → Bool → T → ℕ) (l : Bool) : ℕ := + ∑ m, MotifAdmission.energy q (width m l) + +/-- The finite program chooses `true` only on strict improvement. -/ +def selectLayout (q : T → ℚ) (width : M → Bool → T → ℕ) : Bool := + decide (layoutScore q width true < layoutScore q width false) + +theorem layoutScore_energy (q : T → ℚ) (hq : ∀ e, 0 < q e) (width : M → Bool → T → ℕ) + (p : ℝ) (l : Bool) : + groupEnergy p (fun i => (q i : ℝ)) width l = + (layoutScore q width l : ℝ) / ((MotifAdmission.denominator q : ℝ) * p) := by + rw [groupEnergy, layoutScore, Nat.cast_sum, Finset.sum_div] + refine Finset.sum_congr rfl fun m _ => ?_ + have h := MotifAdmission.norm_sq_eq q hq (width m l) + rw [MotifGrid.norm_sq (MotifGrid.realWidths q) _ (fun e => Rat.cast_pos.mpr (hq e))] at h + rw [← div_div, ← h, Finset.sum_div] + refine Finset.sum_congr rfl fun e _ => ?_ + rw [div_div, mul_comm] + rfl + +theorem selectLayout_eq (q : T → ℚ) (hq : ∀ e, 0 < q e) (width : M → Bool → T → ℕ) + (p : ℝ) (hp : 0 < p) : selectLayout q width = chosenLayout p (fun i => (q i : ℝ)) width := by + have hcmp : groupEnergy p (fun i => (q i : ℝ)) width false ≤ + groupEnergy p (fun i => (q i : ℝ)) width true ↔ + layoutScore q width false ≤ layoutScore q width true := by + rw [layoutScore_energy q hq width p, layoutScore_energy q hq width p, + div_le_div_iff_of_pos_right (mul_pos (Nat.cast_pos.mpr (MotifAdmission.denominator_pos _)) hp), + Nat.cast_le] + by_cases h : layoutScore q width false ≤ layoutScore q width true + · simp [selectLayout, chosenLayout, hcmp.mpr h, not_lt_of_ge h] + · simp [selectLayout, chosenLayout, (mt hcmp.mp h), lt_of_not_ge h] + +theorem layoutScore_le (q : T → ℚ) (width : M → Bool → T → ℕ) (W : ℕ) + (hW : ∀ m l e, width m l e ≤ W) (l : Bool) : + layoutScore q width l ≤ Fintype.card M * (∑ e, MotifAdmission.weight q e) * W ^ 2 := by + unfold layoutScore MotifAdmission.energy + calc + _ ≤ ∑ _m : M, ∑ e, MotifAdmission.weight q e * W ^ 2 := by gcongr; apply hW + _ = _ := by simp [← Finset.sum_mul, mul_assoc] + +/-- Register 0 holds the score address, 1 the integer weight and 2 the payload width. +Registers 3 and 4 are temporaries. The same code updates either layout score. -/ +def accumulateScore : List (Op 5 0) := + [.read 3 0, .binary .mul 4 2 2, .binary .mul 4 1 4, + .binary .add 3 3 4, .write 0 3] + +theorem accumulateScore_trace {w : ℕ} (pub : Fin 0 → Word w) (state : Word w) + (regs : Regs w 5) (mem : Memory w) : + let total := mem (regs 0).val + regs 1 * (regs 2 * regs 2) + ∃ es rs, trace pub state accumulateScore regs mem = + some (es, rs, writeMemory mem (regs 0) total) ∧ + countProbes es = 2 ∧ es.length = 5 ∧ rs 3 = total := by + simp (config := {decide := true}) [accumulateScore, trace, Op.effect, BinaryOp.eval, + Function.update, countProbes] + +/-- A word counter gives the exact natural score while the final sum fits in one word. -/ +theorem scoreWord_exact {w : ℕ} (old weight width : Word w) + (hfit : old.val + weight.val * width.val ^ 2 < 2 ^ w) : + (old + weight * (width * width)).val = old.val + weight.val * width.val ^ 2 := by + simp only [Fin.val_add, Fin.val_mul, Nat.mul_mod_mod, Nat.add_mod_mod, pow_two] + exact Nat.mod_eq_of_lt (by simpa [pow_two] using hfit) + +/-- The exact finite opcode table realizes the score update from supplied registers. -/ +theorem accumulateScore_native {w : ℕ} (pub : Fin 0 → Word w) (state : Word w) + (regs : Regs w 5) (priv : Word w → Word w) (mem : Memory w) : + let machine := (template accumulateScore 3).instantiate w pub + let total := mem (regs 0).val + regs 1 * (regs 2 * regs 2) + ∃ es, execute machine.program 6 ⟨machine.entry, state, regs, priv⟩ mem [] = + some ⟨es, some total⟩ ∧ countProbes es = 2 ∧ es.length = 5 := by + obtain ⟨es, rs, ht, hprobes, hlen, hreg⟩ := accumulateScore_trace pub state regs mem + refine ⟨es, ?_, hprobes, hlen⟩ + change execute _ (1 + accumulateScore.length) _ mem [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hreg] + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordSlices.lean b/lean/OAI/Computability/VPVNP/CompressorRecordSlices.lean new file mode 100644 index 0000000000..60e611273a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordSlices.lean @@ -0,0 +1,370 @@ +import OAI.Computability.VPVNP.SlotDemandSlices +import OAI.Computability.VPVNP.DegreeRefreshKernel +import OAI.Computability.VPVNP.ShrinkPayload +import Mathlib.Data.Fin.Tuple.Take + +/-! +# Interval records for the compressor + +Appendix E scans the widths in each of two ordered concatenations, then +intersects their fields in absolute coordinates. The output records name a +source and a target field and give their respective offsets and common length. +These computations never enumerate the individual bits of a payload. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open Compression.PackingData + +/-- Position and extent of one field in an ordered concatenation. -/ +structure Field where + /-- Ordinal of this field within its ordered concatenation. -/ + index : ℕ + /-- First absolute bit position of the field in the concatenation. -/ + start : ℕ + /-- Number of consecutive bit positions belonging to the field. -/ + width : ℕ + deriving DecidableEq + +/-- The prefix scan assigns absolute starts and consecutive field numbers. -/ +def fieldsFrom (index start : ℕ) : List ℕ → List Field + | [] => [] + | w :: ws => ⟨index, start, w⟩ :: fieldsFrom (index + 1) (start + w) ws + +@[simp] theorem fieldsFrom_length (ws : List ℕ) (index start : ℕ) : + (fieldsFrom index start ws).length = ws.length := by + induction ws generalizing index start <;> simp [fieldsFrom, *] + +/-- The field at a list position stores its width and the sum of all previous widths. -/ +theorem fieldsFrom_get (ws : List ℕ) (index start i : ℕ) (hi : i < ws.length) : + (fieldsFrom index start ws)[i]'(by simpa using hi) = + ⟨index + i, start + (ws.take i).sum, ws[i]⟩ := by + induction ws generalizing index start i with + | nil => simp at hi + | cons w ws ih => + cases i with + | zero => simp [fieldsFrom] + | succ i => + have h : i < ws.length := by simpa using hi + simp [fieldsFrom, ih (index + 1) (start + w) i h, Nat.add_assoc, Nat.add_comm 1] + +/-- All indices and interval endpoints stay inside the two running totals. -/ +theorem fieldsFrom_bounds {ws : List ℕ} {index start : ℕ} {f : Field} + (h : f ∈ fieldsFrom index start ws) : + index ≤ f.index ∧ f.index < index + ws.length ∧ + start ≤ f.start ∧ f.start + f.width ≤ start + ws.sum := by + induction ws generalizing index start with + | nil => simp [fieldsFrom] at h + | cons w ws ih => + rcases List.mem_cons.mp h with rfl | h + · simp + · have := ih h + simp only [List.length_cons, List.sum_cons] + omega + +/-- Test membership of an absolute bit position in the field's half-open interval. -/ +def Field.contains (f : Field) (x : ℕ) : Bool := + decide (f.start ≤ x ∧ x < f.start + f.width) + +private theorem count_fields (ws : List ℕ) (index start x : ℕ) : + (fieldsFrom index start ws).countP (fun f => f.contains x) = + if start ≤ x ∧ x < start + ws.sum then 1 else 0 := by + induction ws generalizing index start with + | nil => simp [fieldsFrom] + | cons w ws ih => + simp only [fieldsFrom, List.countP_cons, List.sum_cons, ih] + simp only [Field.contains, decide_eq_true_eq] + by_cases h₁ : start ≤ x <;> by_cases h₂ : x < start + w <;> + by_cases h₃ : x < start + w + ws.sum <;> + simp [← Nat.add_assoc, Nat.le_of_not_gt, *] <;> omega + +/-- Each entry retains the two field references along with the three words +describing the contiguous copy. -/ +structure SliceRecord where + /-- The field in the source concatenation from which the intersection is copied. -/ + source : Field + /-- The field in the target concatenation that receives the intersection. -/ + target : Field + /-- The source offset, target offset, and length of the overlapping bit interval. -/ + slice : CopySlice + +/-- One comparison of field endpoints. Empty intersections generate no copy. -/ +def intersectFields (pair : Field × Field) : Option SliceRecord := + let s := pair.1 + let t := pair.2 + let slice := copySlice s.start s.width t.start t.width + if slice.length = 0 then none else some ⟨s, t, slice⟩ + +/-- Candidate field pairs in source-major order. -/ +def candidates (old new : List ℕ) : List (Field × Field) := + fieldsFrom 0 0 old ×ˢ fieldsFrom 0 0 new + +/-- Construct copy records by scanning the two lists of fields. -/ +def copyRecords (old new : List ℕ) : List SliceRecord := + (candidates old new).filterMap intersectFields + +/-- The number of pair tests is independent of all numerical widths. -/ +@[simp] theorem candidates_length (old new : List ℕ) : + (candidates old new).length = old.length * new.length := by simp [candidates, List.length_product] + +/-- At most one fixed-size record per pair of fields. -/ +theorem copyRecords_length_le (old new : List ℕ) : + (copyRecords old new).length ≤ old.length * new.length := + (List.length_filterMap_le _ _).trans_eq (candidates_length old new) + +private theorem mem_copyRecords {old new : List ℕ} {r : SliceRecord} (h : r ∈ copyRecords old new) : + r.source ∈ fieldsFrom 0 0 old ∧ r.target ∈ fieldsFrom 0 0 new ∧ + r.slice = copySlice r.source.start r.source.width r.target.start r.target.width ∧ + 0 < r.slice.length := by + obtain ⟨⟨s,t⟩, hp, he⟩ := List.mem_filterMap.mp h + obtain ⟨hs,ht⟩ := List.mem_product.mp hp + simp only [intersectFields] at he + split at he + · simp at he + · obtain rfl := Option.some.inj he + exact ⟨hs,ht,rfl,Nat.pos_of_ne_zero (by assumption)⟩ + +/-- All emitted records fit inside both named fields, including their offsets. -/ +theorem copyRecords_bounds {old new : List ℕ} {r : SliceRecord} (h : r ∈ copyRecords old new) : + 0 < r.slice.length ∧ + r.slice.sourceOffset + r.slice.length ≤ r.source.width ∧ + r.slice.targetOffset + r.slice.length ≤ r.target.width ∧ + r.source.start + r.slice.sourceOffset = r.target.start + r.slice.targetOffset := by + obtain ⟨_, _, hs, hp⟩ := mem_copyRecords h + rw [hs] at hp ⊢ + simp only [copySlice] at hp ⊢ + omega + +/-- Does this stored slice copy the bit with absolute index `x`? -/ +def SliceRecord.copies (r : SliceRecord) (x : ℕ) : Bool := + let a := r.source.start + r.slice.sourceOffset + decide (a ≤ x ∧ x < a + r.slice.length) + +private theorem intersectFields_copies (pair : Field × Field) (x : ℕ) : + ((intersectFields pair).map (fun r => r.copies x)).getD false = + (pair.1.contains x && pair.2.contains x) := by + obtain ⟨s,t⟩ := pair + apply Bool.eq_iff_iff.mpr + by_cases h : min (s.start + s.width) (t.start + t.width) - max s.start t.start = 0 <;> + simp [intersectFields, copySlice, SliceRecord.copies, Field.contains, h] <;> omega + +private theorem product_count {α β : Type*} (ss : List α) (ts : List β) + (p : α → Bool) (q : β → Bool) : + (ss ×ˢ ts).countP (fun ab => p ab.1 && q ab.2) = ss.countP p * ts.countP q := by + induction ss with + | nil => simp + | cons s ss ih => + cases he : p s <;> simp [he, Function.comp_def, ih, Nat.add_mul, Nat.add_comm] + +/-- Exact coverage, counting *occurrences* of records. With equal total widths +every absolute bit is copied exactly once, including when some fields have width zero. -/ +theorem copyRecords_count (old new : List ℕ) (x : ℕ) : + (copyRecords old new).countP (fun r => r.copies x) = + if x < old.sum ∧ x < new.sum then 1 else 0 := by + simp only [copyRecords, candidates, List.countP_filterMap, intersectFields_copies] + refine (product_count (fieldsFrom 0 0 old) (fieldsFrom 0 0 new) + (fun f => f.contains x) (fun f => f.contains x)).trans ?_ + simp only [count_fields, Nat.zero_le, true_and, Nat.zero_add] + split_ifs <;> omega + +/-- A copied bit has one intra-slice index. Both relative addresses at this +index refer to that same absolute bit. -/ +theorem copyRecords_index {old new : List ℕ} {r : SliceRecord} (hr : r ∈ copyRecords old new) + (x : ℕ) : + r.copies x ↔ ∃! k : Fin r.slice.length, + r.source.start + (r.slice.sourceOffset + k.val) = x ∧ + r.target.start + (r.slice.targetOffset + k.val) = x := by + have hs := (copyRecords_bounds hr).2.2.2 + simp only [SliceRecord.copies, decide_eq_true_eq] + constructor + · rintro ⟨hl,hu⟩ + refine ⟨⟨x - (r.source.start + r.slice.sourceOffset), by omega⟩, ⟨by dsimp; omega, by dsimp; omega⟩, ?_⟩ + rintro k ⟨h,_⟩ + exact Fin.ext (by simp only; omega) + · rintro ⟨k,⟨h,_⟩,_⟩ + have := k.isLt + omega + +private theorem field_unique {ws : List ℕ} {index start x : ℕ} {a b : Field} + (ha : a ∈ fieldsFrom index start ws) (hb : b ∈ fieldsFrom index start ws) + (hax : a.start ≤ x ∧ x < a.start + a.width) (hbx : b.start ≤ x ∧ x < b.start + b.width) : + a = b := by + induction ws generalizing index start with + | nil => simp [fieldsFrom] at ha + | cons w ws ih => + rcases List.mem_cons.mp ha with rfl | ha <;> rcases List.mem_cons.mp hb with rfl | hb + · rfl + · have := (fieldsFrom_bounds hb).2.2.1 + dsimp only at hax + omega + · have := (fieldsFrom_bounds ha).2.2.1 + dsimp only at hbx + omega + · exact ih ha hb + +/-- Use a computed slice to read one bit, given access to old fields by number +and relative index. Only the selected old bit is requested. -/ +def readCopiedBit (records : List SliceRecord) (oldBit : ℕ → ℕ → Bool) (x : ℕ) : Option Bool := + (records.find? fun r => r.copies x).map fun r => + let k := x - (r.source.start + r.slice.sourceOffset) + oldBit r.source.index (r.slice.sourceOffset + k) + +/-- The executable reader returns the old bit at the matching absolute +position in any repartition of the same total width. -/ +theorem readCopiedBit_eq {old new : List ℕ} (htotal : old.sum = new.sum) {s : Field} + (hs : s ∈ fieldsFrom 0 0 old) (i : Fin s.width) (bits : ℕ → ℕ → Bool) : + readCopiedBit (copyRecords old new) bits (s.start + i.val) = some (bits s.index i.val) := by + let x := s.start + i.val + have hbound := (fieldsFrom_bounds hs).2.2.2 + have hi := i.isLt + have hx : x < old.sum ∧ x < new.sum := by dsimp [x]; omega + have hcount := copyRecords_count old new x + rw [ite_eq_left hx] at hcount + cases he : (copyRecords old new).find? fun r => r.copies x with + | none => + have hn := List.countP_eq_zero.mpr (List.find?_eq_none.mp he) + omega + | some r => + have hr := List.mem_of_find?_eq_some he + obtain ⟨rs,_,_,_⟩ := mem_copyRecords hr + have ho := (copyRecords_bounds hr).2.1 + have hrc := List.find?_some he + simp only [SliceRecord.copies, decide_eq_true_eq] at hrc + have hrx : r.source.start ≤ x ∧ x < r.source.start + r.source.width := by omega + have hsame : r.source = s := + field_unique rs hs hrx (by dsimp [x]; omega) + change ((copyRecords old new).find? fun r => r.copies x).map _ = _ + rw [he] + simp only [Option.map_some, Option.some.injEq, hsame] + congr 1 + rw [hsame] at hrc + dsimp only [x] at * + omega + +/-- The list scan agrees with the abstract concatenation offset in the shrinking kernel. -/ +theorem orderedField_mem {A : Type*} {n : ℕ} (order : A ≃ Fin n) (w : A → ℕ) (a : A) : + (⟨(order a).val, fieldStart order w a, w a⟩ : Field) ∈ + fieldsFrom 0 0 (List.ofFn fun i => w (order.symm i)) := by + let ws := List.ofFn fun i => w (order.symm i) + have hi : (order a).val < ws.length := by simp [ws] + have h := List.getElem_mem (l := fieldsFrom 0 0 ws) (n := (order a).val) (by simpa using hi) + rw [fieldsFrom_get ws 0 0 _ hi] at h + simpa [ws, fieldStart, ← Fin.ofFn_take_eq_take_ofFn (order a).isLt.le, List.sum_ofFn, + Fin.take] using h + +/-- Generate the stored slice for a pair of fields, whenever it has positive length. -/ +theorem record_mem_of_overlap {old new : List ℕ} (s t : Field) + (hs : s ∈ fieldsFrom 0 0 old) (ht : t ∈ fieldsFrom 0 0 new) + (hp : 0 < (copySlice s.start s.width t.start t.width).length) : + ⟨s, t, copySlice s.start s.width t.start t.width⟩ ∈ copyRecords old new := + List.mem_filterMap.mpr ⟨(s,t), List.mem_product.mpr ⟨hs,ht⟩, by simp [intersectFields, hp.ne']⟩ + +/-- The widths supplied to the descriptor scan by a numbered bundle. -/ +def orderedWidths {A : Type*} {n : ℕ} (order : A ≃ Fin n) (w : A → ℕ) : List ℕ := + List.ofFn fun i => w (order.symm i) + +/-- Construct a field from its ordinal in the supplied order, the prefix width before it, and +its own width. -/ +def numberedField {A : Type*} {n : ℕ} (order : A ≃ Fin n) (w : A → ℕ) (a : A) : Field := + ⟨(order a).val, fieldStart order w a, w a⟩ + +section Shrink + +open Compression + +variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] +variable (number : P.BundleNumbering) (order : P.ThickNumbering) (w : Arc V H Tag L d c → ℕ) +variable (b : Site V Tag L × Fin d) + +/-- Every bit read by the actual AB demand kernel has its slice in the output of the scan. -/ +theorem demandBit_record (hc : 2 ≤ c) (hd : 0 < d) (a : P.ThickFiber b) + (m : P.MotifFiber b) (i : Fin (w a.1.1)) (j : Fin (P.abWidth number w m.1)) + (h : P.demandBitEquiv hc hd number order w b ⟨m,j⟩ = ⟨a,i⟩) : + let sw := fun s : P.ThickFiber b => w s.1.1 + let tw := fun t : P.MotifFiber b => P.abWidth number w t.1 + let r := (⟨numberedField (order b) sw a, numberedField (number b) tw m, + P.demandSlice number order w b a m⟩ : SliceRecord) + r ∈ copyRecords (orderedWidths (order b) sw) (orderedWidths (number b) tw) ∧ + ∃ k < r.slice.length, i.val = r.slice.sourceOffset + k ∧ + j.val = r.slice.targetOffset + k := by + have he := (P.demandBitEquiv_eq_iff_slice number order w b hc hd a m i j).mp h + obtain ⟨k,hk,hi,hj⟩ := he + exact ⟨record_mem_of_overlap _ _ (orderedField_mem _ _ _) (orderedField_mem _ _ _) + (Nat.zero_le k |>.trans_lt hk), k, hk, hi, hj⟩ + +end Shrink + +open Compression Compression.ShrinkPayload in +/-- The same scan, with one surviving wire on its source side, reads the +subdivision bits used by both endpoint maps of the shrinking step. -/ +theorem survivingSlice_read (b q : ℕ) (hq : 0 < q) (i : Fin q) (j : Fin (splitWidth b q i)) + (bits : ℕ → ℕ → Bool) : + let t := numberedField (Equiv.refl (Fin q)) (splitWidth b q) i + readCopiedBit (copyRecords [b] (List.ofFn (splitWidth b q))) bits (t.start + j.val) = + some (sliceWords b q hq (fun k => bits 0 k.val) i j) := by + let s : Field := ⟨0,0,b⟩ + have hs : s ∈ fieldsFrom 0 0 [b] := by simp [fieldsFrom, s] + have htot : [b].sum = (List.ofFn (splitWidth b q)).sum := by simp [List.sum_ofFn, sum_splitWidth b q hq] + have h := readCopiedBit_eq htot hs (sliceBits b q hq ⟨i,j⟩) bits + change readCopiedBit _ bits _ = some (bits 0 (sliceBits b q hq ⟨i,j⟩).val) + have hoff : (sliceBits b q hq ⟨i,j⟩).val = + (numberedField (Equiv.refl (Fin q)) (splitWidth b q) i).start + j.val := + sliceBits_offset b q hq i j + change readCopiedBit (copyRecords [b] (List.ofFn (splitWidth b q))) bits + ((numberedField (Equiv.refl (Fin q)) (splitWidth b q) i).start + j.val) = _ + rw [← hoff] + simpa only [s, Nat.zero_add] using h + +section Refresh + +open Compression.Refresh + +/-- During a degree refresh the target list consists of one concatenated external word. +The generated descriptor for each nonempty source port gives precisely the offset at +which the local kernel reads its bit. -/ +theorem refreshSegment_record {B : Type*} {d : ℕ} (w : Arc B d → ℕ) (s : B × Fin d) + (j : Fin d) (i : Fin (w (s,j))) : + let widths := fun k : Fin d => w (s,k) + let source := numberedField (Equiv.refl (Fin d)) widths j + let target := (⟨0, 0, ∑ k, widths k⟩ : Field) + let r := (⟨source, target, copySlice source.start source.width target.start target.width⟩ : + SliceRecord) + r ∈ copyRecords (List.ofFn widths) [target.width] ∧ + r.slice.sourceOffset = 0 ∧ r.slice.length = w (s,j) ∧ + ∃ addr : Fin target.width, addr.val = r.slice.targetOffset + i.val ∧ + ∀ z : External w, segment w z (s,j) i = z s addr := by + let source := numberedField (Equiv.refl (Fin d)) (fun k => w (s,k)) j + let total := ∑ k : Fin d, w (s,k) + have hwidth : 0 < w (s,j) := (Nat.zero_le i.val).trans_lt i.isLt + let last : Fin (w (s,j)) := ⟨w (s,j) - 1, by omega⟩ + have hstart (k : Fin (w (s,j))) : + (finSigmaFinEquiv (n := fun l => w (s,l)) ⟨j,k⟩).val = source.start + k.val := + segment_offset w s j k + have hend := (finSigmaFinEquiv (n := fun k => w (s,k)) ⟨j,last⟩).isLt + rw [hstart last] at hend + change source.start + (w (s,j) - 1) < total at hend + have hle : source.start + source.width ≤ total := by change source.start + w (s,j) ≤ total; omega + have hs := orderedField_mem (Equiv.refl (Fin d)) (fun k => w (s,k)) j + let target : Field := ⟨0,0,total⟩ + have ht : target ∈ fieldsFrom 0 0 [total] := by simp [target, fieldsFrom] + have hlen : (copySlice source.start source.width 0 total).length = source.width := by + simp [copySlice, min_eq_left hle] + refine ⟨record_mem_of_overlap source target hs ht (hlen.symm ▸ hwidth), ?_, hlen, ?_⟩ + · simp [copySlice] + · exact ⟨finSigmaFinEquiv (n := fun k => w (s,k)) ⟨j,i⟩, by simpa [copySlice] using hstart i, + fun _ => rfl⟩ + +end Refresh + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordSlots.lean b/lean/OAI/Computability/VPVNP/CompressorRecordSlots.lean new file mode 100644 index 0000000000..136e02b7b1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordSlots.lean @@ -0,0 +1,414 @@ +import OAI.Computability.VPVNP.ShrinkingSlots +import OAI.Computability.VPVNP.CompressorSlotRankRAM +import OAI.Computability.VPVNP.ExpanderSlots +import OAI.Computability.VPVNP.DegreeRefreshTopology + +/-! +# Recording the two slot numbers of each surviving arc + +In the third scan of Appendix E, each new position receives two lists of +actual arc identifiers, one for each orientation. Translating the original +CD source to lane zero gives the integer key used by the packed graph. +Each key occurs once per incidence list. Counting smaller keys in that list +therefore computes the same slot number as sorting. The two ranks occupy +separate fields at a common absolute arc address. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Slots + +open Compression Compression.SurvivingSlots Compression.PackingData BurstRAM + +/-- The list at one endpoint after the arc-generation scan, in visitation order. -/ +structure IncidentRow {E S : Type*} (endpoint : E → S) (s : S) where + /-- The duplicate-free list of all arc identifiers incident at the row's specified endpoint. -/ + ids : List E + nodup : ids.Nodup + complete : ∀ a, a ∈ ids ↔ endpoint a = s + +/-- One pass over all generated actual identifiers, appending each to the row +at its endpoint. Incoming and outgoing arrays use the same code with different +endpoint functions. -/ +def collectRows {E S : Type*} [DecidableEq S] (atSite : E → S) + (stream : List E) (rows : S → List E) : S → List E := + stream.foldl (fun rs i ↦ Function.update rs (atSite i) (rs (atSite i) ++ [i])) rows + +/-- Each local array contains exactly its incident identifiers in scan order. -/ +theorem collectRows_eq {E S : Type*} [DecidableEq S] (atSite : E → S) (stream : List E) + (rows : S → List E) (s : S) : + collectRows atSite stream rows s = rows s ++ stream.filter (fun i ↦ decide (atSite i = s)) := by + induction stream generalizing rows with + | nil => simp [collectRows] + | cons i xs ih => + change collectRows atSite xs (Function.update rows (atSite i) (rows (atSite i) ++ [i])) s = _ + rw [ih] + by_cases h : atSite i = s + · simp [h, Function.update, List.append_assoc] + · simp [h, Ne.symm h, Function.update] + +/-- Visiting each generated ID once supplies the incidence rows used by +`actualSlot_numbers` without separate searches over the graph at each site. -/ +def collectedRow {E S : Type*} [DecidableEq S] (atSite : E → S) (stream : List E) + (hn : stream.Nodup) (hall : ∀ i, i ∈ stream) (s : S) : IncidentRow atSite s where + ids := collectRows atSite stream (fun _ ↦ []) s + nodup := by simpa [collectRows_eq] using hn.filter (fun i ↦ decide (atSite i = s)) + complete := by intro i; simp [collectRows_eq, hall] + +variable {V H Tag L : Type*} {d c N J nL : ℕ} +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) +variable (subdiv : Fin 4 → ℕ) + +/-- Forget the absolute lane but retain the entire original CD arc, type and subdivision. -/ +def baseId (i : Id P.Motif subdiv) : Id P.BaseMotif subdiv := + ⟨i.1, P.baseMotif i.2.1, i.2.2⟩ + +/-- At either end, normalizing all motif lanes gives a bijection of the actual +incidence fiber with the fiber used in the sorted base graph. -/ +def incidentBaseEquiv (layout : Bool) (pick : Fin 4 → PackedRole) (s : Site V Tag L) : + {i : Id P.Motif subdiv // endpoint (P.survivingRole layout) pick i = s} ≃ + {z : Id P.BaseMotif subdiv // endpoint (P.roleBase layout) pick z = packedBase s} := + (endpointFiberEquiv (P.survivingRole layout) pick subdiv s).trans + ((Equiv.sigmaCongrRight fun t ↦ + (P.baseRoleFiberEquiv (P.survivingRole layout (pick t)) + (P.survivingRole_translate layout (pick t)) (packedBase s) s.2.2).symm.prodCongr + (Equiv.refl (Fin (subdiv t)))).trans + (endpointFiberEquiv (P.roleBase layout) pick subdiv (packedBase s)).symm) + +@[simp] theorem incidentBaseEquiv_val (layout : Bool) (pick : Fin 4 → PackedRole) + (s : Site V Tag L) (a) : + (incidentBaseEquiv P subdiv layout pick s a).val = baseId P subdiv a.val := rfl + +private theorem baseRow_nodup (layout : Bool) (pick : Fin 4 → PackedRole) (s : Site V Tag L) + (r : IncidentRow (endpoint (P.survivingRole layout) pick (subdiv := subdiv)) s) : + (r.ids.map (baseId P subdiv)).Nodup := by + apply r.nodup.map_on + intro x hx y hy h + let f := incidentBaseEquiv P subdiv layout pick s + let x' := (⟨x, (r.complete _).mp hx⟩ : {a // endpoint (P.survivingRole layout) pick a = s}) + let y' := (⟨y, (r.complete _).mp hy⟩ : {a // endpoint (P.survivingRole layout) pick a = s}) + exact congrArg Subtype.val (f.injective (Subtype.ext (show (f x').val = (f y').val from h))) + +private theorem baseRow_complete (layout : Bool) (pick : Fin 4 → PackedRole) (s : Site V Tag L) + (r : IncidentRow (endpoint (P.survivingRole layout) pick (subdiv := subdiv)) s) + (z : Id P.BaseMotif subdiv) : + z ∈ r.ids.map (baseId P subdiv) ↔ endpoint (P.roleBase layout) pick z = packedBase s := by + let f := incidentBaseEquiv P subdiv layout pick s + constructor + · intro h + obtain ⟨a, ha, rfl⟩ := List.mem_map.mp h + exact (f ⟨a, (r.complete _).mp ha⟩).property + · intro h + let z' := (⟨z, h⟩ : {z // endpoint (P.roleBase layout) pick z = packedBase s}) + exact List.mem_map.mpr ⟨(f.symm z').val, (r.complete _).mpr (f.symm z').property, + congrArg Subtype.val (f.apply_symm_apply z')⟩ + +/-- The radix of the unconsumed-lane-independent relative key. -/ +abbrev keyCount (N J d c : ℕ) (subdiv : Fin 4 → ℕ) := + 4 * ((N * (J * (d * (2 ^ c * d)))) * ∑ t, subdiv t) + +variable (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) + +/-- Integer key stored in the incoming or outgoing incidence row. -/ +def relativeKey (i : Id P.Motif subdiv) : Fin (keyCount N J d c subdiv) := + P.slotIdentifier vertices tags subdiv (baseId P subdiv i) + +/-- A record ID keeps the original absolute lane of the motif. Dummies are +indexed by their absolute source site and local dummy number. -/ +def arcAddress (lanes : L ≃ Fin nL) (deficit : ℕ) : + (Id P.Motif subdiv ⊕ Site V Tag L × Fin deficit) ↪ + Fin (keyCount N J d c subdiv * nL + (N * (J * nL)) * deficit) := by + let genuine : Id P.Motif subdiv ↪ Fin (keyCount N J d c subdiv * nL) := { + toFun := fun i ↦ finProdFinEquiv (relativeKey P subdiv vertices tags i, lanes (P.sourceLane i.2.1)) + inj' := by + rintro ⟨t, m, h⟩ ⟨t', m', h'⟩ e + obtain ⟨eb, eg⟩ := Prod.mk.inj (finProdFinEquiv.injective e) + have ez := P.slotIdentifier_injective vertices tags subdiv eb + change (⟨t, P.baseMotif m, h⟩ : Id P.BaseMotif subdiv) = ⟨t', P.baseMotif m', h'⟩ at ez + obtain rfl : t = t' := congrArg Sigma.fst ez + have emh : (P.baseMotif m, h) = (P.baseMotif m', h') := eq_of_heq (Sigma.mk.inj_iff.mp ez).2 + obtain rfl : m = m' := P.motifLaneEquiv.injective (Prod.ext (Prod.mk.inj emh).1 (lanes.injective eg)) + obtain rfl := Prod.mk.inj emh |>.2 + rfl } + let site := (vertices.prodCongr ((tags.prodCongr lanes).trans finProdFinEquiv)).trans finProdFinEquiv + let dummy := (site.prodCongr (Equiv.refl (Fin deficit))).trans finProdFinEquiv + exact (genuine.sumMap dummy.toEmbedding).trans finSumFinEquiv.toEmbedding + +/-- Two directly addressed endpoint fields for each generated actual arc. -/ +def endpointAddress {E : Type*} {B : ℕ} (arc : E ↪ Fin B) : E × Fin 2 ↪ Fin (B * 2) := + (arc.prodMap (Equiv.refl (Fin 2)).toEmbedding).trans finProdFinEquiv.toEmbedding + +/-- Even with unoccupied mixed-radix keys, the space for both endpoint fields +is linear in the number of absolute sites. -/ +theorem endpointAddress_size (N J nL d c deficit : ℕ) (subdiv : Fin 4 → ℕ) : + (keyCount N J d c subdiv * nL + (N * (J * nL)) * deficit) * 2 = + (N * J * nL) * (2 * (4 * d * (2 ^ c * d) * (∑ t, subdiv t) + deficit)) := by + unfold keyCount + ring + +/-- Counting smaller keys computes the zero-based position in the sorted row. -/ +def rowRank (i : Id P.Motif subdiv) (ids : List (Id P.Motif subdiv)) : ℕ := + ids.countP fun j ↦ decide (relativeKey P subdiv vertices tags j < relativeKey P subdiv vertices tags i) + +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] + +private theorem IncidentRow.length_eq_card {E S : Type*} [Fintype E] [DecidableEq E] [DecidableEq S] + {endSite : E → S} {s} (r : IncidentRow endSite s) : r.ids.length = Fintype.card {a // endSite a = s} := by + rw [← List.toFinset_card_of_nodup r.nodup, Fintype.card_subtype] + congr 1 + ext a + simp [r.complete] + +/-- The count in one absolute row is the fixed surviving degree; the role map +may designate either orientation, including roles shared by parallel edges. -/ +theorem incidentRow_length (hc : 2 ≤ c) (layout : Bool) (pick : Fin 4 → PackedRole) + (s : Site V Tag L) (r : IncidentRow (endpoint (P.survivingRole layout) pick (subdiv := subdiv)) s) : + r.ids.length = survivingDegree d c subdiv := by + classical + rw [r.length_eq_card, Fintype.card_congr (incidentBaseEquiv P subdiv layout pick s)] + exact card_endpoint _ _ _ (P.card_roleBase hc layout) _ + +variable [Module (ZMod 2) Tag] + +/-- Both word-sort ranks agree with the regularized graph, for every absolute +arc and arbitrary input visitation order in the two local lists. -/ +theorem actualSlot_numbers (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset) + (layout : Bool) {d' : ℕ} (hd : survivingDegree d c subdiv ≤ d') (hJ : 1 < J) + (i : Id P.Motif subdiv) + (outRow : IncidentRow (endpoint (P.survivingRole layout) (sourceRole layout)) + (endpoint (P.survivingRole layout) (sourceRole layout) i)) + (inRow : IncidentRow (endpoint (P.survivingRole layout) (targetRole layout)) + (endpoint (P.survivingRole layout) (targetRole layout) i)) : + let := P.slotIdentifierOrder vertices tags subdiv + let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ + let z := baseId P subdiv i + rowRank P subdiv vertices tags i outRow.ids = (I.outgoing (.inl z)).2.val ∧ + rowRank P subdiv vertices tags i inRow.ids = (I.incoming (.inl z)).2.val := by + let := P.slotIdentifierOrder vertices tags subdiv + let z := baseId P subdiv i + let O := outRow.ids.map (baseId P subdiv) + let D := inRow.ids.map (baseId P subdiv) + have atBase (pick : Fin 4 → PackedRole) : endpoint (P.roleBase layout) pick z = + packedBase (endpoint (P.survivingRole layout) pick i) := + (incidentBaseEquiv P subdiv layout pick _ ⟨i, rfl⟩).property + have hO a : a ∈ O.toFinset ↔ endpoint (P.roleBase layout) (sourceRole layout) a = + endpoint (P.roleBase layout) (sourceRole layout) z := by + rw [List.mem_toFinset, atBase]; exact baseRow_complete _ _ _ _ _ outRow a + have hD a : a ∈ D.toFinset ↔ endpoint (P.roleBase layout) (targetRole layout) a = + endpoint (P.roleBase layout) (targetRole layout) z := by + rw [List.mem_toFinset, atBase]; exact baseRow_complete _ _ _ _ _ inRow a + have hn := paddedSlot_numbers (endpoint (P.roleBase layout) (sourceRole layout)) + (endpoint (P.roleBase layout) (targetRole layout)) + (P.roleDisplacement layout (sourceRole layout) (targetRole layout)) + (fun a ↦ (P.survivingSlot_bases_ne hφ layout (subdiv := subdiv) ⟨a.1, a.2.1.1, a.2.2⟩).symm) + (card_endpoint _ _ subdiv (P.card_roleBase hc layout)) (card_endpoint _ _ subdiv (P.card_roleBase hc layout)) + hd (cycleTags tags) (cycleTags_ne tags hJ) z O.toFinset D.toFinset hO hD + have rout := (baseRow_nodup P subdiv layout (sourceRole layout) _ outRow).card_eq_countP + (P := (· < z)) + have rin := (baseRow_nodup P subdiv layout (targetRole layout) _ inRow).card_eq_countP + (P := (· < z)) + rw [List.countP_map] at rout rin + exact ⟨rout.symm.trans hn.1.symm, rin.symm.trans hn.2.symm⟩ + +/-- The numerical incoming field and the source-relative displacement describe the +actual destination of this absolute arc. -/ +theorem actualSlot_route (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset) + (layout : Bool) {d' : ℕ} (hd : survivingDegree d c subdiv ≤ d') (hJ : 1 < J) + (i : Id P.Motif subdiv) : + let := P.slotIdentifierOrder vertices tags subdiv + let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ + let z := baseId P subdiv i + let s := endpoint (P.survivingRole layout) (sourceRole layout) i + let t := endpoint (P.survivingRole layout) (targetRole layout) i + I.graph.actualTarget (I.outgoing (.inl z), s.2.2) = (I.incoming (.inl z), t.2.2) ∧ + (I.outgoing (.inl z)).1 = packedBase s ∧ (I.incoming (.inl z)).1 = packedBase t := by + intro order I z s t + let e := P.survivingLaneEquiv layout subdiv + have he : (z,s.2.2) = e i := by cases i; rfl + have h := P.survivingLane_endpoints layout subdiv z s.2.2 + change endpoint _ _ (e.symm (z,s.2.2)) = _ ∧ endpoint _ _ (e.symm (z,s.2.2)) = _ at h + rw [he, e.symm_apply_apply] at h + refine ⟨(I.actualTarget (.inl z) s.2.2).trans (congrArg (Prod.mk _) (congrArg (fun v : Site V Tag L ↦ v.2.2) h.2).symm), ?_, ?_⟩ + · exact (I.src_eq (.inl z)).trans (congrArg packedBase h.1).symm + · exact (I.dst_eq (.inl z)).trans (congrArg packedBase h.2).symm + +/-- A dummy's endpoint numbers are obtained by a single addition at both ends. +The arc advances the tag at its base and preserves the absolute lane. -/ +theorem dummySlot_route (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset) + (layout : Bool) {d' : ℕ} (hd : survivingDegree d c subdiv ≤ d') (hJ : 1 < J) + (b : V × Tag) (g : L) (j : Fin (d' - survivingDegree d c subdiv)) : + let := P.slotIdentifierOrder vertices tags subdiv + let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ + let z := Sum.inr (b,j) + let rank := survivingDegree d c subdiv + j.val + (I.outgoing z).2.val = rank ∧ (I.incoming z).2.val = rank ∧ + (I.outgoing z).1 = b ∧ (I.incoming z).1 = cycleTags tags b ∧ + I.graph.actualTarget (I.outgoing z, g) = (I.incoming z, g) := by + intro order I z rank + exact ⟨rfl, rfl, rfl, rfl, by simpa [z, paddedShift] using I.actualTarget z g⟩ + +open BurstRAM.PrivateRAM PrimedStackRAM + +/-- Write the known slot of a padding or degree-refresh arc into one endpoint field. -/ +def directWrite : List (Op 2 1) := [.publicWord 0 0, .stateWord 1, .write 0 1] + +theorem directWrite_native {w : ℕ} (pub : Fin 1 → Word w) (rank : Word w) (mem : Memory w) : + let M := (template directWrite 1).instantiate w pub + execute M.program 4 (M.program.start rank) mem [] = + some ⟨[.tick, .tick, .write (pub 0) rank], some rank⟩ ∧ + after mem [.tick, .tick, .write (pub 0) rank] = writeMemory mem (pub 0) rank ∧ + countProbes [.tick, .tick, .write (pub 0) rank] = 1 := by + refine ⟨?_, rfl, rfl⟩ + change execute ((template directWrite 1).instantiate w pub).program (1 + directWrite.length) + ⟨_, rank, fun _ => 0, fun _ => 0⟩ mem [] = _ + rw [execute_template, run_eq_trace] + rfl + +/-- At a refresh, the indexed expander's reverse arc supplies the incoming +slot in the promoted graph. Both fields can be written by `directWrite`. -/ +theorem refresh_internal_route {U T K : Type*} [AddCommGroup K] {D h h₀ : ℕ} + (G : LiftedSlots U D (T × K)) (E : SpectralGeometry.RegularArcGraph (Fin D) h) + (hD : 1 < D) (hh : h + 1 ≤ h₀) (u : U) (port : Fin D) (g : K) (j : Fin h) : + (degreeRefresh G E.toSlotGraph hD hh).actualGraph.target + (((u,port),g), refreshSlots hh (.inr (.inl j))) = + (((u,(E.reverse (port,j)).1),g), refreshSlots hh (.inr (.inl (E.reverse (port,j)).2))) := + degreeRefresh_internal G E.toSlotGraph hD hh u port g j + +/-- Encode the relative key into a machine word with headroom for the increment +used by the unsigned rank comparison. -/ +def keyWord {w : ℕ} (hfit : keyCount N J d c subdiv < 2 ^ w) (i : Id P.Motif subdiv) : Word w := + (relativeKey P subdiv vertices tags i).castLE hfit.le + +omit [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] [DecidableEq V] [DecidableEq Tag] + [DecidableEq L] [Module (ZMod 2) Tag] in +/-- A single native call ranks one actual arc in its unsorted endpoint row and +writes that rank. `actualSlot_numbers` identifies these returned words with the +two fields of the regularized graph. -/ +theorem recordRank_native {w : ℕ} (hfit : keyCount N J d c subdiv < 2 ^ w) + (pub : Fin 2 → Word w) (mem : Memory w) (i : Id P.Motif subdiv) (ids : List (Id P.Motif subdiv)) + (hread : ∀ j : Fin ids.length, mem ((pub 0).val + j.val) = keyWord P subdiv vertices tags hfit ids[j.val]) + (hrow : (pub 0).val + ids.length ≤ 2 ^ w) (hlen : ids.length < 2 ^ w) : + let M := (template (SlotRankRAM.rankCode ids.length) 3).instantiate w pub + let pivot := keyWord P subdiv vertices tags hfit i + let rank := Fin.ofNat (2 ^ w) (rowRank P subdiv vertices tags i ids) + ∃ es, execute M.program (6 * ids.length + 6) (M.program.start pivot) mem [] = + some ⟨es, some rank⟩ ∧ after mem es = writeMemory mem (pub 1) rank ∧ + countProbes es = ids.length + 1 ∧ es.length + 1 = 6 * ids.length + 6 := by + let key := keyWord P subdiv vertices tags hfit + let row := ids.map key + have hl : row.length = ids.length := List.length_map _ + have hr (j : Fin row.length) : mem ((pub 0).val + j.val) = row[j.val] := by + simpa [row, key] using hread ⟨j.val, hl ▸ j.isLt⟩ + have hk (x : Word w) (hx : x ∈ row) : x.val + 1 < 2 ^ w := by + obtain ⟨a, _, rfl⟩ := List.mem_map.mp hx + exact (Nat.succ_le_of_lt (relativeKey P subdiv vertices tags a).isLt).trans_lt hfit + have rankEq : (row.filter fun x ↦ decide (x < key i)).length = rowRank P subdiv vertices tags i ids := by + rw [← List.countP_eq_length_filter, List.countP_map] + rfl + have h := SlotRankRAM.rank_native pub (key i) mem row hr (hl ▸ hrow) (hl ▸ hlen) hk + let Runs (n rank : ℕ) := + let M := (template (SlotRankRAM.rankCode n) 3).instantiate w pub + ∃ es, execute M.program (6*n+6) (M.program.start (key i)) mem [] = + some ⟨es, some (Fin.ofNat _ rank)⟩ ∧ after mem es = writeMemory mem (pub 1) (Fin.ofNat _ rank) ∧ + countProbes es = n+1 ∧ es.length+1 = 6*n+6 + change Runs row.length ((row.filter fun x ↦ decide (x < key i)).length) at h + change Runs ids.length (rowRank P subdiv vertices tags i ids) + rwa [hl, rankEq] at h + +/-- Execution of one endpoint call with its actual write log. The number of +keys is fixed by the compressor block. -/ +abbrev rankExecution {w : ℕ} (n : ℕ) (pub : Fin 2 → Word w) (pivot : Word w) + (mem : Memory w) (es : List (Event w)) (rank : Word w) : Prop := + let M := (template (SlotRankRAM.rankCode n) 3).instantiate w pub + execute M.program (6*n + 6) (M.program.start pivot) mem [] = some ⟨es, some rank⟩ + +/-- Starting with the two incident arrays at the actual source and target, +run both rank calls on the same arc. The second call reads the first call's +post-memory. The resulting arc record contains both correct slot numbers. -/ +theorem actualSlot_writeback {w : ℕ} (hfit : keyCount N J d c subdiv < 2 ^ w) + (hc : 2 ≤ c) (hφ : P.slots.ValidTagOffsets P.tagShift P.offset) + (layout : Bool) {d' : ℕ} (hd : survivingDegree d c subdiv ≤ d') (hJ : 1 < J) + (hsize : d' < 2 ^ w) (i : Id P.Motif subdiv) + (outRow : IncidentRow (endpoint (P.survivingRole layout) (sourceRole layout)) + (endpoint (P.survivingRole layout) (sourceRole layout) i)) + (inRow : IncidentRow (endpoint (P.survivingRole layout) (targetRole layout)) + (endpoint (P.survivingRole layout) (targetRole layout) i)) + (mem : Memory w) (po pi : Fin 2 → Word w) + (hout : ∀ j : Fin outRow.ids.length, mem ((po 0).val + j.val) = + keyWord P subdiv vertices tags hfit outRow.ids[j.val]) + (hin : ∀ j : Fin inRow.ids.length, mem ((pi 0).val + j.val) = + keyWord P subdiv vertices tags hfit inRow.ids[j.val]) + (hrowOut : (po 0).val + outRow.ids.length ≤ 2 ^ w) (hrowIn : (pi 0).val + inRow.ids.length ≤ 2 ^ w) + (hsep : ∀ j : Fin inRow.ids.length, (pi 0).val + j.val ≠ (po 1).val) (hdist : po 1 ≠ pi 1) : + let := P.slotIdentifierOrder vertices tags subdiv + let I := P.regularizedSlotIndexing hc hφ layout subdiv hd tags hJ + let z := Sum.inl (baseId P subdiv i) + let k := survivingDegree d c subdiv + let key := keyWord P subdiv vertices tags hfit i + let outSlot := (I.outgoing z).2.castLE hsize.le + let inSlot := (I.incoming z).2.castLE hsize.le + ∃ es fs, rankExecution k po key mem es outSlot ∧ rankExecution k pi key (after mem es) fs inSlot ∧ + after (after mem es) fs (po 1).val = outSlot ∧ after (after mem es) fs (pi 1).val = inSlot ∧ + countProbes es + countProbes fs = 2 * (k + 1) := by + intro order I z k key outSlot inSlot + have hlo := incidentRow_length P subdiv hc layout (sourceRole layout) _ outRow + have hli := incidentRow_length P subdiv hc layout (targetRole layout) _ inRow + obtain ⟨ho, hi⟩ := actualSlot_numbers P subdiv vertices tags hc hφ layout hd hJ i outRow inRow + have wo : Fin.ofNat (2 ^ w) (rowRank P subdiv vertices tags i outRow.ids) = outSlot := by + apply Fin.ext + change rowRank P subdiv vertices tags i outRow.ids % (2 ^ w) = _ + rw [ho, Nat.mod_eq_of_lt ((I.outgoing z).2.isLt.trans hsize)] + rfl + have wi : Fin.ofNat (2 ^ w) (rowRank P subdiv vertices tags i inRow.ids) = inSlot := by + apply Fin.ext + change rowRank P subdiv vertices tags i inRow.ids % (2 ^ w) = _ + rw [hi, Nat.mod_eq_of_lt ((I.incoming z).2.isLt.trans hsize)] + rfl + obtain ⟨es, he, hm, hp, _⟩ := recordRank_native P subdiv vertices tags hfit po mem i outRow.ids + hout hrowOut (hlo ▸ hd.trans_lt hsize) + rw [wo] at hm + have hread (j : Fin inRow.ids.length) : after mem es ((pi 0).val+j.val) = + keyWord P subdiv vertices tags hfit inRow.ids[j.val] := by + simp [hm, writeMemory, hsep j, hin j] + obtain ⟨fs, hf, hm', hp', _⟩ := recordRank_native P subdiv vertices tags hfit pi (after mem es) i + inRow.ids hread hrowIn (hli ▸ hd.trans_lt hsize) + rw [wi] at hm' + have hv : (po 1).val ≠ (pi 1).val := fun h ↦ hdist (Fin.ext h) + refine ⟨es, fs, ?_, ?_, ?_, ?_, ?_⟩ + · change rankExecution outRow.ids.length po key mem es _ at he + simpa only [hlo, wo] using he + · change rankExecution inRow.ids.length pi key (after mem es) fs _ at hf + simpa only [hli, wi] using hf + · rw [hm', hm]; simp [writeMemory, hv] + · simp [hm', writeMemory] + · rw [hp, hp', hlo, hli]; omega + +omit [Module (ZMod 2) Tag] in +/-- The total number of endpoint-writeback probes in a complete shrinking scan. +Each genuine arc costs one rank scan per endpoint and each dummy costs two +single-word writes. The coefficient of the position count depends only on the +two fixed degrees and the subdivision profile. -/ +theorem writeback_probes (hc : 2 ≤ c) (layout : Bool) (deficit : ℕ) : + let k := survivingDegree d c subdiv + let cost : Id P.Motif subdiv ⊕ Site V Tag L × Fin deficit → ℕ := + Sum.elim (fun _ ↦ 2 * (k + 1)) (fun _ ↦ 2) + ∑ i, cost i = Fintype.card (Site V Tag L) * (2 * (k * (k + 1) + deficit)) := by + intro k cost + let src := endpoint (P.survivingRole layout) (sourceRole layout) (subdiv := subdiv) + have hcard : Fintype.card (Id P.Motif subdiv) = Fintype.card (Site V Tag L) * k := by + rw [Fintype.card_congr (Equiv.sigmaFiberEquiv src).symm, Fintype.card_sigma] + have h s : Fintype.card {a // src a = s} = k := (P.survivingSlot_degree hc layout subdiv s).1 + simp [h] + simp only [Fintype.sum_sum_type, cost, Sum.elim_inl, Sum.elim_inr, Finset.sum_const, + Finset.card_univ, smul_eq_mul, hcard, Fintype.card_prod, Fintype.card_fin] + ring + +end CompressorRecords.Slots + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordTable.lean b/lean/OAI/Computability/VPVNP/CompressorRecordTable.lean new file mode 100644 index 0000000000..4de574ae5b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordTable.lean @@ -0,0 +1,98 @@ +import OAI.Computability.VPVNP.PrimedStackRAMCode +import OAI.Computability.VPVNP.RAMRecords + +/-! +# Bounded incidence lists in the descriptor scans + +The third scan of Appendix E appends old-position and role identifiers to bounded lists at +their new owners. In the first scan the same operation records members of each wire bundle. +The arrays store the count and the contiguous identifier slots separately. The code below +executes one insertion in the burst RAM. Its three external probes and seven instructions +are independent of the payload width described by the identifier. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +/-- The caller supplies the count-cell address, the first row address, the slot capacity and +the identifier in registers 0–3. Registers 4–6 hold the count, slot address and unit. -/ +def appendRecord {k : ℕ} : List (Op 7 k) := + [.read 4 0, .guardLt 4 2, .binary .add 5 1 4, .write 5 3, + .constant 6 1, .binary .add 4 4 6, .write 0 4] + +variable {w : ℕ} + +theorem appendRecord_trace {k : ℕ} (pub : Fin k → Word w) (state : Word w) + (regs : Regs w 7) (mem : Memory w) (hcap : mem (regs 0).val < regs 2) : + let length := mem (regs 0).val + let slot := regs 1 + length + let after := writeMemory (writeMemory mem slot (regs 3)) (regs 0) (length + 1) + ∃ es rs, trace pub state appendRecord regs mem = some (es, rs, after) ∧ + countProbes es = 3 ∧ es.length = 7 ∧ rs 4 = length + 1 := by + simp (config := { decide := true }) [appendRecord, trace, Op.effect, BinaryOp.eval, hcap, + Function.update, countProbes] + exact ⟨rfl, rfl⟩ + +theorem appendRecord_full {k : ℕ} (pub : Fin k → Word w) (state : Word w) + (regs : Regs w 7) (mem : Memory w) (hcap : ¬mem (regs 0).val < regs 2) : + trace pub state appendRecord regs mem = none := by + simp (config := { decide := true }) [appendRecord, trace, Op.effect, hcap, Function.update] + +/-- Array state at one owner. Only the prefix below its stored length is meaningful. -/ +def rowRepresents (mem : Memory w) (count row : Word w) (xs : List (Word w)) : Prop := + (mem count.val).val = xs.length ∧ ∀ i : Fin xs.length, mem (row.val + i.val) = xs[i.val] + +/-- Under the row address bounds, the post-state represents the old list followed by the +new identifier, in the order in which the outer scan visits its incidences. -/ +theorem appendRecord_represents {mem : Memory w} {count row cap value : Word w} + {xs : List (Word w)} (hrep : rowRepresents mem count row xs) + (hcap : xs.length < cap.val) (hfit : row.val + cap.val ≤ 2 ^ w) + (hdisjoint : count.val < row.val ∨ row.val + cap.val ≤ count.val) : + rowRepresents + (writeMemory (writeMemory mem (row + mem count.val) value) + count (mem count.val + 1)) count row (xs ++ [value]) := by + obtain ⟨hlen, hvals⟩ := hrep + have hadd : (row + mem count.val).val = row.val + xs.length := by + rw [Fin.val_add, hlen, Nat.mod_eq_of_lt (by omega)] + have hplus : (mem count.val + 1).val = xs.length + 1 := by + have hv := cap.isLt + have h1 : 1 % (2^w) = 1 := Nat.mod_eq_of_lt (by omega) + rw [Fin.val_add, Fin.val_one' _, h1, hlen, Nat.mod_eq_of_lt (by omega)] + constructor + · simp [writeMemory, hplus] + · intro i + have hi : i.val < xs.length + 1 := by simpa using i.isLt + have hne : row.val + i.val ≠ count.val := by omega + simp only [writeMemory, ite_eq_right hne] + by_cases hpre : i.val < xs.length + · have hx : row.val + i.val ≠ (row + mem count.val).val := by omega + rw [ite_eq_right hx, List.getElem_append_left hpre] + exact hvals ⟨i.val, hpre⟩ + · have hi' : i.val = xs.length := by omega + have he : row.val + i.val = (row + mem count.val).val := by omega + rw [ite_eq_left he, List.getElem_append_right (by omega)] + simp [hi'] + +/-- Executing the fixed instruction table returns the new length in the persistent state. -/ +theorem appendRecord_native {k : ℕ} (pub : Fin k → Word w) (state : Word w) (regs : Regs w 7) + (priv : Word w → Word w) (mem : Memory w) (hcap : mem (regs 0).val < regs 2) : + let M := (template appendRecord 4).instantiate w pub + ∃ es, execute M.program 8 ⟨M.entry, state, regs, priv⟩ mem [] = + some ⟨es, some (mem (regs 0).val + 1)⟩ ∧ countProbes es = 3 ∧ es.length = 7 := by + obtain ⟨es, rs, ht, hprobes, hlen, hreg⟩ := appendRecord_trace pub state regs mem hcap + refine ⟨es, ?_, hprobes, hlen⟩ + change execute ((template appendRecord 4).instantiate w pub).program (1 + (appendRecord (k := k)).length) + _ mem [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hreg] + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordTermScores.lean b/lean/OAI/Computability/VPVNP/CompressorRecordTermScores.lean new file mode 100644 index 0000000000..7b0facc18e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordTermScores.lean @@ -0,0 +1,532 @@ +import OAI.Computability.VPVNP.CompressorRecordScores +import OAI.Computability.VPVNP.PrimedScheduleRAM +import Mathlib.Algebra.BigOperators.Fin + +/-! +# The two layout counters on the stored motif terms + +The dense term row has its repetition count at offset one and its vector of payload +coordinates starting at offset two. One pass visits all motif rows for a fixed role +and layout. Its native worker computes the supply width, including the selector bits. +Eight such passes are preceded by a two-cell clear and followed by one comparison +that writes the common layout into its level's cell. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.TermScores + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- Encode a natural term-score parameter as a machine word. -/ +abbrev word (n : ℕ) : Word w := Fin.ofNat _ n + +/-- The dense term layout, score-counter base, selector width, and destination for the common +layout choice. -/ +structure Tables (w : ℕ) where + /-- First address of the fixed-stride term rows. -/ + termBase : Word w + /-- Distance in words between successive motif term rows. -/ + termStride : Word w + /-- Address of the first of two adjacent layout score counters. -/ + scoreBase : Word w + /-- Selector width charged once for each repetition in the term record. -/ + selectorBits : Word w + /-- Address where the final comparison publishes the chosen layout. -/ + levelCell : Word w + +/-- Parameters for one scoring pass over a fixed payload coordinate and layout side. -/ +structure Axis (w : ℕ) where + /-- Payload coordinate whose width contributes to this scoring pass. -/ + coordinate : Word w + /-- Layout side whose counter the pass updates. -/ + side : Bool + /-- Weight multiplying the squared supply width in this pass. -/ + weight : Word w + +/-- Assemble the seven public operands for the term-score worker from the term layout and +selected scoring axis. -/ +def params (L : Tables w) (A : Axis w) : Fin 7 → Word w := + ![L.termBase, L.termStride, L.scoreBase, L.selectorBits, A.coordinate, word A.side.toNat, A.weight] + +/-- First word of motif term row `i` at the configured stride. -/ +def rowBase (L : Tables w) (i : Word w) := L.termBase + i * L.termStride +/-- Address of the repetition-count word in motif term row `i`. -/ +def repetitions (L : Tables w) (i : Word w) := rowBase L i + 1 +/-- Address of the axis's payload-width coordinate in the specified motif term row. -/ +def payload (L : Tables w) (A : Axis w) (i : Word w) := rowBase L i + 2 + A.coordinate +/-- Select the score-counter address for the Boolean layout side. -/ +def counter (L : Tables w) (l : Bool) := L.scoreBase + word l.toNat + +/-- Natural supply width of one axis and motif, including the selector width for each stored +repetition. -/ +def supplyWidth (L : Tables w) (A : Axis w) (m : Memory w) (i : ℕ) : ℕ := + (m (payload L A (word i)).val).val + (m (repetitions L (word i)).val).val * L.selectorBits.val + +/-- Sum the axis's weighted squared supply widths over the first `n` motif rows. -/ +def axisTotal (L : Tables w) (m : Memory w) (n : ℕ) (A : Axis w) : ℕ := + ∑ i ∈ Finset.range n, A.weight.val * supplyWidth L A m i ^ 2 + +/-- Add the axis totals assigned to the requested layout side. -/ +def total (L : Tables w) (m : Memory w) (n : ℕ) (axes : List (Axis w)) (l : Bool) : ℕ := + (axes.map (fun A => if A.side = l then axisTotal L m n A else 0)).sum + +/-- Enumerating the eight axes by layout and role is the same as summing the four +role scores of the selected layout over the dense motif rows. -/ +theorem total_fin_axes (L : Tables w) (m : Memory w) (n : ℕ) (axes : Fin 8 → Axis w) + (side : ∀ j : Fin 2 × Fin 4, (axes (finProdFinEquiv j)).side = finTwoEquiv j.1) + (l : Bool) : + total L m n (List.ofFn axes) l = + ∑ t : Fin 4, ∑ j : Fin n, (axes (finProdFinEquiv (finTwoEquiv.symm l, t))).weight.val * + supplyWidth L (axes (finProdFinEquiv (finTwoEquiv.symm l, t))) m j.val ^ 2 := by + let f (i : Fin 8) := if (axes i).side = l then axisTotal L m n (axes i) else 0 + change ((List.ofFn axes).map _).sum = _ + rw [List.map_ofFn, List.sum_ofFn] + change ∑ i, f i = _ + rw [← (finProdFinEquiv (m := 2) (n := 4)).sum_comp f, Fintype.sum_prod_type] + have hs (b : Fin 2) (t : Fin 4) : (axes (finProdFinEquiv (b,t))).side = l ↔ b = finTwoEquiv.symm l := by + rw [side]; exact finTwoEquiv.eq_symm_apply.symm + simp only [f, hs, Finset.sum_ite_irrel, Finset.sum_const_zero, Finset.sum_ite_eq', + Finset.mem_univ, ite_true] + apply Finset.sum_congr rfl + intro t _ + exact (Fin.sum_univ_eq_sum_range (fun i => (axes (finProdFinEquiv (finTwoEquiv.symm l,t))).weight.val * + supplyWidth L (axes (finProdFinEquiv (finTwoEquiv.symm l,t))) m i ^ 2) n).symm + +/-- Four probes: read the repetition count and payload, then read and write the counter. -/ +def worker : List (Op 5 7) := + [.stateWord 0, .publicWord 1 1, .binary .mul 1 0 1, .publicWord 2 0, .binary .add 1 2 1, + .constant 2 1, .binary .add 3 1 2, .read 3 3, .publicWord 4 3, .binary .mul 3 3 4, + .constant 4 2, .binary .add 1 1 4, .publicWord 4 4, .binary .add 1 1 4, .read 4 1, + .binary .add 3 4 3, .binary .mul 3 3 3, .publicWord 4 6, .binary .mul 3 4 3, + .publicWord 1 2, .publicWord 4 5, .binary .add 1 1 4, .read 4 1, .binary .add 4 4 3, + .write 1 4, .binary .add 0 0 2] + +/-- Instantiate the native single-row score accumulator with the term layout and axis operands. -/ +def workerMachine (L : Tables w) (A : Axis w) := (template worker 0).instantiate w (params L A) + +/-- The updated machine-word score after adding the current row's weighted squared supply width +to its side's counter. -/ +def nextScore (L : Tables w) (A : Axis w) (m : Memory w) (i : Word w) : Word w := + let width := m (payload L A i).val + m (repetitions L i).val * L.selectorBits + m (counter L A.side).val + A.weight * (width * width) + +/-- The report of one score update, with reads of the repetition count, payload width, and +counter, followed by the counter write and next row cursor. -/ +def workerReport (L : Tables w) (A : Axis w) (m : Memory w) (i : Word w) : Report w := + let u := repetitions L i + let v := payload L A i + let cell := counter L A.side + ⟨List.replicate 7 .tick ++ [.read u (m u.val)] ++ List.replicate 6 .tick ++ [.read v (m v.val)] + ++ List.replicate 7 .tick ++ [.read cell (m cell.val), .tick, .write cell (nextScore L A m i), .tick], + some (i+1)⟩ + +theorem execute_worker (L : Tables w) (A : Axis w) (m : Memory w) (i : Word w) : + let M := workerMachine L A + execute M.program 27 (M.program.start i) m [] = some (workerReport L A m i) := by + rfl + +theorem worker_after (L : Tables w) (A : Axis w) (m : Memory w) (i : Word w) : + after m (workerReport L A m i).events = writeMemory m (counter L A.side) (nextScore L A m i) := rfl + +theorem worker_report_cost (L : Tables w) (A : Axis w) (m : Memory w) (i : Word w) : + let r := workerReport L A m i + r.events.length = 26 ∧ r.probes = 4 ∧ choiceBits r.events = [] := ⟨rfl, rfl, rfl⟩ + +/-- Only the two accumulator addresses and the output cell need separation. Repetition +and coordinate reads may be shared between axes or between rows. -/ +structure Layout (L : Tables w) (n : ℕ) (axes : List (Axis w)) : Prop where + distinct : Function.Injective (counter L) + output : ∀ l, L.levelCell ≠ counter L l + rep : ∀ i < n, ∀ l, repetitions L (word i) ≠ counter L l + coord : ∀ A ∈ axes, ∀ i < n, ∀ l, payload L A (word i) ≠ counter L l + +theorem rowBase_val (L : Tables w) {i : ℕ} (h : L.termBase.val+i*L.termStride.val < 2^w) : + (rowBase L (word i)).val = L.termBase.val+i*L.termStride.val := by + simp only [rowBase, Fin.val_add, Fin.val_mul, Fin.val_ofNat, Nat.mod_mul_mod, + Nat.add_mod_mod, Nat.mod_eq_of_lt h] + +theorem repetitions_val (L : Tables w) {i : ℕ} (h : L.termBase.val+i*L.termStride.val+1 < 2^w) : + (repetitions L (word i)).val = L.termBase.val+i*L.termStride.val+1 := by + have hb := rowBase_val L (i := i) (by omega) + rw [repetitions, Fin.val_add, hb, Fin.val_one', Nat.add_mod_mod, Nat.mod_eq_of_lt h] + +theorem payload_val (L : Tables w) (A : Axis w) {i : ℕ} + (h : L.termBase.val+i*L.termStride.val+2+A.coordinate.val < 2^w) : + (payload L A (word i)).val = L.termBase.val+i*L.termStride.val+2+A.coordinate.val := by + have hb := rowBase_val L (i := i) (by omega) + have h₂ : (2 : Word w).val = 2 := Nat.mod_eq_of_lt (by omega : 2 < 2^w) + rw [payload, Fin.val_add, Fin.val_add, hb, h₂, Nat.mod_add_mod, Nat.mod_eq_of_lt h] + +/-- Consecutive dense term rows and a disjoint two-word scratch region implement all +the read/write separation required by the eight passes. -/ +theorem Layout.ofIntervals (L : Tables w) (n : ℕ) (axes : List (Axis w)) + (rowSize : 1 < L.termStride.val) (fields : ∀ A ∈ axes, 2+A.coordinate.val < L.termStride.val) + (termFit : L.termBase.val+n*L.termStride.val ≤ 2^w) (scoreFit : L.scoreBase.val+1 < 2^w) + (regions : L.termBase.val+n*L.termStride.val ≤ L.scoreBase.val ∨ L.scoreBase.val+2 ≤ L.termBase.val) + (level : L.levelCell.val < L.scoreBase.val ∨ L.scoreBase.val+1 < L.levelCell.val) : Layout L n axes := by + have hv (l : Bool) : (counter L l).val = L.scoreBase.val+l.toNat := by + have hb : l.toNat ≤ 1 := by cases l <;> decide + rw [counter, Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)] + have endRow (i : ℕ) (hi : i < n) : (i+1)*L.termStride.val ≤ n*L.termStride.val := + Nat.mul_le_mul_right _ hi + constructor + · intro l k h + have he := congrArg Fin.val h + rw [hv, hv] at he + cases l <;> cases k <;> simp_all + · intro l h + have he := congrArg Fin.val h + rw [hv] at he + have hb : l.toNat ≤ 1 := by cases l <;> decide + omega + · intro i hi l h + have he := congrArg Fin.val h + have heR := endRow i hi + rw [Nat.add_mul, Nat.one_mul] at heR + rw [repetitions_val L (by omega), hv] at he + have hb : l.toNat ≤ 1 := by cases l <;> decide + omega + · intro A ha i hi l h + have he := congrArg Fin.val h + have hf := fields A ha + have heR := endRow i hi + rw [Nat.add_mul, Nat.one_mul] at heR + rw [payload_val L A (by omega), hv] at he + have hb : l.toNat ≤ 1 := by cases l <;> decide + omega + +/-- A single integer bound, using the number of rows, the fixed weights in the given +layout and the largest supply width, suffices for every counter in the phase. -/ +theorem total_le (L : Tables w) (m : Memory w) (n W : ℕ) (axes : List (Axis w)) (l : Bool) + (widthBound : ∀ A ∈ axes, ∀ i < n, supplyWidth L A m i ≤ W) : + total L m n axes l ≤ n * (axes.map (fun A => if A.side = l then A.weight.val else 0)).sum * W^2 := by + induction axes with + | nil => simp [total] + | cons A rest ih => + have tail := ih fun a ha => widthBound a (List.mem_cons_of_mem _ ha) + have head : axisTotal L m n A ≤ n*(A.weight.val*W^2) := by + calc + _ ≤ ∑ i ∈ Finset.range n, A.weight.val * W^2 := by + apply Finset.sum_le_sum + intro i hi + exact Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (widthBound A (List.mem_cons_self ..) i + (Finset.mem_range.mp hi)) _) + _ = _ := by simp + by_cases h : A.side = l + · simp only [total, List.map_cons, List.sum_cons, h, ite_true, Nat.mul_add, Nat.add_mul] + exact Nat.add_le_add (by simpa [Nat.mul_assoc] using head) tail + · simpa [total, h] using tail + +theorem partial_le_total (L : Tables w) (m : Memory w) (n k : ℕ) (hk : k ≤ n) + (done rest : List (Axis w)) (A : Axis w) (l : Bool) : + total L m n done l + (if A.side = l then axisTotal L m k A else 0) ≤ + total L m n (done ++ A :: rest) l := by + have hmono : axisTotal L m k A ≤ axisTotal L m n A := + Finset.sum_le_sum_of_subset_of_nonneg (Finset.range_mono hk) (fun _ _ _ => Nat.zero_le _) + by_cases h : A.side = l <;> simp [total, h] + omega + +/-- The words in the counters are residues of the integer totals. All other words still +have their values from the entry to the score phase. -/ +structure Snapshot (L : Tables w) (initial current : Memory w) (score : Bool → ℕ) : Prop where + stored : ∀ l, current (counter L l).val = word (score l) + frame : ∀ j, (∀ l, j ≠ (counter L l).val) → current j = initial j + +theorem Snapshot.exact {L : Tables w} {initial current : Memory w} {score : Bool → ℕ} + (s : Snapshot L initial current score) (l : Bool) (fit : score l < 2^w) : + (current (counter L l).val).val = score l := by + rw [s.stored] + exact Nat.mod_eq_of_lt fit + +private theorem word_succ (k : ℕ) : word (w := w) k + 1 = word (k+1) := by + apply Fin.ext + simp only [Fin.val_add, Fin.val_one', Fin.val_ofNat, Nat.mod_add_mod, Nat.add_mod_mod] + +private theorem nextScore_eq (L : Tables w) (A : Axis w) (initial current : Memory w) + (i : ℕ) (score : Bool → ℕ) (snap : Snapshot L initial current score) + (hr : ∀ l, repetitions L (word i) ≠ counter L l) + (hv : ∀ l, payload L A (word i) ≠ counter L l) : + nextScore L A current (word i) = word (score A.side + A.weight.val * supplyWidth L A initial i ^ 2) := by + have hrep := snap.frame _ fun l => Fin.val_ne_of_ne (hr l) + have hpay := snap.frame _ fun l => Fin.val_ne_of_ne (hv l) + apply Fin.ext + simp only [nextScore, hrep, hpay, snap.stored, supplyWidth, pow_two, Fin.val_add, Fin.val_mul, + Fin.val_ofNat, Nat.mul_mod_mod, Nat.mod_mul_mod, Nat.add_mod_mod, Nat.mod_add_mod] + +private theorem snapshot_step (L : Tables w) (A : Axis w) (initial current : Memory w) + (i : ℕ) (score : Bool → ℕ) (snap : Snapshot L initial current score) + (distinct : Function.Injective (counter L)) + (hr : ∀ l, repetitions L (word i) ≠ counter L l) + (hv : ∀ l, payload L A (word i) ≠ counter L l) : + Snapshot L initial (after current (workerReport L A current (word i)).events) + (fun l => score l + if A.side = l then A.weight.val * supplyWidth L A initial i ^ 2 else 0) := by + rw [worker_after, nextScore_eq L A initial current i score snap hr hv] + constructor + · intro l + by_cases h : A.side = l + · subst l; simp [writeMemory] + · have hne := Fin.val_ne_of_ne (fun he => h (distinct he.symm) : counter L l ≠ counter L A.side) + simp [writeMemory, hne, h, snap.stored] + · intro j hj + simp [writeMemory, hj, snap.frame j hj] + +private theorem probes_append (rs ts : List (Report w)) : + RAMBuckets.probeCount Report.probes (rs++ts) = + RAMBuckets.probeCount Report.probes rs + RAMBuckets.probeCount Report.probes ts := by + have h := RAMBuckets.cost_append Report.probes rs ts + simp only [RAMBuckets.cost_eq_length_add_probes, List.length_append] at h + omega + +/-- All rows of one role pass, from a fresh private register file at each call. -/ +theorem pass (L : Tables w) (A : Axis w) (n : ℕ) (initial current : Memory w) + (start : Bool → ℕ) (snap : Snapshot L initial current start) + (distinct : Function.Injective (counter L)) + (hr : ∀ i < n, ∀ l, repetitions L (word i) ≠ counter L l) + (hv : ∀ i < n, ∀ l, payload L A (word i) ≠ counter L l) : + ∃ rs, runSegment (workerMachine L A).program 27 (some 0) current (List.replicate n []) = some rs ∧ + Snapshot L initial (after current (eventLog rs)) + (fun l => start l + if A.side = l then axisTotal L initial n A else 0) ∧ + endState (some 0) rs = some (word n) ∧ rs.length = n ∧ + RAMBuckets.probeCount Report.probes rs = 4*n := by + induction n with + | zero => exact ⟨[], rfl, by simpa [axisTotal, eventLog, after] using snap, rfl, rfl, rfl⟩ + | succ n ih => + obtain ⟨rs, hrun, hs, hend, hlen, hcost⟩ := ih + (fun i hi => hr i (by omega)) (fun i hi => hv i (by omega)) + let m := after current (eventLog rs) + let r := workerReport L A m (word n) + have step := snapshot_step L A initial m n _ hs distinct (hr n (by omega)) (hv n (by omega)) + refine ⟨rs ++ [r], ?_, ?_, ?_, by simp [hlen], ?_⟩ + · rw [List.replicate_succ', PrimedSchedule.runSegment_append, hrun, Option.bind_some, hend] + simp [runSegment, execute_worker, r, m, workerReport] + · have hm : after current (eventLog (rs ++ [r])) = after m r.events := by + simp [eventLog, m, after] + rw [hm] + convert step using 1 + funext l + by_cases h : A.side = l <;> simp [h, axisTotal, Finset.sum_range_succ, Nat.add_assoc] + · rw [endState_append, hend] + change some (word n + 1) = some (word (n+1)) + rw [word_succ] + · rw [probes_append, hcost] + change 4 * n + 4 = 4*(n+1) + omega + +/-- Execute the successive axis-specific public tables, with the previous pass's memory +and a fresh row cursor at each pass boundary. -/ +def runAxes (L : Tables w) (n : ℕ) : List (Axis w) → Memory w → Option (List (Report w)) + | [], _ => some [] + | A :: axes, m => do + let rs ← runSegment (workerMachine L A).program 27 (some 0) m (List.replicate n []) + let ts ← runAxes L n axes (after m (eventLog rs)) + return rs ++ ts + +theorem run_axes (L : Tables w) (n : ℕ) (axes : List (Axis w)) + (initial current : Memory w) (start : Bool → ℕ) (snap : Snapshot L initial current start) + (layout : Layout L n axes) : + ∃ rs, runAxes L n axes current = some rs ∧ + Snapshot L initial (after current (eventLog rs)) (fun l => start l + total L initial n axes l) ∧ + rs.length = axes.length*n ∧ RAMBuckets.probeCount Report.probes rs = axes.length*(4*n) := by + induction axes generalizing current start with + | nil => exact ⟨[], rfl, by simpa [total, eventLog, after] using snap, by simp, by simp [RAMBuckets.probeCount]⟩ + | cons A axes ih => + obtain ⟨rs, hr, hs, _, hn, hc⟩ := pass L A n initial current start snap layout.distinct + layout.rep (layout.coord A (List.mem_cons_self ..)) + let m := after current (eventLog rs) + have smaller : Layout L n axes := + ⟨layout.distinct, layout.output, layout.rep, fun a ha => layout.coord a (List.mem_cons_of_mem _ ha)⟩ + obtain ⟨ts, ht, hst, htn, htc⟩ := ih m _ hs smaller + refine ⟨rs++ts, ?_, ?_, ?_, ?_⟩ + · rw [runAxes, hr] + change (runAxes L n axes m).bind _ = _ + rw [ht] + rfl + · have hm : after current (eventLog (rs++ts)) = after m (eventLog ts) := by simp [eventLog, after, m] + rw [hm] + simpa [total, Nat.add_assoc] using hst + · simp [hn, htn, Nat.add_mul, Nat.add_comm] + · simp [probes_append, hc, htc, Nat.add_mul, Nat.add_comm] + +theorem counter_false (L : Tables w) : counter L false = L.scoreBase := by + change L.scoreBase + 0 = _ + rw [add_zero] + +theorem counter_true (L : Tables w) : counter L true = L.scoreBase + 1 := rfl + +/-- A fixed call clears both scores, even when reusing a scratch area. -/ +def clearCode : List (Op 3 1) := + [.publicWord 0 0, .constant 1 0, .write 0 1, .constant 2 1, + .binary .add 0 0 2, .write 0 1] + +/-- Instantiate the native call that clears the two adjacent layout score counters. -/ +def clearMachine (L : Tables w) := (template clearCode 1).instantiate w (fun _ => L.scoreBase) + +/-- The six-event report that writes zero to both score counters and returns zero. -/ +def clearReport (L : Tables w) : Report w := + ⟨[.tick,.tick,.write L.scoreBase 0,.tick,.tick,.write (L.scoreBase+1) 0],some 0⟩ + +theorem execute_clear (L : Tables w) (m : Memory w) : + let M := clearMachine L + execute M.program 7 (M.program.start 0) m [] = some (clearReport L) := rfl + +theorem clear_report_cost (L : Tables w) : + let r := clearReport L + r.events.length = 6 ∧ r.probes = 2 ∧ choiceBits r.events = [] := ⟨rfl, rfl, rfl⟩ + +theorem clear_snapshot (L : Tables w) (m : Memory w) : + Snapshot L m (after m (clearReport L).events) (fun _ => 0) := by + change Snapshot L m (writeMemory (writeMemory m L.scoreBase 0) (L.scoreBase+1) 0) _ + constructor + · intro l + cases l <;> simp [counter_false, counter_true, writeMemory] + · intro j hj + have h0 : j ≠ L.scoreBase.val := counter_false L ▸ hj false + have h1 : j ≠ (L.scoreBase+1).val := hj true + simp only [writeMemory, ite_eq_right h0, ite_eq_right h1] + +/-- The comparison reads both accumulators and writes the chosen bit directly to the +designated level cell. The strict branch returns one. -/ +def compareTemplate : Template 11 5 2 where + literalWidth := 1 + entry := 0 + code pc := match pc.val with + | 0 => .publicWord 0 0 1 + | 1 => .readExternal 1 0 2 + | 2 => .constant 2 1 3 + | 3 => .binary .add 0 0 2 4 + | 4 => .readExternal 3 0 5 + | 5 => .jumpLt 3 1 6 7 + | 6 => .constant 4 1 8 + | 7 => .constant 4 0 8 + | 8 => .publicWord 0 1 9 + | 9 => .writeExternal 0 4 10 + | _ => .returnState 4 + +/-- Instantiate the comparison call with the two-counter base and the destination level cell. -/ +def compareMachine (L : Tables w) := compareTemplate.instantiate w ![L.scoreBase, L.levelCell] + +/-- Choose layout one exactly when its score is strictly smaller than layout zero's score, +resolving ties in favor of zero. -/ +def bit (L : Tables w) (m : Memory w) : Word w := + if m (L.scoreBase+1).val < m L.scoreBase.val then 1 else 0 + +/-- The comparison report reads both scores, writes the chosen bit to the level cell, and +returns that bit. -/ +def compareReport (L : Tables w) (m : Memory w) : Report w := + ⟨[.tick,.read L.scoreBase (m L.scoreBase.val),.tick,.tick, + .read (L.scoreBase+1) (m (L.scoreBase+1).val),.tick,.tick,.tick, + .write L.levelCell (bit L m)],some (bit L m)⟩ + +theorem execute_compare (L : Tables w) (m : Memory w) : + let M := compareMachine L + execute M.program 10 (M.program.start 0) m [] = some (compareReport L m) := by + let M := compareMachine L + let c := (((M.program.start 0).put 1 0 L.scoreBase).put 2 1 (m L.scoreBase.val)).put 3 2 1 + let d := (c.put 4 0 (L.scoreBase+1)).put 5 3 (m (L.scoreBase+1).val) + let pc := if m (L.scoreBase+1).val < m L.scoreBase.val then (6 : Fin 11) else 7 + change (execute M.program 4 { d with pc := pc } m [] + |>.map (Report.prepend .tick) |>.map (Report.prepend (.read (L.scoreBase+1) (m (L.scoreBase+1).val))) + |>.map (Report.prepend .tick) |>.map (Report.prepend .tick) + |>.map (Report.prepend (.read L.scoreBase (m L.scoreBase.val))) |>.map (Report.prepend .tick)) = _ + by_cases h : m (L.scoreBase+1).val < m L.scoreBase.val <;> + simp only [pc, h, ↓reduceIte, compareReport, bit] <;> rfl + +theorem compare_report_cost (L : Tables w) (m : Memory w) : + let r := compareReport L m + r.events.length = 9 ∧ r.probes = 3 ∧ choiceBits r.events = [] := ⟨rfl, rfl, rfl⟩ + +/-- Actual memory at an arbitrary prefix, after clearing, visiting whole earlier axes, +and then processing the first `k` rows of the current axis. A bound on the final scores +suffices for all such prefix scores. -/ +theorem run_prefix (L : Tables w) (n k : ℕ) (hk : k ≤ n) (done rest : List (Axis w)) + (A : Axis w) (m : Memory w) (layout : Layout L n (done ++ A :: rest)) + (fit : ∀ l, total L m n (done ++ A :: rest) l < 2^w) : + let cleared := after m (clearReport L).events + ∃ first part, runAxes L n done cleared = some first ∧ + runSegment (workerMachine L A).program 27 (some 0) (after cleared (eventLog first)) + (List.replicate k []) = some part ∧ + ∀ l, (after (after cleared (eventLog first)) (eventLog part) (counter L l).val).val = + total L m n done l + if A.side = l then axisTotal L m k A else 0 := by + let m₁ := after m (clearReport L).events + have earlier : Layout L n done := + ⟨layout.distinct, layout.output, layout.rep, fun a ha => layout.coord a (List.mem_append_left _ ha)⟩ + obtain ⟨first, hf, hs, _, _⟩ := run_axes L n done m m₁ _ (clear_snapshot L m) earlier + have hs' : Snapshot L m (after m₁ (eventLog first)) (total L m n done) := by + simpa only [Nat.zero_add] using hs + obtain ⟨part, hp, ht, _, _, _⟩ := pass L A k m _ _ hs' layout.distinct + (fun i hi => layout.rep i (hi.trans_le hk)) + (fun i hi => layout.coord A (List.mem_append_right _ (List.mem_cons_self ..)) i (hi.trans_le hk)) + exact ⟨first, part, hf, hp, fun l => ht.exact l ((partial_le_total L m n k hk done rest A l).trans_lt (fit l))⟩ + +/-- The scheduled clear, eight row passes, and level-cell write all execute the native +instruction tables. Only the row cursors are reset at the pass boundaries. -/ +def run (L : Tables w) (n : ℕ) (axes : List (Axis w)) (m : Memory w) : Option (List (Report w)) := do + let c ← execute (clearMachine L).program 7 ((clearMachine L).program.start 0) m [] + let rs ← runAxes L n axes (after m c.events) + let m' := after (after m c.events) (eventLog rs) + let d ← execute (compareMachine L).program 10 ((compareMachine L).program.start 0) m' [] + return c :: (rs ++ [d]) + +theorem run_eight (L : Tables w) (n : ℕ) (axes : Fin 8 → Axis w) (m : Memory w) + (layout : Layout L n (List.ofFn axes)) (fit : ∀ l, total L m n (List.ofFn axes) l < 2^w) : + let score := total L m n (List.ofFn axes) + let selected : Word w := if score true < score false then 1 else 0 + ∃ rs, run L n (List.ofFn axes) m = some rs ∧ + (∀ l, (after m (eventLog rs) (counter L l).val).val = score l) ∧ + after m (eventLog rs) L.levelCell.val = selected ∧ + (∀ j, j ≠ L.levelCell.val → (∀ l, j ≠ (counter L l).val) → after m (eventLog rs) j = m j) ∧ + endState (some 0) rs = some selected ∧ rs.length = 8*n+2 ∧ + RAMBuckets.probeCount Report.probes rs = 32*n+5 := by + dsimp only + let c := clearReport L + let m₁ := after m c.events + obtain ⟨rs, hrun, hs, hlen, hcost⟩ := run_axes L n (List.ofFn axes) m m₁ _ (clear_snapshot L m) layout + let m₂ := after m₁ (eventLog rs) + let d := compareReport L m₂ + have stored (l : Bool) : (m₂ (counter L l).val).val = total L m n (List.ofFn axes) l := by + have h := congrArg Fin.val (hs.stored l) + change (m₂ (counter L l).val).val = (0 + total L m n (List.ofFn axes) l) % (2^w) at h + rwa [Nat.zero_add, Nat.mod_eq_of_lt (fit l)] at h + have chosen : bit L m₂ = if total L m n (List.ofFn axes) true < total L m n (List.ofFn axes) false + then 1 else 0 := by + change (if (m₂ (L.scoreBase+1).val).val < (m₂ L.scoreBase.val).val then _ else _) = _ + rw [← counter_true L, ← counter_false L, stored, stored] + have hm : after m (eventLog (c :: (rs ++ [d]))) = writeMemory m₂ L.levelCell (bit L m₂) := by + change after m (c.events ++ eventLog (rs++[d])) = _ + rw [show after m (c.events ++ eventLog (rs++[d])) = after m₁ (eventLog (rs++[d])) from List.foldl_append] + simp only [eventLog, List.flatMap_append, List.flatMap_cons, List.flatMap_nil, List.append_nil, + after, List.foldl_append] + rfl + refine ⟨c :: (rs++[d]), ?_, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · rw [run, execute_clear] + change (runAxes L n (List.ofFn axes) m₁).bind _ = _ + rw [hrun] + change (execute (compareMachine L).program 10 ((compareMachine L).program.start 0) m₂ []).bind _ = _ + rw [execute_compare] + rfl + · intro l + rw [hm, writeMemory, ite_eq_right (Fin.val_ne_of_ne (layout.output l).symm), stored] + · simp [hm, writeMemory, chosen] + · intro j hj hjs + rw [hm, writeMemory, ite_eq_right hj] + exact hs.frame j hjs + · change endState c.result (rs ++ [d]) = _ + rw [endState_append] + change some (bit L m₂) = _ + rw [chosen] + · simp [hlen] + · change 2 + RAMBuckets.probeCount Report.probes (rs ++ [d]) = _ + rw [probes_append, hcost, List.length_ofFn] + change 2 + (8*(4*n)+3) = _ + omega + +end CompressorRecords.TermScores + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsABGraph.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsABGraph.lean new file mode 100644 index 0000000000..7b9dd4c3a8 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsABGraph.lean @@ -0,0 +1,103 @@ +import OAI.Computability.VPVNP.CompressorRecordsABScan +import OAI.Computability.VPVNP.CompressorRecordsBundleLists + +/-! +# AB rows in the mathematical motif numbering + +The bundle-total column is indexed by the assigned outgoing port. The native +piece scan constructs widths and starts in the same order as the AB demands +at their two packed endpoints, for every absolute lane and every parallel port. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ABWidths + +open Compression Compression.PackingData BurstRAM PrimedStackRAM + +variable {V H T L : Type} {d c n w : ℕ} +variable [Fintype V] [Fintype H] [Fintype T] [Fintype L] +variable [DecidableEq V] [DecidableEq T] [DecidableEq L] +variable [AddCommGroup H] [AddCommGroup T] [AddCommGroup L] +variable (P : PackingData V H T L d c) (number : P.BundleNumbering) (site : Site V T L ≃ Fin n) +variable (old : Arc V H T L d c → ℕ) + +private theorem width_in_fiber (b : Site V T L × Fin d) (z : P.MotifFiber b) : + P.abWidth number old z.1 = splitWidth (P.bundleWidth old b) (pieceCount d c) (number b z) := by + obtain ⟨m,h⟩ := z + subst b + rfl + +private theorem offset_in_fiber (b : Site V T L × Fin d) (z : P.MotifFiber b) : + pieceStart (P.bundleWidth old b) (pieceCount d c) (number b z).val = + fieldStart (number b) (fun m ↦ P.abWidth number old m.val) z := by + rw [prefix_sum, fieldStart, fieldStart] + apply Finset.sum_congr rfl + intro i _ + rw [width_in_fiber P number old, Equiv.apply_symm_apply] + rfl + +/-- Memory representation of all two-ended AB fields, with natural addresses and +the stride used by the term-row and kernel-slice readers. -/ +structure ABColumns (p : Fin 5 → Word w) (m : Memory w) : Prop where + widths : ∀ b : Site V T L × Fin d, ∀ j : Fin (pieceCount d c), + (m ((p 3).val+(BundleLists.portIndex site b).val*(p 1).val+j.val)).val = + P.abWidth number old ((number b).symm j).val + starts : ∀ b : Site V T L × Fin d, ∀ j : Fin (pieceCount d c), + (m ((p 4).val+(BundleLists.portIndex site b).val*(p 1).val+j.val)).val = + fieldStart (number b) (fun z ↦ P.abWidth number old z.val) ((number b).symm j) + +/-- All AB widths and offsets are computed in one native segment. -/ +theorem graph_run (p : Fin 5 → Word w) (m : Memory w) (layout : Layout p (n*d)) + (count : (p 0).val = pieceCount d c) + (totals : ∀ b : Site V T L × Fin d, + (m ((p 2).val+(BundleLists.portIndex site b).val)).val = P.bundleWidth old b) : + let N := (n*d)*pieceCount d c + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 30 (some (Fin.ofNat _ 0)) m (List.replicate N []) = some rs ∧ + ABColumns P number site old p (after m (eventLog rs)) ∧ + Filled p m (after m (eventLog rs)) N ∧ rs.length = N ∧ + RAMBuckets.cost Report.probes rs = 4*N := by + intro N M + obtain ⟨rs,hr,hf,_,hn,_,hc⟩ := run p (n*d) m layout.regions + have size : (n*d)*(p 0).val = N := congrArg ((n*d)*·) count + refine ⟨rs,size ▸ hr,⟨?_,?_⟩,size ▸ hf,size ▸ hn,size ▸ hc⟩ + all_goals + intro b j + let u := BundleLists.portIndex site b + let s := j.cast count.symm + have hs : s.val < (p 1).val := s.isLt.trans_le layout.stride + have hidx : u.val*(p 1).val+s.val < (n*d)*(p 1).val := by + have h := Nat.mul_le_mul_right (p 1).val u.isLt + rw [Nat.succ_mul] at h; omega + have idx (t : Fin 2) : (p (t.natAdd 3) + Fin.ofNat (2^w) (u.val*(p 1).val+s.val)).val = + (p (t.natAdd 3)).val+u.val*(p 1).val+j.val := by + have h := layout.outFit t + have hj : j.val = s.val := rfl + rw [Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt (by omega),Nat.add_assoc,hj] + have htaddr : (p 2 + Fin.ofNat (2^w) u.val).val = (p 2).val+u.val := by + have h := layout.totalFit; have hu := u.isLt + rw [Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt (by omega)] + obtain ⟨hwidth,hstart⟩ := hf.piece layout.regions u s + change (after m (eventLog rs) ((p (Fin.natAdd 3 (0 : Fin 2))+Fin.ofNat _ (u.val*(p 1).val+s.val)).val)).val = + splitWidth (m (p 2+Fin.ofNat _ u.val).val).val (p 0).val s at hwidth + change (after m (eventLog rs) ((p (Fin.natAdd 3 (1 : Fin 2))+Fin.ofNat _ (u.val*(p 1).val+s.val)).val)).val = + pieceStart (m (p 2+Fin.ofNat _ u.val).val).val (p 0).val s.val at hstart + rw [idx 0,htaddr,totals] at hwidth + rw [idx 1,htaddr,totals] at hstart + change _ = pieceStart (P.bundleWidth old b) (p 0).val j.val at hstart + rw [count] at hstart + · apply hwidth.trans + rw [width_in_fiber,Equiv.apply_symm_apply] + exact congrArg (fun q ↦ if j.val < P.bundleWidth old b % q then P.bundleWidth old b / q + 1 + else P.bundleWidth old b / q) count + · apply hstart.trans + simpa only [Equiv.apply_symm_apply] using offset_in_fiber P number old b ((number b).symm j) + +end CompressorRecords.ABWidths + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsABScan.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsABScan.lean new file mode 100644 index 0000000000..b551acc1c0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsABScan.lean @@ -0,0 +1,228 @@ +import OAI.Computability.VPVNP.CompressorRecordsABWidths + +/-! +# The complete rectangular AB-piece scan + +One finite program iterates over all piece ranks at all bundles. The total +column remains readable at every visit. Both output rectangles are directly +indexed by bundle and sorted rank; stride padding is untouched. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ABWidths + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression +variable {w : ℕ} + +private abbrev word (n : ℕ) : Word w := Fin.ofNat _ n + +/-- The two words produced for one AB piece, its equal-split width and its starting offset in +the bundle's concatenated payload. -/ +def value (p : Fin 5 → Word w) (m : Memory w) (i : Word w) : Fin 2 → Word w := + let t := m (input p i).val + ![ShrinkSliceArrays.splitValue t (p 0) (rank p i), offset t (p 0) (rank p i)] + +/-- Separation of the row-total column and the two write rectangles. -/ +structure Regions (p : Fin 5 → Word w) (N : ℕ) : Prop where + fits : N ≤ 2^w + unique : ∀ (t u : Fin 2) j, j fin_cases u <;> first | exact hne rfl | change (p _).val + _ = (p _).val + _ at h + all_goals first + | change (p 3).val + ((i/q)*s+i%q) = (p 4).val + ((j/q)*s+j%q) at h; omega + | change (p 4).val + ((i/q)*s+i%q) = (p 3).val + ((j/q)*s+j%q) at h; omega + subst u + have ho := Nat.add_left_cancel h + have hr := congrArg (· % s) ho + rw [Nat.mul_add_mod_of_lt ((Nat.mod_lt i L.positive).trans_le L.stride), + Nat.mul_add_mod_of_lt ((Nat.mod_lt j L.positive).trans_le L.stride)] at hr + have hb : i/q = j/q := Nat.eq_of_mul_eq_mul_right (L.positive.trans_le L.stride) + (Nat.add_right_cancel (hr ▸ ho)) + exact ⟨rfl, (Nat.mod_add_div i q).symm.trans (by rw [hr,hb,Nat.mod_add_div])⟩ + · intro i hi t j hj h + have h' := congrArg Fin.val h + rw [input,Fin.val_add,rowval i hi,addr t j hj] at h' + have hb : i/q < B := (Nat.div_lt_iff_lt_mul L.positive).mpr hi + have hinput : (p 2).val+i/q < 2^w := by have := L.totalFit; omega + rw [Nat.mod_eq_of_lt hinput] at h' + have ho := off j hj + have ha := L.totalApart t + change (p 2).val+B ≤ (p (t.natAdd 3)).val ∨ (p (t.natAdd 3)).val+B*s ≤ (p 2).val at ha + rcases ha with ha | ha + · exact (Nat.ne_of_lt ((Nat.add_lt_add_left hb _).trans_le (ha.trans (Nat.le_add_right ..)))) h' + · exact (Nat.ne_of_gt ((Nat.add_lt_add_left ho _).trans_le (ha.trans (Nat.le_add_right ..)))) h' + +/-- All completed ranks and the exact frame of their writes. -/ +structure Filled (p : Fin 5 → Word w) (initial m : Memory w) (k : ℕ) : Prop where + readback : ∀ t j, j simp [i] + · simpa only [h,and_false,ite_false] using old.readback t j (by omega) + · intro addr outside + rw [writeMemory, ite_eq_right (outside 1 k (by omega)), writeMemory, ite_eq_right (outside 0 k (by omega))] + exact old.frame _ fun t j hj ↦ outside t j (by omega) + +private theorem segment {p : Fin 5 → Word w} {N k : ℕ} {initial m : Memory w} + (reg : Regions p N) (old : Filled p initial m k) (steps : ℕ) (bound : k+steps ≤ N) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 30 (some (word k)) m (List.replicate steps []) = some rs ∧ + endState (some (word k)) rs = some (word (k+steps)) ∧ + Filled p initial (after m (eventLog rs)) (k+steps) ∧ rs.length = steps ∧ + (∀ r ∈ rs, r.events.length = 29 ∧ countProbes r.events = 3) ∧ RAMBuckets.cost Report.probes rs = 4*steps := by + induction steps generalizing k m with + | zero => exact ⟨[],rfl,rfl,old,rfl,by simp,rfl⟩ + | succ s ih => + let i := word (w := w) k + let r : Report w := ⟨events p m i, some (i+1)⟩ + have hi : i+1 = word (k+1) := by + apply Fin.ext + simp [i, word, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + have he : k+1+s = k+(s+1) := by omega + obtain ⟨rs,hr,hl,hf,hn,hw,hc⟩ := ih (step reg old (by omega)) (by omega) + refine ⟨r::rs,?_,?_,?_,by simp [hn],?_,?_⟩ + · rw [List.replicate_succ,runSegment,native] + simp only [r, i, hi, hr, Option.map_some] + · change endState (some (i+1)) rs = _ + rw [hi,hl,he] + · change Filled p initial ((events p m i ++ eventLog rs).foldl BurstRAM.update m) _ + rw [List.foldl_append,← he]; exact hf + · intro z hz + rcases List.mem_cons.mp hz with rfl | h + · exact work p m i + · exact hw z h + · rw [RAMBuckets.cost, hc, Nat.mul_succ] + have hx : r.probes = 3 := (work p m i).2 + omega + +/-- One call and three external probes per piece in the combined AB rectangle. -/ +theorem run (p : Fin 5 → Word w) (B : ℕ) (m : Memory w) (reg : Regions p (B*(p 0).val)) : + let M := (template visit 0).instantiate w p + let N := B*(p 0).val + ∃ rs, runSegment M.program 30 (some (word 0)) m (List.replicate N []) = some rs ∧ + Filled p m (after m (eventLog rs)) N ∧ endState (some (word 0)) rs = some (word N) ∧ + rs.length = N ∧ (∀ r ∈ rs, r.events.length = 29 ∧ countProbes r.events = 3) ∧ + RAMBuckets.cost Report.probes rs = 4*N := by + intro M N + have h : Filled p m m 0 := ⟨fun _ _ hi ↦ by omega,fun _ _ ↦ rfl⟩ + obtain ⟨rs,hr,hc,hf,hn,hw,cost⟩ := segment reg h N (by omega) + exact ⟨rs,hr,by simpa only [Nat.zero_add] using hf, by simpa only [Nat.zero_add] using hc,hn,hw,cost⟩ + +private theorem div_pack {b i q : ℕ} (hi : i < q) : (b*q+i)/q = b := by + rw [Nat.mul_comm, Nat.mul_add_div (by omega), Nat.div_eq_of_lt hi, Nat.add_zero] + +theorem Filled.piece {p : Fin 5 → Word w} {B : ℕ} {initial m : Memory w} + (reg : Regions p (B*(p 0).val)) (h : Filled p initial m (B*(p 0).val)) + (b : Fin B) (r : Fin (p 0).val) : + let idx := word (b.val*(p 1).val+r.val) + let total := (initial (p 2+word b.val).val).val + (m (p 3+idx).val).val = splitWidth total (p 0).val r ∧ + (m (p 4+idx).val).val = pieceStart total (p 0).val r.val := by + intro idx total + let n := b.val*(p 0).val + r.val + have hn : n < B*(p 0).val := by + have h' := Nat.mul_le_mul_right (p 0).val b.isLt + rw [Nat.succ_mul] at h' + have := r.isLt + dsimp [n]; omega + have hn' : (word (w := w) n).val = n := Nat.mod_eq_of_lt (hn.trans_le reg.fits) + have rowEq : row p (word n) = word b.val := by + change word ((word (w := w) n).val / (p 0).val) = _ + rw [hn',div_pack r.isLt] + have rankEq : rank p (word n) = word r.val := by + change word ((word (w := w) n).val % (p 0).val) = _ + rw [hn',Nat.mul_add_mod_of_lt r.isLt] + have hval : (word (w := w) r.val).val = r.val := Nat.mod_eq_of_lt (r.isLt.trans (p 0).isLt) + have hidx : row p (word n)*p 1+rank p (word n) = idx := by + rw [rowEq,rankEq,Fin.ofNat_mul,Fin.ofNat_add] + apply Fin.ext; simp only [Fin.val_ofNat, idx, word, Nat.add_mod_mod] + have atWidth := h.readback 0 n hn + have atStart := h.readback 1 n hn + change m (p 3+(row p (word n)*p 1+rank p (word n))).val = ShrinkSliceArrays.splitValue + (initial (p 2+row p (word n)).val) (p 0) (rank p (word n)) at atWidth + change m (p 4+(row p (word n)*p 1+rank p (word n))).val = offset + (initial (p 2+row p (word n)).val) (p 0) (rank p (word n)) at atStart + rw [hidx,rowEq,rankEq] at atWidth atStart + have hr : (word (w := w) r.val).val < (p 0).val := by rw [hval]; exact r.isLt + constructor + · rw [atWidth,ShrinkSliceArrays.splitValue_eq _ _ _ hr] + exact congrArg _ (Fin.ext hval) + · rw [atStart, offset_exact _ _ _ hr, hval] + +end CompressorRecords.ABWidths + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsABWidths.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsABWidths.lean new file mode 100644 index 0000000000..f1cd42a044 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsABWidths.lean @@ -0,0 +1,141 @@ +import OAI.Computability.VPVNP.CompressorShrinkSliceArrays +import OAI.Computability.VPVNP.CompressorRecordsShrinkRAM + +/-! +# Native equal-piece widths and prefix offsets for all AB bundles + +The source index enumerates the piece ranks of each bundle consecutively. +One probe retrieves its total thick width. Two writes give the width and +prefix offset of this particular piece. Division by zero at a zero remainder +implements the zero indicator in the machine's prescribed word arithmetic. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ABWidths + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression +open ShrinkRAM (div mod select) +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Public words give the number of pieces, rectangle stride, total-width column, +AB width and AB offset bases. The latter two rectangles share their row stride. -/ +def visit : List (Op 13 5) := + [.stateWord 0, .publicWord 1 0, .binary .div 2 0 1, .binary .mod 3 0 1, + .publicWord 4 2, .binary .add 4 4 2, .read 5 4, .binary .div 6 5 1, .binary .mod 7 5 1, + .constant 8 1, .binary .add 9 3 8, .binary .div 9 7 9, .binary .div 9 9 9, + .binary .add 10 6 9, .binary .sub 11 3 7, .binary .mul 11 9 11, .binary .add 11 7 11, + .binary .mul 6 3 6, .binary .add 11 6 11, .publicWord 6 1, .binary .mul 2 2 6, + .binary .add 2 2 3, .publicWord 4 3, .binary .add 4 4 2, .write 4 10, + .publicWord 4 4, .binary .add 4 4 2, .write 4 11, .binary .add 0 0 8] + +/-- Recover the bundle number from the linear piece cursor by dividing by the number of pieces +per bundle. -/ +def row (p : Fin 5 → Word w) (i : Word w) := div i (p 0) +/-- Recover the piece's rank within its bundle as the remainder of the linear cursor. -/ +def rank (p : Fin 5 → Word w) (i : Word w) := mod i (p 0) +/-- Address of the selected bundle's total-width word in the input column. -/ +def input (p : Fin 5 → Word w) (i : Word w) := p 2+row p i +/-- Address of a piece's width or offset in the corresponding output rectangle, using the +bundle stride and piece rank. -/ +def address (p : Fin 5 → Word w) (t : Fin 2) (i : Word w) := + p (t.natAdd 3)+(row p i*p 1+rank p i) + +/-- The machine-word indicator that this rank receives one of the extra units left over after +dividing the bundle width. -/ +def extra (b q r : Word w) := + let t := div (mod b q) (r+1) + div t t + +/-- The sum of the widths assigned to earlier pieces, including their share of the division +remainder. -/ +def offset (b q r : Word w) := + r * div b q + select (extra b q r) (mod b q) r + +/-- The events for one AB-piece visit, including the read of the bundle total and the writes of +the piece width and prefix offset. -/ +def events (p : Fin 5 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + let t := m (input p i).val + List.replicate 6 .tick ++ [.read (input p i) t] ++ List.replicate 17 .tick ++ + [.write (address p 0 i) (ShrinkSliceArrays.splitValue t (p 0) (rank p i)), .tick, .tick, + .write (address p 1 i) (offset t (p 0) (rank p i)), .tick] + +theorem native (p : Fin 5 → Word w) (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program 30 (M.program.start i) m [] = some ⟨events p m i, some (i+1)⟩ := by + change execute ((template visit 0).instantiate w p).program (1+visit.length) + ⟨_,i,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + rw [execute_template, run_eq_trace] + rfl + +theorem work (p : Fin 5 → Word w) (m : Memory w) (i : Word w) : + (events p m i).length = 29 ∧ countProbes (events p m i) = 3 := ⟨rfl,rfl⟩ + +/-- Starting index of piece rank r in a balanced split. -/ +def pieceStart (b q r : ℕ) := r*(b/q) + min r (b%q) + +theorem prefix_succ (b q r : ℕ) (h : r < q) : + pieceStart b q (r+1) = pieceStart b q r + splitWidth b q ⟨r,h⟩ := by + unfold pieceStart splitWidth + simp only [Nat.succ_mul] + split <;> omega + +theorem prefix_sum {b q : ℕ} (i : Fin q) : + pieceStart b q i.val = PackingData.fieldStart (Equiv.refl (Fin q)) (splitWidth b q) i := by + have aux (r : ℕ) (h : r ≤ q) : pieceStart b q r = + ∑ t : Fin r, splitWidth b q (Fin.castLE h t) := by + induction r with + | zero => simp [pieceStart] + | succ r ih => + rw [Fin.sum_univ_castSucc, prefix_succ b q r (by omega), ih (by omega)] + rfl + exact aux i.val i.isLt.le + +private theorem div_val (a b : Word w) : (div a b).val = a.val/b.val := + Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt a.isLt) + +private theorem mod_val (a b : Word w) : (mod a b).val = a.val%b.val := + Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt a.isLt) + +theorem offset_exact (b q r : Word w) (h : r.val < q.val) : + (offset b q r).val = pieceStart b.val q.val r.val := by + have hp : 1 < 2^w := by have := q.isLt; omega + have he : (r+1).val = r.val+1 := by + rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt hp, Nat.mod_eq_of_lt (by have := q.isLt; omega)] + have hsum : pieceStart b.val q.val r.val ≤ b.val := by + unfold pieceStart + have ht := Nat.mul_le_mul_right (b.val/q.val) h.le + have hd := Nat.div_add_mod b.val q.val + have hm := min_le_right r.val (b.val%q.val) + omega + let t := div (mod b q) (r+1) + have ht : t.val = b.val % q.val / (r.val+1) := by rw [div_val, mod_val, he] + have hx : select (extra b q r) (mod b q) r = if r.val < b.val%q.val then r else mod b q := by + by_cases hl : r.val < b.val%q.val + · have ht' : 0 < t.val := ht ▸ Nat.div_pos (by omega) (Nat.zero_lt_succ _) + have h1 : extra b q r = 1 := Fin.ext (by + change (div t t).val = (1 : Word w).val + rw [div_val,Nat.div_self ht', Fin.val_one',Nat.mod_eq_of_lt hp]) + simp [hl, h1] + · have hz : t.val = 0 := ht.trans (Nat.div_eq_of_lt (by omega)) + have h0 : extra b q r = 0 := Fin.ext (by change (div t t).val = 0; rw [div_val,hz]) + simp [hl,h0] + rw [offset,hx,Fin.val_add,Fin.val_mul,div_val,Nat.mod_add_mod] + split + · rename_i hl + simpa only [pieceStart,min_eq_left hl.le] using + Nat.mod_eq_of_lt (hsum.trans_lt b.isLt) + · rename_i hl + rw [mod_val] + simpa only [pieceStart,min_eq_right (Nat.le_of_not_gt hl)] using + Nat.mod_eq_of_lt (hsum.trans_lt b.isLt) + +end CompressorRecords.ABWidths + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBlockPlanner.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBlockPlanner.lean new file mode 100644 index 0000000000..d2d56872c8 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBlockPlanner.lean @@ -0,0 +1,198 @@ +import OAI.Computability.VPVNP.CompressorRecordsOnline +import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +import OAI.Computability.VPVNP.CompressorRecordsLevelFields +import OAI.Computability.VPVNP.LiveAuxiliaryHeaders + +/-! +# Compiling a finite block of native scans + +Each phase contains its worker and exactly the expressions for that worker's +public bank. The phase's position in the program determines the tag written +by its planner. The initial sequence and one complete block determine the +instruction table. The number of repeated blocks enters through the runtime +row count. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockPlanner + +open BurstRAM BurstRAM.PrivateRAM PhaseRecipe PrimedStackRAM Schedule +open scoped Fin.CommRing + +/-- One scheduled scan, pairing its worker with expressions for the initial cursor, exclusive +stopping cursor, and public operands. -/ +structure Visit where + /-- The native pass selected for this scan and the arity of its operand bank. -/ + worker : Schedule.Pass + /-- Expression giving the state word passed to the worker at the start of the scan. -/ + initial : Expr + /-- Expression giving the exclusive end cursor at which this worker's scan finishes. -/ + stop : Expr + /-- An operand expression for each public input of the selected worker. -/ + params : Fin worker.params → Expr + +/-- Combine a native pass with the cursor and operand expressions from a phase of matching +arity. -/ +def Visit.ofPhase (P : Schedule.Pass) (phase : PhaseRecipe.Phase P.params) : Visit := + ⟨P,phase.initial,phase.stop,phase.params⟩ + +/-- Build a scheduled visit for a straight-line stack-RAM worker, with its result register, +cursor bounds, and public operands. -/ +def ops {r k : ℕ} (code : List (PrimedStackRAM.Op r k)) (out : Fin r) (initial stop : Expr) + (params : Fin k → Expr) : Visit := + ⟨⟨_,_,_,PrimedStackRAM.template code out⟩,initial,stop,params⟩ + +/-- Move a verified scratch column to the next level's published incidence directory. -/ +def copy (count source dest : Expr) : Visit := + ops LiveAuxiliaryHeaders.copyWord 7 (.lit 0) count ![.lit 0,source,dest] + +private def put : List (PrimedStackRAM.Op 4 2) := + [.stateWord 0,.publicWord 1 0,.publicWord 2 1,.write 1 2,.constant 3 1,.binary .add 0 0 3] + +/-- Publish a single fixed subdivision or header field in the current level. -/ +def publish (dest value : Expr) : Visit := ops put 0 (.lit 0) (.lit 1) ![dest,value] + +theorem publish_native {w : ℕ} (dest value : Expr) (pub : Fin 2 → Word w) (s : Word w) + (m : Memory w) : + let M := ((publish dest value).worker.table.instantiate w pub).program + let es := [.tick,.tick,.tick,.write (pub 0) (pub 1),.tick,.tick] + execute M 7 (M.start s) m [] = some ⟨es,some (s+1)⟩ ∧ + after m es = writeMemory m (pub 0) (pub 1) ∧ countProbes es = 1 ∧ choiceBits es = [] := by + refine ⟨?_,rfl,rfl,rfl⟩ + change execute ((PrimedStackRAM.template put 0).instantiate w pub).program (1+put.length) + ⟨((PrimedStackRAM.template put 0).instantiate w pub).entry,s,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + rw [execute_template,run_eq_trace] + rfl + +/-- The finite visits needed to run the initial scans once and a block of scans repeatedly, +with the level advance per block. -/ +structure Script where + /-- Number of descriptor levels advanced by each complete repetition of the block. -/ + levelsPerBlock : ℕ + /-- The visits executed once before the first repeated block. -/ + initial : List Visit + /-- The ordered visits that make up one repetition of the scheduled block. -/ + block : List Visit + +namespace Script + +variable (A : Script) + +/-- Number of visit positions in the initial sequence followed by one block. -/ +abbrev size := A.initial.length+A.block.length + +/-- Look up a visit in the concatenated indexing of initial phases and block phases. -/ +def visit (j : Fin A.size) : Visit := + Fin.addCases (fun i ↦ A.initial[i.val]) (fun i ↦ A.block[i.val]) j + +/-- The native worker at each of the script's visit positions. -/ +def catalog : Schedule.Catalog A.size := fun j ↦ (A.visit j).worker + +/-- Each occurrence gets its own finite worker label, even when several +occurrences run the same native table on different operands. -/ +def phase (j : Fin A.size) : PhaseRecipe.Phase (Schedule.arity A.catalog) := + Phase.ofParams (params_le_arity A.catalog j) j.succ.val (A.visit j).initial (A.visit j).stop + (A.visit j).params + +/-- Compile the visit recipes and block level advance into the online scheduler's +configuration. -/ +def plan : Schedule.Online.Config A.catalog A.initial.length A.block.length where + levelsPerBlock := A.levelsPerBlock + recipes j := ⟨(A.phase j).registerCount,(A.phase j).recipe⟩ + +/-- Instantiate the online scheduler for this script on the supplied workspace ports. -/ +def program {w : ℕ} (ports : Schedule.Ports w) := Schedule.Online.program A.plan ports + +theorem phase_tag (j : Fin A.size) : (A.phase j).tag = j.succ.val := rfl +theorem phase_initial (j : Fin A.size) : (A.phase j).initial = (A.visit j).initial := rfl +theorem phase_stop (j : Fin A.size) : (A.phase j).stop = (A.visit j).stop := rfl + +theorem phase_param (j : Fin A.size) (i : Fin (A.visit j).worker.params) : + (A.phase j).params (i.castLE (params_le_arity A.catalog j)) = (A.visit j).params i := by + simp only [phase,Phase.ofParams] + split_ifs with h + · rfl + · exact False.elim (h i.isLt) + +theorem initial_visit (j : Fin A.initial.length) : A.visit (j.castAdd A.block.length) = + A.initial[j.val] := + Fin.addCases_left .. + +theorem block_visit (j : Fin A.block.length) : A.visit (j.natAdd A.initial.length) = + A.block[j.val] := + Fin.addCases_right .. + +theorem calendar_total (t : ℕ) : (Schedule.Online.calendar A.plan).total t = + A.initial.length+t*A.block.length := by + simp [Schedule.Online.calendar, Schedule.LevelCalendar.recipeCalendar, + Schedule.LevelCalendar.Calendar.total] + +theorem block_phase (t : ℕ) (j : Fin A.block.length) : + (Schedule.Online.calendar A.plan).phase (A.initial.length+t*A.block.length+j.val) = + (j.natAdd A.initial.length).val ∧ + (Schedule.Online.calendar A.plan).level (A.initial.length+t*A.block.length+j.val) = t := by + let K := Schedule.Online.calendar A.plan + have hb : K.block.length = A.block.length := + by simp [K,Schedule.Online.calendar,Schedule.LevelCalendar.recipeCalendar] + have hi : K.initial.length = A.initial.length := + by simp [K,Schedule.Online.calendar,Schedule.LevelCalendar.recipeCalendar] + simpa only [hb,hi,Fin.val_cast,Fin.val_natAdd] using K.block_phase t (j.cast hb.symm) + +end Script + +/-- Runtime cursor parameters are produced before the first calendar visit. +They occupy eight persistent scalar cells in the initial level. This bank +survives subsequent launches that overwrite the active frame. -/ +def cursor (frame : Expr) : Visit := + let src (i : ℕ) := Expr.load (frame.add (.lit i)) + let count := (((src 3).mul (src 4)).mul (src 5)).mul (src 2) + let col (c : Fin 6) := (src 7).add ((Expr.lit c.val).mul count) + ⟨Schedule.cursorPass,.lit 0,count,Fin.append (fun j : Fin 5 ↦ src (j.val+2)) col⟩ + +theorem cursor_parameters {w b l a width start : ℕ} (frame : Expr) (pub : Fin 5 → Word w) + (state : Word w) + (m : Memory w) (base : Word w) (he : frame.eval pub state m = base) + (stored : ∀ j : Fin 6, m (base+((j.val+2 : ℕ) : Word w)).val = + ![(2^a : Word w),((b+l : ℕ) : Word w),(2^b : Word w),(2^l : Word w),(width : Word w),(start + : Word w)] j) : + (cursor frame).stop.eval pub state m = ((CursorRAM.rowCount b l a : ℕ) : Word w) ∧ + (fun j ↦ ((cursor frame).params j).eval pub state m) = CursorRAM.publicWords w b l a width + start := by + let src (i : ℕ) := m (base+(i : Word w)).val + have read (j : Fin 6) : src (j.val+2) = + ![(2^a : Word w),((b+l : ℕ) : Word w),(2^b : Word w),(2^l : Word w),(width : Word w),(start + : Word w)] j := + stored j + have n : (src 3 * src 4 * src 5 * src 2) = ((CursorRAM.rowCount b l a : ℕ) : Word w) := by + rw [show src 3 = _ from read 1,show src 4 = _ from read 2,show src 5 = + _ from read 3,show src 2 = _ from read 0] + simp [CursorRAM.rowCount] + constructor + · simpa only [cursor,Expr.mul,Expr.eval,Expr.add,BinaryOp.eval,he] using n + · apply funext + intro (j : Fin (5+6)) + cases j using Fin.addCases with + | left i => + have hpub : CursorRAM.publicWords w b l a width start (i.castAdd 6) = + ![(2^a : Word w),((b+l : ℕ) : Word w),(2^b : Word w),(2^l : Word w),(width : Word + w),(start : Word w)] i.castSucc := by + fin_cases i <;> simp [CursorRAM.publicWords,CursorRAM.encode] + simp only [cursor,Fin.append_left,Expr.eval,Expr.add,BinaryOp.eval,he,hpub] + exact read i.castSucc + | right c => + have hstart : src 7 = (start : Word w) := read 5 + have hpub : CursorRAM.publicWords w b l a width start (c.natAdd 5) = + (start : Word w)+(c.val : Word w)*((CursorRAM.rowCount b l a : ℕ) : Word w) := by + fin_cases c <;> simp [CursorRAM.publicWords,CursorRAM.encode] + simp only [cursor,Fin.append_right,Expr.eval,Expr.add,Expr.mul,BinaryOp.eval,he,hpub] + change src 7 + (c.val : Word w)*(src 3*src 4*src 5*src 2) = _ + rw [hstart,n] + +end CompressorRecords.BlockPlanner + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleGather.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleGather.lean new file mode 100644 index 0000000000..26b95c83e1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleGather.lean @@ -0,0 +1,164 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleLists +import OAI.Computability.VPVNP.CompressorRecordsBundleRank +import OAI.Computability.VPVNP.CompressorBundleKeyMaterialization + +/-! +# Recovering the two bundle numberings from the classified arc directory + +The preimage pass stores original arc IDs. To rank one of them, gather the +keys at those IDs into a consecutive row and run the native rank scan on the +row. Both steps use the same actual arc order, including distinct parallel +arcs. Their order in memory can differ from their order by relative key. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleGather + +open Compression Compression.PackingData BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open BundleLists Slots BundleRank + +variable {V H Tag L : Type} {A n d c w N J : ℕ} +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) +variable (arcs : Arc V H Tag L d c ≃ Fin A) (site : Site V Tag L ≃ Fin n) +variable (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) + +private def incident {E S : Type*} {m : ℕ} {port : E → S} {b : S} + (order : Fin m ≃ {e // port e = b}) : IncidentRow port b where + ids := List.ofFn fun i ↦ (order i).val + nodup := List.nodup_ofFn_ofInjective (Subtype.val_injective.comp order.injective) + complete e := by + rw [List.mem_ofFn] + constructor + · rintro ⟨i,rfl⟩; exact (order i).prop + · intro he; exact ⟨order.symm ⟨e,he⟩,congrArg Subtype.val (order.apply_symm_apply _)⟩ + +/-- The typed thick row is in the actual ID order used by the append scan. -/ +def thickRow (b : Port V Tag L d) : IncidentRow (fun a : P.ThickWire ↦ a.val.1) b := + incident ((ordinalEquiv P arcs site hA hn (.inl b)).trans (thickEquiv P b)) + +/-- The typed motif row has the same indices as the native row of original IDs. -/ +def motifRow (b : Port V Tag L d) : IncidentRow P.bundle b := + incident ((ordinalEquiv P arcs site hA hn (.inr b)).trans (motifEquiv P b)) + +/-- A successful native key scan on this bundle, together with the untouched +old width column. Its report sequence includes all addresses and costs. -/ +structure Gathered (g : Fin 3 → Word w) (count arcCount widthBase : ℕ) + (mem : Memory w) (rs : List (Report w)) : Prop where + run : SlotOwners.FilledRun ((template BundleKeys.materializeKey 0).instantiate w g).program + 13 3 12 count (g 2) (fun i ↦ mem ((g 1).val + (mem ((g 0).val+i)).val)) mem rs + widths : ∀ e < arcCount, after mem (eventLog rs) (widthBase+e) = mem (widthBase+e) + +/-- From the actual memory of the preimage pass, gather keys by indirect lookup. +Every returned position now addresses the classifier's key for its typed arc. -/ +theorem gather (p : Fin 6 → Word w) (hp : (p 2).val = n*d+n*d) (b : Bucket V Tag L d) + (mem : Memory w) (filled : PreimagesAt p (wordOwner P arcs site) mem A) + (g : Fin 3 → Word w) (src : g 0 = rowAt p (Fin.ofNat _ (bucketIndex site b).val)) + (widthBase : ℕ) + (reg : BundleKeys.KeyRowRegions g (arcList (w := w) P arcs site b).length A widthBase) : + ∃ rs, Gathered g (arcList (w := w) P arcs site b).length A widthBase mem rs ∧ + ∀ i : Fin (arcList (w := w) P arcs site b).length, + after mem (eventLog rs) ((g 2).val+i.val) = + mem ((g 1).val+(arcs (ordinalEquiv P arcs site hA hn b i).val).val) := by + let u := Fin.ofNat (2^w) (bucketIndex site b).val + have hu : u < p 2 := by + change (bucketIndex site b).val % (2^w) < (p 2).val + rw [Nat.mod_eq_of_lt ((bucketIndex site b).isLt.trans_le hn), hp] + exact (bucketIndex site b).isLt + have hids (i : Fin (arcList (w := w) P arcs site b).length) : + (mem ((g 0).val+i.val)).val = (arcs (ordinalEquiv P arcs site hA hn b i).val).val := by + rw [src, (filled.rows u hu).2 i] + change ((arcList P arcs site b).get i).val = _ + rw [ordinalEquiv_id P arcs site hA hn, Fin.val_ofNat, + Nat.mod_eq_of_lt ((arcs _).isLt.trans_le hA)] + obtain ⟨rs, run, widths⟩ := BundleKeys.materialize_run g mem (arcList P arcs site b).length A + widthBase reg (fun i hi ↦ (hids ⟨i,hi⟩).trans_lt (arcs _).isLt) + refine ⟨rs, ⟨run,widths⟩, fun i ↦ ?_⟩ + rw [run.filled i.val i.isLt, hids i] + +/-- Materialized row addresses correspond one-for-one to old thick wires. +The classifier column can be populated anywhere disjoint from the destination. -/ +theorem thick_read (b : Port V Tag L d) (mem out : Memory w) (g : Fin 3 → Word w) + (hf : 2^c*d ≤ 2^w) + (keys : ∀ a : P.ThickWire, mem ((g 1).val+(arcs a.val).val) = (thickKey P a).castLE hf) + (copy : ∀ i : Fin (arcList (w := w) P arcs site (.inl b)).length, + out ((g 2).val+i.val) = mem ((g 1).val+(arcs (ordinalEquiv P arcs site hA hn (.inl b) i).val).val)) : + let r := thickRow P arcs site hA hn b + ∀ i : Fin r.ids.length, out ((g 2).val+i.val) = (thickKey P r.ids[i.val]).castLE hf := by + intro r i + let j : Fin (arcList (w := w) P arcs site (.inl b)).length := + ⟨i.val, by simpa [r,thickRow,incident] using i.isLt⟩ + have he : r.ids[i.val] = (thickEquiv P b (ordinalEquiv P arcs site hA hn (.inl b) j)).val := by + simp [r,thickRow,incident,j] + rw [he, copy j] + exact keys (thickEquiv P b (ordinalEquiv P arcs site hA hn (.inl b) j)).val + +theorem motif_read (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (b : Port V Tag L d) + (mem out : Memory w) (g : Fin 3 → Word w) (hf : N*(J*(d*(2^c*d))) ≤ 2^w) + (keys : ∀ m : P.Motif, mem ((g 1).val+(arcs m.val).val) = (motifKey P vertices tags m).castLE hf) + (copy : ∀ i : Fin (arcList (w := w) P arcs site (.inr b)).length, + out ((g 2).val+i.val) = mem ((g 1).val+(arcs (ordinalEquiv P arcs site hA hn (.inr b) i).val).val)) : + let r := motifRow P arcs site hA hn b + ∀ i : Fin r.ids.length, out ((g 2).val+i.val) = (motifKey P vertices tags r.ids[i.val]).castLE hf := by + intro r i + let j : Fin (arcList (w := w) P arcs site (.inr b)).length := + ⟨i.val, by simpa [r,motifRow,incident] using i.isLt⟩ + have he : r.ids[i.val] = (motifEquiv P b (ordinalEquiv P arcs site hA hn (.inr b) j)).val := by + simp [r,motifRow,incident,j] + rw [he, copy j] + exact keys (motifEquiv P b (ordinalEquiv P arcs site hA hn (.inr b) j)).val + +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] + +/-- Gather an actual DD row from the classified directory. Starting in that +post-memory, ranking any of its members writes its concatenation number. -/ +theorem gather_rank_thick (hc : 2 ≤ c) (p : Fin 6 → Word w) (hp : (p 2).val = n*d+n*d) + (b : Port V Tag L d) (mem : Memory w) (filled : PreimagesAt p (wordOwner P arcs site) mem A) + (g : Fin 3 → Word w) (src : g 0 = rowAt p (Fin.ofNat _ (bucketIndex site (.inl b)).val)) + (widthBase : ℕ) (reg : BundleKeys.KeyRowRegions g (2^c*d/4) A widthBase) + (hf : 2^c*d < 2^w) + (keys : ∀ a : P.ThickWire, mem ((g 1).val+(arcs a.val).val) = (thickKey P a).castLE hf.le) : + ∃ rs, Gathered g (2^c*d/4) A widthBase mem rs ∧ + ∀ (x : P.ThickFiber b) (dst : Word w), + RankWrite (2^c*d/4) ![g 2,dst] (after mem (eventLog rs)) ((thickKey P x.val).castLE hf.le) + (Fin.ofNat _ (P.sortedThickNumbering hc b x).val) := by + have hA : A ≤ 2^w := by have := reg.keysFit; omega + have hn : n*d+n*d ≤ 2^w := hp ▸ (p 2).isLt.le + have hlen := arcList_length P arcs site hc hA hn (.inl b) + change (arcList P arcs site (.inl b)).length = 2^c*d/4 at hlen + obtain ⟨rs,run,copy⟩ := gather P arcs site hA hn p hp (.inl b) mem filled g src widthBase (hlen ▸ reg) + refine ⟨rs, hlen ▸ run, fun x dst ↦ ?_⟩ + exact thick_rank_native P hc hf b (thickRow P arcs site hA hn b) x ![g 2,dst] _ + (thick_read P arcs site hA hn b mem _ g hf.le keys copy) reg.destinationFits + +/-- Gather the actual CD row and rank a member to obtain its AB piece number +in the sorted bundle numbering. -/ +theorem gather_rank_motif (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (hc : 2 ≤ c) + (p : Fin 6 → Word w) (hp : (p 2).val = n*d+n*d) (b : Port V Tag L d) + (mem : Memory w) (filled : PreimagesAt p (wordOwner P arcs site) mem A) + (g : Fin 3 → Word w) (src : g 0 = rowAt p (Fin.ofNat _ (bucketIndex site (.inr b)).val)) + (widthBase : ℕ) (reg : BundleKeys.KeyRowRegions g (pieceCount d c) A widthBase) + (hf : N*(J*(d*(2^c*d))) < 2^w) + (keys : ∀ m : P.Motif, mem ((g 1).val+(arcs m.val).val) = (motifKey P vertices tags m).castLE hf.le) : + ∃ rs, Gathered g (pieceCount d c) A widthBase mem rs ∧ + ∀ (x : P.MotifFiber b) (dst : Word w), + RankWrite (pieceCount d c) ![g 2,dst] (after mem (eventLog rs)) ((motifKey P vertices tags x.val).castLE hf.le) + (Fin.ofNat _ (P.sortedBundleNumbering vertices tags hc b x).val) := by + have hA : A ≤ 2^w := by have := reg.keysFit; omega + have hn : n*d+n*d ≤ 2^w := hp ▸ (p 2).isLt.le + have hlen := arcList_length P arcs site hc hA hn (.inr b) + change (arcList P arcs site (.inr b)).length = pieceCount d c at hlen + obtain ⟨rs,run,copy⟩ := gather P arcs site hA hn p hp (.inr b) mem filled g src widthBase (hlen ▸ reg) + refine ⟨rs, hlen ▸ run, fun x dst ↦ ?_⟩ + exact motif_rank_native P vertices tags hc hf b (motifRow P arcs site hA hn b) x ![g 2,dst] _ + (motif_read P arcs site hA hn vertices tags b mem _ g hf.le keys copy) reg.destinationFits + +end CompressorRecords.BundleGather + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleGraph.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleGraph.lean new file mode 100644 index 0000000000..1672d023f8 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleGraph.lean @@ -0,0 +1,133 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleScan +import OAI.Computability.VPVNP.CompressorRecordsBundleWords +import OAI.Computability.VPVNP.CompressorRecordsBundleLists + +/-! +# Classification of all actual old arcs in a shrinking pass + +The complete native scan assigns every absolute outgoing slot to its thick-wire +or CD bundle and writes its relative sorting key. Distinct parallel wires retain +their original array indices. The combined bucket column can serve immediately +as the owner array of the bounded-append pass. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleRAM + +open Compression BurstRAM PrimedStackRAM BundleKeys +open scoped Fin.CommRing + +variable {V : Type} {n a g w : ℕ} +variable (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) (order : V ≃ Fin n) +local notation "P" => orderedDyadicPacking G order +local notation "A" => n*2^(packingLaneBits a g)*2^a + +/-- Test whether both endpoints of an old arc are thick under the shrinking placement, making +the arc a thick payload wire. -/ +def bothThick (e : OldArc V a g) : Bool := + decide ((P).thick (sourcePosition e) ∧ (P).thick (sourcePosition ((P).actual e))) + +private theorem bucket_number (layout : Bool) (e : OldArc V a g) : + bucketFromRows (numBundles n a g) (2^a) e.1.2.val + (siteRow G order layout (sourcePosition e)) + (siteRow G order layout (sourcePosition ((P).actual e))) = + (BundleLists.bucketIndex (Shrink.packedIndex order) (BundleLists.bucketOf P e)).val := by + by_cases h : (P).thick (sourcePosition e) ∧ (P).thick (sourcePosition ((P).actual e)) + · let wire : (P).ThickWire := ⟨e,h⟩ + rw [thick_bucket G order layout wire, BundleLists.bucketOf_thick P wire, + BundleLists.bucketIndex_thick_val, Shrink.packedIndex_val] + rfl + · let m : (P).Motif := ⟨e,h⟩ + rw [motif_bucket G order layout m, BundleLists.bucketOf_motif P m, + BundleLists.bucketIndex_motif_val, Shrink.packedIndex_val] + rfl + +private theorem key_fits (e : OldArc V a g) : keyAt order (bothThick G order e) e < A := by + let C := Shrink.colors a + let J := Shrink.J a + have hn : 1 ≤ n := Nat.succ_le_of_lt (Nat.zero_lt_of_lt (order e.1.1.1).isLt) + have hA : A = n * 2^J * 2^a * (2^C * 2^a) * 2^g := by + simp only [packingLaneBits, pow_add, C, J, Shrink.colors, Shrink.J]; ring + rw [hA] + unfold bothThick + by_cases h : (P).thick (sourcePosition e) ∧ (P).thick (sourcePosition ((P).actual e)) + · let wire : (P).ThickWire := ⟨e,h⟩ + let fib : (P).ThickFiber e.1 := ⟨wire,rfl⟩ + rw [decide_eq_true h, thick_key G order e.1 fib] + exact (Fin.isLt _).trans_le ((Nat.le_mul_of_pos_left _ (by positivity : + 0 < n*2^J*2^a)).trans (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g))) + · let m : (P).Motif := ⟨e,h⟩ + rw [decide_eq_false h, motif_key G order m] + have hk := ((P).baseMotifIndex order (bitWordFinEquiv J) ((P).baseMotif m)).isLt + apply hk.trans_le + exact (show n*(2^J*(2^a*(2^C*2^a))) = n*2^J*2^a*(2^C*2^a) by ring).le.trans + (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g)) + +/-- Numerical bucket and key columns indexed by the original absolute arc number. -/ +structure Classified (p : Fin 11 → Word w) (m : Memory w) : Prop where + owner : ∀ (i : Word w), i.val < A → m (p 9+i).val = + BundleLists.wordOwner P (oldArcOrder order) (Shrink.packedIndex order) i + key : ∀ e : OldArc V a g, (m (p 10 + Fin.ofNat _ (oldArcOrder order e).val).val).val = + keyAt order (bothThick G order e) e + +/-- The typed key is the bounded mask/slot key on the entire thick fiber. -/ +theorem Classified.thick_key {p : Fin 11 → Word w} {m : Memory w} (h : Classified G order p m) + (b : Shrink.Packed V a g × Fin (2^a)) (z : (P).ThickFiber b) : + (m (p 10 + Fin.ofNat _ (oldArcOrder order z.val.val).val).val).val = ((P).thickFiberIndex b z).val := by + rw [h.key, show bothThick G order z.val.val = true from decide_eq_true z.val.property] + exact BundleKeys.thick_key G order b z + +/-- All motif keys are indexed using the zero-residual-lane representative of the CD arc. -/ +theorem Classified.motif_key {p : Fin 11 → Word w} {m : Memory w} (h : Classified G order p m) + (z : (P).Motif) : + (m (p 10 + Fin.ofNat _ (oldArcOrder order z.val).val).val).val = + ((P).baseMotifIndex order (bitWordFinEquiv (Shrink.J a)) ((P).baseMotif z)).val := by + rw [h.key, show bothThick G order z.val = false from decide_eq_false z.property] + exact BundleKeys.motif_key G order z + +theorem classified_run (p : Fin 11 → Word w) (layout : Bool) (m : Memory w) + (hp : Params p a (Shrink.colors a) (Shrink.J a) g (numBundles n a g)) + (regions : Regions p m A) + (read : ∀ e : OldArc V a g, ∀ i : Word w, i.val = (oldArcOrder order e).val → + ReadsPlacement p m i (siteRow G order layout (sourcePosition e)) + (siteRow G order layout (sourcePosition ((P).actual e)))) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program (1+visit.length) (some (Fin.ofNat _ 0)) m + (List.replicate A []) = some rs ∧ ScanResult p A 0 A m rs ∧ + Classified G order p (after m (eventLog rs)) := by + intro M + obtain ⟨rs,he,h⟩ := scan_run p A 0 A m regions (by omega) + refine ⟨rs,he,h,⟨?_,?_⟩⟩ + · intro i hi + let e := (oldArcOrder order).symm ⟨i.val,hi⟩ + have hv : i.val = (oldArcOrder order e).val := + (congrArg Fin.val ((oldArcOrder order).apply_symm_apply ⟨i.val,hi⟩)).symm + have hc := (classify_oldArc order hp e hv (read e i hv)).1 + rw [bucket_number G order layout e] at hc + change after m (eventLog rs) (outAddr p 0 i) = _ + rw [h.readback 0 i (Nat.zero_le _) (by simpa only [Nat.zero_add] using hi)] + change bucket p m i = _ + exact hc.trans (by simp [BundleLists.wordOwner, encodedPlacement, hi,e]) + · intro e + let i := Fin.ofNat (2^w) (oldArcOrder order e).val + have hv : i.val = (oldArcOrder order e).val := + Nat.mod_eq_of_lt ((oldArcOrder order e).isLt.trans_le regions.fits) + have hi : i.val < 0 + A := by rw [hv, Nat.zero_add]; exact Fin.isLt _ + change (after m (eventLog rs) (outAddr p 1 i)).val = _ + rw [h.readback 1 i (Nat.zero_le _) hi] + change (key p m i).val = _ + rw [(classify_oldArc order hp e hv (read e i hv)).2] + have hb : ((siteRow G order layout (sourcePosition e)).thick && + (siteRow G order layout (sourcePosition ((P).actual e))).thick) = + bothThick G order e := by simp [siteRow, bothThick] + rw [hb] + exact Nat.mod_eq_of_lt ((key_fits G order e).trans_le regions.fits) + +end CompressorRecords.BundleRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleInputs.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleInputs.lean new file mode 100644 index 0000000000..49324752e1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleInputs.lean @@ -0,0 +1,101 @@ +import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout +import OAI.Computability.VPVNP.CompressorRecordsBundleWords +import OAI.Computability.VPVNP.CompressorRecordsShrinkGraph + +/-! +# Reading the classifier inputs from the two preceding directories + +The first probe follows the actual outgoing column of the old state. The +quotient of its value is the site index of the destination in the completed +shrinking scan. The source quotient is the corresponding source site index. +Thus the five placement lookups address the rows of the two typed endpoints. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleRAM + +open BurstRAM Compression +open scoped Fin.CommRing + +variable {w a g : ℕ} + +private theorem input_number (X : State a (packingLaneBits a g)) (e : BundleKeys.OldArc X.Base a g) : + IncidenceDirectory.actualPort (w := w) X (packingInputEdges X.Base a g e) = + ShrinkRAM.word w (BundleKeys.oldArcOrder X.baseIndex e).val := by + rw [BundleKeys.oldArcOrder_val, Shrink.oldNumber_original] + rfl + +/-- Reassembling the typed arc preserves its actual destination and incoming slot. -/ +theorem input_target (X : State a (packingLaneBits a g)) (e : BundleKeys.OldArc X.Base a g) : + packingInputEdges X.Base a g (X.packingData.actual e) = + X.slots.actualGraph.target (packingInputEdges X.Base a g e) := by + let A := packingArcEquiv X.Base a g + obtain ⟨z, rfl⟩ := A.surjective e + have pack (v : (X.Base × Fin (2^a)) × BitWord (packingLaneBits a g)) : + packingInputEdges X.Base a g (A v) = ((v.1.1,v.2),v.1.2) := + (packingInputEdges X.Base a g).apply_symm_apply ((v.1.1,v.2),v.1.2) + rw [orderedDyadicPacking_actual X.slots X.baseIndex z, pack, pack] + rfl + +/-- Dividing a physical port number by the degree recovers its shrinking site index. -/ +theorem site_quotient (X : State a (packingLaneBits a g)) (degree : Word w) + (hd : degree.val = 2^a) (e : BundleKeys.OldArc X.Base a g) (v : Word w) + (hv : v.val = (BundleKeys.oldArcOrder X.baseIndex e).val) : + ShrinkRAM.div v degree = ShrinkRAM.word w (Shrink.oldNumber X.baseIndex (sourcePosition e)) := by + change ShrinkRAM.word w (v.val / degree.val) = _ + rw [hd, hv, BundleKeys.oldArcOrder_val, Nat.mul_comm, Nat.mul_add_div (Nat.two_pow_pos _), + Nat.div_eq_of_lt e.1.2.isLt, Nat.add_zero] + +private theorem word_eq {x : Word w} {v : ℕ} (h : x.val = v) : x = (v : Word w) := by + subst v + exact Fin.ext (Nat.mod_eq_of_lt x.isLt).symm + +/-- The source and destination words read by the classifier are the entries +computed by the typed placement scan, at the two ends of this old arc. -/ +theorem ReadsPlacement.of_directory (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) + {p : Fin 11 → Word w} {shrPub : Fin 14 → Word w} {m : Memory w} {layout : Bool} + (inc : T.ActualColumns X m) + (placement : ShrinkRAM.PlacementColumns X.slots X.baseIndex shrPub layout m) + (hdegree : (p 0).val = 2^a) (hOut : p 5 = T.actualOut) + (hThick : p 6 = shrPub 11) (hOwner : p 7 = shrPub 10) (hAssigned : p 8 = shrPub 12) + (fit : Fintype.card X.Base * 2^(packingLaneBits a g) * 2^a ≤ 2^w) + (e : BundleKeys.OldArc X.Base a g) {i : Word w} (hi : i.val = (BundleKeys.oldArcOrder X.baseIndex e).val) : + ReadsPlacement p m i (BundleKeys.siteRow X.slots X.baseIndex layout (sourcePosition e)) + (BundleKeys.siteRow X.slots X.baseIndex layout (sourcePosition (X.packingData.actual e))) := by + let src := sourcePosition e + let dst := sourcePosition (X.packingData.actual e) + let idx (x : Shrink.Old X.Base a g) := ShrinkRAM.word w (Shrink.oldNumber X.baseIndex x) + have hsrc : sourceSite p i = idx src := site_quotient X _ hdegree e _ hi + have hid : i = IncidenceDirectory.actualPort X (packingInputEdges X.Base a g e) := by + rw [input_number]; exact word_eq hi + have hm : m (p 5+i).val = ShrinkRAM.word w (BundleKeys.oldArcOrder X.baseIndex (X.packingData.actual e)).val := by + rw [hOut, hid, inc.actualOut, ← input_target, input_number] + have hdst : targetSite p m i = idx dst := by + apply site_quotient X _ hdegree (X.packingData.actual e) + rw [hm] + exact Nat.mod_eq_of_lt ((BundleKeys.oldArcOrder X.baseIndex (X.packingData.actual e)).isLt.trans_le fit) + let siteRow := BundleKeys.siteRow X.slots X.baseIndex layout + have row (x : Shrink.Old X.Base a g) : + (m (shrPub 10+idx x).val).val = (siteRow x).owner ∧ + (m (shrPub 11+idx x).val).val = (siteRow x).thick.toNat ∧ + (m (shrPub 12+idx x).val).val = (siteRow x).assigned := by + have h := placement.atSite x + exact ⟨congrArg Prod.fst h, congrArg (Prod.fst ∘ Prod.snd) h, + congrArg (Prod.fst ∘ Prod.snd ∘ Prod.snd) h⟩ + constructor + all_goals + simp only [readValue, readAddress, Matrix.cons_val, hsrc, hdst, hThick, hOwner, hAssigned] + · exact word_eq (row src).2.1 + · exact word_eq (row dst).2.1 + · exact word_eq (row src).1 + · exact word_eq (row src).2.2 + · exact word_eq (row dst).2.2 + +end CompressorRecords.BundleRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleKeys.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleKeys.lean new file mode 100644 index 0000000000..1115b82d7b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleKeys.lean @@ -0,0 +1,127 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrink +import OAI.Computability.VPVNP.SlotBundleNumbering + +/-! +# Bundle addresses and relative sorting keys from physical source ports + +The classifying scan reads both thickness flags and the bundle assignment at each +endpoint. Its table separates thick wires from CD wires while retaining every +old port as its absolute identifier. Sorting keys remove the residual lane and +retain the original port, mask, and slot-label fields. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleKeys + +open Compression VPVNP.CompressorRecords.Shrink + +/-- The two bundle arrays are adjacent. A CD wire belongs to its thin endpoint, +with the source used when both endpoints are thin. -/ +def numericBucket (numBundles degree srcOwner srcAssigned dstAssigned slot : ℕ) + (srcThick dstThick : Bool) : ℕ := + if srcThick && dstThick then srcOwner*degree+slot + else numBundles + (if srcThick then dstAssigned else srcAssigned) + +/-- The thick-wire key uses the two suppressed source fields. The motif key +includes the normalized source base, tag and physical outgoing slot. -/ +def numericKey (degree tagCount colorCount base tag slot mask label : ℕ) (both : Bool) : ℕ := + let thick := mask*degree+label + if both then thick else (((base*tagCount+tag)*degree+slot)*colorCount+mask)*degree+label + +variable {V : Type} {n a g : ℕ} +variable (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) (order : V ≃ Fin n) +local notation "P" => orderedDyadicPacking G order + +/-- An arc in the pre-shrink graph, carrying the source port, lane information, and mask used +to classify it into a packed bundle. -/ +abbrev OldArc (V : Type) (a g : ℕ) := Arc V (BitWord a) (BitWord (J a)) (BitWord g) + (2^a) (colors a) + +/-- Scan each physical outgoing slot, keeping the separate parallel-port numbers. -/ +def oldArcOrder : OldArc V a g ≃ Fin ((n*2^(packingLaneBits a g))*2^a) := + let endpoints : OldArc V a g ≃ Old V a g × Fin (2^a) := + ⟨fun e ↦ (sourcePosition e,e.1.2), fun p ↦ ((p.1.1,p.2),p.1.2),fun _ ↦ rfl,fun _ ↦ rfl⟩ + endpoints.trans (((oldIndex order).prodCongr (Equiv.refl _)).trans finProdFinEquiv) + +theorem oldArcOrder_val (e : OldArc V a g) : + (oldArcOrder order e).val = oldNumber order (sourcePosition e)*2^a+e.1.2.val := by + change e.1.2.val + 2^a*(oldIndex order (sourcePosition e)).val = _ + rw [oldIndex_val]; ac_rfl + +/-- Numeric owner of either kind of bundle in the combined count and row arrays. -/ +def bundleAddress (b : Packed V a g × Fin (2^a)) : ℕ := packedNumber order b.1 * 2^a+b.2.val + +/-- Number of packed port bundles in one of the two classification arrays, also the offset +where the CD bundle array begins. -/ +def numBundles (n a g : ℕ) := (n*(2^(J a)*2^g))*2^a + +/-- Compute an old arc's within-bundle sort key from the decoded source number and outgoing +slot, using the thick-wire or CD ordering as selected. -/ +def keyAt (both : Bool) (e : OldArc V a g) : ℕ := + let f := Shrink.decode a (colors a) (J a+g) (oldNumber order (sourcePosition e)) + numericKey (2^a) (2^(J a)) (2^(colors a)) f.base (f.low/2^g) e.1.2.val f.mask f.slot both + +private theorem tag_value (z : BitWord (J a) × BitWord g) : + lowNumber z / 2^g = (bitWordFinEquiv (J a) z.1).val := by + unfold lowNumber join + rw [Nat.mul_comm, Nat.mul_add_div (Nat.two_pow_pos _), Nat.div_eq_of_lt (bitWordFinEquiv g z.2).isLt, + Nat.add_zero] + +/-- The value emitted in a thick bundle equals its sort key at its actual lane. -/ +theorem thick_key (b : Packed V a g × Fin (2^a)) (wire : (P).ThickFiber b) : + keyAt order true wire.val.val = ((P).thickFiberIndex b wire).val := by + rw [keyAt, decode_oldNumber, numericKey] + change _ * 2^a + _ = _ + 2^a * _ + ac_rfl + +/-- The CD sorting key is the key of the normalized original arc in Appendix C. -/ +theorem motif_key (m : (P).Motif) : + keyAt order false m.val = ((P).baseMotifIndex order (bitWordFinEquiv (J a)) ((P).baseMotif m)).val := by + rw [keyAt, decode_oldNumber, numericKey] + dsimp only + rw [tag_value] + change (((_ * 2^(J a) + _) * 2^a + _) * 2^(colors a) + _) * 2^a + _ = + (_ + 2^a * _) + 2^(colors a)*2^a * _ + 2^a*(2^(colors a)*2^a) * _ + + 2^(J a)*(2^a*(2^(colors a)*2^a)) * _ + have arithmetic (x t s mask h d T C : ℕ) : + (((x*T+t)*d+s)*C+mask)*d+h = (h+d*mask)+C*d*s+d*(C*d)*t+T*(d*(C*d))*x := by ring + exact arithmetic .. + +/-- Four stored placement columns and the source and target vertices of the assigned +bundle, expressed solely in terms of the constructed packing. -/ +def siteRow (layout : Bool) (x : Old V a g) : Shrink.Row ℕ := + let e := (P).assignedBundle x + ⟨packedNumber order x.1, packedNumber order e.1, packedNumber order ((P).siteGraph.target e).1, + join a (packedNumber order e.1) e.2.val, decide ((P).thick x), + packedNumber order ((P).placement layout x)⟩ + +/-- Look up the independently stored source and destination placement records. -/ +def bucketFromRows (num degree port : ℕ) (src dst : Shrink.Row ℕ) : ℕ := + numericBucket num degree src.owner src.assigned dst.assigned port src.thick dst.thick + +theorem thick_bucket (layout : Bool) (wire : (P).ThickWire) : + bucketFromRows (numBundles n a g) (2^a) wire.val.1.2.val + (siteRow G order layout (sourcePosition wire.val)) + (siteRow G order layout (sourcePosition ((P).actual wire.val))) = + bundleAddress order wire.val.1 := by + have ⟨hs,ht⟩ := wire.property + simp [bucketFromRows, siteRow, numericBucket, hs, ht, PackingData.placement, bundleAddress] + rfl + +theorem motif_bucket (layout : Bool) (m : (P).Motif) : + bucketFromRows (numBundles n a g) (2^a) m.val.1.2.val + (siteRow G order layout (sourcePosition m.val)) (siteRow G order layout (sourcePosition ((P).actual m.val))) = + numBundles n a g + bundleAddress order ((P).bundle m) := by + by_cases hs : (P).thick (sourcePosition m.val) + · have ht : ¬(P).thick (sourcePosition ((P).actual m.val)) := fun h ↦ m.property ⟨hs,h⟩ + simp [bucketFromRows, numericBucket, siteRow, hs, ht, bundleAddress, join, PackingData.bundle, PackingData.C] + · simp [bucketFromRows, numericBucket, siteRow, hs, bundleAddress, join, PackingData.bundle, PackingData.C] + +end CompressorRecords.BundleKeys + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleLists.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleLists.lean new file mode 100644 index 0000000000..b9cfb00bb5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleLists.lean @@ -0,0 +1,267 @@ +import OAI.Computability.VPVNP.CompressorRecordPlacement +import OAI.Computability.VPVNP.SlotDemandKernel +import Mathlib.Data.List.NodupEquivFin + +/-! +# Scanning original wires into the two lists of each packed bundle + +In the first scan of Appendix E, an arc thick at both ends belongs to the +payload of its source bundle. Every other arc is a CD motif assigned to the +bundle of its thin C endpoint. The classified arc directory supplies one row +identifier per original arc. The native bounded-append pass then visits each +original arc once, recording its identifier in exactly one row. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleLists + +open Compression Compression.PackingData BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- The filtered physical identifiers are exactly those earlier than the cursor +which map to the row's owner. -/ +theorem mem_preimagePrefix_iff (place : Word w → Word w) (owner i : Word w) + (k : ℕ) (hk : k ≤ 2 ^ w) : + i ∈ preimagePrefix place owner k ↔ i.val < k ∧ place i = owner := by + simp only [preimagePrefix, List.mem_filter, List.mem_map, List.mem_range, beq_iff_eq] + apply and_congr_left + intro _ + constructor + · rintro ⟨j, hj, rfl⟩ + simpa only [Fin.val_ofNat, Nat.mod_eq_of_lt (hj.trans_le hk)] using hj + · intro hi + exact ⟨i.val, hi, Fin.ext (Nat.mod_eq_of_lt i.isLt)⟩ + +/-- In a representable range, filtering the consecutive word identifiers keeps +their strict numeric order. -/ +theorem preimagePrefix_pairwise (place : Word w → Word w) (owner : Word w) + (k : ℕ) (hk : k ≤ 2 ^ w) : + (preimagePrefix place owner k).Pairwise (· < ·) := by + apply List.Pairwise.filter + apply List.pairwise_map.mpr + refine List.pairwise_lt_range.imp_of_mem ?_ + intro a b ha hb hab + change a % (2 ^ w) < b % (2 ^ w) + simpa only [Nat.mod_eq_of_lt ((List.mem_range.mp ha).trans_le hk), + Nat.mod_eq_of_lt ((List.mem_range.mp hb).trans_le hk)] using hab + +/-- Looking up the number of preceding identifiers in an owner's row recovers +the identifier at that rank. -/ +theorem preimagePrefix_get_at_rank (place : Word w → Word w) (owner i : Word w) + (k : ℕ) (hi : i.val < k) (hp : place i = owner) : + ∃ h : (preimagePrefix place owner i.val).length < (preimagePrefix place owner k).length, + (preimagePrefix place owner k)[(preimagePrefix place owner i.val).length]'h = i := by + have cast : Fin.ofNat (2 ^ w) i.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt) + have step : preimagePrefix place owner (i.val + 1) = preimagePrefix place owner i.val ++ [i] := by + simp only [preimagePrefix, List.range_succ, List.map_append, List.map_singleton, List.filter_append, + cast, List.filter_cons, List.filter_nil, beq_iff_eq, hp, ite_true] + obtain ⟨n, hn⟩ := Nat.exists_eq_add_of_le hi + have pref : preimagePrefix place owner (i.val + 1) <+: preimagePrefix place owner k := by + conv_rhs => arg 3; rw [hn] + conv_rhs => rw [preimagePrefix, List.range_add, List.map_append, List.filter_append] + exact List.prefix_append _ _ + rw [step] at pref + have hidx : (preimagePrefix place owner i.val).length < + (preimagePrefix place owner i.val ++ [i]).length := by simp + refine ⟨hidx.trans_le pref.length_le, ?_⟩ + rw [← pref.getElem hidx, List.getElem_append_right (le_refl _)] + simp + +variable {V H Tag L : Type} {d c A n : ℕ} +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) + +/-- A packed site and one of its outgoing slots, identifying the bundle at that port. -/ +abbrev Port (V Tag L : Type*) (d : ℕ) := Site V Tag L × Fin d +/-- The choice of a thick-wire payload row or a CD motif row at a packed port. -/ +abbrev Bucket (V Tag L : Type*) (d : ℕ) := Port V Tag L d ⊕ Port V Tag L d + +/-- The left summand receives thick wires, the right summand receives motifs. -/ +def bucketOf (a : Arc V H Tag L d c) : Bucket V Tag L d := + if h : P.thick (sourcePosition a) ∧ P.thick (sourcePosition (P.actual a)) + then .inl a.1 else .inr (P.bundle ⟨a,h⟩) + +@[simp] theorem bucketOf_thick (a : P.ThickWire) : bucketOf P a.val = .inl a.val.1 := by + simp [bucketOf, a.prop] + +@[simp] theorem bucketOf_motif (m : P.Motif) : bucketOf P m.val = .inr (P.bundle m) := by + simp [bucketOf, m.prop] + +/-- The left row over a port consists of exactly its original thick wires. -/ +def thickEquiv (b : Port V Tag L d) : {a // bucketOf P a = .inl b} ≃ P.ThickFiber b where + toFun x := by + have h : P.thick (sourcePosition x.val) ∧ P.thick (sourcePosition (P.actual x.val)) := by + by_contra hn + simpa [bucketOf, hn] using x.prop + exact ⟨⟨x.val,h⟩, by simpa [bucketOf,h] using x.prop⟩ + invFun x := ⟨x.val.val, (bucketOf_thick P x.val).trans (congrArg Sum.inl x.prop)⟩ + left_inv _ := Subtype.ext rfl + right_inv _ := Subtype.ext (Subtype.ext rfl) + +/-- The right row over a port consists of exactly its assigned CD motifs. -/ +def motifEquiv (b : Port V Tag L d) : {a // bucketOf P a = .inr b} ≃ P.MotifFiber b where + toFun x := by + have h : ¬ (P.thick (sourcePosition x.val) ∧ P.thick (sourcePosition (P.actual x.val))) := by + intro ht + simpa [bucketOf, ht] using x.prop + exact ⟨⟨x.val,h⟩, by simpa [bucketOf,h] using x.prop⟩ + invFun x := ⟨x.val.val, (bucketOf_motif P x.val).trans (congrArg Sum.inr x.prop)⟩ + left_inv _ := Subtype.ext rfl + right_inv _ := Subtype.ext (Subtype.ext rfl) + +/-- Contiguous bundle indices, with slot number varying fastest. -/ +def portIndex (site : Site V Tag L ≃ Fin n) : Port V Tag L d ≃ Fin (n*d) := + (site.prodCongr (Equiv.refl (Fin d))).trans finProdFinEquiv + +/-- Number the thick-wire rows first and the CD motif rows second, using the same site-and-slot +order in each half. -/ +def bucketIndex (site : Site V Tag L ≃ Fin n) : Bucket V Tag L d ≃ Fin (n*d+n*d) := + ((portIndex site).sumCongr (portIndex site)).trans finSumFinEquiv + +omit [AddCommGroup Tag] [AddCommGroup L] in +theorem bucketIndex_thick_val (site : Site V Tag L ≃ Fin n) (b : Port V Tag L d) : + (bucketIndex site (.inl b)).val = (site b.1).val * d + b.2.val := by + change b.2.val + d * (site b.1).val = _ + ac_rfl + +omit [AddCommGroup Tag] [AddCommGroup L] in +theorem bucketIndex_motif_val (site : Site V Tag L ≃ Fin n) (b : Port V Tag L d) : + (bucketIndex site (.inr b)).val = n*d + ((site b.1).val * d + b.2.val) := by + change n*d + (b.2.val + d * (site b.1).val) = _ + ac_rfl + +variable (arcs : Arc V H Tag L d c ≃ Fin A) (site : Site V Tag L ≃ Fin n) + +/-- Map a physical old arc identifier to the encoded row that collects it during bounded +append. -/ +def wordOwner : Word w → Word w := encodedPlacement arcs (bucketIndex site) (bucketOf P) + +/-- The ordered list of original arc identifiers for a classified row. -/ +def arcList (b : Bucket V Tag L d) : List (Word w) := + preimagePrefix (wordOwner P arcs site) (Fin.ofNat _ (bucketIndex site b).val) A + +theorem wordOwner_at (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) (a : Arc V H Tag L d c) : + wordOwner P arcs site (Fin.ofNat (2^w) (arcs a).val) = + Fin.ofNat _ (bucketIndex site (bucketOf P a)).val := by + apply Fin.ext + rw [wordOwner, encodedPlacement_eq arcs (bucketIndex site) (bucketOf P) hA hn, + Equiv.symm_apply_apply, Fin.val_ofNat, Nat.mod_eq_of_lt ((bucketIndex site _).isLt.trans_le hn)] + +/-- Physical row membership of an original wire in either summand. -/ +theorem mem_arcList_iff (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) (a : Arc V H Tag L d c) + (b : Bucket V Tag L d) : + Fin.ofNat (2^w) (arcs a).val ∈ arcList P arcs site b ↔ bucketOf P a = b := by + rw [arcList, mem_preimagePrefix_iff _ _ _ _ hA, wordOwner_at P arcs site hA hn a] + simp only [Fin.val_ofNat, Nat.mod_eq_of_lt ((arcs a).isLt.trans_le hA), (arcs a).isLt, + true_and, Fin.ext_iff, Nat.mod_eq_of_lt ((bucketIndex site _).isLt.trans_le hn)] + exact Fin.val_injective.eq_iff.trans (bucketIndex site).injective.eq_iff + +theorem arcList_nodup (hA : A ≤ 2^w) (b : Bucket V Tag L d) : + (arcList (w := w) P arcs site b).Nodup := + (preimagePrefix_pairwise _ _ _ hA).imp fun h ↦ h.ne + +/-- Decode a stored arc ID to the corresponding member of the typed fiber. -/ +def memberEquiv (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) (b : Bucket V Tag L d) : + {i // i ∈ arcList (w := w) P arcs site b} ≃ {a // bucketOf P a = b} where + toFun i := by + have hi := ((mem_preimagePrefix_iff _ _ _ _ hA).mp i.prop).1 + let a := arcs.symm ⟨i.val.val,hi⟩ + have eqn : Fin.ofNat (2^w) (arcs a).val = i.val := by + rw [show arcs a = _ from arcs.apply_symm_apply _]; exact Fin.ext (Nat.mod_eq_of_lt i.val.isLt) + exact ⟨a,(mem_arcList_iff P arcs site hA hn a b).mp (eqn ▸ i.prop)⟩ + invFun a := ⟨Fin.ofNat _ (arcs a.val).val,(mem_arcList_iff P arcs site hA hn _ b).mpr a.prop⟩ + left_inv i := by apply Subtype.ext; simp + right_inv a := by + apply Subtype.ext + apply arcs.injective + simpa only [Equiv.apply_symm_apply, Fin.ext_iff, Fin.val_ofNat] using Nat.mod_eq_of_lt ((arcs a.val).isLt.trans_le hA) + +/-- Scan-order numbering of the complete fiber. Reading a cell at this +ordinal and decoding its original arc identifier implements this equivalence. -/ +def ordinalEquiv (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) (b : Bucket V Tag L d) : + Fin (arcList (w := w) P arcs site b).length ≃ {a // bucketOf P a = b} := + (List.Nodup.getEquiv _ (arcList_nodup P arcs site hA b)).trans (memberEquiv P arcs site hA hn b) + +theorem ordinalEquiv_id (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) (b : Bucket V Tag L d) + (i : Fin (arcList (w := w) P arcs site b).length) : + (arcList P arcs site b).get i = Fin.ofNat (2^w) (arcs (ordinalEquiv P arcs site hA hn b i).val).val := + (congrArg Subtype.val ((memberEquiv P arcs site hA hn b).symm_apply_apply + ((List.Nodup.getEquiv _ (arcList_nodup P arcs site hA b)) i))).symm + +/-- The number of thick wires or motif pieces expected in a classified bundle row. -/ +def rowLength : Bucket V Tag L d → ℕ := + Sum.elim (fun _ ↦ 2^c*d/4) (fun _ ↦ pieceCount d c) + +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] + +theorem fiber_card (hc : 2 ≤ c) (b : Bucket V Tag L d) : + Fintype.card {a // bucketOf P a = b} = rowLength (c := c) b := by + cases b with + | inl b => exact (Fintype.card_congr (thickEquiv P b)).trans (P.card_thick_fiber hc b) + | inr b => exact (Fintype.card_congr (motifEquiv P b)).trans (P.card_motifs_bundle hc b) + +theorem arcList_length (hc : 2 ≤ c) (hA : A ≤ 2^w) (hn : n*d+n*d ≤ 2^w) + (b : Bucket V Tag L d) : + (arcList (w := w) P arcs site b).length = rowLength (c := c) b := + (encodedPlacement_rowLength arcs (bucketIndex site) (bucketOf P) hA hn b).trans + (fiber_card P hc b) + +/-- Once the classification and zero counts occupy their physical arrays, +the native preimage pass fills every bundle's two lists. There is one call +and four external probes per original arc. -/ +theorem fill_run (hc : 2 ≤ c) (p : Fin 6 → Word w) (reg : RowRegions p) + (hA : (p 0).val = A) (hn : (p 2).val = n*d+n*d) (hcap : pieceCount d c ≤ (p 4).val) + (mem : Memory w) (owners : ∀ i : Word w, i < p 0 → ownerAt p mem i = wordOwner P arcs site i) + (zero : ∀ u : Word w, u < p 2 → mem (countAt p u).val = 0) : + let M := (template collectPreimage 3).instantiate w p + ∃ rs, runSegment M.program 23 (some 0) mem (List.replicate A []) = some rs ∧ + PreimagesAt p (wordOwner P arcs site) (after mem (eventLog rs)) A ∧ + (∀ b : Bucket V Tag L d, let u := Fin.ofNat (2^w) (bucketIndex site b).val + rowRepresents (after mem (eventLog rs)) (countAt p u) (rowAt p u) (arcList P arcs site b)) ∧ + rs.length = A ∧ RAMBuckets.cost Report.probes rs = 5*A ∧ + ∀ r ∈ rs, r.events.length = 22 := by + intro M + have ha : A ≤ 2^w := hA ▸ (p 0).isLt.le + have hb : n*d+n*d ≤ 2^w := hn ▸ (p 2).isLt.le + have legal (i : Word w) (hi : i < p 0) : wordOwner P arcs site i < p 2 := by + let j : Fin A := ⟨i.val, hA ▸ hi⟩ + have e : Fin.ofNat (2^w) j.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt) + change (encodedPlacement _ _ _ i).val < (p 2).val + rw [← e, encodedPlacement_eq arcs (bucketIndex site) (bucketOf P) ha hb j, hn] + exact (bucketIndex site _).isLt + have capacity (u : Word w) (hu : u < p 2) : + (preimagePrefix (wordOwner P arcs site) u (p 0).val).length ≤ (p 4).val := by + let j : Fin (n*d+n*d) := ⟨u.val, hn ▸ hu⟩ + obtain ⟨b, he⟩ := (bucketIndex site (d := d)).surjective j + have eu : Fin.ofNat (2^w) (bucketIndex site b).val = u := by + rw [he]; exact Fin.ext (Nat.mod_eq_of_lt u.isLt) + rw [← eu, hA] + change (arcList P arcs site b).length ≤ _ + rw [arcList_length P arcs site hc ha hb] + cases b with + | inl b => + apply le_trans _ hcap + exact Nat.div_le_div_right (by omega : 2^c*d ≤ 3*(2^c*d)) + | inr b => exact hcap + have start : PreimagesAt p (wordOwner P arcs site) mem 0 := by + refine ⟨owners, fun u hu ↦ ?_⟩ + simp [preimagePrefix, rowRepresents, zero u hu] + obtain ⟨rs,hr,hlists,hlen,hwork⟩ := collectPreimages_run reg legal capacity start A (by simp [hA]) + have full : PreimagesAt p (wordOwner P arcs site) (after mem (eventLog rs)) A := by + simpa only [Nat.zero_add] using hlists + refine ⟨rs,hr,full,fun b ↦ full.rows _ ?_,hlen,?_,fun r hr' ↦ (hwork r hr').1⟩ + · change (bucketIndex site b).val % (2^w) < (p 2).val + have h := (bucketIndex site b).isLt + rw [Nat.mod_eq_of_lt (h.trans_le hb), hn]; exact h + · exact (preimagePass_cost (fun r hr' ↦ (hwork r hr').2)).trans (by rw [hlen]) + +end CompressorRecords.BundleLists + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundlePass.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundlePass.lean new file mode 100644 index 0000000000..be38ba35dc --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundlePass.lean @@ -0,0 +1,108 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleGraph +import OAI.Computability.VPVNP.CompressorRecordsBundleInputs +import OAI.Computability.VPVNP.CompressorSlotFrames + +/-! +# Native classification and list construction in a shrinking pass + +The classification worker follows the old graph's outgoing incidence and reads +both endpoints' placement rows. Its owner output supplies the physical input of +the bounded-append worker. The two passes together charge fourteen calls plus +probes per old outgoing port. Widths remain indexed by these same absolute IDs. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleRAM + +open BurstRAM PrimedStackRAM Compression BundleKeys + +variable {w a g : ℕ} +variable (X : State a (packingLaneBits a g)) +local notation "N" => Fintype.card X.Base +local notation "A" => N * 2^(packingLaneBits a g) * 2^a + +/-- Complete classification from the two constructed directories, with the precise +source width still addressable by old absolute ID wherever the width column is +reserved outside the two new columns. -/ +theorem classify_directory (T : IncidenceDirectory w) (p : Fin 11 → Word w) + (shrPub : Fin 14 → Word w) (layout : Bool) (m : Memory w) + (inc : T.ActualColumns X m) (placement : ShrinkRAM.PlacementColumns X.slots X.baseIndex shrPub layout m) + (hp : Params p a (Shrink.colors a) (Shrink.J a) g (numBundles N a g)) (reg : Regions p m A) + (hOut : p 5 = T.actualOut) (hThick : p 6 = shrPub 11) (hOwner : p 7 = shrPub 10) + (hAssigned : p 8 = shrPub 12) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program (1+visit.length) (some (Fin.ofNat _ 0)) m (List.replicate A []) = some rs ∧ + ScanResult p A 0 A m rs ∧ Classified X.slots X.baseIndex p (after m (eventLog rs)) := + classified_run X.slots X.baseIndex p layout m hp reg fun e _ hi ↦ + ReadsPlacement.of_directory X T inc placement hp.degree hOut hThick hOwner hAssigned reg.fits e hi + +theorem ScanResult.width_at {p : Fin 11 → Word w} {m : Memory w} {rs : List (Report w)} + (h : ScanResult p A 0 A m rs) (T : IncidenceDirectory w) (inc : T.ActualColumns X m) + (apart : ∀ e : OldArc X.Base a g, ∀ t : Fin 2, ∀ i : Word w, i.val < A → + (T.width + Fin.ofNat _ (oldArcOrder X.baseIndex e).val).val ≠ outAddr p t i) + (e : OldArc X.Base a g) : + after m (eventLog rs) (T.width + Fin.ofNat _ (oldArcOrder X.baseIndex e).val).val = + Fin.ofNat _ (X.packingWidth e) := by + rw [h.preserve _ (fun t i _ hi ↦ apart e t i (by simpa only [Nat.zero_add] using hi))] + have he : Fin.ofNat (2^w) (oldArcOrder X.baseIndex e).val = + IncidenceDirectory.actualPort X (packingInputEdges X.Base a g e) := by + rw [oldArcOrder_val, Shrink.oldNumber_original] + rfl + rw [he]; exact inc.width (packingInputEdges X.Base a g e) + +/-- The classifier's bucket column supplies every owner word needed to append all +old arc IDs. The combined cost uses the same old-port count for both passes. -/ +theorem classify_and_collect (T : IncidenceDirectory w) (p : Fin 11 → Word w) + (shrPub : Fin 14 → Word w) (layout : Bool) (m : Memory w) + (inc : T.ActualColumns X m) (placement : ShrinkRAM.PlacementColumns X.slots X.baseIndex shrPub layout m) + (hp : Params p a (Shrink.colors a) (Shrink.J a) g (numBundles N a g)) (reg : Regions p m A) + (hOut : p 5 = T.actualOut) (hThick : p 6 = shrPub 11) (hOwner : p 7 = shrPub 10) + (hAssigned : p 8 = shrPub 12) (q : Fin 6 → Word w) (qreg : RowRegions q) + (hinput : q 1 = p 9) (hA : (q 0).val = A) + (hcount : (q 2).val = numBundles N a g + numBundles N a g) + (hcap : PackingData.pieceCount (2^a) (Shrink.colors a) ≤ (q 4).val) + (zero : ∀ u : Word w, u < q 2 → m (countAt q u).val = 0) + (apart : ∀ u : Word w, u < q 2 → ∀ t : Fin 2, ∀ i : Word w, i.val < A → + (countAt q u).val ≠ outAddr p t i) : + let M := (template visit 0).instantiate w p + let L := (template collectPreimage 3).instantiate w q + let arcs := oldArcOrder (a := a) (g := g) X.baseIndex + let sites := Shrink.packedIndex (a := a) (g := g) X.baseIndex + ∃ rs ls, runSegment M.program (1+visit.length) (some (Fin.ofNat _ 0)) m (List.replicate A []) = some rs ∧ + runSegment L.program 23 (some 0) (after m (eventLog rs)) (List.replicate A []) = some ls ∧ + ScanResult p A 0 A m rs ∧ Classified X.slots X.baseIndex p (after m (eventLog rs)) ∧ + PreimagesAt q (BundleLists.wordOwner X.packingData arcs sites) + (after (after m (eventLog rs)) (eventLog ls)) A ∧ + (∀ addr, OutsidePreimageWrites q addr → + after (after m (eventLog rs)) (eventLog ls) addr = after m (eventLog rs) addr) ∧ + (∀ b : BundleLists.Bucket X.Base (BitWord (Shrink.J a)) (BitWord g) (2^a), + let u := Fin.ofNat (2^w) (BundleLists.bucketIndex sites b).val + rowRepresents (after (after m (eventLog rs)) (eventLog ls)) (countAt q u) (rowAt q u) + (BundleLists.arcList X.packingData arcs sites b)) ∧ + RAMBuckets.cost Report.probes rs + RAMBuckets.cost Report.probes ls = 14*A := by + classical + intro M L arcs sites + obtain ⟨rs,he,hr,hc⟩ := classify_directory X T p shrPub layout m inc placement hp reg hOut hThick hOwner hAssigned + let afterClass := after m (eventLog rs) + have owners (i : Word w) (hi : i < q 0) : + ownerAt q afterClass i = BundleLists.wordOwner X.packingData arcs sites i := by + unfold ownerAt; rw [hinput] + exact hc.owner i (hA ▸ hi) + have zeros (u : Word w) (hu : u < q 2) : afterClass (countAt q u).val = 0 := + (hr.preserve _ (fun t i _ hi ↦ apart u hu t i (by simpa only [Nat.zero_add] using hi))).trans (zero u hu) + have hcolors : 2 ≤ Shrink.colors a := by unfold Shrink.colors; have := Nat.two_pow_pos a; omega + obtain ⟨ls,hl,hpre,hrows,_,hcost,_⟩ := BundleLists.fill_run X.packingData arcs sites hcolors + q qreg hA hcount hcap afterClass owners zeros + refine ⟨rs,ls,he,hl,hr,hc,hpre,(collectPreimages_cursor_frame (k := 0) qreg hl).2,hrows,?_⟩ + change RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs + _ = _ + rw [hr.cost, hcost] + omega + +end CompressorRecords.BundleRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundlePrefixGraph.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundlePrefixGraph.lean new file mode 100644 index 0000000000..fd329638ad --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundlePrefixGraph.lean @@ -0,0 +1,281 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundlePrefixRAM +import OAI.Computability.VPVNP.CompressorBundleSortedWidths +import OAI.Computability.VPVNP.SlotDemandSlices + +/-! +# Field starts and totals in the two sorted rows of a packed bundle + +Each prefix scan reads a fixed-size live row within a rectangle. The thick row +uses the old concatenation order, and the motif row uses the CD piece numbers. +Their two full scans run consecutively on the external width arrays produced by +scattering the original ports. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundlePrefixGraph + +open BurstRAM Compression Compression.PackingData BundleLists BundlePrefixRAM + +variable {w : ℕ} + +/-- Width, offset and total readbacks for a physical set of rows indexed by +a finite site type, each row indexed by a possibly different fiber type. -/ +def Widths {B k : ℕ} {S : Type*} {F : S → Type*} (index : S ≃ Fin B) + (number : ∀ b, F b ≃ Fin k) (width : ∀ b, F b → ℕ) (p : Fin 5 → Word w) (m : Memory w) := + ∀ b (i : Fin k), (m ((p 2).val+(index b).val*(p 1).val+i.val)).val = width b ((number b).symm i) + +/-- Every live item in each bundle row stores the sum of widths of the items preceding it in +the given ordering. -/ +def Starts {B k : ℕ} {S : Type*} {F : S → Type*} (index : S ≃ Fin B) + (number : ∀ b, F b ≃ Fin k) (width : ∀ b, F b → ℕ) (p : Fin 5 → Word w) (m : Memory w) := + ∀ b (x : F b), (m ((p 3).val+(index b).val*(p 1).val+(number b x).val)).val = + fieldStart (number b) (width b) x + +private theorem prefix_total {B k : ℕ} {S : Type*} {F : S → Type*} [∀ b, Fintype (F b)] + (index : S ≃ Fin B) (number : ∀ b, F b ≃ Fin k) (width : ∀ b, F b → ℕ) + (p : Fin 5 → Word w) (m : Memory w) (read : Widths index number width p m) (b : S) : + prefixSum p m (index b).val k = ∑ x, width b x := by + rw [prefixSum, ← Fin.sum_univ_eq_sum_range, ← (number b).symm.sum_comp (width b)] + exact Finset.sum_congr rfl (fun j _ ↦ read b j) + +private theorem prefix_start {B k : ℕ} {S : Type*} {F : S → Type*} (index : S ≃ Fin B) + (number : ∀ b, F b ≃ Fin k) (width : ∀ b, F b → ℕ) (p : Fin 5 → Word w) (m : Memory w) + (read : Widths index number width p m) (b : S) (x : F b) : + prefixSum p m (index b).val (number b x).val = fieldStart (number b) (width b) x := by + rw [prefixSum, ← Fin.sum_univ_eq_sum_range, fieldStart] + exact Finset.sum_congr rfl (fun j _ ↦ read b (j.castLE (number b x).isLt.le)) + +/-- Execute the full row scan with a bound on the mathematical sum, recovering +every source-field start and total at its physical address. -/ +theorem numbered_run {B k : ℕ} {S : Type*} {F : S → Type*} [∀ b, Fintype (F b)] (index : S ≃ Fin B) + (number : ∀ b, F b ≃ Fin k) (width : ∀ b, F b → ℕ) (p : Fin 5 → Word w) (m : Memory w) + (layout : BundlePrefixRAM.Layout p B) (hk : (p 0).val = k) (read : Widths index number width p m) + (fit : ∀ b, (∑ x, width b x) < 2^w) : + ∃ rs, FullRun p B m rs ∧ Starts index number width p (after m (eventLog rs)) ∧ + ∀ b, (after m (eventLog rs) ((p 4).val+(index b).val)).val = ∑ x, width b x := by + have fits (b : ℕ) (hb : b < B) : prefixSum p m b (p 0).val < 2^w := by + let s := index.symm ⟨b,hb⟩ + have he : (index s).val = b := congrArg Fin.val (index.apply_symm_apply _) + rw [hk, ← he, prefix_total index number width p m read s] + exact fit s + obtain ⟨rs,run⟩ := full_run p B m layout fits + refine ⟨rs,run,fun b x ↦ ?_,fun b ↦ ?_⟩ + · exact (run.starts _ (index b).isLt _ (hk ▸ (number b x).isLt)).trans + (prefix_start index number width p m read b x) + · exact (run.totals _ (index b).isLt).trans (hk ▸ prefix_total index number width p m read b) + +/-- Static separation of a region from the two tables a prefix scan writes. -/ +structure Outside (p : Fin 5 → Word w) (B base size : ℕ) : Prop where + starts : BundleGather.separated base size (p 3).val (B*(p 1).val) + totals : BundleGather.separated base size (p 4).val B + +private theorem slot_lt {B k stride b j : ℕ} (hb : b < B) (hj : j < k) (hk : k ≤ stride) : + b * stride + j < B * stride := by + have h := Nat.mul_le_mul_right stride (Nat.succ_le_of_lt hb) + rw [Nat.succ_mul] at h + omega + +theorem Outside.preserve {p : Fin 5 → Word w} {B base size : ℕ} {m : Memory w} {rs} + (h : Outside p B base size) (layout : BundlePrefixRAM.Layout p B) (run : FullRun p B m rs) + (j : ℕ) (hj : j < size) : after m (eventLog rs) (base+j) = m (base+j) := by + apply run.frame + · intro b hb l hl + have := slot_lt hb hl layout.size_le_stride + have := h.starts.outside hj + omega + · intro b hb + have := h.totals.outside hj + omega + +variable {V H Tag L : Type} {d c n A : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) (site : Site V Tag L ≃ Fin n) +variable (old : Arc V H Tag L d c → ℕ) + +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] [DecidableEq V] [DecidableEq Tag] [DecidableEq L] + +/-- The AB width producer reads one old thick-wire total per absolute bundle. -/ +def ThickTotals (totalBase : Word w) (post : Memory w) : Prop := + ∀ b, (post (totalBase.val+(portIndex site b).val)).val = P.bundleWidth old b + +/-- Sum of the original CD widths assigned to a bundle. -/ +def motifTotal (b : Port V Tag L d) : ℕ := ∑ x : P.MotifFiber b, old x.1.1 + +variable (dd : P.ThickNumbering) (cd : P.BundleNumbering) + +/-- The original arc width carried by a thick wire in the selected bundle. -/ +abbrev thickWidth (b : Port V Tag L d) (x : P.ThickFiber b) := old x.1.1 +/-- The original arc width carried by a CD motif assigned to the selected bundle. -/ +abbrev motifWidth (b : Port V Tag L d) (x : P.MotifFiber b) := old x.1.1 + +/-- Prefix parameters use the two halves of the sorted-width rectangle in +the same port order. Each scan may place its output tables independently. -/ +structure RowLayout (s t u : Fin 5 → Word w) (A n d c : ℕ) : Prop where + scatter : BundleWidthScatter.Layout s A n d c + thick : BundlePrefixRAM.Layout t (n*d) + motif : BundlePrefixRAM.Layout u (n*d) + thickSize : (t 0).val = 2^c*d/4 + motifSize : (u 0).val = pieceCount d c + thickStride : t 1 = s 3 + motifStride : u 1 = s 3 + thickBase : t 2 = s 4 + motifBase : (u 2).val = (s 4).val+(n*d)*(s 3).val + keepMotif : Outside t (n*d) (u 2).val ((n*d)*(u 1).val) + keepThick : Outside u (n*d) (t 2).val ((n*d)*(t 1).val) + keepStarts : Outside u (n*d) (t 3).val ((n*d)*(t 1).val) + keepTotals : Outside u (n*d) (t 4).val (n*d) + +/-- Public words for a contiguous pair of start rectangles followed by the +two total columns. The input sorted-width rectangle stays at its original +base. The two modes use the same fixed worker. -/ +def prefixPublic (s : Fin 5 → Word w) (B d c base : ℕ) (motif : Bool) : Fin 5 → Word w := + let block := B*(s 3).val + let k := if motif then pieceCount d c else 2^c*d/4 + let widths := if motif then (s 4).val+block else (s 4).val + let starts := if motif then base+block else base + let totals := if motif then base+2*block+B else base+2*block + ![Fin.ofNat _ k,s 3,Fin.ofNat _ widths,Fin.ofNat _ starts,Fin.ofNat _ totals] + +/-- A single capacity bound certifies the layout of both prefix scans. -/ +theorem RowLayout.packed (s : Fin 5 → Word w) (A n d c base : ℕ) (hc : 2 ≤ c) (hd : 0 < d) + (space : BundleWidthScatter.Layout s A n d c) + (afterWidths : (s 4).val+2*((n*d)*(s 3).val) ≤ base) + (fit : base+2*((n*d)*(s 3).val)+2*(n*d) < 2^w) : + RowLayout s (prefixPublic s (n*d) d c base false) (prefixPublic s (n*d) d c base true) A n d c := by + let B := n*d + let block := B*(s 3).val + let t := prefixPublic s B d c base false + let u := prefixPublic s B d c base true + change (s 4).val+2*block ≤ base at afterWidths + change base+2*block+2*B < 2^w at fit + have small : 2^c*d/4 ≤ pieceCount d c := by unfold pieceCount; omega + have positive : 0 < 2^c*d/4 := by + obtain ⟨k,rfl⟩ := Nat.exists_eq_add_of_le hc + rw [pow_add, show 2^2 = 4 by decide, Nat.mul_assoc] + have := Nat.mul_pos (Nat.two_pow_pos k) hd + omega + have live := space.slots + have modulus := (s 3).isLt + have ht₀ : (t 0).val = 2^c*d/4 := Nat.mod_eq_of_lt (show 2^c*d/4 < 2^w by omega) + have hu₀ : (u 0).val = pieceCount d c := Nat.mod_eq_of_lt (show pieceCount d c < 2^w by omega) + have ht₁ : t 1 = s 3 := rfl + have hu₁ : u 1 = s 3 := rfl + have ht₂ : t 2 = s 4 := Fin.ext (Nat.mod_eq_of_lt (s 4).isLt) + have hu₂ : (u 2).val = (s 4).val+block := Nat.mod_eq_of_lt (show (s 4).val+block < 2^w by omega) + have ht₃ : (t 3).val = base := Nat.mod_eq_of_lt (show base < 2^w by omega) + have hu₃ : (u 3).val = base+block := Nat.mod_eq_of_lt (show base+block < 2^w by omega) + have ht₄ : (t 4).val = base+2*block := Nat.mod_eq_of_lt (show base+2*block < 2^w by omega) + have hu₄ : (u 4).val = base+2*block+B := Nat.mod_eq_of_lt (show base+2*block+B < 2^w by omega) + change RowLayout s t u A n d c + refine ⟨space, ?_, ?_, ht₀, hu₀, ht₁, hu₁, ht₂, hu₂, ?_, ?_, ?_, ?_⟩ + all_goals constructor + all_goals simp only [BundleGather.separated, ht₀, hu₀, ht₁, hu₁, ht₂, hu₂, ht₃, hu₃, ht₄, hu₄] + all_goals dsimp only [block,B] at * + all_goals omega + +/-- The two prefix workers, and the typed contents of all six tables after the +second worker finishes. Each worker's full frame is available in its report. -/ +structure Completed (t u : Fin 5 → Word w) (initial : Memory w) (ts us : List (Report w)) : Prop where + thick : FullRun t (n*d) initial ts + motif : FullRun u (n*d) (after initial (eventLog ts)) us + thickWidths : Widths (portIndex site) dd (thickWidth P old) t (after (after initial (eventLog ts)) (eventLog us)) + motifWidths : Widths (portIndex site) cd (motifWidth P old) u (after (after initial (eventLog ts)) (eventLog us)) + thickStarts : Starts (portIndex site) dd (thickWidth P old) t (after (after initial (eventLog ts)) (eventLog us)) + motifStarts : Starts (portIndex site) cd (motifWidth P old) u (after (after initial (eventLog ts)) (eventLog us)) + thickTotals : ThickTotals P site old (t 4) (after (after initial (eventLog ts)) (eventLog us)) + motifTotals : ∀ b, ((after (after initial (eventLog ts)) (eventLog us)) ((u 4).val+(portIndex site b).val)).val = + motifTotal P old b + +/-- Given the actual output rows of the width scatter, execute the thick and +CD prefix scans in sequence. The final tables retain every live sorted width, +its offset in the corresponding concatenation, and the row's total. -/ +theorem prefix_runs (s t u : Fin 5 → Word w) (layout : RowLayout s t u A n d c) + (m : Memory w) + (th : ∀ b i, (m ((BundleWidthScatter.rowBase s site (.inl b)).val+i.val)).val = old ((dd b).symm i).1.1) + (mo : ∀ b i, (m ((BundleWidthScatter.rowBase s site (.inr b)).val+i.val)).val = old ((cd b).symm i).1.1) + (thFit : ∀ b, P.bundleWidth old b < 2^w) (moFit : ∀ b, motifTotal P old b < 2^w) : + ∃ ts us, Completed P site old dd cd t u m ts us := by + let idx := portIndex site (d := d) + have thWidth : Widths idx dd (thickWidth P old) t m := by + intro b i + have h := th b i + rw [BundleWidthScatter.rowBase_val site layout.scatter, show (bucketIndex site (.inl b)).val = (idx b).val from rfl] at h + simpa only [layout.thickBase,layout.thickStride] using h + have cdWidth : Widths idx cd (motifWidth P old) u m := by + intro b i + have h := mo b i + rw [BundleWidthScatter.rowBase_val site layout.scatter, show (bucketIndex site (.inr b)).val = n*d+(idx b).val from rfl, + Nat.add_mul, ← Nat.add_assoc] at h + simpa only [layout.motifBase,layout.motifStride] using h + obtain ⟨ts,ht,st,tt⟩ := numbered_run idx dd (thickWidth P old) t m layout.thick layout.thickSize thWidth thFit + let mid := after m (eventLog ts) + have cdMid : Widths idx cd (motifWidth P old) u mid := by + intro b i + have hs := slot_lt (idx b).isLt i.isLt (layout.motifSize ▸ layout.motif.size_le_stride) + dsimp only [mid] + rw [Nat.add_assoc, layout.keepMotif.preserve layout.thick ht _ hs, ← Nat.add_assoc] + exact cdWidth b i + obtain ⟨us,hu,su,tu⟩ := numbered_run idx cd (motifWidth P old) u mid layout.motif layout.motifSize cdMid moFit + refine ⟨ts,us,ht,hu,?_,?_,?_,su,?_,tu⟩ + · intro b i + have hlt : i.val < (t 0).val := by rw [layout.thickSize]; exact i.isLt + have hs := slot_lt (idx b).isLt hlt layout.thick.size_le_stride + rw [Nat.add_assoc, layout.keepThick.preserve layout.motif hu _ hs, ← Nat.add_assoc] + dsimp only [mid] + rw [ht.saved.widths layout.thick _ _ (idx b).isLt hlt] + exact thWidth b i + · intro b i + rw [hu.saved.widths layout.motif _ _ (idx b).isLt (by rw [layout.motifSize]; exact i.isLt)] + exact cdMid b i + · intro b x + have hs := slot_lt (idx b).isLt (dd b x).isLt (layout.thickSize ▸ layout.thick.size_le_stride) + rw [Nat.add_assoc, layout.keepStarts.preserve layout.motif hu _ hs, ← Nat.add_assoc] + exact st b x + · intro b + rw [layout.keepTotals.preserve layout.motif hu _ (idx b).isLt] + exact tt b + +theorem motifTotal_le (hc : 2 ≤ c) (W : ℕ) (hW : ∀ a, old a ≤ W) (b : Port V Tag L d) : + motifTotal P old b ≤ pieceCount d c * W := by + have h := Finset.sum_le_sum (s := Finset.univ) (fun x : P.MotifFiber b ↦ fun _ ↦ hW x.1.1) + simpa [motifTotal, P.card_motifs_bundle hc] using h + +/-- Scatter each old port once, then visit each occupied width cell exactly +once across the two prefix scans. Their combined call-plus-probe count is ten +times the number of old ports. A uniform bound on the old widths suffices. -/ +theorem scatter_prefix_runs (arcs : Arc V H Tag L d c ≃ Fin A) (hc : 2 ≤ c) + (s t u : Fin 5 → Word w) (layout : RowLayout s t u A n d c) + (m : Memory w) (stored : BundleWidthScatter.RankedInput P cd dd arcs site s m old) + (W : ℕ) (bound : ∀ a, old a ≤ W) (fit : pieceCount d c * W < 2^w) : + let M := (PrimedStackRAM.template BundleWidthScatter.visit 0).instantiate w s + ∃ ws ts us, let scattered := after m (eventLog ws) + runSegment M.program 19 (some 0) m (List.replicate A []) = some ws ∧ + endState (some 0) ws = some (Fin.ofNat _ A) ∧ BundleWidthScatter.Filled s m scattered A ∧ + ws.length = A ∧ (∀ r ∈ ws, r.events.length = 18 ∧ r.probes = 4) ∧ + Completed P site old dd cd t u scattered ts us ∧ + RAMBuckets.cost Report.probes ws + RAMBuckets.cost Report.probes ts + RAMBuckets.cost Report.probes us = 10*A := by + obtain ⟨ws,wr,we,wd,wl,ww,wcost,wth,wmo⟩ := + BundleWidthScatter.graph_run P cd dd arcs site s m old layout.scatter stored + have hsmall : 2^c*d/4 ≤ pieceCount d c := by unfold pieceCount; omega + have hth (b : Port V Tag L d) : P.bundleWidth old b < 2^w := + ((P.bundleWidth_le hc old bound b).trans (Nat.mul_le_mul_right W hsmall)).trans_lt fit + obtain ⟨ts,us,done⟩ := prefix_runs P site old dd cd s t u layout _ wth wmo hth + (fun b ↦ (motifTotal_le P old hc W bound b).trans_lt fit) + refine ⟨ws,ts,us,wr,we,wd,wl,ww,done,?_⟩ + let e : Arc V H Tag L d c ≃ Fin ((n*d)*(2^c*d)) := + ((portIndex site).prodCongr (((bitWordFinEquiv c).prodCongr P.slotLabel).trans finProdFinEquiv)).trans finProdFinEquiv + have card : (n*d)*(2^c*d) = A := by simpa using Fintype.card_congr (e.symm.trans arcs) + rw [wcost,done.thick.cost,done.motif.cost,layout.thickSize,layout.motifSize] + have size := BundleKeys.bundle_row_lengths_add (d := d) hc + calc + 5*A + 5*(n*d*(2^c*d/4)) + 5*(n*d*pieceCount d c) = + 5*A + 5*(n*d*(2^c*d/4+pieceCount d c)) := by ring + _ = 10*A := by rw [size,card]; omega + +end CompressorRecords.BundlePrefixGraph + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundlePrefixRAM.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundlePrefixRAM.lean new file mode 100644 index 0000000000..34983e251c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundlePrefixRAM.lean @@ -0,0 +1,329 @@ +import OAI.Computability.VPVNP.PrimedStackRAMCode +import OAI.Computability.VPVNP.PrimedScheduleRAM +import OAI.Computability.VPVNP.RAMRecords +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Data.ZMod.Defs + +/-! +# Native prefix sums of sorted thick-wire widths + +A persistent cursor visits each live width in row order. On the first visit +to a bundle the running total is reset, regardless of the previous memory +contents. The start of each wire and the final total of each bundle are +written to separate descriptor tables. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundlePrefixRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Public words give the live row size, physical row stride, sorted-width +base, wire-start base, and row-total base. -/ +def visit : List (Op 8 5) := + [.stateWord 0, .publicWord 1 0, .binary .div 2 0 1, .binary .mod 3 0 1, + .publicWord 4 1, .binary .mul 4 2 4, .binary .add 4 4 3, + .publicWord 5 2, .binary .add 5 5 4, .read 5 5, + .publicWord 6 4, .binary .add 6 6 2, .read 7 6, + .constant 1 1, .binary .add 3 3 1, .binary .div 3 1 3, .binary .sub 3 1 3, + .binary .mul 7 3 7, .publicWord 3 3, .binary .add 3 3 4, .write 3 7, + .binary .add 7 7 5, .write 6 7, .binary .add 0 0 1] + +/-- The bundle row visited by a linear prefix-scan cursor. -/ +def row (p : Fin 5 → Word w) (i : Word w) : Word w := BinaryOp.div.eval i (p 0) +/-- The cursor's position among the live items of its current bundle row. -/ +def pos (p : Fin 5 → Word w) (i : Word w) : Word w := BinaryOp.mod.eval i (p 0) +/-- The item's offset in a strided rectangle, computed from its row number and live position. -/ +def index (p : Fin 5 → Word w) (i : Word w) : Word w := row p i * p 1 + pos p i +/-- The word multiplier that discards the previous total at position zero and retains it at +later positions of a live row. -/ +def gate (j : Word w) : Word w := 1 - BinaryOp.div.eval 1 (j + 1) +/-- The prefix offset for the current item, starting a fresh sum at the first item in each +bundle. -/ +def start (p : Fin 5 → Word w) (mem : Memory w) (i : Word w) : Word w := + gate (pos p i) * mem (p 4 + row p i).val +/-- Read the current item's width from the strided input rectangle. -/ +def width (p : Fin 5 → Word w) (mem : Memory w) (i : Word w) : Word w := + mem (p 2 + index p i).val + +/-- Store the current item's prefix offset and advance its bundle's total by the item's width. -/ +def stepMemory (p : Fin 5 → Word w) (mem : Memory w) (i : Word w) : Memory w := + writeMemory (writeMemory mem (p 3 + index p i) (start p mem i)) + (p 4 + row p i) (start p mem i + width p mem i) + +/-- One prefix-scan visit's ticks and probes, reading the width and old row total before +writing the item start and updated total. -/ +def events (p : Fin 5 → Word w) (mem : Memory w) (i : Word w) : List (Event w) := + let total := p 4 + row p i + List.replicate 9 .tick ++ [.read (p 2 + index p i) (width p mem i), .tick, .tick, + .read total (mem total.val)] ++ List.replicate 7 .tick ++ + [.write (p 3 + index p i) (start p mem i), .tick, + .write total (start p mem i + width p mem i), .tick] + +theorem native (p : Fin 5 → Word w) (mem : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program 25 (M.program.start i) mem [] = some ⟨events p mem i, some (i + 1)⟩ := by + let M := (template visit 0).instantiate w p + change execute M.program (1 + visit.length) ⟨M.entry, i, fun _ => 0, fun _ => 0⟩ mem [] = _ + rw [execute_template, run_eq_trace] + rfl + +theorem events_after (p : Fin 5 → Word w) (mem : Memory w) (i : Word w) : + after mem (events p mem i) = stepMemory p mem i := rfl + +theorem events_work (p : Fin 5 → Word w) (mem : Memory w) (i : Word w) : + countProbes (events p mem i) = 4 ∧ (events p mem i).length = 24 := ⟨rfl, rfl⟩ + +/-- Natural prefix sum in row `b` of the sorted-width table. -/ +def prefixSum (p : Fin 5 → Word w) (initial : Memory w) (b j : ℕ) : ℕ := + ∑ a ∈ Finset.range j, (initial ((p 2).val + b * (p 1).val + a)).val + +/-- The three physical regions fit, and each pair is disjoint in either order. -/ +structure Layout (p : Fin 5 → Word w) (B : ℕ) : Prop where + positive : 0 < (p 0).val + size_le_stride : (p 0).val ≤ (p 1).val + widthsFit : (p 2).val + B * (p 1).val ≤ 2 ^ w + startsFit : (p 3).val + B * (p 1).val ≤ 2 ^ w + totalsFit : (p 4).val + B ≤ 2 ^ w + widthsStarts : (p 2).val + B * (p 1).val ≤ (p 3).val ∨ (p 3).val + B * (p 1).val ≤ (p 2).val + widthsTotals : (p 2).val + B * (p 1).val ≤ (p 4).val ∨ (p 4).val + B ≤ (p 2).val + startsTotals : (p 3).val + B * (p 1).val ≤ (p 4).val ∨ (p 4).val + B ≤ (p 3).val + +theorem prefix_succ (p : Fin 5 → Word w) (m : Memory w) (b j : ℕ) : + prefixSum p m b (j + 1) = prefixSum p m b j + (m ((p 2).val + b * (p 1).val + j)).val := + Finset.sum_range_succ .. + +private theorem prefix_mono (p : Fin 5 → Word w) (m : Memory w) (b : ℕ) : + Monotone (prefixSum p m b) := monotone_nat_of_le_succ fun j => by rw [prefix_succ]; omega + +private theorem gate_exact (j : Word w) (hj : j.val + 1 < 2 ^ w) : + gate j = if j.val = 0 then 0 else 1 := by + have one : (1 : Word w).val = 1 := by + change 1 % (2 ^ w) = 1 + exact Nat.mod_eq_of_lt (by omega) + have inc : (j + 1).val = j.val + 1 := by rw [Fin.val_add, one, Nat.mod_eq_of_lt hj] + have div : (BinaryOp.div.eval (1 : Word w) (j + 1)).val = 1 / (j.val + 1) := by + change (1 : Word w).val / (j + 1).val % (2 ^ w) = _ + rw [one, inc, Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt (by omega))] + by_cases h : j.val = 0 + · have d : BinaryOp.div.eval (1 : Word w) (j + 1) = 1 := by + apply Fin.ext + rw [div, h, one] + simp [gate, h, d] + · have d : BinaryOp.div.eval (1 : Word w) (j + 1) = 0 := by + apply Fin.ext + rw [div, Nat.div_eq_of_lt (by omega)] + rfl + simp [gate, h, d] + +private theorem coord_bound {B k stride b j : ℕ} (hb : b < B) (hj : j < k) (hs : k ≤ stride) : + b * stride + j < B * stride := by + have h := Nat.mul_le_mul_right stride (Nat.succ_le_of_lt hb) + rw [Nat.succ_mul] at h + omega + +private theorem coord_unique {s b a j l : ℕ} (hj : j < s) (hl : l < s) + (h : b * s + j = a * s + l) : b = a ∧ j = l := by + have js := Nat.mul_add_mod_of_lt hj (a := b) + have ls := Nat.mul_add_mod_of_lt hl (a := a) + have eq : j = l := js.symm.trans ((congrArg (· % s) h).trans ls) + exact ⟨Nat.eq_of_mul_eq_mul_right (by omega) (Nat.add_right_cancel (eq ▸ h)), eq⟩ + +/-- The starts of all visited wires, and the latest nonempty prefix total +of each visited bundle, are stored. Every cell outside the writable rows +and the total column retains its initial value. -/ +structure Saved (p : Fin 5 → Word w) (B t : ℕ) (initial mem : Memory w) : Prop where + starts : ∀ b < B, ∀ j < (p 0).val, b * (p 0).val + j < t → + (mem ((p 3).val + b * (p 1).val + j)).val = prefixSum p initial b j + totals : ∀ b < B, ∀ q, 0 < q → q ≤ (p 0).val → b * (p 0).val + q ≤ t → + (q = (p 0).val ∨ b * (p 0).val + q = t) → + (mem ((p 4).val + b)).val = prefixSum p initial b q + frame : ∀ addr, + (∀ b < B, ∀ j < (p 0).val, addr ≠ (p 3).val + b * (p 1).val + j) → + (∀ b < B, addr ≠ (p 4).val + b) → mem addr = initial addr + + +private theorem starts_ne_total {p : Fin 5 → Word w} {B b j u : ℕ} + (layout : Layout p B) (hb : b < B) (hj : j < (p 0).val) (hu : u < B) : + (p 3).val + b * (p 1).val + j ≠ (p 4).val + u := by + have h := coord_bound hb hj layout.size_le_stride + have dis := layout.startsTotals + omega + +theorem Saved.widths {p : Fin 5 → Word w} {B t : ℕ} {initial mem : Memory w} + (done : Saved p B t initial mem) (layout : Layout p B) (b j : ℕ) + (hb : b < B) (hj : j < (p 0).val) : + mem ((p 2).val + b * (p 1).val + j) = initial ((p 2).val + b * (p 1).val + j) := by + have h := coord_bound hb hj layout.size_le_stride + apply done.frame + · intro a ha l hl + have bound := coord_bound ha hl layout.size_le_stride + have apart := layout.widthsStarts + omega + · intro a ha + have apart := layout.widthsTotals + omega + +private theorem saved_step {p : Fin 5 → Word w} {B t : ℕ} {initial mem : Memory w} + (layout : Layout p B) (fit : ∀ b < B, prefixSum p initial b (p 0).val < 2^w) + (done : Saved p B t initial mem) (i : Word w) (hi : i.val = t) + (ht : t < B * (p 0).val) : + Saved p B (t+1) initial (stepMemory p mem i) := by + let b := t / (p 0).val + let j := t % (p 0).val + have hb : b < B := (Nat.div_lt_iff_lt_mul layout.positive).mpr ht + have hj : j < (p 0).val := Nat.mod_lt _ layout.positive + have ht' : t = b * (p 0).val + j := by + dsimp [b, j] + rw [Nat.mul_comm, Nat.div_add_mod] + have hr : (row p i).val = b := by + change (i.val / (p 0).val) % (2 ^ w) = _ + rw [Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt i.isLt), hi] + have hp : (pos p i).val = j := by + change (i.val % (p 0).val) % (2 ^ w) = _ + rw [Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt i.isLt), hi] + have offBound := coord_bound hb hj layout.size_le_stride + have wf := layout.widthsFit + have sf := layout.startsFit + have tf := layout.totalsFit + have off : (index p i).val = b * (p 1).val + j := by + rw [index, Fin.val_add, Fin.val_mul, hr, hp, Nat.mod_add_mod, Nat.mod_eq_of_lt (by omega)] + have wa : (p 2 + index p i).val = (p 2).val + b * (p 1).val + j := by + rw [Fin.val_add, off, Nat.mod_eq_of_lt (by omega), Nat.add_assoc] + have sa : (p 3 + index p i).val = (p 3).val + b * (p 1).val + j := by + rw [Fin.val_add, off, Nat.mod_eq_of_lt (by omega), Nat.add_assoc] + have ta : (p 4 + row p i).val = (p 4).val + b := by + rw [Fin.val_add, hr, Nat.mod_eq_of_lt (by omega)] + have wval : width p mem i = initial ((p 2).val + b * (p 1).val + j) := by + rw [width, wa, done.widths layout b j hb hj] + have sval : (start p mem i).val = prefixSum p initial b j := by + have kg := (p 0).isLt + rw [start, gate_exact _ (by rw [hp]; omega), hp, ta] + by_cases hzero : j = 0 + · simp [hzero, prefixSum] + · rw [ite_eq_right hzero, one_mul] + exact done.totals b hb j (by omega) hj.le (by omega) (.inr ht'.symm) + have totalFit : prefixSum p initial b (j+1) < 2^w := + ((prefix_mono p initial b) (Nat.succ_le_of_lt hj)).trans_lt (fit b hb) + have tval : (start p mem i + width p mem i).val = prefixSum p initial b (j+1) := by + rw [Fin.val_add, sval, wval, ← prefix_succ, Nat.mod_eq_of_lt totalFit] + constructor + · intro a ha l hl hvisit + have diff := starts_ne_total layout ha hl hb + simp only [stepMemory, writeMemory, ta, sa, ite_eq_right diff] + by_cases eq : (p 3).val + a * (p 1).val + l = (p 3).val + b * (p 1).val + j + · obtain ⟨rfl, rfl⟩ := coord_unique (hl.trans_le layout.size_le_stride) + (hj.trans_le layout.size_le_stride) (by omega : a * (p 1).val + l = b * (p 1).val + j) + rw [ite_eq_left rfl] + exact sval + · rw [ite_eq_right eq] + have hn : a * (p 0).val + l ≠ t := by + intro same + obtain ⟨rfl,rfl⟩ := coord_unique hl hj (same.trans ht') + exact eq rfl + exact done.starts a ha l hl (by omega) + · intro a ha q hq hqk hvisit latest + have diff := Ne.symm (starts_ne_total layout hb hj ha) + simp only [stepMemory, writeMemory, ta, sa, ite_eq_right diff] + by_cases same : a = b + · subst a + have eq : q = j+1 := by rcases latest with h | h <;> omega + rw [ite_eq_left rfl, eq] + exact tval + · rw [ite_eq_right (fun h => same (Nat.add_left_cancel h))] + have before : a * (p 0).val + q ≠ t + 1 := by + intro eq + have e : a * (p 0).val + (q-1) = b * (p 0).val + j := by omega + exact same (coord_unique (by omega) hj e).1 + exact done.totals a ha q hq hqk (by omega) (.inl (latest.resolve_right before)) + · intro addr hs ht + simp only [stepMemory, writeMemory, ta, sa, ite_eq_right (hs b hb j hj), + ite_eq_right (ht b hb), done.frame addr hs ht] + +/-- Execution and work of a prefix of the native calls. -/ +structure ScanRun (p : Fin 5 → Word w) (B t : ℕ) (initial : Memory w) (rs : List (Report w)) : Prop where + executed : runSegment ((template visit 0).instantiate w p).program 25 (some 0) + initial (List.replicate t []) = some rs + cursor : endState (some 0) rs = some (Fin.ofNat _ t) + saved : Saved p B t initial (after initial (eventLog rs)) + length : rs.length = t + work : ∀ r ∈ rs, r.probes = 4 ∧ r.events.length = 24 + cost : RAMBuckets.cost Report.probes rs = 5 * t + +theorem scan_run (p : Fin 5 → Word w) (B : ℕ) (initial : Memory w) (layout : Layout p B) + (fit : ∀ b < B, prefixSum p initial b (p 0).val < 2^w) + (t : ℕ) (ht : t ≤ B * (p 0).val) : ∃ rs, ScanRun p B t initial rs := by + induction t with + | zero => + refine ⟨[], rfl, rfl, ⟨?_, ?_, fun _ _ _ => rfl⟩, rfl, by simp, rfl⟩ <;> intros <;> omega + | succ t ih => + obtain ⟨rs, prev⟩ := ih (by omega) + let i := Fin.ofNat (2 ^ w) t + let mem := after initial (eventLog rs) + let r : Report w := ⟨events p mem i, some (i + 1)⟩ + have hbound := Nat.mul_le_mul_left B layout.size_le_stride + have hw := layout.widthsFit + have hv : i.val = t := Nat.mod_eq_of_lt (by omega) + have inc : i+1 = Fin.ofNat (2 ^ w) (t+1) := by + apply Fin.ext + simp [i, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + have afterBoth : after initial (eventLog (rs ++ [r])) = stepMemory p mem i := by + simp only [eventLog, List.flatMap_append, List.flatMap_singleton, after, List.foldl_append, mem] + rfl + refine ⟨rs ++ [r], ?_, ?_, ?_, ?_, ?_, ?_⟩ + · rw [List.replicate_succ', PrimedSchedule.runSegment_append, prev.executed] + simp only [Option.bind_some, prev.cursor, runSegment, Option.map_some] + change (match execute ((template visit 0).instantiate w p).program 25 + (((template visit 0).instantiate w p).program.start i) mem [] with + | none => none | some s => some [s]).map (rs ++ ·) = _ + rw [native p mem i] + rfl + · rw [endState_append, prev.cursor] + exact congrArg some inc + · rw [afterBoth] + exact saved_step layout fit prev.saved i hv ht + · simp [prev.length] + · intro s hs + rcases List.mem_append.mp hs with he | he + · exact prev.work s he + · obtain rfl := List.mem_singleton.mp he + exact events_work p mem i + · have hp : r.probes = 4 := (events_work p mem i).1 + rw [RAMBuckets.cost_append, prev.cost, RAMBuckets.cost, hp, RAMBuckets.cost, Nat.mul_succ] + +/-- Full row-major execution, including exact natural wire offsets and row +totals. The frame includes the padding cells between live row prefixes. -/ +structure FullRun (p : Fin 5 → Word w) (B : ℕ) (initial : Memory w) (rs : List (Report w)) : Prop + extends ScanRun p B (B * (p 0).val) initial rs where + starts : ∀ b < B, ∀ j < (p 0).val, (after initial (eventLog rs) ((p 3).val + b * (p 1).val + j)).val = + prefixSum p initial b j + totals : ∀ b < B, (after initial (eventLog rs) ((p 4).val + b)).val = prefixSum p initial b (p 0).val + frame : ∀ addr, + (∀ b < B, ∀ j < (p 0).val, addr ≠ (p 3).val + b * (p 1).val + j) → + (∀ b < B, addr ≠ (p 4).val + b) → after initial (eventLog rs) addr = initial addr + +/-- A single fixed program scans all `B*k` entries. Only input width sums +must fit in a word. Every row total is initialized by the worker itself. -/ +theorem full_run (p : Fin 5 → Word w) (B : ℕ) (initial : Memory w) (layout : Layout p B) + (fit : ∀ b < B, prefixSum p initial b (p 0).val < 2^w) : + ∃ rs, FullRun p B initial rs := by + obtain ⟨rs, run⟩ := scan_run p B initial layout fit (B * (p 0).val) (le_refl _) + refine ⟨rs, run, ?_, ?_, run.saved.frame⟩ + · intro b hb j hj + exact run.saved.starts b hb j hj (coord_bound hb hj (le_refl _)) + · intro b hb + have bound := Nat.mul_le_mul_right (p 0).val (Nat.succ_le_of_lt hb) + rw [Nat.succ_mul] at bound + exact run.saved.totals b hb (p 0).val layout.positive (le_refl _) bound (.inl rfl) + +end CompressorRecords.BundlePrefixRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleRAM.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleRAM.lean new file mode 100644 index 0000000000..aec1960245 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleRAM.lean @@ -0,0 +1,168 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkRAM +import OAI.Computability.VPVNP.RAMRecords + +/-! +# Native classification of old segments in a shrinking pass + +For each old outgoing port, the worker follows the actual incidence once and +reads the shrinking placement at both endpoints. It emits a bundle identifier +and a key for the segment's order within that bundle. Thick-to-thick wires use +the source owner and old outgoing slot. The other wires use the thin endpoint's +assigned bundle. The old width column is already indexed by this same port. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open ShrinkRAM (div mod select) + +variable {w : ℕ} + +/-- Straight-line RAM operations for the old-port classifier, with 24 registers and 11 public +operands. -/ +abbrev Ops := List (Op 24 11) + +/-- Read one external cell at a public column base plus a register offset. -/ +private def readColumn (column : Fin 11) (offset dst : Fin 24) : Ops := + [.publicWord 23 column, .binary .add 23 23 offset, .read dst 23] + +private def writeColumn (column : Fin 11) (src : Fin 24) : Ops := + [.publicWord 23 column, .binary .add 23 23 0, .write 23 src] + +/-- Registers 14 through 18 decode the source tag, port label, mask and +base. Registers 19 and 21 collect the thick-to-thick values, and 20 and +22 collect the selected bucket and key. -/ +private def classify : Ops := + [.binary .mul 13 8 9, + .binary .div 14 5 2, .binary .mod 15 14 3, .binary .div 14 14 3, + .binary .mod 16 14 1, .binary .div 14 14 1, .binary .mod 17 14 4, + .binary .div 18 14 4, + .binary .mul 19 10 1, .binary .add 19 19 6, + .binary .sub 20 12 11, .binary .mul 20 8 20, .binary .add 20 11 20, + .publicWord 23 4, .binary .add 20 23 20, + .binary .sub 19 19 20, .binary .mul 19 13 19, .binary .add 20 20 19, + .binary .mul 21 17 1, .binary .add 21 21 16, + .binary .mul 22 18 3, .binary .add 22 22 15, .binary .mul 22 22 1, + .binary .add 22 22 6, .binary .mul 22 22 4, .binary .add 22 22 17, + .binary .mul 22 22 1, .binary .add 22 22 16, + .binary .sub 21 21 22, .binary .mul 21 13 21, .binary .add 22 22 21] + +/-- Public words are the degree, residual radix, tag radix, mask radix, +number of external bundles, actual outgoing column, thickness, owner and +assigned columns, and the output bucket and key columns. -/ +def visit : Ops := + [.stateWord 0, .publicWord 1 0, .publicWord 2 1, .publicWord 3 2, .publicWord 4 3, + .binary .div 5 0 1, .binary .mod 6 0 1] ++ readColumn 5 0 7 ++ [.binary .div 7 7 1] ++ + readColumn 6 5 8 ++ readColumn 6 7 9 ++ readColumn 7 5 10 ++ readColumn 8 5 11 ++ + readColumn 8 7 12 ++ classify ++ writeColumn 9 20 ++ writeColumn 10 22 ++ + [.constant 23 1, .binary .add 0 0 23] + +/-- The mixed-radix source fields recovered from an old outgoing-port number to compute its +bundle and sorting key. -/ +structure Digits (α : Type) where + /-- The original base-site index remaining after the lane fields have been divided out. -/ + base : α + /-- The source tag digit extracted after discarding the residual lane coordinate. -/ + tag : α + /-- The outgoing port's slot within the old site. -/ + slot : α + /-- The source mask digit used in both the thick-wire and CD sort keys. -/ + mask : α + /-- The source slot-label digit, the least significant field of the within-bundle sorting + key. -/ + label : α + +/-- Recover the source base, tag, outgoing slot, mask, and slot label from a linear old-port +index and the public radices. -/ +def decode (p : Fin 11 → Word w) (i : Word w) : Digits (Word w) := + let site := div i (p 0) + let q := div site (p 1) + let lane := div q (p 2) + let baseMask := div lane (p 0) + ⟨div baseMask (p 3), mod q (p 2), mod i (p 0), mod baseMask (p 3), mod lane (p 0)⟩ + +/-- Remove the outgoing-slot digit to obtain the source site of the current old port. -/ +def sourceSite (p : Fin 11 → Word w) (i : Word w) := div i (p 0) +/-- Follow the current port's actual incidence and remove its incoming-slot digit to obtain the +target site. -/ +def targetSite (p : Fin 11 → Word w) (m : Memory w) (i : Word w) := div (m (p 5+i).val) (p 0) + +/-- The destination depends on the first probe. Remaining addresses depend +only on that destination, the persistent index and the public radices. -/ +def readAddress (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : Fin 6 → Word w := + let src := sourceSite p i + let dst := targetSite p m i + ![p 5+i, p 6+src, p 6+dst, p 7+src, p 8+src, p 8+dst] + +/-- Read one of the six classification inputs for the old port, including incidence and +endpoint placement data. -/ +def readValue (p : Fin 11 → Word w) (m : Memory w) (i : Word w) (t : Fin 6) := + m (readAddress p m i t).val + +/-- Choose the thick source-port bucket when both endpoints are thick, or the assigned thin +endpoint's CD bucket otherwise. -/ +def bucket (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : Word w := + let r := readValue p m i + let cd := p 4 + select (r 1) (r 4) (r 5) + let dd := r 3 * p 0 + (decode p i).slot + select (r 1 * r 2) cd dd + +/-- Encode the old port's sort key, using mask and label for thick wires and the normalized +source fields for CD motifs. -/ +def key (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : Word w := + let r := readValue p m i + let f := decode p i + let cd := (((f.base * p 2 + f.tag) * p 0 + f.slot) * p 3 + f.mask) * p 0 + f.label + let dd := f.mask * p 0 + f.label + select (r 1 * r 2) cd dd + +/-- Write the classified bucket and sort key into separate columns indexed by the old outgoing +port. -/ +def update (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : Memory w := + writeMemory (writeMemory m (p 9+i) (bucket p m i)) (p 10+i) (key p m i) + +/-- The classifier visit's six input reads, local calculation ticks, and writes of the bucket +and key at the old port index. -/ +def events (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + let read (t : Fin 6) := Event.read (readAddress p m i t) (readValue p m i t) + List.replicate 9 .tick ++ [read 0,.tick,.tick,.tick,read 1,.tick,.tick,read 2, + .tick,.tick,read 3,.tick,.tick,read 4,.tick,.tick,read 5] ++ + List.replicate (classify.length+2) .tick ++ [.write (p 9+i) (bucket p m i), + .tick,.tick,.write (p 10+i) (key p m i),.tick,.tick] + +theorem events_after (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : + after m (events p m i) = update p m i := rfl + +theorem events_work (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : + (events p m i).length = visit.length ∧ countProbes (events p m i) = 8 := ⟨rfl,rfl⟩ + +set_option maxRecDepth 8192 in +set_option maxHeartbeats 1200000 in +private theorem visit_trace (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : + ∃ rs, trace p i visit (fun _ ↦ 0) m = some (events p m i,rs,update p m i) ∧ rs 0 = i+1 := by + simp (config := {decide := true}) [visit, classify, readColumn, writeColumn, events, update, bucket, + key, decode, readValue, readAddress, sourceSite, targetSite, select, div, mod, trace, Op.effect, + BinaryOp.eval, Function.update, List.replicate_succ] + rfl + +/-- The actual interpreter returns the next source port and the six reads +followed by two writes, with fresh private registers on every call. -/ +theorem visit_native (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program (1 + visit.length) (M.program.start i) m [] = + some ⟨events p m i, some (i+1)⟩ := by + obtain ⟨rs, ht, hr⟩ := visit_trace p m i + let M := (template visit 0).instantiate w p + change execute M.program (1 + visit.length) ⟨M.entry, i, fun _ ↦ 0, fun _ ↦ 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hr] + +end CompressorRecords.BundleRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleRank.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleRank.lean new file mode 100644 index 0000000000..986de4f618 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleRank.lean @@ -0,0 +1,198 @@ +import OAI.Computability.VPVNP.CompressorRecordSlots +import OAI.Computability.VPVNP.SlotBundleNumbering + +/-! +# Ranks of the CD pieces and the old thick wires in an absolute bundle + +Appendix E collects two bounded lists at each packed bundle. The old arc label +distinguishes parallel wires. A CD piece is ranked by its old arc after +discarding the residual lane. A thick wire is ranked by its color and slot. +Translating either list to role-A lane zero preserves these comparisons, so +the native unsigned rank scan computes the numbers used in the shrinking step. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleRank + +open Compression Compression.PackingData Slots + +variable {V H Tag L : Type} {d c N J : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) + +/-- Numeric key of an absolute CD occurrence, independent of its residual lane. -/ +def motifKey (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (m : P.Motif) : + Fin (N * (J * (d * (2 ^ c * d)))) := + P.baseMotifIndex vertices tags (P.baseMotif m) + +/-- Numeric key in the old thick-wire concatenation, in outgoing numbering. -/ +def thickKey (a : P.ThickWire) : Fin (2 ^ c * d) := + finProdFinEquiv (bitWordFinEquiv c a.1.2.1, P.slotLabel a.1.2.2) + +theorem thickKey_val (a : P.ThickWire) : + (thickKey P a).val = (bitWordFinEquiv c a.1.2.1).val * d + (P.slotLabel a.1.2.2).val := by + change _ + d * _ = _ + ring + +theorem motifKey_val (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (m : P.Motif) : + (motifKey P vertices tags m).val = + ((((vertices m.1.1.1.1).val * J + (tags m.1.1.1.2.1).val) * d + m.1.1.2.val) * + 2 ^ c + (bitWordFinEquiv c m.1.2.1).val) * d + (P.slotLabel m.1.2.2).val := by + change (((_ + d * _) + (2 ^ c * d) * _) + (d * (2 ^ c * d)) * _) + (J * (d * (2 ^ c * d))) * _ = _ + dsimp only [baseMotif, translateMotif, translateArc, translateSite] + ring + +private theorem row_length {E S : Type*} [Fintype E] [DecidableEq E] [DecidableEq S] + {port : E → S} {b : S} (r : IncidentRow port b) : + r.ids.length = Fintype.card {e // port e = b} := by + rw [← List.toFinset_card_of_nodup r.nodup, Fintype.card_subtype] + congr 1 + ext e + simp [r.complete] + +private theorem count_rank {E S : Type*} [Fintype E] [DecidableEq E] [DecidableEq S] + {port : E → S} {b : S} (r : IncidentRow port b) {n k : ℕ} (key : E → Fin k) + (num : {a // port a = b} ≃ Fin n) + (hlt : ∀ x y, num x < num y ↔ key x.1 < key y.1) (a : {e // port e = b}) : + (num a).val = r.ids.countP (fun e ↦ decide (key e < key a.1)) := by + let lower := num.subtypeEquiv (p := fun x ↦ key x.1 < key a.1) + (q := fun i ↦ i.val < (num a).val) (fun x ↦ (hlt x a).symm) + let ids := r.ids.toFinset.filter (fun e ↦ key e < key a.1) + let members : {x : {e // port e = b} // key x.1 < key a.1} ≃ ids := { + toFun := fun x ↦ ⟨x.1.1, Finset.mem_filter.mpr + ⟨List.mem_toFinset.mpr ((r.complete _).mpr x.1.2), x.2⟩⟩ + invFun := fun x ↦ ⟨⟨x.1, (r.complete _).mp (List.mem_toFinset.mp (Finset.mem_filter.mp x.2).1)⟩, + (Finset.mem_filter.mp x.2).2⟩ + left_inv := fun _ ↦ rfl + right_inv := fun _ ↦ rfl } + rw [← Fintype.card_fin_lt_of_le (num a).isLt.le, ← Fintype.card_congr lower, + Fintype.card_congr members, Fintype.card_coe] + exact r.nodup.card_eq_countP + +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] + +theorem motifRow_length (hc : 2 ≤ c) (b : Site V Tag L × Fin d) (r : IncidentRow P.bundle b) : + r.ids.length = 3 * (2 ^ c * d) / 4 := by + classical + exact (row_length r).trans (P.card_motifs_bundle hc b) + +theorem thickRow_length (hc : 2 ≤ c) (b : Site V Tag L × Fin d) + (r : IncidentRow (fun e : P.ThickWire ↦ e.1.1) b) : + r.ids.length = 2 ^ c * d / 4 := by + classical + exact (row_length r).trans (P.card_thick_fiber hc b) + +/-- The piece numbers of Appendix C compare by the relative keys even at an +arbitrary absolute bundle. Transport back uses the lane of role A. -/ +theorem sortedBundle_lt (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (hc : 2 ≤ c) + (b : Site V Tag L × Fin d) (x y : P.MotifFiber b) : + P.sortedBundleNumbering vertices tags hc b x < P.sortedBundleNumbering vertices tags hc b y ↔ + motifKey P vertices tags x.1 < motifKey P vertices tags y.1 := by + let z : Site V Tag L × Fin d := ((b.1.1, b.1.2.1, 0), b.2) + let toZero (u : P.MotifFiber b) : P.MotifFiber z := + ⟨P.translateMotif u.1 (-b.1.2.2), by simp [z, u.2, translateSite]⟩ + let key := fun u : P.MotifFiber z ↦ motifKey P vertices tags u.1 + let := LinearOrder.lift' key (P.motifFiberIndex_injective vertices tags z) + let e := (Fintype.orderIsoFinOfCardEq (P.MotifFiber z) (P.card_motifs_bundle hc z)).symm + change e (toZero x) < e (toZero y) ↔ _ + rw [e.lt_iff_lt] + change motifKey P vertices tags (P.translateMotif x.1 _) < + motifKey P vertices tags (P.translateMotif y.1 _) ↔ _ + simp [motifKey] + +theorem sortedThick_lt (hc : 2 ≤ c) (b : Site V Tag L × Fin d) (x y : P.ThickFiber b) : + P.sortedThickNumbering hc b x < P.sortedThickNumbering hc b y ↔ thickKey P x.1 < thickKey P y.1 := by + let z : Site V Tag L × Fin d := ((b.1.1, b.1.2.1, 0), b.2) + let toZero (u : P.ThickFiber b) : P.ThickFiber z := + ⟨P.translateThickWire u.1 (-b.1.2.2), by + change (translateSite u.1.1.1.1 _, u.1.1.1.2) = _ + simp [z, u.2, translateSite]⟩ + let := LinearOrder.lift' (P.thickFiberIndex z) (P.thickFiberIndex_injective z) + let e := (Fintype.orderIsoFinOfCardEq (P.ThickFiber z) (P.card_thick_fiber hc z)).symm + change e (toZero x) < e (toZero y) ↔ _ + rw [e.lt_iff_lt] + rfl + +/-- Count smaller keys in the collected CD row to recover its piece number. -/ +theorem motif_rank (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (hc : 2 ≤ c) + (b : Site V Tag L × Fin d) (r : IncidentRow P.bundle b) (x : P.MotifFiber b) : + (P.sortedBundleNumbering vertices tags hc b x).val = + r.ids.countP (fun y ↦ decide (motifKey P vertices tags y < motifKey P vertices tags x.1)) := by + classical + exact count_rank r _ _ (sortedBundle_lt P vertices tags hc b) x + +/-- Count smaller keys in the collected thick row to recover its concatenation number. -/ +theorem thick_rank (hc : 2 ≤ c) (b : Site V Tag L × Fin d) + (r : IncidentRow (fun a : P.ThickWire ↦ a.1.1) b) (x : P.ThickFiber b) : + (P.sortedThickNumbering hc b x).val = + r.ids.countP (fun a ↦ decide (thickKey P a < thickKey P x.1)) := by + classical + exact count_rank r _ _ (sortedThick_lt P hc b) x + +open BurstRAM + +/-- The native call ranks the pivot, writes the designated field and has a fixed +number of dispatches and probes for a row of this length. -/ +def RankWrite {w : ℕ} (n : ℕ) (pub : Fin 2 → Word w) (mem : Memory w) (pivot rank : Word w) : Prop := + ∃ es, rankExecution n pub pivot mem es rank ∧ + after mem es = writeMemory mem (pub 1) rank ∧ + countProbes es = n + 1 ∧ es.length + 1 = 6 * n + 6 + +private theorem rank_write {E : Type*} {w K n : ℕ} (key : E → Fin K) (hfit : K < 2 ^ w) + (ids : List E) (i : E) (rank : Fin n) + (hl : ids.length = n) (hr : rank.val = ids.countP (fun e ↦ decide (key e < key i))) + (hcap : n ≤ K) (pub : Fin 2 → Word w) (mem : Memory w) + (hread : ∀ j : Fin ids.length, mem ((pub 0).val + j.val) = (key ids[j.val]).castLE hfit.le) + (haddr : (pub 0).val + n ≤ 2 ^ w) : + RankWrite n pub mem ((key i).castLE hfit.le) (Fin.ofNat _ rank.val) := by + let word := fun e ↦ (key e).castLE hfit.le + let row := ids.map word + have hlen : row.length = n := (List.length_map _).trans hl + have hmem (j : Fin row.length) : mem ((pub 0).val + j.val) = row[j.val] := by + simpa [row, word] using hread ⟨j.val, by simpa [row] using j.isLt⟩ + have hheadroom (k : Word w) (hk : k ∈ row) : k.val + 1 < 2 ^ w := by + obtain ⟨e, _, rfl⟩ := List.mem_map.mp hk + exact (Nat.succ_le_of_lt (key e).isLt).trans_lt hfit + have heq : (row.filter fun x ↦ decide (x < word i)).length = rank.val := by + rw [← List.countP_eq_length_filter, List.countP_map, hr] + rfl + have run := SlotRankRAM.rank_native pub (word i) mem row hmem (hlen ▸ haddr) + (hlen ▸ hcap.trans_lt hfit) hheadroom + change RankWrite row.length pub mem (word i) (Fin.ofNat _ (row.filter fun x ↦ decide (x < word i)).length) at run + rwa [hlen, heq] at run + +/-- Rank and write the actual CD piece number from the bundle's unsorted row. -/ +theorem motif_rank_native {w : ℕ} (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (hc : 2 ≤ c) + (hfit : N * (J * (d * (2 ^ c * d))) < 2 ^ w) (b : Site V Tag L × Fin d) + (r : IncidentRow P.bundle b) (x : P.MotifFiber b) + (pub : Fin 2 → Word w) (mem : Memory w) + (hread : ∀ j : Fin r.ids.length, mem ((pub 0).val + j.val) = + (motifKey P vertices tags r.ids[j.val]).castLE hfit.le) + (haddr : (pub 0).val + 3 * (2 ^ c * d) / 4 ≤ 2 ^ w) : + RankWrite (3 * (2 ^ c * d) / 4) pub mem ((motifKey P vertices tags x.1).castLE hfit.le) + (Fin.ofNat _ (P.sortedBundleNumbering vertices tags hc b x).val) := by + have cap := Fintype.card_le_of_injective _ (P.motifFiberIndex_injective vertices tags b) + rw [P.card_motifs_bundle hc b, Fintype.card_fin] at cap + exact rank_write _ hfit _ _ _ (motifRow_length P hc b r) (motif_rank P vertices tags hc b r x) + cap pub mem hread haddr + +/-- Rank and write the actual thick wire's position in the concatenation. -/ +theorem thick_rank_native {w : ℕ} (hc : 2 ≤ c) (hfit : 2 ^ c * d < 2 ^ w) + (b : Site V Tag L × Fin d) (r : IncidentRow (fun a : P.ThickWire ↦ a.1.1) b) + (x : P.ThickFiber b) (pub : Fin 2 → Word w) (mem : Memory w) + (hread : ∀ j : Fin r.ids.length, mem ((pub 0).val + j.val) = + (thickKey P r.ids[j.val]).castLE hfit.le) + (haddr : (pub 0).val + (2 ^ c * d) / 4 ≤ 2 ^ w) : + RankWrite (2 ^ c * d / 4) pub mem ((thickKey P x.1).castLE hfit.le) + (Fin.ofNat _ (P.sortedThickNumbering hc b x).val) := + rank_write _ hfit _ _ _ (thickRow_length P hc b r) (thick_rank P hc b r x) + (Nat.div_le_self _ _) pub mem hread haddr + +end CompressorRecords.BundleRank + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleRoleIndex.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleRoleIndex.lean new file mode 100644 index 0000000000..6b63d3cd51 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleRoleIndex.lean @@ -0,0 +1,52 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleKeys +import OAI.Computability.VPVNP.CompressorSlotOwnerDecode + +/-! +# Converting the old source-port order to the role-record order + +The shrink role table keeps the residual lane as its last digit. Its preceding +digits are the same normalized source-port key used to sort CD records. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleKeys + +open Compression + +variable {V : Type} {n a g : ℕ} +variable (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) (order : V ≃ Fin n) + +/-- Reindex every old actual wire, including thick wires and parallel padding. -/ +theorem oldArcIndex_eq_key_lane (e : OldArc V a g) : + (Slots.oldArcIndex (orderedDyadicPacking G order) order (bitWordFinEquiv (Shrink.J a)) + (bitWordFinEquiv g) e).val = + keyAt order false e * 2^g + (bitWordFinEquiv g e.1.1.2.2).val := by + rw [keyAt, Shrink.decode_oldNumber, numericKey] + dsimp only + have ht : Shrink.lowNumber (sourcePosition e).1.2 / 2^g = + (bitWordFinEquiv (Shrink.J a) e.1.1.2.1).val := by + unfold Shrink.lowNumber Shrink.join + rw [Nat.mul_comm, Nat.mul_add_div (Nat.two_pow_pos _), Nat.div_eq_of_lt (Fin.isLt _), Nat.add_zero] + rfl + rw [ht] + let x := (order e.1.1.1).val + let t := (bitWordFinEquiv (Shrink.J a) e.1.1.2.1).val + let s := e.1.2.val + let u := (bitWordFinEquiv (Shrink.colors a) e.2.1).val + let h := (bitWordFinEquiv a e.2.2).val + let v := (bitWordFinEquiv g e.1.1.2.2).val + let d := 2^a + let C := 2^(Shrink.colors a) + let J := 2^(Shrink.J a) + change v + 2^g * ((h+d*u)+C*d*s+d*(C*d)*t+J*(d*(C*d))*x) = + ((((x*J+t)*d+s)*C+u)*d+h)*2^g+v + ring + +end CompressorRecords.BundleKeys + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleScan.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleScan.lean new file mode 100644 index 0000000000..63625e6834 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleScan.lean @@ -0,0 +1,249 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleRAM +import OAI.Computability.VPVNP.RAMChain +import OAI.Computability.VPVNP.RAMBuckets + +/-! +# Native scan classifying each old outgoing port + +The old port's mate selects two of the six input addresses. During the scan +these addresses and their contents agree with their values in the initial +memory. Each old port receives a bucket and a sorting key in separate output +columns. A complete scan costs nine units per old port, including the call. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- The bucket and the sorting key, respectively, in the original port order. -/ +def outAddr (p : Fin 11 → Word w) (t : Fin 2) (i : Word w) : ℕ := + (p (t.natAdd 9) + i).val + +/-- Select the bucket word or the sort-key word produced by classifying an old outgoing port. -/ +def field (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : Fin 2 → Word w := + ![bucket p m i, key p m i] + +/-- The six initial input addresses can overlap freely. Every output cell +has a unique port and column, disjoint from those input addresses. -/ +structure Regions (p : Fin 11 → Word w) (snapshot : Memory w) (N : ℕ) : Prop where + fits : N ≤ 2 ^ w + unique : ∀ (t u : Fin 2) (i j : Word w), i.val < N → j.val < N → + (outAddr p t i = outAddr p u j ↔ t = u ∧ i = j) + inputs : ∀ (c : Fin 6) (t : Fin 2) (i j : Word w), i.val < N → j.val < N → + (readAddress p snapshot i c).val ≠ outAddr p t j + +/-- Two consecutive output regions of capacity `N`. Old columns on either +side of the interval can be shared with other passes. -/ +theorem Regions.packed (p : Fin 11 → Word w) (snapshot : Memory w) {base N : ℕ} + (fit : base + 2*N ≤ 2 ^ w) (cols : ∀ t : Fin 2, (p (t.natAdd 9)).val = base+t.val*N) + (old : ∀ (c : Fin 6) (i : Word w), i.val < N → + (readAddress p snapshot i c).val < base ∨ base+2*N ≤ (readAddress p snapshot i c).val) : + Regions p snapshot N := by + have within (t : Fin 2) (i : Word w) (hi : i.val < N) : t.val*N + i.val < 2*N := by + have h := Nat.mul_le_mul_right N t.isLt + rw [Nat.succ_mul] at h + omega + have addr (t : Fin 2) (i : Word w) (hi : i.val < N) : + outAddr p t i = base + (t.val*N+i.val) := by + have h := within t i hi + rw [outAddr, Fin.val_add, cols, Nat.mod_eq_of_lt (by omega)] + omega + refine ⟨by omega, ?_, ?_⟩ + · intro t u i j hi hj + rw [addr t i hi, addr u j hj, Nat.add_left_cancel_iff] + constructor + · intro h + have he : i = j := Fin.ext ((Nat.mul_add_mod_of_lt hi (a := t.val)).symm.trans + ((congrArg (· % N) h).trans (Nat.mul_add_mod_of_lt hj))) + subst j + exact ⟨Fin.ext (Nat.eq_of_mul_eq_mul_right (by omega) (Nat.add_right_cancel h)), rfl⟩ + · rintro ⟨rfl, rfl⟩ + rfl + · intro c t i j hi hj + have hold := old c i hi + have ht := within t j hj + rw [addr t j hj] + omega + +private def store (p : Fin 11 → Word w) (snapshot m : Memory w) (i : Word w) : Memory w := + writeMemory (writeMemory m (p 9+i) (bucket p snapshot i)) (p 10+i) (key p snapshot i) + +private theorem store_other (p : Fin 11 → Word w) (snapshot m : Memory w) (i : Word w) + (addr : ℕ) (h : ∀ t : Fin 2, addr ≠ outAddr p t i) : + store p snapshot m i addr = m addr := by + have h₀ : addr ≠ (p 9+i).val := h 0 + have h₁ : addr ≠ (p 10+i).val := h 1 + simp [store, writeMemory, h₀, h₁] + +private theorem store_field {p : Fin 11 → Word w} {snapshot : Memory w} {N : ℕ} + (reg : Regions p snapshot N) (m : Memory w) (i : Word w) (hi : i.val < N) (t : Fin 2) : + store p snapshot m i (outAddr p t i) = field p snapshot i t := by + have eqv (u : Fin 2) : (outAddr p t i = outAddr p u i) ↔ t = u := by + simp only [reg.unique t u i i hi hi, and_true] + change (if outAddr p t i = outAddr p 1 i then key p snapshot i + else if outAddr p t i = outAddr p 0 i then bucket p snapshot i else _) = _ + simp only [eqv] + fin_cases t <;> rfl + +/-- The mate read alone determines the choice of input addresses. -/ +theorem readAddress_eq {p : Fin 11 → Word w} {snapshot m : Memory w} (i : Word w) + (h : m (readAddress p snapshot i 0).val = snapshot (readAddress p snapshot i 0).val) : + readAddress p m i = readAddress p snapshot i := by + change m (p 5+i).val = snapshot (p 5+i).val at h + simp only [readAddress, targetSite, h] + +private theorem events_same {p : Fin 11 → Word w} {m snapshot : Memory w} (i : Word w) + (agree : ∀ c : Fin 6, m (readAddress p snapshot i c).val = snapshot (readAddress p snapshot i c).val) : + events p m i = events p snapshot i := by + have ha := readAddress_eq i (agree 0) + have hv : readValue p m i = readValue p snapshot i := by + funext t + simpa [readValue, ha] using agree t + simp only [events, bucket, key, ha, hv] + +/-- The report sequence in increasing old-position order. Every lookup is +expressed directly in the initial external memory. -/ +def scanReports (p : Fin 11 → Word w) (snapshot : Memory w) (k : ℕ) : ℕ → List (Report w) + | 0 => [] + | n+1 => ⟨events p snapshot (Fin.ofNat _ k), some (Fin.ofNat _ (k+1))⟩ :: + scanReports p snapshot (k+1) n + +private theorem after_snapshot (p : Fin 11 → Word w) (snapshot m : Memory w) (i : Word w) : + after m (events p snapshot i) = store p snapshot m i := rfl + +private theorem after_succ (p : Fin 11 → Word w) (snapshot m : Memory w) (k n : ℕ) : + after m (eventLog (scanReports p snapshot k (n+1))) = + after (store p snapshot m (Fin.ofNat _ k)) + (eventLog (scanReports p snapshot (k+1) n)) := by + simp only [scanReports, eventLog, List.flatMap_cons, after, List.foldl_append] + rfl + +private theorem scan_native_aux {p : Fin 11 → Word w} {N : ℕ} (snapshot : Memory w) + (reg : Regions p snapshot N) (k n : ℕ) (m : Memory w) (bound : k+n ≤ N) + (agree : ∀ c i, i.val < N → m (readAddress p snapshot i c).val = snapshot (readAddress p snapshot i c).val) : + let M := (template visit 0).instantiate w p + runSegment M.program (1+visit.length) (some (Fin.ofNat _ k)) m (List.replicate n []) = + some (scanReports p snapshot k n) := by + induction n generalizing k m with + | zero => rfl + | succ n ih => + let i := Fin.ofNat (2^w) k + have hv : i.val = k := Nat.mod_eq_of_lt (by have := reg.fits; omega) + have hi : i.val < N := by omega + have hn : i+1 = Fin.ofNat (2^w) (k+1) := by + apply Fin.ext + simp [i, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + have he := events_same i (fun c ↦ agree c i hi) + have hnext := ih (k+1) (store p snapshot m i) (by omega) + (fun c j hj ↦ (store_other _ _ _ _ _ (fun t ↦ reg.inputs c t j i hj hi)).trans (agree c j hj)) + dsimp only + rw [List.replicate_succ, runSegment, visit_native p m i, he, hn] + simp only [after_snapshot, hnext, Option.map_some, scanReports, i] + +/-- The complete native segment, with no change to the six input addresses. -/ +theorem scan_native (p : Fin 11 → Word w) (N k n : ℕ) (m : Memory w) (reg : Regions p m N) + (bound : k+n ≤ N) : + let M := (template visit 0).instantiate w p + runSegment M.program (1+visit.length) (some (Fin.ofNat _ k)) m (List.replicate n []) = + some (scanReports p m k n) := + scan_native_aux m reg k n m bound (fun _ _ _ ↦ rfl) + +private theorem scan_preserve {p : Fin 11 → Word w} {N : ℕ} {snapshot : Memory w} + (reg : Regions p snapshot N) (m : Memory w) (k n addr : ℕ) (bound : k+n ≤ N) + (outside : ∀ (t : Fin 2) (i : Word w), k ≤ i.val → i.val < k+n → addr ≠ outAddr p t i) : + after m (eventLog (scanReports p snapshot k n)) addr = m addr := by + induction n generalizing k m with + | zero => rfl + | succ n ih => + let i := Fin.ofNat (2^w) k + have hv : i.val = k := Nat.mod_eq_of_lt (by have := reg.fits; omega) + rw [after_succ, ih _ (k+1) (by omega) (fun t j hj hlt ↦ outside t j (by omega) (by omega))] + exact store_other _ _ _ _ _ (fun t ↦ outside t i (by omega) (by omega)) + +private theorem scan_field {p : Fin 11 → Word w} {N : ℕ} {snapshot : Memory w} + (reg : Regions p snapshot N) (m : Memory w) (k n : ℕ) (bound : k+n ≤ N) + (t : Fin 2) (i : Word w) (hi : k ≤ i.val) (hi' : i.val < k+n) : + after m (eventLog (scanReports p snapshot k n)) (outAddr p t i) = field p snapshot i t := by + induction n generalizing k m with + | zero => omega + | succ n ih => + rw [after_succ] + rcases eq_or_lt_of_le hi with he | he + · have hv : Fin.ofNat (2^w) k = i := Fin.ext (by simp [he]) + rw [hv] + rw [scan_preserve reg _ _ _ _ (by omega)] + · exact store_field reg _ i (by omega) t + · intro u j hj hlt h + have hij := ((reg.unique t u i j (by omega) (by omega)).mp h).2 + subst j + omega + · exact ih _ _ (by omega) (by omega) (by omega) + +/-- The returned registers, external work and complete memory contents of a +bundle scan, including the untouched portion of each output column. -/ +structure ScanResult (p : Fin 11 → Word w) (N k n : ℕ) (m : Memory w) (rs : List (Report w)) : Prop where + endCursor : endState (some (Fin.ofNat _ k)) rs = some (Fin.ofNat _ (k+n)) + calls : rs.length = n + work : ∀ r ∈ rs, r.events.length = visit.length ∧ countProbes r.events = 8 + cost : RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = 9*n + readback : ∀ (t : Fin 2) (i : Word w), k ≤ i.val → i.val < k+n → + after m (eventLog rs) (outAddr p t i) = field p m i t + preserve : ∀ addr, (∀ (t : Fin 2) (i : Word w), k ≤ i.val → i.val < k+n → addr ≠ outAddr p t i) → + after m (eventLog rs) addr = m addr + inputs : ∀ (c : Fin 6) (i : Word w), i.val < N → + after m (eventLog rs) (readAddress p m i c).val = m (readAddress p m i c).val + +private theorem scan_accounting (p : Fin 11 → Word w) (m : Memory w) (k n : ℕ) : + let rs := scanReports p m k n + endState (some (Fin.ofNat _ k)) rs = some (Fin.ofNat _ (k+n)) ∧ rs.length = n ∧ + (∀ r ∈ rs, r.events.length = visit.length ∧ countProbes r.events = 8) ∧ + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = 9*n := by + induction n generalizing k with + | zero => exact ⟨rfl, rfl, by simp [scanReports], rfl⟩ + | succ n ih => + obtain ⟨hend,hlen,hwork,hcost⟩ := ih (k+1) + refine ⟨?_, ?_, ?_, ?_⟩ + · rw [scanReports, endState, hend] + congr 2 + omega + · simp only [scanReports, List.length_cons, hlen] + · intro r hr + rcases List.mem_cons.mp hr with rfl | h + · exact events_work p m _ + · exact hwork r h + · rw [scanReports, RAMBuckets.cost, (events_work p m _).2, hcost, Nat.mul_succ] + omega + +/-- Execute the whole interval from its initial memory. Every one of the +two output columns agrees with the classification computed from the six +original input values. -/ +theorem scan_run (p : Fin 11 → Word w) (N k n : ℕ) (m : Memory w) (regions : Regions p m N) + (bound : k+n ≤ N) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program (1+visit.length) (some (Fin.ofNat _ k)) m (List.replicate n []) = some rs ∧ + ScanResult p N k n m rs := by + obtain ⟨he,hl,hw,hc⟩ := scan_accounting p m k n + refine ⟨scanReports p m k n, scan_native p N k n m regions bound, he, hl, hw, hc, + scan_field regions m k n bound, fun addr ↦ scan_preserve regions m k n addr bound, ?_⟩ + intro c i hi + apply scan_preserve regions m k n _ bound + exact fun t j _ hlt ↦ regions.inputs c t i j hi (hlt.trans_le bound) + +/-- Following a stored mate after the scan selects the same destination +cells as following it before the scan. -/ +theorem ScanResult.readAddress_stable {p : Fin 11 → Word w} {N k n : ℕ} {m : Memory w} {rs} + (r : ScanResult p N k n m rs) (i : Word w) (hi : i.val < N) : + readAddress p (after m (eventLog rs)) i = readAddress p m i := + readAddress_eq i (r.inputs 0 i hi) + +end CompressorRecords.BundleRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleWidthScatter.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleWidthScatter.lean new file mode 100644 index 0000000000..e4f517ff66 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleWidthScatter.lean @@ -0,0 +1,316 @@ +import OAI.Computability.VPVNP.CompressorRecordsPortRankScan +import OAI.Computability.VPVNP.CompressorRecordsBundleLists + +/-! +# Sorting the old widths by absolute bundle and rank + +One burst call per old outgoing port reads its bucket, its rank, and its width. +It copies the width directly into that rank of the corresponding bundle row. +Each row is visited in old-port scan order but is stored in sorted key order. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleWidthScatter + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.PackingData BundleLists + +variable {w : ℕ} + +/-- The scatter worker reads one old port's bucket, rank, and width, stores the width in the +ranked bundle row, and advances the cursor. -/ +def visit : List (Op 7 5) := + [.stateWord 0, .publicWord 1 0, .binary .add 1 1 0, .read 2 1, + .publicWord 1 1, .binary .add 1 1 0, .read 3 1, + .publicWord 1 2, .binary .add 1 1 0, .read 4 1, + .publicWord 1 3, .binary .mul 2 2 1, .publicWord 1 4, .binary .add 2 1 2, + .binary .add 2 2 3, .write 2 4, .constant 1 1, .binary .add 0 0 1] + +/-- Address of the current old port in one of the three input columns for bucket, rank, and +width. -/ +def source (p : Fin 5 → Word w) (t : Fin 3) (i : Word w) : Word w := + p (t.castAdd 2)+i + +/-- Address of the width's destination, determined by the port's bucket, the public row stride, +and its rank. -/ +def outAddress (p : Fin 5 → Word w) (m : Memory w) (i : Word w) : Word w := + p 4 + m (source p 0 i).val * p 3 + m (source p 1 i).val + +/-- Read the width of the current old port from the third input column. -/ +def width (p : Fin 5 → Word w) (m : Memory w) (i : Word w) : Word w := m (source p 2 i).val + +/-- The ticks, three input reads, and single width write made by one scatter visit. -/ +def events (p : Fin 5 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + let read (t : Fin 3) := Event.read (source p t i) (m (source p t i).val) + [.tick,.tick,.tick,read 0,.tick,.tick,read 1,.tick,.tick,read 2, + .tick,.tick,.tick,.tick,.tick,.write (outAddress p m i) (width p m i),.tick,.tick] + +theorem native (p : Fin 5 → Word w) (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program 19 (M.program.start i) m [] = some ⟨events p m i,some (i+1)⟩ := by + change execute ((template visit 0).instantiate w p).program (1+visit.length) + ⟨_,i,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + rw [execute_template, run_eq_trace] + rfl + +/-- Represent a natural scan index as a machine word of the scatter worker's width. -/ +abbrev word (j : ℕ) : Word w := Fin.ofNat _ j + +/-- Exactly the occupied width cells of the scanned prefix have been written. -/ +structure Filled (p : Fin 5 → Word w) (initial m : Memory w) (k : ℕ) + (payload : Word w → Word w → Word w := fun _ x ↦ x) : Prop where + readback : ∀ j < k, m (outAddress p initial (word j)).val = payload (word j) (width p initial (word j)) + frame : ∀ a, (∀ j < k, a ≠ (outAddress p initial (word j)).val) → m a = initial a + +/-- The input cells are disjoint from all scatter destinations, and distinct live ports have +distinct destinations. -/ +structure Regions (p : Fin 5 → Word w) (initial : Memory w) (A : ℕ) : Prop where + apart : ∀ t j, j < A → ∀ l < A, (source p t (word j)).val ≠ (outAddress p initial (word l)).val + unique : ∀ j < A, ∀ l < A, outAddress p initial (word j) = outAddress p initial (word l) → j = l + +private theorem filled_step {p : Fin 5 → Word w} {initial m : Memory w} {k A : ℕ} + {payload : Word w → Word w → Word w} (reg : Regions p initial A) + (prior : Filled p initial m k payload) (hk : k < A) : + Filled p initial (writeMemory m (outAddress p m (word k)) + (payload (word k) (width p m (word k)))) (k+1) payload := by + have read (t : Fin 3) : m (source p t (word k)).val = initial (source p t (word k)).val := + prior.frame _ (fun j hj ↦ reg.apart t k hk j (hj.trans hk)) + have ha : outAddress p m (word k) = outAddress p initial (word k) := by simp only [outAddress, read] + have hw : width p m (word k) = width p initial (word k) := read 2 + rw [ha,hw] + constructor + · intro j hj + by_cases he : j = k + · simp [he,writeMemory] + · have hne : (outAddress p initial (word j)).val ≠ (outAddress p initial (word k)).val := + fun h ↦ he (reg.unique j (by omega) k hk (Fin.ext h)) + simpa only [writeMemory, ite_eq_right hne] using prior.readback j (by omega) + · intro a outside + rw [writeMemory, ite_eq_right (outside k (by omega))] + exact prior.frame _ (fun j hj ↦ outside j (by omega)) + +/-- Scatter a word computed from the port index and the third input column. +All workers using this layout share the same address, frame and cost proof. -/ +theorem scatter_values {C : Type*} (program : Program w C) (fuel ticks : ℕ) + (p : Fin 5 → Word w) (initial : Memory w) (A : ℕ) (reg : Regions p initial A) + (payload : Word w → Word w → Word w) + (worker : ∀ (mem : Memory w) (i : Word w), ∃ es, + execute program fuel (program.start i) mem [] = some ⟨es,some (i+1)⟩ ∧ + after mem es = writeMemory mem (outAddress p mem i) (payload i (width p mem i)) ∧ + es.length = ticks ∧ countProbes es = 4) : + ∃ rs, runSegment program fuel (some 0) initial (List.replicate A []) = some rs ∧ + endState (some 0) rs = some (word A) ∧ Filled p initial (after initial (eventLog rs)) A payload ∧ + rs.length = A ∧ (∀ r ∈ rs, r.events.length = ticks ∧ r.probes = 4) ∧ RAMBuckets.cost Report.probes rs = 5*A := by + have aux (n k : ℕ) (m : Memory w) (prior : Filled p initial m k payload) (hk : k+n ≤ A) : + ∃ rs, runSegment program fuel (some (word k)) m (List.replicate n []) = some rs ∧ + endState (some (word k)) rs = some (word (k+n)) ∧ Filled p initial (after m (eventLog rs)) (k+n) payload ∧ + rs.length = n ∧ (∀ r ∈ rs, r.events.length = ticks ∧ r.probes = 4) ∧ RAMBuckets.cost Report.probes rs = 5*n := by + induction n generalizing k m with + | zero => exact ⟨[],rfl,rfl,prior,rfl,by simp,rfl⟩ + | succ n ih => + obtain ⟨es,he,hm,hl,hp⟩ := worker m (word k) + let r : Report w := ⟨es,some (word k+1)⟩ + have hn : word (w := w) k+1 = word (k+1) := by + apply Fin.ext + simp [word, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + have eqn : (k+1)+n = k+(n+1) := by omega + have next : Filled p initial (after m es) (k+1) payload := hm ▸ filled_step reg prior (by omega) + obtain ⟨rs,hr,hs,hf,hlen,hw,hc⟩ := ih (k+1) (after m es) next (by omega) + refine ⟨r::rs, ?_, ?_, ?_, by simp [hlen], ?_, ?_⟩ + · rw [List.replicate_succ, runSegment, he, hn] + simpa only [r, hn, Option.map_some] using congrArg (Option.map (r :: ·)) hr + · change endState (some (word k+1)) rs = _ + rw [hn,hs,eqn] + · change Filled p initial ((es ++ eventLog rs).foldl BurstRAM.update m) _ payload + rw [List.foldl_append, ← eqn]; exact hf + · intro s h + rcases List.mem_cons.mp h with rfl | h + · exact ⟨hl,hp⟩ + · exact hw s h + · rw [RAMBuckets.cost, show r.probes = 4 from hp, hc, Nat.mul_succ]; omega + simpa only [word, Fin.ofNat_zero, Nat.zero_add] using aux A 0 initial ⟨by simp, fun _ _ ↦ rfl⟩ (by omega) + +/-- Complete native scatter, with a frame also covering holes inside the rectangle. -/ +theorem run (p : Fin 5 → Word w) (initial : Memory w) (A : ℕ) (reg : Regions p initial A) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 19 (some 0) initial (List.replicate A []) = some rs ∧ + endState (some 0) rs = some (word A) ∧ Filled p initial (after initial (eventLog rs)) A ∧ + rs.length = A ∧ (∀ r ∈ rs, r.events.length = 18 ∧ r.probes = 4) ∧ RAMBuckets.cost Report.probes rs = 5*A := by + apply scatter_values _ _ _ p initial A reg (fun _ x ↦ x) + exact fun m i ↦ ⟨events p m i,native p m i,rfl,rfl,rfl⟩ + +variable {V H Tag L : Type} {d c n A : ℕ} +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) (cd : P.BundleNumbering) (dd : P.ThickNumbering) + +/-- Each old arc belongs to exactly one of the two finite fibers, numbered by +the piece order for CD and the concatenation order for DD. -/ +def fiberNumber : (b : Bucket V Tag L d) → {a // bucketOf P a = b} ≃ Fin (rowLength (c := c) b) + | .inl b => (thickEquiv P b).trans (dd b) + | .inr b => (motifEquiv P b).trans (cd b) + +/-- The arc's position in its assigned bucket under the supplied ordering of CD motifs or thick +wires. -/ +def rankOf (a : Arc V H Tag L d c) : ℕ := + (fiberNumber P cd dd (bucketOf P a) ⟨a,rfl⟩).val + +private theorem rank_at {a : Arc V H Tag L d c} {b} (ha : bucketOf P a = b) : + rankOf P cd dd a = (fiberNumber P cd dd b ⟨a,ha⟩).val := by subst b; rfl + +theorem rank_thick {b : Port V Tag L d} (x : P.ThickFiber b) : + rankOf P cd dd x.1.1 = (dd b x).val := by + rw [rank_at P cd dd ((bucketOf_thick P x.1).trans (congrArg Sum.inl x.2))] + rfl + +theorem rank_motif {b : Port V Tag L d} (x : P.MotifFiber b) : + rankOf P cd dd x.1.1 = (cd b x).val := by + rw [rank_at P cd dd ((bucketOf_motif P x.1).trans (congrArg Sum.inr x.2))] + rfl + +private theorem arc_eq_of_rank {a a' : Arc V H Tag L d c} + (h : bucketOf P a = bucketOf P a') (r : rankOf P cd dd a = rankOf P cd dd a') : a = a' := by + rw [rank_at P cd dd h, rank_at P cd dd (a := a') rfl] at r + exact congrArg Subtype.val ((fiberNumber P cd dd _).injective (Fin.ext r)) + +variable (arcs : Arc V H Tag L d c ≃ Fin A) (site : Site V Tag L ≃ Fin n) + +/-- Absolute old-port identifier, shared by the width, rank, and owner columns. -/ +abbrev arcWord (a : Arc V H Tag L d c) : Word w := word (arcs a).val + +/-- Contents of the three columns consumed by the width scatter. -/ +structure RankedInput (p : Fin 5 → Word w) (m : Memory w) (old : Arc V H Tag L d c → ℕ) : Prop where + owners : ∀ a, m (source p 0 (arcWord arcs a)).val = word (bucketIndex site (bucketOf P a)).val + ranks : ∀ a, m (source p 1 (arcWord arcs a)).val = word (rankOf P cd dd a) + widths : ∀ a, (m (source p 2 (arcWord arcs a)).val).val = old a + +/-- Both sets of rows share a stride. The three input arrays can occupy any +intervals disjoint from the output rectangle. -/ +structure Layout (p : Fin 5 → Word w) (A n d c : ℕ) : Prop where + slots : pieceCount d c ≤ (p 3).val + bucketsFit : n*d+n*d ≤ 2^w + sourceFits : ∀ t : Fin 3, (p (t.castAdd 2)).val+A ≤ 2^w + rectangle : (p 4).val+(n*d+n*d)*(p 3).val ≤ 2^w + apart : ∀ t : Fin 3, (p (t.castAdd 2)).val+A ≤ (p 4).val ∨ + (p 4).val+(n*d+n*d)*(p 3).val ≤ (p (t.castAdd 2)).val + +private theorem slot_lt {p : Fin 5 → Word w} (layout : Layout p A n d c) + (a : Arc V H Tag L d c) : rankOf P cd dd a < (p 3).val := by + apply (fiberNumber P cd dd _ ⟨a,rfl⟩).isLt.trans_le + apply le_trans _ layout.slots + cases bucketOf P a with + | inl b => change 2^c*d/4 ≤ 3*(2^c*d)/4; omega + | inr b => rfl + +private def offset (site : Site V Tag L ≃ Fin n) (stride : ℕ) (a : Arc V H Tag L d c) : ℕ := + (bucketIndex site (bucketOf P a)).val * stride + rankOf P cd dd a + +private theorem offset_lt {p : Fin 5 → Word w} (layout : Layout p A n d c) + (a : Arc V H Tag L d c) : offset P cd dd site (p 3).val a < (n*d+n*d)*(p 3).val := by + have hb := Nat.mul_le_mul_right (p 3).val (bucketIndex site (bucketOf P a)).isLt + rw [Nat.succ_mul] at hb + have hs := slot_lt P cd dd layout a + dsimp [offset] + omega + +theorem output_eq {p : Fin 5 → Word w} {initial : Memory w} {old : Arc V H Tag L d c → ℕ} + (layout : Layout p A n d c) (h : RankedInput P cd dd arcs site p initial old) + (a : Arc V H Tag L d c) : (outAddress p initial (arcWord arcs a)).val = + (p 4).val + offset P cd dd site (p 3).val a := by + rw [outAddress,h.owners,h.ranks] + have hs := slot_lt P cd dd layout a + have fit := layout.rectangle + have bound := offset_lt P cd dd site layout a + dsimp [offset] at bound ⊢ + rw [Fin.val_add, Fin.val_add, Fin.val_mul, Fin.val_natCast, Fin.val_natCast, + Nat.mod_eq_of_lt ((bucketIndex site _).isLt.trans_le layout.bucketsFit), + Nat.mod_eq_of_lt (hs.trans (p 3).isLt), Nat.mod_add_mod, Nat.mod_eq_of_lt (show (bucketIndex site (bucketOf P a)).val * (p 3).val < 2^w by omega), Nat.mod_eq_of_lt (by omega)] + omega + +private theorem offset_inj {p : Fin 5 → Word w} (layout : Layout p A n d c) : + Function.Injective (offset P cd dd site (p 3).val) := by + intro a a' he + have h := slot_lt P cd dd layout a + have h' := slot_lt P cd dd layout a' + unfold offset at he + have hr := congrArg (· % (p 3).val) he + rw [Nat.mul_add_mod_of_lt h,Nat.mul_add_mod_of_lt h'] at hr + rw [hr, Nat.add_right_cancel_iff] at he + have hq := Nat.eq_of_mul_eq_mul_right (Nat.zero_lt_of_lt h) he + exact arc_eq_of_rank P cd dd ((bucketIndex site).injective (Fin.ext hq)) hr + +theorem regions_of_layout {p : Fin 5 → Word w} {initial : Memory w} {old : Arc V H Tag L d c → ℕ} + (layout : Layout p A n d c) (h : RankedInput P cd dd arcs site p initial old) : Regions p initial A := by + have eqv (j : ℕ) (hj : j < A) : + (outAddress p initial (word j)).val = (p 4).val + offset P cd dd site (p 3).val (arcs.symm ⟨j,hj⟩) := by + simpa [arcWord] using output_eq P cd dd arcs site layout h (arcs.symm ⟨j,hj⟩) + constructor + · intro t j hj l hl + have ht := layout.sourceFits t + have hr := offset_lt P cd dd site layout (arcs.symm ⟨l,hl⟩) + rw [eqv l hl, source, Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)] + rcases layout.apart t with hs | hs <;> omega + · intro j hj l hl e + have he := congrArg Fin.val e + rw [eqv j hj, eqv l hl, Nat.add_left_cancel_iff] at he + have ha := offset_inj P cd dd site layout he + exact congrArg Fin.val (arcs.symm.injective ha) + +/-- First width word of a chosen absolute bundle. -/ +def rowBase (p : Fin 5 → Word w) (site : Site V Tag L ≃ Fin n) (b : Bucket V Tag L d) : Word w := + p 4 + word (bucketIndex site b).val * p 3 + +omit [AddCommGroup Tag] [AddCommGroup L] in +theorem rowBase_val {p : Fin 5 → Word w} (layout : Layout p A n d c) + (b : Bucket V Tag L d) : + (rowBase p site b).val = (p 4).val + (bucketIndex site b).val*(p 3).val := by + have he := Nat.mul_le_mul_right (p 3).val (bucketIndex site b).isLt + rw [Nat.succ_mul] at he + have hf := layout.rectangle + rw [rowBase, Fin.val_add, Fin.val_mul, Fin.val_ofNat, Nat.mod_eq_of_lt ((bucketIndex site b).isLt.trans_le + layout.bucketsFit), Nat.add_mod_mod] + apply Nat.mod_eq_of_lt + by_cases hz : (p 3).val = 0 + · simp [hz] + · omega + +/-- Scattering directly from the absolute-port rank and width columns yields +the sorted concatenation at both bundle ends and the CD piece widths in their +own order. The scan consumes exactly five calls-plus-probes units per old port. -/ +theorem graph_run (p : Fin 5 → Word w) (initial : Memory w) (old : Arc V H Tag L d c → ℕ) + (layout : Layout p A n d c) (h : RankedInput P cd dd arcs site p initial old) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 19 (some 0) initial (List.replicate A []) = some rs ∧ + endState (some 0) rs = some (word A) ∧ Filled p initial (after initial (eventLog rs)) A ∧ + rs.length = A ∧ (∀ r ∈ rs, r.events.length = 18 ∧ r.probes = 4) ∧ RAMBuckets.cost Report.probes rs = 5*A ∧ + (∀ b i, (after initial (eventLog rs) ((rowBase p site (.inl b)).val+i.val)).val = + old ((dd b).symm i).1.1) ∧ + (∀ b i, (after initial (eventLog rs) ((rowBase p site (.inr b)).val+i.val)).val = + old ((cd b).symm i).1.1) := by + obtain ⟨rs,hr,hc,hf,hl,hw,cost⟩ := run p initial A (regions_of_layout P cd dd arcs site layout h) + have atArc (a : Arc V H Tag L d c) : + (after initial (eventLog rs) ((rowBase p site (bucketOf P a)).val + rankOf P cd dd a)).val = old a := by + have he := output_eq P cd dd arcs site layout h a + rw [rowBase_val site layout] + rw [show (p 4).val + (bucketIndex site (bucketOf P a)).val*(p 3).val + rankOf P cd dd a = + (outAddress p initial (arcWord arcs a)).val by rw [he]; exact Nat.add_assoc ..] + rw [hf.readback (arcs a).val (arcs a).isLt] + exact h.widths a + refine ⟨rs,hr,hc,hf,hl,hw,cost,?_,?_⟩ + · intro b i + let x := (dd b).symm i + have he := atArc x.1.1 + rw [bucketOf_thick P x.1, x.2, rank_thick P cd dd x] at he + simpa only [x, Equiv.apply_symm_apply] using he + · intro b i + let x := (cd b).symm i + have he := atArc x.1.1 + rw [bucketOf_motif P x.1, x.2, rank_motif P cd dd x] at he + simpa only [x, Equiv.apply_symm_apply] using he + +end CompressorRecords.BundleWidthScatter + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsBundleWords.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleWords.lean new file mode 100644 index 0000000000..2f4da809b8 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsBundleWords.lean @@ -0,0 +1,102 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleRAM +import OAI.Computability.VPVNP.CompressorRecordsBundleKeys + +/-! +# Exact bundle keys from the native classifier + +An old physical site ends in a tag and a residual lane. Successive word +quotients separate those digits without multiplying their radices in a word. +The old outgoing port is a further least-significant digit. The resulting +keys agree with the thick-fiber and motif numbering of the compressor. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleRAM + +open BurstRAM Compression +open ShrinkRAM (div mod select) +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- The binary radices are exact for digit decoding. The bucket offset +enters only sums and products, so its word encoding suffices. -/ +structure Params (p : Fin 11 → Word w) (a c j g numBundles : ℕ) : Prop where + degree : (p 0).val = 2^a + residual : (p 1).val = 2^g + tag : (p 2).val = 2^j + mask : (p 3).val = 2^c + offset : p 4 = (numBundles : Word w) + +private theorem of_val {x : Word w} {n : ℕ} (h : x.val = n) : x = (n : Word w) := by + subst n + exact Fin.ext (Nat.mod_eq_of_lt x.isLt).symm + +private theorem div_val (x y : Word w) : (div x y).val = x.val / y.val := + Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt) + +private theorem mod_val (x y : Word w) : (mod x y).val = x.val % y.val := + Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt) + +theorem decode_exact {p : Fin 11 → Word w} {a c j g B : ℕ} + (hp : Params p a c j g B) (i : Word w) : + let f := Shrink.decode a c (j+g) (i.val / 2^a) + decode p i = ⟨(f.base : Word w), (f.low / 2^g : ℕ), (i.val % 2^a : ℕ), + (f.mask : Word w), (f.slot : Word w)⟩ := by + have q (x : ℕ) : x / 2^g / 2^j = x / 2^(j+g) := by + rw [Nat.div_div_eq_div_mul, pow_add, Nat.mul_comm (2^j)] + have t (x : ℕ) : x / 2^g % 2^j = x % 2^(j+g) / 2^g := by + rw [pow_add, Nat.mod_mul_left_div_self] + dsimp only [decode, Shrink.decode] + congr 1 <;> apply of_val <;> + simp only [div_val, mod_val, hp.degree, hp.residual, hp.tag, hp.mask, q, t] + +/-- The five shrinking values the classifier reads from its old source and +destination. The destination index is obtained by its first, actual-mate read. -/ +structure ReadsPlacement (p : Fin 11 → Word w) (m : Memory w) (i : Word w) + (src dst : Shrink.Row ℕ) : Prop where + srcThick : readValue p m i 1 = (src.thick.toNat : Word w) + dstThick : readValue p m i 2 = (dst.thick.toNat : Word w) + owner : readValue p m i 3 = (src.owner : Word w) + srcAssigned : readValue p m i 4 = (src.assigned : Word w) + dstAssigned : readValue p m i 5 = (dst.assigned : Word w) + +/-- The emitted words encode the combined bucket and its numerical sorting key, +with the layout and the two endpoint rows supplied by the previous pass. -/ +theorem classify_rows {p : Fin 11 → Word w} {a c j g B : ℕ} (hp : Params p a c j g B) + {m : Memory w} {i : Word w} {src dst : Shrink.Row ℕ} (hr : ReadsPlacement p m i src dst) : + let f := Shrink.decode a c (j+g) (i.val / 2^a) + let slot := i.val % 2^a + bucket p m i = (BundleKeys.bucketFromRows B (2^a) slot src dst : Word w) ∧ + key p m i = (BundleKeys.numericKey (2^a) (2^j) (2^c) f.base (f.low / 2^g) slot f.mask + f.slot (src.thick && dst.thick) : Word w) := by + dsimp only [bucket, key] + rw [decode_exact hp, hr.srcThick, hr.dstThick, hr.owner, hr.srcAssigned, hr.dstAssigned, + hp.offset, of_val hp.degree, of_val hp.tag, of_val hp.mask] + cases hs : src.thick <;> cases hd : dst.thick <;> + simp [BundleKeys.bucketFromRows, BundleKeys.numericBucket, BundleKeys.numericKey, hs, hd] + +/-- The persistent index of a typed old arc gives the same source site and +outgoing port to the native classifier and to the two fiber orders. -/ +theorem classify_oldArc {V : Type} {n a g : ℕ} (order : V ≃ Fin n) + {p : Fin 11 → Word w} (hp : Params p a (Shrink.colors a) (Shrink.J a) g (BundleKeys.numBundles n a g)) + (e : BundleKeys.OldArc V a g) {i : Word w} (hi : i.val = (BundleKeys.oldArcOrder order e).val) + {m : Memory w} {src dst : Shrink.Row ℕ} (hr : ReadsPlacement p m i src dst) : + bucket p m i = (BundleKeys.bucketFromRows (BundleKeys.numBundles n a g) (2^a) e.1.2.val src dst : Word w) ∧ + key p m i = (BundleKeys.keyAt order (src.thick && dst.thick) e : Word w) := by + obtain ⟨hb, hk⟩ := classify_rows hp hr + rw [BundleKeys.oldArcOrder_val] at hi + have hs : i.val % 2^a = e.1.2.val := hi ▸ Nat.mul_add_mod_of_lt e.1.2.isLt + have hv : i.val / 2^a = Shrink.oldNumber order (sourcePosition e) := by + rw [hi, Nat.mul_comm, Nat.mul_add_div (Nat.two_pow_pos _), Nat.div_eq_of_lt e.1.2.isLt, Nat.add_zero] + rw [hs, hv] at hk + exact ⟨hs ▸ hb, hk⟩ + +end CompressorRecords.BundleRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsChosenGeometry.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsChosenGeometry.lean new file mode 100644 index 0000000000..f7523e350a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsChosenGeometry.lean @@ -0,0 +1,123 @@ +import OAI.Computability.VPVNP.CompressorRecordsTermLayout +import OAI.Computability.VPVNP.CompressorRecordsSelectedFinish + +/-! +# Shrinking geometry after an admitted native term stream + +The term pass writes each CD motif's grid row, repetition count and eight payload +widths. Its post-memory goes directly into the comparison, chosen placement, +absolute role scan, and bounded preimage builder. All previously written term rows +remain accessible at their original motif ordinals throughout. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ChosenGeometry + +open Compression BurstRAM ShrinkMotif SelectedArena +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) +variable (dense term stride selectors : Word w) (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) +variable (cap : ℕ) (s : SelectedScore.Selection B X) (before : Memory w) (terms : List (Report w)) + +/-- The post-term reports of this level, with both the selected layout and child lists. -/ +structure Construction (w : ℕ) where + /-- The score, placement, and role passes executed on the memory containing the admitted term + rows. -/ + placed : SelectedStage.Passes w + /-- The passes that clear and collect the child preimages of the chosen placement. -/ + children : SelectedFinish.Passes w + +/-- The memory after applying the placement passes and then the child-preimage passes to the +term pass's output. -/ +def Construction.final (r : Construction w) (m : Memory w) := r.children.final (r.placed.final m) + +/-- The chronological reports of placement followed by the child-directory clearing and +collection scans. -/ +def Construction.reports (r : Construction w) := r.placed.all ++ (r.children.clear ++ r.children.collect) + +/-- Execution and readback evidence for constructing the chosen geometry from the admitted +terms, including probe and scan costs. -/ +structure Run (r : Construction w) : Prop where + placed : SelectedStage.Execution X term stride selectors p₀ T (after before (eventLog terms)) r.placed + selected : SelectedStage.Stored B X term stride p₀ s (after before (eventLog terms)) r.placed + geometry : SelectedFinish.Built B X term stride selectors p₀ s (after before (eventLog terms)) r.placed r.children + scores : r.placed.scores.length = 8*motifs X+2 + scoreProbes : RAMBuckets.probeCount Report.probes r.placed.scores = 32*motifs X+5 + placementCost : RAMBuckets.cost Report.probes r.placed.positions = 9*positions X + roleCost : RAMBuckets.cost Report.probes r.placed.roles = 11*DemandRAM.oldCount X + +theorem Construction.replay (r : Construction w) (m : Memory w) : + after m (eventLog r.reports) = r.final m := by + rw [Construction.reports,eventLog,List.flatMap_append,after,List.foldl_append] + change after (after m (eventLog r.placed.all)) (eventLog (r.children.clear++r.children.collect)) = _ + rw [SelectedStage.Passes.all_after,SelectedFinish.Passes.after_append] + rfl + +theorem Run.charge (r : Construction w) (h : Run B X term stride selectors p₀ T s before terms r) : + RAMBuckets.cost Report.probes r.reports = (40*motifs X+7) + 9*positions X + 11*DemandRAM.oldCount X + + (2*ShrinkPreimages.newCount X+5*ShrinkPreimages.oldCount X) := by + simp only [Construction.reports,SelectedStage.Passes.all,RAMBuckets.cost_append] + rw [RAMBuckets.cost_eq_length_add_probes _ r.placed.scores,h.scores,h.scoreProbes,h.placementCost,h.roleCost, + ← RAMBuckets.cost_append,h.geometry.raw.cost] + omega + +/-- The original admitted term rows can be read after the last preimage call. -/ +theorem Run.fields (r : Construction w) (h : Run B X term stride selectors p₀ T s before terms r) + (u : X.packingData.Motif) : + TermRecordScan.Fields B.shrink ShrinkSliceArrays.supplyRoles demandMass_pos + (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth u) (s u).val + (ShrinkTermSelection.rowBase X term stride.val u) (r.final (after before (eventLog terms))) := by + let j := (ShrinkMotifOrder.entries X).symm u + let L := scoreTables X term stride selectors + have hrow := h.geometry.terms j + have hr : (SelectedScore.motifOrder X).entries j = u := (ShrinkMotifOrder.entries X).apply_symm_apply u + have hb : SelectedScore.headAt X L j = ShrinkTermSelection.rowBase X term stride.val u := by + dsimp only [SelectedScore.headAt,TermScores.rowBase,ShrinkTermSelection.rowBase] + change term + (j.val : Word w)*stride = ((term.val + (ShrinkMotifOrder.stateNumber X u).val * stride.val : ℕ) : Word w) + rw [← ShrinkMotifOrder.entries_ordinal] + have hterm : (term.val : Word w) = term := Fin.ext (Nat.mod_eq_of_lt term.isLt) + have hstride : (stride.val : Word w) = stride := Fin.ext (Nat.mod_eq_of_lt stride.isLt) + simp [hterm,hstride,j] + change TermRecordScan.Fields B.shrink SelectedScore.supplyOrder.entries demandMass_pos + (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth ((SelectedScore.motifOrder X).entries j)) + (s ((SelectedScore.motifOrder X).entries j)).val (SelectedScore.headAt X L j) + (r.final (after before (eventLog terms))) at hrow + rw [hr,hb] at hrow + exact hrow + +theorem build {first : Bool} (hp : ShrinkRAM.Params p₀ a (Shrink.colors a) (Shrink.J a) g first) + (written : ShrinkTermSelection.Written B.shrink X dense term stride.val cap s before terms) + (dir : let m := after before (eventLog terms) + Shrink.Directory X.slots X.baseIndex (ShrinkRAM.column p₀ m 6) (ShrinkRAM.column p₀ m 7) + (ShrinkRAM.column p₀ m 8) (ShrinkRAM.column p₀ m 9)) + (inc : T.ActualColumns X (after before (eventLog terms))) (old : OldInputs X term stride p₀ T) + (hI : T.actualIn.val+DemandRAM.oldCount X ≤ origin X term stride) + (hW : T.width.val+DemandRAM.oldCount X ≤ origin X term stride) + (wide : 10 ≤ stride.val) (room : SelectedFinish.stop X term stride ≤ 2^w) + (hw : ∀ t, MotifAdmission.weight relativeMass t < 2^w) (hs : selectors.val=B.shrink.selectorBits) + (scoreFit : ∀ l, layoutScore relativeMass (X.packingData.termWidths B.shrink X.shrinkNumber X.packingWidth s) l < 2^w) : + ∃ r : Construction w, Run B X term stride selectors p₀ T s before terms r := by + let L := scoreTables X term stride selectors + let m := after before (eventLog terms) + have hterms : SelectedScore.Stored B X s (SelectedScore.headAt X L) m := + SelectedScore.stored_of_term_run B X L dense cap s before terms written + have hpos : 0 < ShrinkPreimages.oldCount X := Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos _) + have fit : Fits X term stride := by + change endAddr X term stride + ShrinkPreimages.newCount X + ShrinkPreimages.oldCount X ≤ 2^w at room + change endAddr X term stride < 2^w + omega + obtain ⟨p,hep,hgp,hsc,hsp,hposc,hrole⟩ := SelectedStage.run B X term stride selectors p₀ T s m + hterms dir inc old hI hW hp wide fit hw hs scoreFit + obtain ⟨q,hq⟩ := SelectedFinish.build B X term stride selectors p₀ s m p hgp hterms wide room + exact ⟨⟨p,q⟩,⟨hep,hgp,hq,hsc,hsp,hposc,hrole⟩⟩ + +end CompressorRecords.ChosenGeometry + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsController.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsController.lean new file mode 100644 index 0000000000..5f3e6f9e70 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsController.lean @@ -0,0 +1,517 @@ +import OAI.Computability.VPVNP.CompressorRecordFrame +import OAI.Computability.VPVNP.RAMRecords + +/-! +# Native controller for the compressor's directory of stages + +Each directory row contains a worker tag, initial and exclusive final cursors, +and a padded bank of public operands. The controller snapshots the row before +writing the active frame. Its five public words are the frame base, directory +base, ordinal cell, row-count cell, and dispatch-tag cell. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Controller + +open BurstRAM BurstRAM.PrivateRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Number of controller instruction addresses, including six load-and-store instructions for +each of the stop word and padded operand slots. -/ +abbrev PCs (g : ℕ) := 21 + (g+1)*6 +/-- Number of controller registers, including a snapshot register for the stop word and each +padded public operand. -/ +abbrev Regs (g : ℕ) := 10 + (g+1) + +private abbrev Label (g : ℕ) := Fin 21 ⊕ (Fin (g+1) × Fin 6) +private def labels (g : ℕ) : Label g ≃ Fin (PCs g) := + ((Equiv.refl _).sumCongr finProdFinEquiv).trans finSumFinEquiv + +private def head (g : ℕ) (i : Fin 21) := labels g (.inl i) +private def slot {g : ℕ} (j : Fin (g+1)) (i : Fin 6) := labels g (.inr (j,i)) +private def reg (g : ℕ) (i : Fin 10) : Fin (Regs g) := i.castAdd (g+1) +private def bank {g : ℕ} (j : Fin (g+1)) : Fin (Regs g) := j.natAdd 10 +private def storePC (g i : ℕ) := if h : i < g+1 then slot ⟨i,h⟩ 3 else head g 17 +private def loadPC (g i : ℕ) := if h : i < g+1 then slot ⟨i,h⟩ 0 else storePC g 0 +private def width (g : ℕ) := Nat.clog 2 (g+4) + +private def headCode (g : ℕ) : Fin 21 → Instr (width g) (PCs g) (Regs g) 5 + | 0 => .publicWord (reg g 0) 2 (head g 1) + | 1 => .readExternal (reg g 1) (reg g 0) (head g 2) + | 2 => .publicWord (reg g 2) 3 (head g 3) + | 3 => .readExternal (reg g 2) (reg g 2) (head g 4) + | 4 => .jumpLt (reg g 1) (reg g 2) (head g 5) (head g 19) + | 5 => .publicWord (reg g 3) 1 (head g 6) + | 6 => .constant (reg g 4) (Fin.ofNat _ (g+3)) (head g 7) + | 7 => .binary .mul (reg g 4) (reg g 1) (reg g 4) (head g 8) + | 8 => .binary .add (reg g 3) (reg g 3) (reg g 4) (head g 9) + | 9 => .readExternal (reg g 5) (reg g 3) (head g 10) + | 10 => .constant (reg g 4) 1 (head g 11) + | 11 => .binary .add (reg g 3) (reg g 3) (reg g 4) (head g 12) + | 12 => .readExternal (reg g 6) (reg g 3) (head g 13) + | 13 => .binary .add (reg g 3) (reg g 3) (reg g 4) (head g 14) + | 14 => .publicWord (reg g 7) 0 (head g 15) + | 15 => .publicWord (reg g 8) 4 (head g 16) + | 16 => .binary .add (reg g 1) (reg g 1) (reg g 4) (loadPC g 0) + | 17 => .writeExternal (reg g 0) (reg g 1) (head g 18) + | 18 => .writeExternal (reg g 8) (reg g 5) (head g 20) + | 19 => .accept + | _ => .returnState (reg g 6) + +private def slotCode {g : ℕ} (j : Fin (g+1)) : Fin 6 → Instr (width g) (PCs g) (Regs g) 5 + | 0 => .constant (reg g 9) (Fin.ofNat _ j.val) (slot j 1) + | 1 => .binary .add (reg g 9) (reg g 3) (reg g 9) (slot j 2) + | 2 => .readExternal (bank j) (reg g 9) (loadPC g (j.val+1)) + | 3 => .constant (reg g 9) (Fin.ofNat _ j.val) (slot j 4) + | 4 => .binary .add (reg g 9) (reg g 7) (reg g 9) (slot j 5) + | 5 => .writeExternal (reg g 9) (bank j) (storePC g (j.val+1)) + +/-- The program size depends only on the largest arity among the fixed worker tables. -/ +def table (g : ℕ) : Template (PCs g) (Regs g) 5 where + literalWidth := width g + entry := head g 0 + code pc := match (labels g).symm pc with + | .inl i => headCode g i + | .inr (j,i) => slotCode j i + +/-- The directory controller instantiated at the live word width with its five public workspace +addresses. -/ +abbrev machine (g : ℕ) (pub : Fin 5 → Word w) := (table g).instantiate w pub + +/-- Modular address arithmetic of the native program. -/ +def rowBase (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) : Word w := + pub 1 + m (pub 2).val * ((g+3 : ℕ) : Word w) + +/-- Read a directory or frame field at a word offset from the given source address. -/ +def field (src : Word w) (m : Memory w) (i : ℕ) : Word w := m (src + (i : Word w)).val + +private def prefixEvents (pub : Fin 5 → Word w) (m : Memory w) : List (Event w) := + [.tick, .read (pub 2) (m (pub 2).val), .tick, .read (pub 3) (m (pub 3).val), .tick] + +/-- The terminating controller report after reading the current ordinal and directory row +count. -/ +def doneReport (pub : Fin 5 → Word w) (m : Memory w) : Report w := ⟨prefixEvents pub m, none⟩ + +private def readEvents (src : Word w) (m : Memory w) (i : ℕ) : ℕ → List (Event w) + | 0 => [] + | n+1 => [.tick, .tick, .read (src+(i : Word w)) (field src m i)] ++ readEvents src m (i+1) n + +private def writeEvents (dst : Word w) (v : ℕ → Word w) (i : ℕ) : ℕ → List (Event w) + | 0 => [] + | n+1 => [.tick, .tick, .write (dst+(i : Word w)) (v i)] ++ writeEvents dst v (i+1) n + +private def rowHeader (base : Word w) (pub : Fin 5 → Word w) (m : Memory w) : List (Event w) := + prefixEvents pub m ++ [.tick, .tick, .tick, .tick, .read base (m base.val), + .tick, .tick, .read (base+1) (m (base+1).val), .tick, .tick, .tick, .tick] + +/-- Full transcript including the snapshot of the stop word and all padded operands. -/ +def rowReport (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) : Report w := + let base := rowBase g pub m + let src := base + 2 + ⟨rowHeader base pub m ++ readEvents src m 0 (g+1) ++ + writeEvents (pub 0) (field src m) 0 (g+1) ++ + [.write (pub 2) (m (pub 2).val+1), .write (pub 4) (m base.val)], + some (m (base+1).val)⟩ + +private theorem literal_fit (g i : ℕ) (hi : i < g+4) : i < 2^width g := + hi.trans_le (Nat.le_pow_clog (by decide : 1 < 2) _) + +private theorem code_head (g : ℕ) (pub : Fin 5 → Word w) (i : Fin 21) : + (machine g pub).code (head g i) = (headCode g i).resize w := by + simp [machine, table, Template.instantiate, head] + +private theorem code_slot {g : ℕ} (pub : Fin 5 → Word w) (j : Fin (g+1)) (i : Fin 6) : + (machine g pub).code (slot j i) = (slotCode j i).resize w := by + simp [machine, table, Template.instantiate, slot] + +private theorem update_left {a b : ℕ} {α : Type*} (l : Fin a → α) (r : Fin b → α) + (i : Fin a) (v : α) : + Function.update (Fin.append l r) (i.castAdd b) v = Fin.append (Function.update l i v) r := by + funext t + cases t using Fin.addCases with + | left j => by_cases h : j = i <;> simp [Function.update, h] + | right j => + have h : j.natAdd a ≠ i.castAdd b := fun e ↦ by have := congrArg Fin.val e; simp at this; omega + simp [Function.update_of_ne h] + +private theorem update_right {a b : ℕ} {α : Type*} (l : Fin a → α) (r : Fin b → α) + (i : Fin b) (v : α) : + Function.update (Fin.append l r) (i.natAdd a) v = Fin.append l (Function.update r i v) := by + funext t + cases t using Fin.addCases with + | left j => + have h : j.castAdd b ≠ i.natAdd a := fun e ↦ by have := congrArg Fin.val e; simp at this; omega + simp [Function.update_of_ne h] + | right j => by_cases h : j = i <;> simp [Function.update, h] + +private def config {g : ℕ} (pc : Fin (PCs g)) (s : Word w) (lo : Fin 10 → Word w) + (hi : Fin (g+1) → Word w) : Config w (PCs g) (Regs g) := ⟨pc,s,Fin.append lo hi,fun _ ↦ 0⟩ + +private theorem start_eq (g : ℕ) (pub : Fin 5 → Word w) (s : Word w) : + (machine g pub).program.start s = config (head g 0) s (fun _ ↦ 0) (fun _ ↦ 0) := by + change Config.mk _ _ (fun _ ↦ 0) _ = Config.mk _ _ _ _ + congr 1 + funext j + cases j using Fin.addCases <;> simp + +private theorem step_cfg {g : ℕ} (pub : Fin 5 → Word w) (pc : Fin (PCs g)) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) : + (machine g pub).program.step (config pc s lo hi) = + ((machine g pub).code pc).run pub (config pc s lo hi) := rfl + +private theorem cfg_put {g : ℕ} (pc next : Fin (PCs g)) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) (r : Fin 10) (v : Word w) : + (config pc s lo hi).put next (reg g r) v = config next s (Function.update lo r v) hi := by + simp [Config.put, config, reg, update_left] + +private theorem cfg_bank {g : ℕ} (pc next : Fin (PCs g)) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) (j : Fin (g+1)) (v : Word w) : + (config pc s lo hi).put next (bank j) v = config next s lo (Function.update hi j v) := by + simp [Config.put, config, bank, update_right] + +private theorem reg_cfg {g : ℕ} (pc : Fin (PCs g)) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) (r : Fin 10) : + (config pc s lo hi).reg (reg g r) = lo r := by simp [config, reg] + +private theorem bank_cfg {g : ℕ} (pc : Fin (PCs g)) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) (j : Fin (g+1)) : + (config pc s lo hi).reg (bank j) = hi j := by simp [config, bank] + +private theorem load_one {g : ℕ} (pub : Fin 5 → Word w) (j : Fin (g+1)) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) (m : Memory w) (bs : List Bool) (f : ℕ) : + let a := lo 3 + (j.val : Word w) + execute (machine g pub).program (f+3) (config (loadPC g j.val) s lo hi) m bs = + (execute (machine g pub).program f (config (loadPC g (j.val+1)) s + (Function.update lo 9 a) (Function.update hi j (m a.val))) m bs).map + (LiveStageLink.prependLog [.tick,.tick,.read a (m a.val)]) := by + have lit := literal_fit g j.val (by have := j.isLt; omega) + rw [show loadPC g j.val = slot j 0 by simp [loadPC, j.isLt]] + simp (config := {decide := true}) [execute, step_cfg, code_slot, slotCode, Instr.resize, Instr.run, + cfg_put, cfg_bank, reg_cfg, BinaryOp.eval, Nat.mod_eq_of_lt lit, Function.update_idem, + Function.comp_def, Report.prepend] + rfl + +private theorem store_one {g : ℕ} (pub : Fin 5 → Word w) (j : Fin (g+1)) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) (m : Memory w) (bs : List Bool) (f : ℕ) : + let a := lo 7 + (j.val : Word w) + execute (machine g pub).program (f+3) (config (storePC g j.val) s lo hi) m bs = + (execute (machine g pub).program f (config (storePC g (j.val+1)) s + (Function.update lo 9 a) hi) (writeMemory m a (hi j)) bs).map + (LiveStageLink.prependLog [.tick,.tick,.write a (hi j)]) := by + have lit := literal_fit g j.val (by have := j.isLt; omega) + rw [show storePC g j.val = slot j 3 by simp [storePC, j.isLt]] + simp (config := {decide := true}) [execute, step_cfg, code_slot, slotCode, Instr.resize, Instr.run, + cfg_put, reg_cfg, bank_cfg, BinaryOp.eval, Nat.mod_eq_of_lt lit, Function.update_idem, + Function.comp_def, Report.prepend] + rfl + +private theorem cfg_move {g : ℕ} (pc next : Fin (PCs g)) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) : + Config.mk next (config pc s lo hi).persistent (config pc s lo hi).reg + (config pc s lo hi).privateMem = config next s lo hi := rfl + +private def closing (lo : Fin 10 → Word w) : List (Event w) := + [.write (lo 0) (lo 1), .write (lo 8) (lo 5)] + +private theorem store_tail (g : ℕ) (pub : Fin 5 → Word w) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) (m : Memory w) + (bs : List Bool) (f : ℕ) (v : ℕ → Word w) (hv : ∀ j, hi j = v j.val) + (i n : ℕ) (hlen : i+n = g+1) : + execute (machine g pub).program (f+3+3*n) (config (storePC g i) s lo hi) m bs = + if bs = [] then some ⟨writeEvents (lo 7) v i n ++ closing lo, some (lo 6)⟩ else none := by + induction n generalizing i lo m with + | zero => + simp only [Nat.add_zero] at hlen + subst i + by_cases h : bs = [] <;> + simp [storePC, execute, step_cfg, code_head, headCode, Instr.resize, Instr.run, + reg_cfg, cfg_move, h, writeEvents, closing, Report.prepend] + | succ n ih => + let j : Fin (g+1) := ⟨i, by omega⟩ + have eqf : f+3+3*(n+1) = (f+3+3*n)+3 := by omega + rw [eqf, store_one pub j, ih _ _ (i+1) (by omega)] + by_cases h : bs = [] <;> simp (config := {decide := true}) [h, hv, writeEvents, closing, + LiveStageLink.prependLog, j] + +private theorem load_tail (g : ℕ) (pub : Fin 5 → Word w) (s : Word w) + (lo : Fin 10 → Word w) (hi : Fin (g+1) → Word w) (m : Memory w) + (bs : List Bool) (f i n : ℕ) (hlen : i+n = g+1) + (hv : ∀ j : Fin (g+1), j.val < i → hi j = field (lo 3) m j.val) : + execute (machine g pub).program (f+3+3*(g+1)+3*n) (config (loadPC g i) s lo hi) m bs = + if bs = [] then some ⟨readEvents (lo 3) m i n ++ + writeEvents (lo 7) (field (lo 3) m) 0 (g+1) ++ closing lo, some (lo 6)⟩ else none := by + induction n generalizing i lo hi with + | zero => + simp only [Nat.add_zero] at hlen + subst i + simp only [Nat.mul_zero, Nat.add_zero, loadPC, lt_self_iff_false, ↓reduceDIte, readEvents, + List.nil_append] + exact store_tail g pub s lo hi m bs f _ (fun j ↦ hv j j.isLt) 0 (g+1) (by omega) + | succ n ih => + let j : Fin (g+1) := ⟨i, by omega⟩ + let a := lo 3 + (i : Word w) + have hx : ∀ t : Fin (g+1), t.val < i+1 → + Function.update hi j (m a.val) t = field (Function.update lo 9 a 3) m t.val := by + intro t ht + by_cases h : t = j + · subst t; simp (config := {decide := true}) [j, a, field] + · have hh : t.val ≠ i := fun e ↦ h (Fin.ext e) + simp (config := {decide := true}) [Function.update_of_ne h, hv t (by omega)] + have eqf : f+3+3*(g+1)+3*(n+1) = (f+3+3*(g+1)+3*n)+3 := by omega + rw [eqf, load_one pub j, ih _ _ (i+1) (by omega) hx] + by_cases h : bs = [] <;> simp (config := {decide := true}) [h, readEvents, field, closing, + LiveStageLink.prependLog, j] + +private def ready (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) : Fin 10 → Word w := + let base := rowBase g pub m + ![pub 2, m (pub 2).val + 1, m (pub 3).val, base+2, 1, m base.val, + m (base+1).val, pub 0, pub 4, 0] + +set_option maxHeartbeats 600000 in +private theorem row_header_run (g : ℕ) (pub : Fin 5 → Word w) (s : Word w) + (m : Memory w) (bs : List Bool) (f : ℕ) (active : m (pub 2).val < m (pub 3).val) : + execute (machine g pub).program (f+17) ((machine g pub).program.start s) m bs = + (execute (machine g pub).program f (config (loadPC g 0) s (ready g pub m) (fun _ ↦ 0)) m bs).map + (LiveStageLink.prependLog (rowHeader (rowBase g pub m) pub m)) := by + have stride : ((g : Word (width g)) + 3).val = g+3 := by + rw [← show ((g+3 : ℕ) : Word (width g)) = (g : Word (width g))+3 by simp] + exact Nat.mod_eq_of_lt (literal_fit g (g+3) (by omega)) + have one := Nat.mod_eq_of_lt (literal_fit g 1 (by omega)) + rw [start_eq] + simp (config := {decide := true}) [execute, step_cfg, code_head, headCode, Instr.resize, Instr.run, + stride, one, + cfg_put, reg_cfg, cfg_move, active, BinaryOp.eval, + Function.comp_def, Report.prepend] + congr 1 + · funext z; simp [LiveStageLink.prependLog, rowHeader, prefixEvents, rowBase] + · congr 2 + funext i + fin_cases i <;> simp (config := {decide := true}) [ready, rowBase, add_assoc] + exact one_add_one_eq_two + +/-- The complete native directory-row call, at any sufficient cap and for any proposed stream. -/ +theorem execute_row (g : ℕ) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (fuel : ℕ) (active : m (pub 2).val < m (pub 3).val) + (cap : 20+6*(g+1) ≤ fuel) : + execute (machine g pub).program fuel ((machine g pub).program.start s) m bs = + if bs = [] then some (rowReport g pub m) else none := by + let pad := fuel - (20+6*(g+1)) + rw [show fuel = (pad+3+3*(g+1)+3*(g+1))+17 by dsimp [pad]; omega, row_header_run g pub s m bs _ active, + load_tail g pub s (ready g pub m) (fun _ ↦ 0) m bs pad 0 (g+1) (by omega) (by simp)] + by_cases h : bs = [] <;> simp [h, ready, rowReport, LiveStageLink.prependLog, closing, + List.append_assoc] + +/-- An exhausted directory accepts immediately after reading the ordinal and row count. -/ +theorem execute_done (g : ℕ) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (fuel : ℕ) (closed : m (pub 3).val ≤ m (pub 2).val) (cap : 6 ≤ fuel) : + execute (machine g pub).program fuel ((machine g pub).program.start s) m bs = + if bs = [] then some (doneReport pub m) else none := by + obtain ⟨f,rfl⟩ : ∃ f, fuel = f+6 := ⟨fuel-6, by omega⟩ + rw [start_eq] + by_cases h : bs = [] <;> + simp (config := {decide := true}) [execute, step_cfg, code_head, headCode, Instr.resize, Instr.run, + cfg_put, reg_cfg, cfg_move, not_lt_of_ge closed, h, doneReport, prefixEvents, Report.prepend] + +private theorem probes_append (a b : List (Event w)) : + countProbes (a++b) = countProbes a + countProbes b := by + induction a with + | nil => simp [countProbes] + | cons e a ih => cases e <;> simp [countProbes, ih, Nat.add_assoc] + +private theorem choices_append (a b : List (Event w)) : + choiceBits (a++b) = choiceBits a ++ choiceBits b := by + induction a with + | nil => rfl + | cons e a ih => cases e <;> simp [choiceBits, ih] + +private theorem read_cost (src : Word w) (m : Memory w) (i n : ℕ) : + (readEvents src m i n).length = 3*n ∧ countProbes (readEvents src m i n) = n ∧ + choiceBits (readEvents src m i n) = [] := by + induction n generalizing i with + | zero => exact ⟨rfl,rfl,rfl⟩ + | succ n ih => + obtain ⟨hl,hp,hc⟩ := ih (i+1) + simp [readEvents, countProbes, choiceBits, hl, hp, hc, Nat.mul_succ, Nat.add_comm] + omega + +private theorem write_cost (dst : Word w) (v : ℕ → Word w) (i n : ℕ) : + (writeEvents dst v i n).length = 3*n ∧ countProbes (writeEvents dst v i n) = n ∧ + choiceBits (writeEvents dst v i n) = [] := by + induction n generalizing i with + | zero => exact ⟨rfl,rfl,rfl⟩ + | succ n ih => + obtain ⟨hl,hp,hc⟩ := ih (i+1) + simp [writeEvents, countProbes, choiceBits, hl, hp, hc, Nat.mul_succ, Nat.add_comm] + omega + +theorem rowReport_cost (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) : + (rowReport g pub m).events.length = 19+6*(g+1) ∧ + countProbes (rowReport g pub m).events = 6+2*(g+1) ∧ + choiceBits (rowReport g pub m).events = [] := by + let src := rowBase g pub m + 2 + obtain ⟨hl,hp,hc⟩ := read_cost src m 0 (g+1) + obtain ⟨hl',hp',hc'⟩ := write_cost (pub 0) (field src m) 0 (g+1) + simp only [rowReport, show rowBase g pub m + 2 = src by rfl, List.length_append, probes_append, + choices_append, hl, hp, hc, hl', hp', hc'] + simp [rowHeader, prefixEvents, countProbes, choiceBits] + omega + +theorem doneReport_cost (pub : Fin 5 → Word w) (m : Memory w) : + (doneReport pub m).events.length = 5 ∧ countProbes (doneReport pub m).events = 2 ∧ + choiceBits (doneReport pub m).events = [] := ⟨rfl,rfl,rfl⟩ + +private theorem after_append (m : Memory w) (a b : List (Event w)) : + after m (a++b) = after (after m a) b := List.foldl_append + +private theorem read_after (src : Word w) (m m' : Memory w) (i n : ℕ) : + after m' (readEvents src m i n) = m' := by + induction n generalizing i with + | zero => rfl + | succ n ih => exact ih (i+1) + +/-- The memory after copying the selected row's exclusive stop and padded operands into the +active worker frame. -/ +def frameMemory (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) : Memory w := + after m (writeEvents (pub 0) (field (rowBase g pub m + 2) m) 0 (g+1)) + +theorem after_done (pub : Fin 5 → Word w) (m : Memory w) : after m (doneReport pub m).events = m := rfl + +theorem after_row (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) : + after m (rowReport g pub m).events = + writeMemory (writeMemory (frameMemory g pub m) (pub 2) (m (pub 2).val+1)) + (pub 4) (m (rowBase g pub m).val) := by + simp only [rowReport, after_append, read_after] + rfl + +theorem after_row_tag (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) : + after m (rowReport g pub m).events (pub 4).val = m (rowBase g pub m).val := by + rw [after_row]; simp [writeMemory] + +theorem after_row_ordinal (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) + (h : pub 2 ≠ pub 4) : + after m (rowReport g pub m).events (pub 2).val = m (pub 2).val + 1 := by + rw [after_row]; simp [writeMemory, Fin.val_ne_of_ne h] + +private theorem writes_outside (dst : Word w) (v : ℕ → Word w) (m : Memory w) (a i n : ℕ) + (h : ∀ t, i ≤ t → t < i+n → a ≠ (dst+(t : Word w)).val) : + after m (writeEvents dst v i n) a = m a := by + induction n generalizing i m with + | zero => rfl + | succ n ih => + change after (writeMemory m (dst+(i : Word w)) (v i)) (writeEvents dst v (i+1) n) a = m a + rw [ih _ (i+1) (fun t h₁ h₂ ↦ h t (by omega) (by omega))] + simp [writeMemory, h i le_rfl (by omega)] + +/-- A worker-data word, a future directory word, or the row count is preserved when +it lies outside the frame and the two mutable control cells. -/ +theorem after_row_outside (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) (a : ℕ) + (ho : a ≠ (pub 2).val) (ht : a ≠ (pub 4).val) + (hf : ∀ i : Fin (g+1), a ≠ (pub 0 + (i.val : Word w)).val) : + after m (rowReport g pub m).events a = m a := by + rw [after_row] + simp only [writeMemory, ht, ho, ↓reduceIte, frameMemory] + exact writes_outside _ _ _ _ _ _ fun t _ h ↦ hf ⟨t, by omega⟩ + +private theorem writes_at (dst : Word w) (v : ℕ → Word w) (m : Memory w) (k i n : ℕ) + (lo : i ≤ k) (hi : k < i+n) (fit : i+n ≤ 2^w) : + after m (writeEvents dst v i n) (dst+(k : Word w)).val = v k := by + induction n generalizing m i with + | zero => omega + | succ n ih => + change after (writeMemory m (dst+(i : Word w)) (v i)) (writeEvents dst v (i+1) n) _ = _ + by_cases eqn : k = i + · subst k + rw [writes_outside] + · simp [writeMemory] + · intro t h₁ h₂ he + have hx : (i : Word w) = (t : Word w) := add_left_cancel (Fin.ext he) + have hv := congrArg Fin.val hx + simp only [Fin.val_natCast, Nat.mod_eq_of_lt (show i < 2^w by omega), + Nat.mod_eq_of_lt (show t < 2^w by omega)] at hv + omega + · exact ih _ (i+1) (by omega) (by omega) (by omega) + +/-- The first frame word is the exclusive stop. The remaining words are the +worker's padded parameter bank. All field values refer to the entry memory. -/ +theorem after_row_frame (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) (i : Fin (g+1)) + (fit : g+1 ≤ 2^w) (ho : pub 0 + (i.val : Word w) ≠ pub 2) + (ht : pub 0 + (i.val : Word w) ≠ pub 4) : + after m (rowReport g pub m).events (pub 0 + (i.val : Word w)).val = + field (rowBase g pub m + 2) m i.val := by + rw [after_row] + simp only [writeMemory, Fin.val_ne_of_ne ho, Fin.val_ne_of_ne ht, ↓reduceIte, frameMemory] + exact writes_at _ _ _ _ 0 (g+1) (by omega) (by have := i.isLt; omega) (by omega) + +/-- A directory fitting in the physical address space uses the ordinary row-major index. -/ +theorem rowBase_val (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) + (fit : (pub 1).val + (m (pub 2).val).val * (g+3) < 2^w) : + (rowBase g pub m).val = (pub 1).val + (m (pub 2).val).val * (g+3) := by + simp only [rowBase, Fin.val_add, Fin.val_mul, Fin.val_natCast, Nat.mul_mod_mod, + Nat.add_mod_mod, Nat.mod_eq_of_lt fit] + +/-- When a row is present, advancing its ordinal never wraps around. -/ +theorem after_row_ordinal_val (g : ℕ) (pub : Fin 5 → Word w) (m : Memory w) + (h : pub 2 ≠ pub 4) (active : m (pub 2).val < m (pub 3).val) : + (after m (rowReport g pub m).events (pub 2).val).val = (m (pub 2).val).val+1 := by + have ht := (m (pub 3).val).isLt + have hl := Fin.lt_def.mp active + rw [after_row_ordinal g pub m h, Fin.val_add, Fin.val_one', + Nat.mod_eq_of_lt (show 1 < 2^w by omega), Nat.mod_eq_of_lt (by omega)] + +private theorem guessed_pad {C : Type*} {P : Program w C} {f c es out} + (h : Guessed P f c es out) (pad : ℕ) : Guessed P (f+pad) c es out := by + induction h with + | done hs => simpa [Nat.succ_add] using Guessed.done (f := _+pad) hs + | step hs _ ih => simpa [Nat.succ_add] using Guessed.step hs ih + | branch hs _ ih => simpa [Nat.succ_add] using Guessed.branch hs ih + | read hs _ ih => simpa [Nat.succ_add] using Guessed.read hs ih + | write hs _ ih => simpa [Nat.succ_add] using Guessed.write hs ih + +private theorem exact_cap {C : Type*} {P : Program w C} {c : C} {m : Memory w} + {bs : List Bool} {rep : Report w} {ticks : ℕ} (hl : rep.events.length = ticks) + (hs : ∀ f, ticks < f → execute P f c m bs = if bs = [] then some rep else none) (fuel : ℕ) : + execute P fuel c m bs = if bs = [] ∧ ticks < fuel then some rep else none := by + by_cases hf : ticks < fuel + · simpa [hf] using hs fuel hf + simp only [hf, and_false, ↓reduceIte] + cases he : execute P fuel c m bs with + | none => rfl + | some t => + obtain ⟨hg,hm,hb⟩ := execute_spec he + have big := execute_iff.mpr ⟨guessed_pad hg (ticks+1), hm, hb⟩ + rw [hs _ (by omega)] at big + split at big + · have eqn : rep = t := Option.some.inj big + subst t + have := hg.length_lt + omega + · contradiction + +/-- For every cap, the controller succeeds exactly when the complete +deterministic transcript and its terminal instruction fit in that cap. -/ +theorem execute_cap (g : ℕ) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (fuel : ℕ) : + let rep := if m (pub 2).val < m (pub 3).val then rowReport g pub m else doneReport pub m + execute (machine g pub).program fuel ((machine g pub).program.start s) m bs = + if bs = [] ∧ rep.events.length < fuel then some rep else none := by + dsimp only + split + · rename_i active + apply exact_cap rfl + intro f hf + exact execute_row g pub s m bs f active (by rw [(rowReport_cost ..).1] at hf; omega) + · rename_i h + apply exact_cap rfl + intro f hf + exact execute_done g pub s m bs f (le_of_not_gt h) (by rw [(doneReport_cost ..).1] at hf; omega) + +end CompressorRecords.Controller + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCopyIncidence.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCopyIncidence.lean new file mode 100644 index 0000000000..025698d05c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCopyIncidence.lean @@ -0,0 +1,399 @@ +import OAI.Computability.VPVNP.CompressorDescriptorSpace +import OAI.Computability.VPVNP.CompressorRecordRefreshAllocation +import OAI.Computability.VPVNP.CompressorRecordsSchedule +import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +import OAI.Computability.VPVNP.LiveAuxiliaryHeaders + +/-! +# Copying the six incidence columns into the next level + +The worker copies one external word per call. Each column starts at cursor zero +and stops after its populated rows. The three base columns therefore copy only +base ports, even when the actual columns have many more lane positions. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CopyIncidence + +open BurstRAM BurstRAM.PrivateRAM Compression PrimedStackRAM PhaseRecipe +open scoped Fin.CommRing + +variable {w a l : ℕ} + +/-- The scheduled worker that copies one external incidence word per call. -/ +abbrev copyPass : Schedule.Pass := ⟨_,_,_,template LiveAuxiliaryHeaders.copyWord 7⟩ + +/-- The copy worker's public bank, containing zero followed by the source and destination +column bases. -/ +def copyPublic (src dst : Word w) : Fin 3 → Word w := ![0, src, dst] + +/-- Schedule a tagged column copy from cursor zero to the supplied stop using the source and +destination address expressions. -/ +def copyPhase {g : ℕ} (hg : 3 ≤ g) (tag : ℕ) (stop src dst : Expr) : Phase g := + Phase.ofParams hg tag (.lit 0) stop ![.lit 0, src, dst] + +/-- The copy cursor adds a word offset to each array head. -/ +def cell (base : Word w) (j : ℕ) : ℕ := (base + (j : Word w)).val + +private abbrev program (src dst : Word w) := (copyPass.table.instantiate w (copyPublic src dst)).program + +/-- The report returned by the native one-word copy. -/ +def row (src dst : Word w) (j : ℕ) (m : Memory w) : Report w := + (execute (program src dst) 12 ((program src dst).start (j : Word w)) m []).getD ⟨[],none⟩ + +private theorem row_spec (src dst : Word w) (j : ℕ) (m : Memory w) : + let r := row src dst j m + execute (program src dst) 12 ((program src dst).start (j : Word w)) m [] = some r ∧ + r.result = some ((j+1 : ℕ) : Word w) ∧ + after m r.events = writeMemory m (dst+(j : Word w)) (m (cell src j)) ∧ + r.events.length = 11 ∧ r.probes = 2 ∧ choiceBits r.events = [] := by + obtain ⟨es,he,hm,hlen,hprobes,hchoices⟩ := + LiveAuxiliaryHeaders.copyWord_native (copyPublic src dst) (j : Word w) m + change execute (program src dst) 12 ((program src dst).start (j : Word w)) m [] = _ at he + have hrow : row src dst j m = ⟨es,some ((j : Word w)+1)⟩ := by + unfold row + rw [he] + rfl + dsimp only + rw [hrow] + refine ⟨he,by simp,?_,hlen,hprobes,hchoices⟩ + simpa [copyPublic,cell] using hm + +/-- Chronological reports of one column, beginning at an arbitrary row. -/ +def scan (src dst : Word w) : ℕ → ℕ → Memory w → List (Report w) + | _, 0, _ => [] + | k, n+1, m => + let r := row src dst k m + r :: scan src dst (k+1) n (after m r.events) + +private theorem scan_after (src dst : Word w) (k n : ℕ) (m : Memory w) : + after m (eventLog (scan src dst k (n+1) m)) = + after (after m (row src dst k m).events) + (eventLog (scan src dst (k+1) n (after m (row src dst k m).events))) := + List.foldl_append + +/-- Twelve units of private fuel suffice. Each call has eleven events, +two probes and no branch choices. Its charge includes one unit for the call. -/ +theorem scan_native (src dst : Word w) (k n : ℕ) (m : Memory w) : + let P := (copyPass.table.instantiate w (copyPublic src dst)).program + let rs := scan src dst k n m + runSegment P 12 (some (k : Word w)) m (List.replicate n []) = some rs ∧ + endState (some (k : Word w)) rs = some ((k+n : ℕ) : Word w) ∧ + rs.length = n ∧ (∀ r ∈ rs, r.events.length = 11 ∧ r.probes = 2 ∧ choiceBits r.events = []) ∧ + RAMBuckets.cost Report.probes rs = 3*n := by + induction n generalizing k m with + | zero => exact ⟨rfl,rfl,rfl,by simp [scan],rfl⟩ + | succ n ih => + let r := row src dst k m + obtain ⟨he,hs,_,work⟩ := row_spec src dst k m + obtain ⟨hr,hend,hl,hw,hc⟩ := ih (k+1) (after m r.events) + dsimp only + refine ⟨?_,?_,?_,?_,?_⟩ + · rw [List.replicate_succ,runSegment,he] + change (runSegment (program src dst) 12 r.result _ _).map (r :: ·) = _ + rw [show r.result = _ from hs,hr]; rfl + · change endState r.result _ = _ + rw [hs,hend,show k+1+n = k+(n+1) by omega] + · exact congrArg Nat.succ hl + · intro z hz + rcases List.mem_cons.mp hz with rfl | h + · exact work + · exact hw _ h + · change 1+r.probes+RAMBuckets.cost _ _ = _ + rw [hc,show r.probes = 2 from work.2.1]; omega + +theorem scan_outside (src dst : Word w) (k n : ℕ) (m : Memory w) (addr : ℕ) + (away : ∀ j, k ≤ j → j < k+n → addr ≠ cell dst j) : + after m (eventLog (scan src dst k n m)) addr = m addr := by + induction n generalizing k m with + | zero => rfl + | succ n ih => + rw [scan_after, ih _ _ (fun j hj h ↦ away j (by omega) (by omega)), (row_spec ..).2.2.1] + exact ite_eq_right (away k le_rfl (by omega)) + +private theorem cell_inj (base : Word w) {i j : ℕ} (hi : i < 2^w) (hj : j < 2^w) + (eqn : cell base i = cell base j) : i = j := by + have h : (i : Word w) = (j : Word w) := add_left_cancel (Fin.ext eqn : base+(i : Word w) = base+(j : Word w)) + have v : i % (2^w) = j % (2^w) := congrArg Fin.val h + simpa only [Nat.mod_eq_of_lt hi,Nat.mod_eq_of_lt hj] using v + +theorem scan_read (src dst : Word w) (k n : ℕ) (m : Memory w) (fit : k+n ≤ 2^w) + (apart : ∀ i j, k ≤ i → i < k+n → k ≤ j → j < k+n → cell src i ≠ cell dst j) + (i : ℕ) (lo : k ≤ i) (hi : i < k+n) : + after m (eventLog (scan src dst k n m)) (cell dst i) = m (cell src i) := by + induction n generalizing k m with + | zero => omega + | succ n ih => + rw [scan_after] + by_cases e : i = k + · subst i + rw [scan_outside _ _ _ _ _ _ (fun j hj h eqn ↦ by + have := cell_inj dst (by omega) (by omega) eqn + omega), (row_spec ..).2.2.1] + exact ite_eq_left rfl + · rw [ih _ _ (by omega) (fun i j hi hi' hj hj' ↦ apart i j (by omega) (by omega) (by omega) (by omega)) + (by omega) (by omega), (row_spec ..).2.2.1] + exact ite_eq_right (apart i k lo hi le_rfl (by omega)) + + +/-- If the destination rows avoid the tag and active frame, every call +retains the dispatch parameters and satisfies the exclusive cursor guard. -/ +theorem scan_valid {d : ℕ} (C : Schedule.Catalog d) (worker : Fin d) (ports : Schedule.Ports w) + (pub : Fin (C worker).params → Word w) (bound src dst : Word w) (k n : ℕ) (m : Memory w) + (stop : k+n = bound.val) (ready : Schedule.Ready C worker ports pub bound m) + (away : ∀ j, k ≤ j → j < k+n → cell dst j ≠ ports.tag.val ∧ + ∀ i : Fin ((C worker).params+1), cell dst j ≠ cell ports.activeFrame i.val) : + Schedule.ValidTrace C worker ports pub bound (k : Word w) m (scan src dst k n m) := by + induction n generalizing k m with + | zero => + have h : (k : Word w) = bound := Fin.ext (by + change k % (2^w) = bound.val + simp only [Nat.add_zero] at stop + rw [stop,Nat.mod_eq_of_lt bound.isLt]) + exact ⟨ready,h.ge⟩ + | succ n ih => + have hk : k < bound.val := by omega + have hlt : (k : Word w) < bound := by + change k % (2^w) < bound.val + rwa [Nat.mod_eq_of_lt (hk.trans bound.isLt)] + have safe := away k le_rfl (by omega) + have keep (v : ℕ) (h : cell dst k ≠ v) : + after m (row src dst k m).events v = m v := by + rw [(row_spec ..).2.2.1] + exact ite_eq_right h.symm + refine ⟨ready,hlt,((k+1 : ℕ) : Word w),(row_spec ..).2.1,ih _ _ (by omega) ?_ ?_⟩ + · refine ⟨(keep _ safe.1).trans ready.1,?_,?_⟩ + · exact (keep _ (by simpa [cell] using safe.2 0)).trans ready.2.1 + · funext i + exact (keep _ (safe.2 i.succ)).trans (congrFun ready.2.2 i) + · exact fun j hj h ↦ away j (by omega) (by omega) + +/-- The populated length of an incidence column, counting base ports for the first three +columns and actual ports for the other three. -/ +def rows (X : State a l) (c : Fin 6) : ℕ := + if c.val < 3 then Fintype.card X.Base * 2^a else X.positions * 2^a + +/-- Only live cells of the six arrays participate in the separation hypotheses. +The source may lie on either side of any destination column. -/ +structure Regions (X : State a l) (T U : IncidenceDirectory w) : Prop where + fits : ∀ c, rows X c ≤ 2^w + source : ∀ c d i j, i < rows X c → j < rows X d → cell (T.column c) i ≠ cell (U.column d) j + destination : ∀ c d i j, c ≠ d → i < rows X c → j < rows X d → + cell (U.column c) i ≠ cell (U.column d) j + +private theorem cell_val (base : Word w) {n j : ℕ} (room : base.val+n ≤ 2^w) (hj : j < n) : + cell base j = base.val+j := by + have hv : (j : Word w).val = j := Nat.mod_eq_of_lt (by omega) + rw [cell,Fin.val_add,hv,Nat.mod_eq_of_lt (by omega)] + +/-- Natural disjoint half-open intervals give the word-address conditions, +including at the largest address representable by a machine word. -/ +theorem Regions.of_intervals (X : State a l) (T U : IncidenceDirectory w) + (roomT : ∀ c, (T.column c).val + rows X c ≤ 2^w) + (roomU : ∀ c, (U.column c).val + rows X c ≤ 2^w) + (apart : ∀ c d, (T.column c).val + rows X c ≤ (U.column d).val ∨ + (U.column d).val + rows X d ≤ (T.column c).val) + (distinct : ∀ c d, c ≠ d → (U.column c).val + rows X c ≤ (U.column d).val ∨ + (U.column d).val + rows X d ≤ (U.column c).val) : Regions X T U := by + constructor + · intro c; have := roomU c; omega + · intro c d i j hi hj + rw [cell_val _ (roomT c) hi,cell_val _ (roomU d) hj] + have := apart c d + omega + · intro c d i j hcd hi hj + rw [cell_val _ (roomU c) hi,cell_val _ (roomU d) hj] + have := distinct c d hcd + omega + +private theorem actual_rows (X : State a l) : + X.positions * 2^a = Fintype.card X.Base * 2^l * 2^a := by + rw [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv l),Fintype.card_fin] + +theorem rows_le_slots (X : State a l) (c : Fin 6) : rows X c ≤ X.positions * 2^a := by + unfold rows + split + · rw [actual_rows] + exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos l)) + · exact le_rfl + +/-- The native degree-refresh output can occupy either side of the canonical +level directory. Each column has room for the new state's actual slots, +and the copy scan uses the shorter base-port count in its first three columns. -/ +theorem Regions.refresh_to_level (X : State a l) (P : PortRefresh.Allocation.Plan) + (L : DescriptorSpace.Layout) (level : Fin L.levels) + (scratchRoom : P.stop ≤ 2^w) (levelRoom : DescriptorSpace.endAddress L < 2^w) + (scratchCapacity : X.positions * 2^a ≤ P.capacity) + (levelCapacity : X.positions * 2^a ≤ DescriptorSpace.slotCapacity L) + (apart : P.stop ≤ DescriptorSpace.incidenceStart L level ∨ + DescriptorSpace.incidenceStart L level + 6*(X.positions * 2^a) ≤ P.next) : + Regions X (P.output w) (DescriptorSpace.packedIncidence L w level (X.positions * 2^a)) := by + let n := X.positions * 2^a + let start := DescriptorSpace.incidenceStart L level + let U := DescriptorSpace.packedIncidence L w level n + have room : start + 6*n < 2^w := DescriptorSpace.packed_incidence_room L levelRoom level levelCapacity + have fit : n ≤ 2^w := by omega + have layout : U.Layout X := by + change (DescriptorSpace.packedIncidence L w level (X.positions * 2^a)).Layout X + rw [actual_rows] + exact DescriptorSpace.packed_layout L X level levelRoom (by rwa [← actual_rows]) + have dest (c : Fin 6) (j : ℕ) (hj : j < n) : + start ≤ cell (U.column c) j ∧ cell (U.column c) j < start + 6*n := by + have hc := Nat.mul_le_mul_right n c.isLt + rw [Nat.succ_mul] at hc + have hbase : (U.column c).val = start + c.val*n := by + rw [show U = DescriptorSpace.packedIncidence L w level n from rfl,DescriptorSpace.packed_column] + exact Nat.mod_eq_of_lt (by change start+c.val*n < _; omega) + rw [cell_val _ (by rw [hbase]; omega : (U.column c).val+n ≤ 2^w) hj,hbase] + constructor <;> omega + refine ⟨fun c ↦ (rows_le_slots X c).trans fit,?_,?_⟩ + · intro c d i j hi hj + have hi' : i < n := hi.trans_le (rows_le_slots X c) + have hj' : j < n := hj.trans_le (rows_le_slots X d) + have hw : (i : Word w).val = i := Nat.mod_eq_of_lt (hi'.trans_le fit) + have hs := P.column_interval scratchRoom c (i : Word w) (by rw [hw]; exact hi'.trans_le scratchCapacity) + have hd := dest d j hj' + change P.next ≤ cell ((P.output w).column c) i ∧ cell ((P.output w).column c) i < P.stop at hs + change P.stop ≤ start ∨ start + 6*n ≤ P.next at apart + change cell ((P.output w).column c) i ≠ cell (U.column d) j + omega + · intro c d i j hcd hi hj eqn + have slot (t : Fin 6) (k : ℕ) (hk : k < rows X t) : (k : Word w).val < Fintype.card X.Base * 2^l * 2^a := by + have h : k < n := hk.trans_le (rows_le_slots X t) + rw [← actual_rows] + exact (Nat.mod_le ..).trans_lt h + exact hcd (((layout.apart c d (i : Word w) (j : Word w) (slot c i hi) (slot d j hj)).mp eqn).1) + +variable (X : State a l) (T U : IncidenceDirectory w) + +/-- The complete copy scan for one incidence column between the source and destination level +directories. -/ +def columnScan (c : Fin 6) (m : Memory w) := + scan (T.column c) (U.column c) 0 (rows X c) m + +/-- Execute each column in sequence, feeding its actual final memory to +the next worker. Each column has a fresh zero cursor and public operands. -/ +def reports : List (Fin 6) → Memory w → List (Report w) + | [], _ => [] + | c :: cs, m => + let rs := columnScan X T U c m + rs ++ reports cs (after m (eventLog rs)) + +private theorem reports_after (c : Fin 6) (cs : List (Fin 6)) (m : Memory w) : + let out := after m (eventLog (columnScan X T U c m)) + after m (eventLog (reports X T U (c::cs) m)) = after out (eventLog (reports X T U cs out)) := by + simp only [reports,eventLog,List.flatMap_append,after,List.foldl_append] + +/-- Each worker call sequence runs with its own two column heads. -/ +inductive Runs : List (Fin 6) → Memory w → List (Report w) → Prop + | nil (m) : Runs [] m [] + | cons (c : Fin 6) {cs m rs more} + (native : runSegment (program (T.column c) (U.column c)) 12 (some 0) m + (List.replicate (rows X c) []) = some rs) + (next : Runs cs (after m (eventLog rs)) more) : Runs (c::cs) m (rs++more) + +theorem reports_run (cs : List (Fin 6)) (m : Memory w) : + Runs X T U cs m (reports X T U cs m) := by + induction cs generalizing m with + | nil => exact .nil m + | cons c cs ih => + exact .cons c (scan_native (T.column c) (U.column c) 0 (rows X c) m).1 (ih _) + +theorem reports_outside (cs : List (Fin 6)) (m : Memory w) (v : ℕ) + (away : ∀ c ∈ cs, ∀ j, j < rows X c → v ≠ cell (U.column c) j) : + after m (eventLog (reports X T U cs m)) v = m v := by + induction cs generalizing m with + | nil => rfl + | cons c cs ih => + rw [reports_after,ih _ (fun d hd ↦ away d (.tail _ hd))] + exact scan_outside _ _ _ _ _ _ (fun j _ hj ↦ away c (.head _) j (by simpa using hj)) + +theorem reports_read (reg : Regions X T U) (cs : List (Fin 6)) (m : Memory w) + (c : Fin 6) (hc : c ∈ cs) (j : ℕ) (hj : j < rows X c) : + after m (eventLog (reports X T U cs m)) (cell (U.column c) j) = m (cell (T.column c) j) := by + induction cs generalizing m with + | nil => simp at hc + | cons d ds ih => + rw [reports_after] + by_cases h : c ∈ ds + · rw [ih _ h] + exact scan_outside _ _ _ _ _ _ (fun i _ hi ↦ reg.source c d j i hj (by simpa using hi)) + · have he : c = d := (List.mem_cons.mp hc).resolve_right h + subst d + rw [reports_outside X T U ds _ _ (fun d hd i hi ↦ reg.destination c d j i + (fun e ↦ h (e ▸ hd)) hj hi)] + exact scan_read _ _ _ _ _ (by simpa using reg.fits c) + (fun i t _ hi _ ht ↦ reg.source c c i t (by simpa using hi) (by simpa using ht)) j + (Nat.zero_le j) (by simpa using hj) + +theorem reports_work (cs : List (Fin 6)) (m : Memory w) : + let rs := reports X T U cs m + rs.length = (cs.map (rows X)).sum ∧ RAMBuckets.cost Report.probes rs = 3*(cs.map (rows X)).sum ∧ + ∀ r ∈ rs, r.events.length = 11 ∧ r.probes = 2 ∧ choiceBits r.events = [] := by + induction cs generalizing m with + | nil => exact ⟨rfl,rfl,by simp [reports]⟩ + | cons c cs ih => + let rs := columnScan X T U c m + obtain ⟨_,_,hl,hw,hcost⟩ := scan_native (T.column c) (U.column c) 0 (rows X c) m + obtain ⟨ht,hct,hwt⟩ := ih (after m (eventLog rs)) + dsimp only + simp only [reports,List.map_cons,List.sum_cons,List.length_append,RAMBuckets.cost_append,List.mem_append] + exact ⟨congrArg₂ (·+·) hl ht, (congrArg₂ (·+·) hcost hct).trans (Nat.mul_add ..).symm, + fun r h ↦ h.elim (hw r) (hwt r)⟩ + +/-- The six column indices in the order used to copy the full incidence directory. -/ +def allColumns : List (Fin 6) := [0,1,2,3,4,5] + +private theorem mem_allColumns (c : Fin 6) : c ∈ allColumns := by fin_cases c <;> decide + +private theorem full_count : (allColumns.map (rows X)).sum = + 3*(Fintype.card X.Base * 2^a) + 3*(X.positions * 2^a) := by + change _ + (_ + (_ + (_ + (_ + (_ + 0))))) = _ + dsimp [allColumns,rows] + omega + +/-- The scratch incidence state is transferred in six actual native segments. +All populated destination cells represent the same graph, including inverse +ports, displacements and widths. The charge is three units per copied cell. -/ +theorem copy_directory (m : Memory w) (reg : Regions X T U) (rep : T.Represents X m) : + let rs := reports X T U allColumns m + let out := after m (eventLog rs) + let N := 3*(Fintype.card X.Base * 2^a) + 3*(X.positions * 2^a) + Runs X T U allColumns m rs ∧ U.Represents X out ∧ rs.length = N ∧ + RAMBuckets.cost Report.probes rs = 3*N ∧ + (∀ r ∈ rs, r.events.length = 11 ∧ r.probes = 2 ∧ choiceBits r.events = []) ∧ + ∀ v, (∀ c j, j < rows X c → v ≠ cell (U.column c) j) → out v = m v := by + intro rs out N + have readback (c : Fin 6) (j : ℕ) (hj : j < rows X c) := + reports_read X T U reg allColumns m c (mem_allColumns c) j hj + have base (c : Fin 6) (hc : c.val < 3) (e : X.Base × Fin (2^a)) : + out (U.column c + IncidenceDirectory.basePort X e).val = + m (T.column c + IncidenceDirectory.basePort X e).val := by + rw [IncidenceDirectory.basePort_number] + exact readback c _ (by simp only [rows,ite_eq_left hc]; exact (IncidenceDirectory.baseOrder X e).isLt) + have actual (c : Fin 6) (hc : 3 ≤ c.val) (e : (X.Base × BitWord l) × Fin (2^a)) : + out (U.column c + IncidenceDirectory.actualPort X e).val = + m (T.column c + IncidenceDirectory.actualPort X e).val := by + rw [IncidenceDirectory.actualPort_number] + apply readback + rw [rows,ite_eq_right (Nat.not_lt.mpr hc),State.positions,Fintype.card_prod, + Fintype.card_congr (bitWordFinEquiv l),Fintype.card_fin] + exact (IncidenceDirectory.actualOrder X e).isLt + have hrep : U.Represents X out := ⟨fun e ↦ (base 0 (by decide) e).trans (rep.baseOut e), + fun e ↦ (base 1 (by decide) e).trans (rep.baseIn e), + fun e ↦ (base 2 (by decide) e).trans (rep.shift e), + fun e ↦ (actual 3 (by decide) e).trans (rep.actualOut e), + fun e ↦ (actual 4 (by decide) e).trans (rep.actualIn e), + fun e ↦ (actual 5 (by decide) e).trans (rep.width e)⟩ + obtain ⟨hlen,hcost,hwork⟩ := reports_work X T U allColumns m + rw [full_count] at hlen hcost + exact ⟨reports_run ..,hrep,hlen,hcost,hwork,fun v hv ↦ reports_outside X T U allColumns m v (fun c _ ↦ hv c)⟩ + +end CompressorRecords.CopyIncidence + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCursor.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCursor.lean new file mode 100644 index 0000000000..f10911d5c4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCursor.lean @@ -0,0 +1,407 @@ +import OAI.Computability.VPVNP.CompressorRecordsCursorCapacity +import OAI.Computability.VPVNP.CompressorRecordsCursorWords +import OAI.Computability.VPVNP.CompressorRecordGreedyInit + +/-! +# Level-zero records of the compressor + +Six parallel columns are indexed by a base or actual port number. At either +granularity the outgoing column stores an incoming port, and the incoming +column gives the unique outgoing port. Two additional columns give the base +arc's displacement and the actual arc's width. Every cell in these columns +has a direct address in the current level. To query a width at an incoming +port, follow that port's incoming entry into the width column. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM CursorNetwork Compression CursorRAM + +/-- A state-independent incidence directory for the native descriptor stages. -/ +structure IncidenceDirectory (w : ℕ) where + /-- Base address of the column mapping each outgoing base port to its incoming mate. -/ + baseOut : Word w + /-- Base address of the inverse column mapping each incoming base port to its outgoing mate. -/ + baseIn : Word w + /-- Base address of the lane-displacement column indexed by outgoing base port. -/ + shift : Word w + /-- Base address of the column mapping each outgoing actual port to its incoming mate. -/ + actualOut : Word w + /-- Base address of the inverse column mapping each incoming actual port to its outgoing + mate. -/ + actualIn : Word w + /-- Base address of the arc-width column indexed by outgoing actual port. -/ + width : Word w + +namespace IncidenceDirectory + +variable {w a l : ℕ} + +/-- Encode a base port as its base-site number times the degree plus its slot. -/ +def basePort (X : State a l) (e : X.Base × Fin (2^a)) : Word w := + encode w ((X.baseIndex e.1).val * 2^a + e.2.val) + +/-- Encode an actual port by combining the base-site index, binary lane number, and slot in +that order. -/ +def actualPort (X : State a l) (e : (X.Base × BitWord l) × Fin (2^a)) : Word w := + encode w (((X.baseIndex e.1.1).val * 2^l + (bitWordFinEquiv l e.1.2).val)*2^a + e.2.val) + +/-- Complete base and actual incidence records of a state. -/ +structure Represents (T : IncidenceDirectory w) (X : State a l) (m : Memory w) : Prop where + baseOut : ∀ e, m (T.baseOut + basePort X e).val = basePort X (X.slots.base.target e) + baseIn : ∀ e, m (T.baseIn + basePort X e).val = basePort X (X.slots.base.target.symm e) + shift : ∀ e, m (T.shift + basePort X e).val = encode w (bitWordFinEquiv l (X.slots.displacement e)).val + actualOut : ∀ e, m (T.actualOut + actualPort X e).val = actualPort X (X.slots.actualGraph.target e) + actualIn : ∀ e, m (T.actualIn + actualPort X e).val = actualPort X (X.slots.actualGraph.target.symm e) + width : ∀ e, m (T.width + actualPort X e).val = encode w (X.width ((e.1.1,e.2),e.1.2)) + +/-- Read the actual source width at any incoming slot in two direct probes. -/ +theorem Represents.incomingWidth {T : IncidenceDirectory w} {X : State a l} {m : Memory w} + (rep : T.Represents X m) (e : (X.Base × BitWord l) × Fin (2^a)) : + let src := X.slots.actualGraph.target.symm e + m (T.width + m (T.actualIn + actualPort X e).val).val = + encode w (X.width ((src.1.1,src.2),src.1.2)) := by + rw [rep.actualIn]; exact rep.width _ + +/-- Use these same base records in the greedy operand scans. -/ +def greedyTables (T : IncidenceDirectory w) (a : ℕ) (labels zero : Word w) : Greedy.PortTables w := + ⟨encode w (2^a), T.baseOut, T.baseIn, T.shift, labels, zero⟩ + +theorem Represents.greedy {T : IncidenceDirectory w} {X : State a l} {m : Memory w} + (rep : T.Represents X m) (labels zero : Word w) + (hd : 2^a < 2^w) (hfit : Fintype.card X.Base * 2^a ≤ 2^w) : + (T.greedyTables a labels zero).Represents X.slots.base X.baseIndex m where + degree := Nat.mod_eq_of_lt hd + fits := hfit + vertices := (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)).trans hfit + outgoing := rep.baseOut + incoming := rep.baseIn + +end IncidenceDirectory + +namespace CursorRAM + +variable {w b l a pad : ℕ} {S : Type} [Fintype S] + +/-- A level-zero cursor coordinate and base bit string together with one port slot. -/ +abbrev BasePort (b l a : ℕ) := (Fin (b+l) × BitWord b) × Fin (2^a) +/-- A level-zero base position refined by its lane bit string and a port slot. -/ +abbrev ActualPort (b l a : ℕ) := ((Fin (b+l) × BitWord b) × BitWord l) × Fin (2^a) + +/-- The loop counter enumerates all actual sources once. -/ +def actualOrder (b l a : ℕ) : ActualPort b l a ≃ Fin (rowCount b l a) := + ((cursorActualIndex b l).prodCongr (Equiv.refl _)).trans finProdFinEquiv + +/-- Number level-zero base ports consecutively in cursor-base order, with slots consecutive +inside each base position. -/ +def baseOrder (b l a : ℕ) : BasePort b l a ≃ Fin ((b+l)*2^b*2^a) := + ((cursorBaseIndex b l).prodCongr (Equiv.refl _)).trans finProdFinEquiv + +theorem actualOrder_val (e : ActualPort b l a) : + (actualOrder b l a e).val = cursorActualSlotNumber e := by + change e.2.val + 2^a * _ = _ * 2^a + e.2.val + ac_rfl + +theorem baseOrder_val (e : BasePort b l a) : + (baseOrder b l a e).val = cursorBaseSlotNumber e := by + change e.2.val + 2^a * _ = _ * 2^a + e.2.val + ac_rfl + +/-- The eleven initializer operands giving the degree, cursor dimension, base and lane radices, +arc width, and six incidence column bases. -/ +def publicWords (w b l a W start : ℕ) : Fin 11 → Word w := + ![encode w (2^a), encode w (b+l), encode w (2^b), encode w (2^l), encode w W, + encode w (start + 0*rowCount b l a), encode w (start + 1*rowCount b l a), + encode w (start + 2*rowCount b l a), encode w (start + 3*rowCount b l a), + encode w (start + 4*rowCount b l a), encode w (start + 5*rowCount b l a)] + +/-- Lay out the six level-zero incidence columns at equally spaced addresses starting at the +supplied workspace location. -/ +def directory (w b l a start : ℕ) : IncidenceDirectory w := + let p := publicWords w b l a 0 start + ⟨p 5, p 6, p 7, p 8, p 9, p 10⟩ + +theorem publicWords_parameters (w b l a W start : ℕ) : + Parameters (publicWords w b l a W start) b l a W := ⟨rfl,rfl,rfl,rfl,rfl⟩ + +variable (hD : 1 < b+l) (hd : 2+pad = 2^a) (bits : S → ℕ) +local notation "X₀" => cursorState (cursorCoordinateLabels b l) hD hd bits +local notation "W₀" => ∑ s, bits s + +/-- The level-zero record for an actual outgoing port, encoding its base source and target, +displacement, actual target, and width. -/ +noncomputable def typedRow (e : ActualPort b l a) : Row (Word w) := + let B := IncidenceDirectory.basePort (w := w) X₀ + let A := IncidenceDirectory.actualPort (w := w) X₀ + let src := (e.1.1,e.2) + ⟨B src, B ((X₀).slots.base.target src), encode w (bitWordFinEquiv l ((X₀).slots.displacement src)).val, + A ((X₀).slots.actualGraph.target e), encode w ((X₀).width (src,e.1.2))⟩ + +private theorem baseNumber (e : BasePort b l a) : + IncidenceDirectory.basePort X₀ e = encode w (baseOrder b l a e).val := by + rw [baseOrder_val]; rfl + +private theorem actualNumber (e : ActualPort b l a) : + IncidenceDirectory.actualPort X₀ e = encode w (actualOrder b l a e).val := by + rw [actualOrder_val, cursorActualSlotNumber, cursorActualIndex_val]; rfl + +/-- The actual emitted six values use the slot permutation of the typed state. -/ +theorem visit_row (start : ℕ) (fit : rowCount b l a < 2^w) (e : ActualPort b l a) : + wordRow (publicWords w b l a W₀ start) (encode w (actualOrder b l a e).val) = + typedRow hD hd bits e := by + rcases e with ⟨⟨⟨j,x⟩,g⟩,s⟩ + rw [actualOrder_val, cursorActualSlotNumber, cursorActualIndex_val, cursorBaseIndex_val, + wordRow_exact (publicWords_parameters ..) hD (by omega) fit j.isLt + (bitWordFinEquiv b x).isLt (bitWordFinEquiv l g).isLt s.isLt] + dsimp only [typedRow] + simp only [Row.mk.injEq] + refine ⟨?_, ?_, ?_, ?_, ?_⟩ + · exact (congrArg (encode w) (congrArg (fun v => v*2^a+s.val) (cursorBaseIndex_val j x))).symm + · exact ((baseNumber hD hd bits _).trans (congrArg (encode w) + ((baseOrder_val _).trans (cursorBaseTargetNumber hD hd bits j x s)))).symm + · exact (congrArg (encode w) (cursorDisplacementNumber hD hd bits j x s)).symm + · exact ((actualNumber hD hd bits _).trans (congrArg (encode w) + ((actualOrder_val _).trans (cursorActualTargetNumber hD hd bits j x g s)))).symm + · exact (congrArg (encode w) (cursorSlotWidth hD hd bits j x g s)).symm + +/-- Decode a row within a given column. The base arrays occupy prefixes of their +reserved regions. The words after each base prefix are immaterial. -/ +private noncomputable def column (t : Fin 6) (i : ℕ) : Word w := + haveI : NeZero (b+l) := ⟨by omega⟩ + haveI : NeZero (rowCount b l a) := ⟨by unfold rowCount; positivity⟩ + let e := (baseOrder b l a).symm (Fin.ofNat _ i) + let z := (actualOrder b l a).symm (Fin.ofNat _ i) + ![IncidenceDirectory.basePort X₀ ((X₀).slots.base.target e), + IncidenceDirectory.basePort X₀ ((X₀).slots.base.target.symm e), + encode w (bitWordFinEquiv l ((X₀).slots.displacement e)).val, + IncidenceDirectory.actualPort X₀ ((X₀).slots.actualGraph.target z), + IncidenceDirectory.actualPort X₀ ((X₀).slots.actualGraph.target.symm z), + encode w ((X₀).width ((z.1.1,z.2),z.1.2))] t + +/-- Interpret an external address relative to the level's reserved region. -/ +private noncomputable def specification (start : ℕ) (addr : ℕ) : Word w := + column hD hd bits (Fin.ofNat _ ((addr-start)/rowCount b l a)) ((addr-start)%rowCount b l a) + +private theorem baseRows_le (b l a : ℕ) : (b+l)*2^b*2^a ≤ rowCount b l a := + Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos l)) + +private theorem atColumn {start : ℕ} (room : start + 6*rowCount b l a ≤ 2^w) + (t : Fin 6) {i : ℕ} (hi : i < rowCount b l a) : + specification (w := w) hD hd bits start ((encode w (start + t.val * rowCount b l a) + encode w i).val) = + column hD hd bits t i := by + let n := rowCount b l a + have haddr : start + t.val * n + i < 2^w := by + have h : t.val*n+i < 6*n := packed_lt t.isLt hi + change start+6*n ≤ 2^w at room + omega + have hpre : start + t.val*n < 2^w := by omega + have hival : i < 2^w := by omega + change column hD hd bits (Fin.ofNat _ ((_ - start)/n)) ((_ - start)%n) = _ + rw [Fin.val_add, Fin.val_ofNat, Fin.val_ofNat, Nat.mod_eq_of_lt hpre, Nat.mod_eq_of_lt hival, + Nat.mod_eq_of_lt haddr, Nat.add_assoc, Nat.add_sub_cancel_left, Nat.mul_add_mod_of_lt hi, + Nat.mul_comm t.val n, Nat.mul_add_div (by omega), Nat.div_eq_of_lt hi, Nat.add_zero] + have ht : Fin.ofNat 6 t.val = t := Fin.ext (Nat.mod_eq_of_lt t.isLt) + rw [ht] + +private theorem baseCol {start : ℕ} (room : start + 6*rowCount b l a ≤ 2^w) + (t : Fin 6) (e : BasePort b l a) : + specification (w := w) hD hd bits start + ((encode w (start + t.val * rowCount b l a) + IncidenceDirectory.basePort X₀ e).val) = + column hD hd bits t (baseOrder b l a e).val := by + rw [baseNumber] + exact atColumn hD hd bits room t ((baseOrder b l a e).isLt.trans_le (baseRows_le ..)) + +private theorem actualCol {start : ℕ} (room : start + 6*rowCount b l a ≤ 2^w) + (t : Fin 6) (e : ActualPort b l a) : + specification (w := w) hD hd bits start + ((encode w (start + t.val * rowCount b l a) + IncidenceDirectory.actualPort X₀ e).val) = + column hD hd bits t (actualOrder b l a e).val := by + rw [actualNumber]; exact atColumn hD hd bits room t (actualOrder b l a e).isLt + +private theorem directory_spec {start : ℕ} (room : start + 6*rowCount b l a ≤ 2^w) : + (directory w b l a start).Represents X₀ (specification hD hd bits start) := by + constructor + all_goals intro e + case baseOut => + apply (baseCol hD hd bits room 0 e).trans + simp [column] + erw [Equiv.symm_apply_apply] + case baseIn => + apply (baseCol hD hd bits room 1 e).trans + simp [column] + erw [Equiv.symm_apply_apply] + case shift => + apply (baseCol hD hd bits room 2 e).trans + simp [column] + erw [Equiv.symm_apply_apply] + case actualOut => + apply (actualCol hD hd bits room 3 e).trans + simp [column] + erw [Equiv.symm_apply_apply] + case actualIn => + apply (actualCol hD hd bits room 4 e).trans + simp [column] + erw [Equiv.symm_apply_apply] + case width => + apply (actualCol hD hd bits room 5 e).trans + simp [column] + erw [Equiv.symm_apply_apply] + +private noncomputable def typedWrites (T : IncidenceDirectory w) (e : ActualPort b l a) : List (Word w × Word w) := + let r := typedRow (w := w) hD hd bits e + let src := IncidenceDirectory.actualPort (w := w) X₀ e + [(T.baseOut+r.sourceBase,r.targetBase), (T.baseIn+r.targetBase,r.sourceBase), + (T.shift+r.sourceBase,r.displacement), (T.actualOut+src,r.targetActual), + (T.actualIn+r.targetActual,src), (T.width+src,r.width)] + +private theorem rowWrites_typed (start : ℕ) (fit : rowCount b l a < 2^w) (e : ActualPort b l a) : + rowWrites (publicWords w b l a W₀ start) (actualOrder b l a e).val = + typedWrites hD hd bits (directory w b l a start) e := by + dsimp only [rowWrites] + rw [visit_row hD hd bits start fit e] + dsimp only [typedWrites] + rw [actualNumber hD hd bits e] + rfl + +private theorem written_correct {T : IncidenceDirectory w} {m : Memory w} (rep : T.Represents X₀ m) + (e : ActualPort b l a) (v : Word w × Word w) (hv : v ∈ typedWrites hD hd bits T e) : + m v.1.val = v.2 := by + simp only [typedWrites, List.mem_cons, List.not_mem_nil, or_false] at hv + rcases hv with rfl | rfl | rfl | rfl | rfl | rfl + · exact rep.baseOut _ + · exact (rep.baseIn _).trans (congrArg (IncidenceDirectory.basePort X₀) + ((X₀).slots.base.target.symm_apply_apply _)) + · exact rep.shift _ + · exact rep.actualOut _ + · exact (rep.actualIn _).trans (congrArg (IncidenceDirectory.actualPort X₀) + ((X₀).slots.actualGraph.target.symm_apply_apply e)) + · exact rep.width _ + +private theorem complete_of_writes (T : IncidenceDirectory w) (m : Memory w) + (h : ∀ e v, v ∈ typedWrites hD hd bits T e → m v.1.val = v.2) : T.Represents X₀ m := by + have atIndex (e : ActualPort b l a) (i : Fin 6) := h e + ((typedWrites hD hd bits T e).get i) (List.get_mem ..) + constructor + · intro e; exact atIndex ((e.1,0),e.2) 0 + · intro e + let z := (X₀).slots.base.target.symm e + have he := atIndex ((z.1,0),z.2) 1 + change m (T.baseIn+IncidenceDirectory.basePort X₀ ((X₀).slots.base.target z)).val = + IncidenceDirectory.basePort X₀ z at he + rwa [show (X₀).slots.base.target z = e from (X₀).slots.base.target.apply_symm_apply e] at he + · intro e; exact atIndex ((e.1,0),e.2) 2 + · intro e; exact atIndex e 3 + · intro e + let z := (X₀).slots.actualGraph.target.symm e + have he := atIndex z 4 + change m (T.actualIn+IncidenceDirectory.actualPort X₀ ((X₀).slots.actualGraph.target z)).val = + IncidenceDirectory.actualPort X₀ z at he + rwa [show (X₀).slots.actualGraph.target z = e from (X₀).slots.actualGraph.target.apply_symm_apply e] at he + · intro e; exact atIndex e 5 + +open PrimedStackRAM in +/-- From arbitrary memory, the fixed finite program initializes the graph directory of +the typed compressor. It visits every actual outgoing slot and accounts for six probes +plus one call. The full incoming columns follow from bijectivity of the slot matchings. -/ +theorem initialize_cursor {start : ℕ} (room : start + 6*rowCount b l a ≤ 2^w) + (widthFits : W₀ < 2^w) (m : Memory w) : + let p := publicWords w b l a W₀ start + let n := rowCount b l a + let M := (template visit 0).instantiate w p + let rs := scanReports p 0 n + let mem := after m (eventLog rs) + let T := directory w b l a start + runSegment M.program (1+visit.length) (some (encode w 0)) m (List.replicate n []) = some rs ∧ + T.Represents X₀ mem ∧ + (∀ e : ActualPort b l a, (mem (T.width + IncidenceDirectory.actualPort X₀ e).val).val = + (X₀).width ((e.1.1,e.2),e.1.2)) ∧ + rs.length = n ∧ (∀ r ∈ rs, r.events.length = visit.length ∧ countProbes r.events = 6) ∧ + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = 7*n ∧ + (∀ addr, ¬ Touches p 0 n addr → mem addr = m addr) := by + intro p n M rs mem T + let spec := specification (w := w) hD hd bits start + have fit : n < 2^w := by + have hp : 0 < n := by dsimp [n, rowCount]; positivity + change start+6*n ≤ 2^w at room + omega + have correct := written_correct hD hd bits (directory_spec hD hd bits room) + have typed (e : ActualPort b l a) : rowWrites p (actualOrder b l a e).val = + typedWrites hD hd bits T e := rowWrites_typed hD hd bits start fit e + have agree (i : ℕ) (_ : 0 ≤ i) (hi : i < 0+n) (av) (hv : av ∈ rowWrites p i) : + spec av.1.val = av.2 := by + let u : Fin n := ⟨i,by omega⟩ + let e := (actualOrder b l a).symm u + have he : (actualOrder b l a e).val = i := congrArg Fin.val ((actualOrder b l a).apply_symm_apply u) + exact correct e av (by rwa [← he, typed] at hv) + obtain ⟨out, hout, _, _, hfinal, hkeep⟩ := scan_run p 0 n m spec agree + have hnative := scan_native p 0 n m + obtain rfl : out = rs := Option.some.inj (hout.symm.trans hnative) + have hrep : T.Represents X₀ mem := by + apply complete_of_writes hD hd bits T mem + intro e v hv + have hmem := (typed e).symm ▸ hv + have htouch : Touches p 0 n v.1.val := + ⟨(actualOrder b l a e).val, Nat.zero_le _, by rw [Nat.zero_add]; exact (actualOrder b l a e).isLt, + v,hmem,rfl⟩ + exact (hfinal _ htouch).trans (correct e v hv) + refine ⟨hnative,hrep,?_,scanReports_length ..,scanReports_work p 0 n,scan_cost ..,hkeep⟩ + rintro ⟨⟨⟨j,x⟩,g⟩,i⟩ + apply (congrArg Fin.val (hrep.width (((j,x),g),i))).trans + apply Nat.mod_eq_of_lt + change (X₀).width (((j,x),i),g) < _ + erw [cursorSlotWidth hD hd bits j x g i] + split <;> omega + +/-- Linear cost in the Section 12 position count at fixed dyadic degree. -/ +theorem initialization_cost (p : Fin 11 → Word w) : + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) (scanReports p 0 (rowCount b l a)) = + (7*2^a) * (2^(b+l)*(b+l)) := by + rw [scan_cost, rowCount, pow_add]; ring + +open CursorBounds CursorRouting Filter PrimedStackRAM in +/-- At all sufficiently large input lengths the native initialization constructs the +complete Section 12 directory. The same threshold covers every partition of the virtual +address into a contiguous base block and lane block. -/ +theorem eventually_initialize (B a pad : ℕ) (hB : 1 ≤ B) (hd : 2+pad = 2^a) + {start : ℕ → ℕ} (hs : PolynomiallyBounded start) : + ∀ᶠ n : ℕ in atTop, ∀ b l, b+l = virtualBits B n → ∃ hD : 1 < b+l, + let w := wordBits B n + let widths : RAMSystem (b+l) → ℕ := ramFieldBits (virtualBucket n) w + let X := cursorState (cursorCoordinateLabels b l) hD hd widths + let p := publicWords w b l a (initialWidth B n) (start n) + let N := rowCount b l a + let M := (template visit 0).instantiate w p + let rs := scanReports p 0 N + ∀ m : Memory w, + runSegment M.program (1+visit.length) (some (encode w 0)) m (List.replicate N []) = some rs ∧ + (directory w b l a (start n)).Represents X (after m (eventLog rs)) ∧ + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = + (7*2^a)*initialPositions B n ∧ + (∀ r ∈ probeRecords (start n) rs, RecordFitsWord r) := by + filter_upwards [eventually_cursorCapacity B a hB hs] with n h + intro b l he + obtain ⟨hD, hroom, hw, hclock⟩ := h b l he + refine ⟨hD, ?_⟩ + intro w widths X p N M rs m + have hwidth : (∑ s, widths s) = initialWidth B n := by + dsimp only [widths, w, initialWidth] + rw [he] + have hi := initialize_cursor hD hd widths hroom (hwidth ▸ hw) m + dsimp only at hi + rw [hwidth] at hi + refine ⟨hi.1,hi.2.1,?_,fun _ hr ↦ scan_probeRecords_fitsWord p hclock hr⟩ + change RAMBuckets.cost _ (scanReports p 0 (rowCount b l a)) = _ + rw [scan_cost, rowCount_eq_positions he] + ring + +end CursorRAM + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCursorCapacity.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorCapacity.lean new file mode 100644 index 0000000000..4754177dbf --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorCapacity.lean @@ -0,0 +1,100 @@ +import OAI.Computability.VPVNP.CompressorRecordsCursorWords +import OAI.Computability.VPVNP.CompressorRecordsCursorScan +import OAI.Computability.VPVNP.CursorCompressionBudget +import OAI.Computability.VPVNP.PolynomialBounds +import OAI.Computability.VPVNP.RAMWordBounds + +/-! +# Word space for initializing the cursor records + +At fixed degree, the number of rows is polynomial in the input length and +independent of where the physical address is split into base and lane blocks. +The same word accommodates the initial width, the six arrays and a timestamp +for every probe of the scan. A polynomially bounded starting offset can be +chosen before the eventual length threshold. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CursorRAM + +open CursorBounds Filter + +/-- Splitting the virtual address does not change the number of actual ports. -/ +theorem rowCount_eq_positions {B n b l : ℕ} (h : b+l = virtualBits B n) (a : ℕ) : + rowCount b l a = initialPositions B n * 2^a := by + unfold rowCount initialPositions + rw [← h, pow_add] + ac_rfl + +/-- The number of actual cursor positions is polynomially bounded for fixed address exponent. -/ +theorem bounded_positions (B : ℕ) : PolynomiallyBounded (initialPositions B) := by + let upper := ((PolynomiallyBounded.const 2).mul PolynomiallyBounded.id).pow (B+2) + refine (upper.mul upper).of_eventually_le 1 fun n hn ↦ ?_ + have hlog : 2 ^ n.log2 ≤ n := (Nat.le_log2 (by omega : n ≠ 0)).mp le_rfl + have hc : 2 ^ Nat.clog 2 n ≤ 2*n := calc + _ ≤ 2 ^ (n.log2 + 1) := Nat.pow_le_pow_right Nat.zero_lt_two (BurstRAM.clog_le_log2_succ n) + _ = 2 * 2 ^ n.log2 := pow_succ' .. + _ ≤ _ := Nat.mul_le_mul_left _ hlog + have hv : 2 ^ virtualBits B n ≤ (2*n) ^ (B+2) := calc + _ ≤ 2 ^ ((B+2)*Nat.clog 2 n) := Nat.pow_le_pow_right Nat.zero_lt_two (virtualBits_le B n) + _ = (2 ^ Nat.clog 2 n) ^ (B+2) := by rw [Nat.mul_comm, pow_mul] + _ ≤ _ := Nat.pow_le_pow_left hc _ + exact Nat.mul_le_mul hv (Nat.lt_two_pow_self.le.trans hv) + +/-- A fixed polynomially bounded natural address fits strictly below the word modulus. -/ +theorem eventual_word_room (B : ℕ) (hB : 1 ≤ B) {f : ℕ → ℕ} + (hf : PolynomiallyBounded f) : ∀ᶠ n : ℕ in atTop, f n < 2 ^ wordBits B n := by + obtain ⟨A,d,N,h⟩ := hf + filter_upwards [eventually_ge_atTop N, eventually_ge_atTop A, + BurstRAM.eventually_polynomial_lt_wordModulus (d+1)] with n hn hA hp + apply lt_of_le_of_lt ((h n hn).trans (Nat.mul_le_mul_right (n^d) hA)) + rw [← pow_succ'] + exact hp (addressBits B n) (BurstRAM.log2_le_addressWidth hB n) + +private theorem eventual_width (B : ℕ) (hB : 1 ≤ B) : + ∀ᶠ n : ℕ in atTop, initialWidth B n < 2 ^ wordBits B n := by + have ha := Compression.eventually_absorb_polylog + (56 * ((B : ℝ) + 3)^2 * ((B : ℝ) + 10)^4) 6 + (show (1/4 : ℝ) < 1 by norm_num) (show (0 : ℝ) < 1 by norm_num) + filter_upwards [ha, eventually_ge_atTop 2, eventual_word_room B hB PolynomiallyBounded.id] + with n habs hn hword + have hw : (initialWidth B n : ℝ) ≤ n := (initialWidth_bound B n hn).trans (by simpa using habs) + exact (show initialWidth B n ≤ n by exact_mod_cast hw).trans_lt hword + +/-- All capacity conditions for the first descriptor scan. Seven words of +cost per row account for one call and its six probes. The threshold works +for every split of the virtual address at each sufficiently large length. -/ +theorem eventually_cursorCapacity (B a : ℕ) (hB : 1 ≤ B) {start : ℕ → ℕ} + (hs : PolynomiallyBounded start) : + ∀ᶠ n : ℕ in atTop, ∀ b l, b+l = virtualBits B n → + 1 < b+l ∧ start n + 6*rowCount b l a ≤ 2 ^ wordBits B n ∧ + initialWidth B n < 2 ^ wordBits B n ∧ start n + 7*rowCount b l a ≤ 2 ^ wordBits B n := by + have hrows := (bounded_positions B).mul (PolynomiallyBounded.const (2^a)) + have hcost := hs.add ((PolynomiallyBounded.const 7).mul hrows) + filter_upwards [eventually_ge_atTop 3, eventual_word_room B hB hcost, eventual_width B hB] + with n hn hroom hwidth + intro b l he + have hc : 1 < Nat.clog 2 n := (Nat.lt_clog_iff_pow_lt Nat.one_lt_two).mpr (by omega) + have hd := (hc.trans_le (Nat.le_mul_of_pos_left _ hB)).trans_le (addressBits_le_virtualBits B n hn) + change start n + 7 * (initialPositions B n * 2^a) < 2 ^ wordBits B n at hroom + rw [← rowCount_eq_positions he] at hroom + exact ⟨he ▸ hd, by omega, hwidth, hroom.le⟩ + +/-- Every chronological RAM record of the native scan has a word-sized +address, timestamp and ordinal as soon as the scan's ending cost fits. -/ +theorem scan_probeRecords_fitsWord {w start k n : ℕ} (p : Fin 11 → BurstRAM.Word w) + (room : start + 7*n ≤ 2^w) {r : RAMMemory.Record (BurstRAM.Word w)} + (hr : r ∈ BurstRAM.probeRecords start (scanReports p k n)) : BurstRAM.RecordFitsWord r := by + apply BurstRAM.probeRecords_fitsWord _ hr + change start + RAMBuckets.cost (fun r : BurstRAM.Report w ↦ BurstRAM.countProbes r.events) + (scanReports p k n) ≤ 2^w + rwa [scan_cost] + +end CompressorRecords.CursorRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCursorCoordinates.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorCoordinates.lean new file mode 100644 index 0000000000..e285b5586e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorCoordinates.lean @@ -0,0 +1,225 @@ +import OAI.Computability.VPVNP.CursorState +import OAI.Computability.VPVNP.BitSlotXor + +/-! +# Numerical coordinates for the initial compressor graph + +The RAM visits outgoing slots in cursor, base-address, lane and slot order. +Physical address bits have increasing significance, whereas the compressor +numbers each binary block with its first coordinate most significant. Reversing +the coordinates within each designated block identifies the cursor's one-bit +flip with the corresponding power of two in its RAM word. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CursorNetwork + +open Compression (BitWord bitWordFinEquiv bitWordFinEquiv_val bitWordFinEquiv_add_val) + +variable {b l a p : ℕ} {S : Type} [Fintype S] + +/-- Designate a low base-address block and a high lane block. Each compressor +block is ordered most significant bit first. -/ +def cursorCoordinateLabels (b l : ℕ) : Fin (b + l) ≃ Fin b ⊕ Fin l := + finSumFinEquiv.symm.trans (Fin.revPerm.sumCongr Fin.revPerm) + +/-- Cursor-major base numbering. -/ +def cursorBaseIndex (b l : ℕ) : Fin (b + l) × BitWord b ≃ Fin ((b + l) * 2 ^ b) := + ((Equiv.refl _).prodCongr (bitWordFinEquiv b)).trans finProdFinEquiv + +/-- Base-major numbering of positions, with consecutive lanes. -/ +def cursorActualIndex (b l : ℕ) : + (Fin (b + l) × BitWord b) × BitWord l ≃ Fin (((b + l) * 2 ^ b) * 2 ^ l) := + ((cursorBaseIndex b l).prodCongr (bitWordFinEquiv l)).trans finProdFinEquiv + +/-- Source or destination slot in the base records. -/ +def cursorBaseSlotNumber (e : (Fin (b + l) × BitWord b) × Fin (2 ^ a)) : ℕ := + (cursorBaseIndex b l e.1).val * 2 ^ a + e.2.val + +/-- Source or destination slot in the actual-wire records. -/ +def cursorActualSlotNumber (e : ((Fin (b + l) × BitWord b) × BitWord l) × Fin (2 ^ a)) : ℕ := + (cursorActualIndex b l e.1).val * 2 ^ a + e.2.val + +theorem cursorBaseIndex_val (j : Fin (b + l)) (x : BitWord b) : + (cursorBaseIndex b l (j,x)).val = j.val * 2 ^ b + (bitWordFinEquiv b x).val := by + change (bitWordFinEquiv b x).val + 2 ^ b * j.val = _ + ac_rfl + +theorem cursorActualIndex_val (v : Fin (b + l) × BitWord b) (g : BitWord l) : + (cursorActualIndex b l (v,g)).val = + (cursorBaseIndex b l v).val * 2 ^ l + (bitWordFinEquiv l g).val := by + change (bitWordFinEquiv l g).val + 2 ^ l * (cursorBaseIndex b l v).val = _ + ac_rfl + +/-- The record numbering agrees with the indexed vertex order used by +the greedy scans on the initial compressor state. -/ +theorem cursorState_baseIndex_val (hD : 1 < b + l) (hd : 2 + p = 2 ^ a) (bits : S → ℕ) + (v : Fin (b + l) × BitWord b) : + ((cursorState (cursorCoordinateLabels b l) hD hd bits).baseIndex v).val = + (cursorBaseIndex b l v).val := rfl + +/-- Numeric destination vertex of a base slot. -/ +def cursorNextBase (b l j x i : ℕ) : ℕ := + ((j + 1) % (b + l)) * 2 ^ b + (x ^^^ (if i = 1 ∧ j < b then 2 ^ j else 0)) + +/-- Numeric lane displacement of the slot. -/ +def cursorLaneMask (b j i : ℕ) : ℕ := + if i = 1 ∧ b ≤ j then 2 ^ (j - b) else 0 + +private theorem bitWord_zero (n : ℕ) : (bitWordFinEquiv n 0).val = 0 := by + simpa using bitWordFinEquiv_add_val (0 : BitWord n) 0 + +private theorem bitWord_single {n : ℕ} (j : Fin n) : + (bitWordFinEquiv n (fun k ↦ if k = j.rev then 1 else 0)).val = 2 ^ j.val := by + induction n with + | zero => exact j.elim0 + | succ n ih => + induction j using Fin.lastCases with + | last => + have ht : Fin.tail (fun k : Fin (n + 1) ↦ if k = (Fin.last n).rev then + (1 : ZMod 2) else 0) = 0 := by + funext k + simp [Fin.tail] + rw [bitWordFinEquiv_val, ht, bitWord_zero] + simp + decide + | cast j => + have ht : Fin.tail (fun k : Fin (n + 1) ↦ if k = j.castSucc.rev then + (1 : ZMod 2) else 0) = (fun k ↦ if k = j.rev then 1 else 0) := by + funext k + simp [Fin.tail, Fin.rev_castSucc] + rw [bitWordFinEquiv_val, ht, ih] + simp [Fin.rev_castSucc, (Fin.succ_ne_zero _).symm] + +private theorem padding_slot_flip (i : Fin (2 + p)) : slotSide i = true ↔ i.val = 1 := by + obtain ⟨s | k, rfl⟩ := (paddingSlots p).surjective i + · rw [slotSide_real] + cases s with + | false => exact (by decide : (false = true ↔ (0 : ℕ) = 1)) + | true => exact (by decide : (true = true ↔ (1 : ℕ) = 1)) + · rw [slotSide_pad] + change false = true ↔ 2 + k.val = 1 + simp; omega + +private theorem partition_base (j : Fin (b + l)) (side : Bool) : + (bitWordFinEquiv b ((addressPartition (cursorCoordinateLabels b l) + (stepShift j side)).1)).val = if side = true ∧ j.val < b then 2 ^ j.val else 0 := by + by_cases h : side = true ∧ j.val < b + · let t : Fin b := ⟨j.val, h.2⟩ + have he : (addressPartition (cursorCoordinateLabels b l) (stepShift j side)).1 = + (fun k ↦ if k = t.rev then 1 else 0) := by + funext k + change (if side = true ∧ j = k.rev.castAdd l then (1 : ZMod 2) else 0) = _ + have hj : j = k.rev.castAdd l ↔ k = t.rev := by + rw [← Fin.rev_inj (i := k) (j := t.rev), Fin.rev_rev, eq_comm (a := k.rev)] + rw [Fin.ext_iff, Fin.ext_iff] + rfl + simp [hj, h.1] + rw [he, bitWord_single, ite_eq_left h] + · have he : (addressPartition (cursorCoordinateLabels b l) (stepShift j side)).1 = 0 := by + funext k + change (if side = true ∧ j = k.rev.castAdd l then (1 : ZMod 2) else 0) = 0 + exact ite_eq_right (fun ⟨hs, he⟩ ↦ h ⟨hs, he ▸ k.rev.isLt⟩) + rw [he, bitWord_zero, ite_eq_right h] + +private theorem partition_lane (j : Fin (b + l)) (side : Bool) : + (bitWordFinEquiv l ((addressPartition (cursorCoordinateLabels b l) + (stepShift j side)).2)).val = if side = true ∧ b ≤ j.val then 2 ^ (j.val - b) else 0 := by + by_cases h : side = true ∧ b ≤ j.val + · let t : Fin l := ⟨j.val - b, by have := j.isLt; omega⟩ + have he : (addressPartition (cursorCoordinateLabels b l) (stepShift j side)).2 = + (fun k ↦ if k = t.rev then 1 else 0) := by + funext k + change (if side = true ∧ j = k.rev.natAdd b then (1 : ZMod 2) else 0) = _ + have hj : j = k.rev.natAdd b ↔ k = t.rev := by + rw [← Fin.rev_inj (i := k) (j := t.rev), Fin.rev_rev, Fin.ext_iff, Fin.ext_iff] + change j.val = b + k.rev.val ↔ k.rev.val = j.val - b + omega + simp [hj, h.1] + rw [he, bitWord_single, ite_eq_left h] + · have he : (addressPartition (cursorCoordinateLabels b l) (stepShift j side)).2 = 0 := by + funext k + change (if side = true ∧ j = k.rev.natAdd b then (1 : ZMod 2) else 0) = 0 + exact ite_eq_right (fun ⟨hs, he⟩ ↦ h ⟨hs, he ▸ Nat.le_add_right b _⟩) + rw [he, bitWord_zero, ite_eq_right h] + +variable (hD : 1 < b + l) (hd : 2 + p = 2 ^ a) (bits : S → ℕ) + +private theorem cursorNextIndex (j : Fin (b + l)) (x : BitWord b) (i : Fin (2 ^ a)) : + (cursorBaseIndex b l + ((cursorState (cursorCoordinateLabels b l) hD hd bits).slots.base.target ((j,x),i)).1).val = + cursorNextBase b l j.val (bitWordFinEquiv b x).val i.val := by + let side := slotSide ((finCongr hd).symm i) + change (cursorBaseIndex b l (finRotate (b + l) j, + x + (addressPartition (cursorCoordinateLabels b l) (stepShift j side)).1)).val = _ + have hs : side = true ↔ i.val = 1 := padding_slot_flip _ + have : NeZero (b + l) := ⟨by omega⟩ + rw [cursorBaseIndex_val, bitWordFinEquiv_add_val, partition_base, finRotate_apply, + Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt hD] + simp only [hs, cursorNextBase] + +/-- Each outgoing base slot writes its own incoming slot number at the +rotated cursor and the updated base address. -/ +theorem cursorBaseTargetNumber (j : Fin (b + l)) (x : BitWord b) (i : Fin (2 ^ a)) : + cursorBaseSlotNumber + ((cursorState (cursorCoordinateLabels b l) hD hd bits).slots.base.target ((j,x),i)) = + cursorNextBase b l j.val (bitWordFinEquiv b x).val i.val * 2 ^ a + i.val := by + exact congrArg (fun n : ℕ ↦ n * 2 ^ a + i.val) (cursorNextIndex hD hd bits j x i) + +/-- The stored displacement is the translated physical bit of the lane block. -/ +theorem cursorDisplacementNumber (j : Fin (b + l)) (x : BitWord b) (i : Fin (2 ^ a)) : + (bitWordFinEquiv l + ((cursorState (cursorCoordinateLabels b l) hD hd bits).slots.displacement ((j,x),i))).val = + cursorLaneMask b j.val i.val := by + let side := slotSide ((finCongr hd).symm i) + change (bitWordFinEquiv l + ((addressPartition (cursorCoordinateLabels b l) (stepShift j side)).2)).val = _ + have hs : side = true ↔ i.val = 1 := padding_slot_flip _ + simp only [partition_lane, hs, cursorLaneMask] + +/-- Flattening the actual graph's target into a record address updates +the base and lane separately and preserves the slot. -/ +theorem cursorActualTargetNumber (j : Fin (b + l)) (x : BitWord b) (g : BitWord l) + (i : Fin (2 ^ a)) : + cursorActualSlotNumber + ((cursorState (cursorCoordinateLabels b l) hD hd bits).slots.actualGraph.target (((j,x),g),i)) = + (cursorNextBase b l j.val (bitWordFinEquiv b x).val i.val * 2 ^ l + + ((bitWordFinEquiv l g).val ^^^ cursorLaneMask b j.val i.val)) * 2 ^ a + i.val := by + let G : Compression.LiftedSlots (Fin (b + l) × BitWord b) (2 ^ a) (BitWord l) := + (cursorState (cursorCoordinateLabels b l) hD hd bits).slots + change (cursorActualIndex b l ((G.base.target ((j,x),i)).1, + g + G.displacement ((j,x),i))).val * 2 ^ a + i.val = _ + rw [cursorActualIndex_val, bitWordFinEquiv_add_val] + have hb := cursorNextIndex hD hd bits j x i + have hl := cursorDisplacementNumber hD hd bits j x i + change (cursorBaseIndex b l (G.base.target ((j,x),i)).1).val = _ at hb + change (bitWordFinEquiv l (G.displacement ((j,x),i))).val = _ at hl + rw [hb, hl] + +private theorem numbered_width {D : ℕ} (v : Position D) (i : Fin (2 + p)) : + paddedWidth bits ((paddedEdgeEquiv D p).symm (v,i)) = if i.val < 2 then ∑ s, bits s else 0 := by + obtain ⟨s | k, rfl⟩ := (paddingSlots p).surjective i + · change paddedWidth bits (match (paddingSlots p).symm (paddingSlots p (.inl s)) with + | .inl t => .inl (v.1,v.2,t) | .inr u => .inr (v,u)) = _ + rw [Equiv.symm_apply_apply] + exact (ite_eq_left ((finTwoEquiv.symm s).isLt)).symm + · change paddedWidth bits (match (paddingSlots p).symm (paddingSlots p (.inr k)) with + | .inl t => .inl (v.1,v.2,t) | .inr u => .inr (v,u)) = _ + rw [Equiv.symm_apply_apply] + exact (ite_eq_right (show ¬2 + k.val < 2 by omega)).symm + +/-- Stay and flip wires reserve all fields. Each further slot is a zero-width copy. -/ +theorem cursorSlotWidth (j : Fin (b + l)) (x : BitWord b) (g : BitWord l) (i : Fin (2 ^ a)) : + (cursorState (cursorCoordinateLabels b l) hD hd bits).width (((j,x),i),g) = + if i.val < 2 then ∑ s, bits s else 0 := + numbered_width bits ((lanePositions (cursorCoordinateLabels b l)).symm ((j,x),g)) + ((finCongr hd).symm i) + +end CursorNetwork + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCursorInit.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorInit.lean new file mode 100644 index 0000000000..262ef95abb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorInit.lean @@ -0,0 +1,158 @@ +import OAI.Computability.VPVNP.CompressorRecordsCursor + +/-! +# Installing the scheduler row for the cursor incidence scan + +The initializer reads eight public words. It multiplies the degree, cursor +count and two binary radices to obtain the loop count. Successive additions +give the starts of the six incidence columns. A single burst then writes the +worker tag, first row, row count and the worker's eleven parameters. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CursorRAM.ScheduleInit + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Row address, worker tag, degree, cursor count, low radix, lane radix, +arc width and first column address, in that order. -/ +def inputs (row tag : Word w) (b l a W start : ℕ) : Fin 8 → Word w := + ![row, tag, encode w (2^a), encode w (b+l), encode w (2^b), encode w (2^l), + encode w W, encode w start] + +/-- Registers zero through seven cache the public inputs. Register eight holds +the row count, and nine through thirteen hold the remaining column starts. -/ +private def setup : List (Op 17 8) := + [.publicWord 0 0, .publicWord 1 1, .publicWord 2 2, .publicWord 3 3, + .publicWord 4 4, .publicWord 5 5, .publicWord 6 6, .publicWord 7 7, + .binary .mul 8 3 4, .binary .mul 8 8 5, .binary .mul 8 8 2, + .binary .add 9 7 8, .binary .add 10 9 8, .binary .add 11 10 8, + .binary .add 12 11 8, .binary .add 13 12 8, .constant 14 0, .constant 15 1, + .stateWord 16, .binary .add 16 16 15] + +private def emit (r : Fin 17) : List (Op 17 8) := [.write 0 r, .binary .add 0 0 15] + +/-- Fixed instruction table for every width and every admissible cursor graph. -/ +def ops : List (Op 17 8) := + setup ++ [1,14,8,2,3,4,5,6,7,9,10,11,12,13].flatMap emit + +private def values (p : Fin 8 → Word w) : List (Word w) := + let n := p 3 * p 4 * p 5 * p 2 + let s := p 7 + [p 1, 0, n, p 2, p 3, p 4, p 5, p 6, s, s+n, s+n+n, s+n+n+n, + s+n+n+n+n, s+n+n+n+n+n] + +private def emitLog (row : Word w) : List (Word w) → List (Event w) + | [] => [] + | x :: xs => .write row x :: .tick :: emitLog (row + 1) xs + +/-- All probes are writes in increasing row-field order. -/ +def events (p : Fin 8 → Word w) : List (Event w) := + List.replicate setup.length .tick ++ emitLog (p 0) (values p) + +set_option maxRecDepth 8192 in +set_option maxHeartbeats 800000 in +private theorem native_trace (p : Fin 8 → Word w) (m : Memory w) (state : Word w) : + ∃ rs m', trace p state ops (fun _ ↦ 0) m = some (events p, rs, m') ∧ rs 16 = state + 1 := by + simp (config := {decide := true}) [ops, setup, emit, events, emitLog, values, trace, Op.effect, + BinaryOp.eval, Function.update, List.replicate_succ] + +theorem native (p : Fin 8 → Word w) (m : Memory w) (state : Word w) : + let M := (template ops 16).instantiate w p + execute M.program (1 + ops.length) (M.program.start state) m [] = + some ⟨events p, some (state + 1)⟩ := by + obtain ⟨rs, m', h, ret⟩ := native_trace p m state + let M := (template ops 16).instantiate w p + change execute M.program (1 + ops.length) ⟨M.entry, state, fun _ ↦ 0, fun _ ↦ 0⟩ m [] = _ + rw [execute_template, run_eq_trace, h] + simp [ret] + +theorem work (p : Fin 8 → Word w) : + ops.length = 48 ∧ (events p).length = 48 ∧ countProbes (events p) = 14 ∧ + choiceBits (events p) = [] := ⟨rfl, rfl, rfl, rfl⟩ + +private theorem after_emit (m : Memory w) (row : Word w) (xs : List (Word w)) : + after m (emitLog row xs) = Greedy.writeRow m row xs := by + induction xs generalizing m row with + | nil => rfl + | cons x xs ih => exact ih (writeMemory m row x) (row+1) + +private theorem after_events (p : Fin 8 → Word w) (m : Memory w) : + after m (events p) = Greedy.writeRow m (p 0) (values p) := after_emit m _ _ + +private theorem values_eq (row tag : Word w) (b l a W start : ℕ) : + values (inputs row tag b l a W start) = + tag :: 0 :: encode w (rowCount b l a) :: List.ofFn (publicWords w b l a W start) := by + simp [values, inputs, publicWords, encode, rowCount, Fin.ofNat_eq_cast] + repeat' apply And.intro + all_goals ring + +private theorem stores_at {m : Memory w} (xs : List (Word w)) (row : Word w) + (h : Greedy.Stores m row xs) (fit : row.val + xs.length ≤ 2^w) {i : ℕ} (hi : i < xs.length) : + m (row.val + i) = xs[i] := by + induction xs generalizing row i with + | nil => simp at hi + | cons x xs ih => + cases i with + | zero => exact h.1 + | succ i => + have hi' : i < xs.length := by simpa using hi + have room : row.val + 1 < 2^w := by simp only [List.length_cons] at fit; omega + have inc : (row + 1).val = row.val + 1 := by + rw [Fin.val_add, Fin.val_one', Nat.mod_eq_of_lt (by omega : 1 < 2^w), Nat.mod_eq_of_lt room] + have ht := ih (row+1) h.2 (by rw [inc]; simp only [List.length_cons] at fit; omega) hi' + simpa only [inc, Nat.add_right_comm, Nat.add_assoc, Nat.one_add, List.getElem_cons_succ] using ht + +/-- From arbitrary external memory the compiled call installs the complete row +read by the scheduler. Fields three through thirteen agree with the parameters +of the cursor scan at the same degree, address split, width and array start. -/ +theorem initialize_row (row tag state : Word w) (b l a W start : ℕ) (m : Memory w) + (fit : row.val + 14 ≤ 2^w) : + let p := inputs row tag b l a W start + let M := (template ops 16).instantiate w p + let out := after m (events p) + execute M.program (1 + ops.length) (M.program.start state) m [] = + some ⟨events p, some (state+1)⟩ ∧ + out row.val = tag ∧ out (row.val+1) = 0 ∧ out (row.val+2) = encode w (rowCount b l a) ∧ + (∀ i : Fin 11, out (row.val+3+i.val) = publicWords w b l a W start i) ∧ + (∀ addr, addr < row.val ∨ row.val + 14 ≤ addr → out addr = m addr) ∧ + (events p).length = 48 ∧ countProbes (events p) = 14 ∧ choiceBits (events p) = [] := by + intro p M out + let words := tag :: 0 :: encode w (rowCount b l a) :: List.ofFn (publicWords w b l a W start) + have length : words.length = 14 := by simp [words] + have mem : out = Greedy.writeRow m row words := by + rw [show out = after m (events p) from rfl, after_events, values_eq] + rfl + have room : row.val + words.length ≤ 2^w := by rwa [length] + have stored : Greedy.Stores out row words := mem ▸ Greedy.writeRow_stores m row words room + have field (i : ℕ) (hi : i < words.length) := stores_at words row stored room hi + refine ⟨native p m state, field (i := 0) (by omega), field (i := 1) (by omega), + field (i := 2) (by omega), ?_, ?_, (work p).2⟩ + · intro i + have hi := i.isLt + have h := field (i := i.val+3) (by omega) + rw [show row.val+3+i.val = row.val+(i.val+3) by omega] + simpa only [words, List.getElem_cons_succ, List.getElem_ofFn] using h + · intro addr ha + exact mem ▸ Greedy.writeRow_outside m row words addr room (by rwa [length]) + +/-- The scheduler reads the exact natural exclusive bound when it fits in a word. -/ +theorem stop_value (row tag : Word w) (b l a W start : ℕ) (m : Memory w) + (room : row.val + 14 ≤ 2^w) (fit : rowCount b l a < 2^w) : + let out := after m (events (inputs row tag b l a W start)) + (out (row.val+2)).val = rowCount b l a := by + dsimp only + rw [(initialize_row row tag 0 b l a W start m room).2.2.2.1] + exact Nat.mod_eq_of_lt fit + +end CompressorRecords.CursorRAM.ScheduleInit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCursorParameterBounds.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorParameterBounds.lean new file mode 100644 index 0000000000..17d3e4ef84 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorParameterBounds.lean @@ -0,0 +1,153 @@ +import OAI.Computability.VPVNP.CompressorRecordsCursorParameters + +/-! +# Integer bounds for producing the cursor parameter frame + +A single length threshold permits every split of the virtual address into +base and lane bits. The same live RAM word holds the eight public inputs, +the intermediates of the width calculation, and the exclusive ends of the +parameter frame, scheduler row and six incidence columns. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CursorRAM.ParametersInit + +open CursorBounds Compression Filter BurstRAM + +/-- Natural values of the eight public words of the parameter initializer. -/ +def inputValues (n r a l row tag start frame : ℕ) : Fin 8 → ℕ := + ![n, r, a, l, row, tag, start, frame] + +/-- The successive integer values of the straight-line width computation. -/ +def widthOperands (r D H : ℕ) : List ℕ := + [1, 2, 4, 8, 10, r+10, (r+10)^2, (r+10)^4, D+1, (D+1)*10, (D+1)*10*H, + (D+1)*10*H+8, ((D+1)*10*H+8)*D, ((D+1)*10*H+8)*D*(r+10)^4] + +private theorem widthOperands_lt {r D H : ℕ} (hD : 0 < D) (hH : 0 < H) + (hfit : ((D+1)*10*H+8)*D*(r+10)^4 < 2^((r+10)^4)) : + ∀ x ∈ widthOperands r D H, x < 2^((r+10)^4) := by + have hsquare : r+10 ≤ (r+10)^2 := by + simpa only [pow_one] using Nat.pow_le_pow_right (show 0 < r+10 by omega) (by decide : 1 ≤ 2) + have hfourth := Nat.pow_le_pow_right (show 0 < r+10 by omega) (by decide : 2 ≤ 4) + have hword := Nat.lt_two_pow_self (n := (r+10)^4) + have hten := Nat.le_mul_of_pos_right (D+1) (by decide : 0 < 10) + have hbucket := Nat.le_mul_of_pos_right ((D+1)*10) hH + have hcursor := Nat.le_mul_of_pos_right ((D+1)*10*H+8) hD + have hbits := Nat.le_mul_of_pos_right (((D+1)*10*H+8)*D) (show 0 < (r+10)^4 by positivity) + intro x hx + simp only [widthOperands, List.mem_cons, List.not_mem_nil, or_false] at hx + rcases hx with h | h | h | h | h | h | h | h | h | h | h | h | h | h <;> subst x <;> omega + +/-- Simultaneous bounds at one length, with the actual frame and directory offsets. -/ +structure Capacity (B n a l row tag start frame : ℕ) : Prop where + length_ge : 3 ≤ n + split : virtualBits B n-l+l = virtualBits B n + cursors : 1 < virtualBits B n + degree_lt : a < wordBits B n + siteBits_lt : virtualBits B n < wordBits B n + public_lt : ∀ i, inputValues n (addressBits B n) a l row tag start frame i < 2^wordBits B n + width_lt : initialWidth B n < 2^wordBits B n + suffix_lt : ∀ x ∈ widthOperands (addressBits B n) (virtualBits B n) (virtualBucket n), + x < 2^wordBits B n + frame_end : frame + 8 < 2^wordBits B n + row_end : row + 14 < 2^wordBits B n + arrays_end : start + 6 * rowCount (virtualBits B n-l) l a < 2^wordBits B n + scan_end : start + 7 * rowCount (virtualBits B n-l) l a ≤ 2^wordBits B n + +/-- Each shift in the parameter suffix yields its full integer power of two. -/ +theorem Capacity.shiftResults_lt {B n a l row tag start frame : ℕ} + (h : Capacity B n a l row tag start frame) : + 2^a < 2^wordBits B n ∧ 2^(virtualBits B n-l) < 2^wordBits B n ∧ 2^l < 2^wordBits B n := by + have hD := h.siteBits_lt + have hl := h.split + exact ⟨Nat.pow_lt_pow_right Nat.one_lt_two h.degree_lt, + Nat.pow_lt_pow_right Nat.one_lt_two (by omega), Nat.pow_lt_pow_right Nat.one_lt_two (by omega)⟩ + +/-- For fixed address and degree exponents and polynomially bounded frame and +directory locations, one threshold works for every admissible lane exponent. -/ +theorem eventually_capacity (B a : ℕ) (hB : 1 ≤ B) {row tag start frame : ℕ → ℕ} + (hr : PolynomiallyBounded row) (ht : PolynomiallyBounded tag) + (hs : PolynomiallyBounded start) (hf : PolynomiallyBounded frame) : + ∀ᶠ n : ℕ in atTop, ∀ l ≤ virtualBits B n, Capacity B n a l (row n) (tag n) (start n) (frame n) := by + filter_upwards [eventually_ge_atTop 3, eventually_cursorCapacity B a hB hs, + eventual_word_room B hB PolynomiallyBounded.id, eventual_word_room B hB ht, + eventual_word_room B hB (hr.add (PolynomiallyBounded.const 14)), + eventual_word_room B hB (hf.add (PolynomiallyBounded.const 8))] with n hn hc hnfit htfit hrfit hffit + intro l hl + let D := virtualBits B n + let b := D-l + let w := wordBits B n + have split : b+l = D := Nat.sub_add_cancel hl + obtain ⟨hD, _, hwfit, hcost⟩ := hc b l split + rw [split] at hD + have count := rowCount_eq_positions split a + change rowCount b l a = 2^D * D * 2^a at count + have hpos := Nat.zero_lt_one.trans hD + have hsitesPos := Nat.mul_pos (Nat.two_pow_pos D) hpos + have hp : 0 < rowCount b l a := count ▸ Nat.mul_pos hsitesPos (Nat.two_pow_pos a) + have hend : start n + 6 * rowCount b l a < 2^w := + (Nat.add_lt_add_left (Nat.mul_lt_mul_of_pos_right (by decide : 6 < 7) hp) _).trans_le hcost + have hrows : rowCount b l a < 2^w := + (Nat.le_mul_of_pos_left _ (by decide : 0 < 6)).trans_lt ((Nat.le_add_left ..).trans_lt hend) + have hsites : 2^D ≤ rowCount b l a := by + rw [count] + exact (Nat.le_mul_of_pos_right _ hpos).trans (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)) + have hdegree : 2^a ≤ rowCount b l a := by + rw [count]; exact Nat.le_mul_of_pos_left _ hsitesPos + have site_lt := (Nat.pow_lt_pow_iff_right Nat.one_lt_two).mp (hsites.trans_lt hrows) + have degree_lt := (Nat.pow_lt_pow_iff_right Nat.one_lt_two).mp (hdegree.trans_lt hrows) + have hw := Nat.lt_two_pow_self (n := w) + have hrD : addressBits B n ≤ D := addressBits_le_virtualBits B n hn + change row n + 14 < 2^w at hrfit + change frame n + 8 < 2^w at hffit + change n < 2^w at hnfit + change tag n < 2^w at htfit + refine ⟨hn, split, hD, degree_lt, site_lt, ?_, hwfit, ?_, hffit, hrfit, hend, hcost⟩ + · intro i + fin_cases i + · exact hnfit + · exact hrD.trans_lt (site_lt.trans hw) + · exact degree_lt.trans hw + · exact hl.trans_lt (site_lt.trans hw) + · exact (Nat.le_add_right ..).trans_lt hrfit + · exact htfit + · exact (Nat.le_add_right ..).trans_lt hend + · exact (Nat.le_add_right ..).trans_lt hffit + · rw [initialWidth, arc_width] at hwfit + exact widthOperands_lt hpos (Nat.two_pow_pos _) hwfit + +/-- The public parameter vector for the native initializer, in live-width words. -/ +def publicInputs (B n a l row tag start frame : ℕ) : Fin 8 → Word (wordBits B n) := + fun i ↦ encode (wordBits B n) (inputValues n (addressBits B n) a l row tag start frame i) + +theorem Capacity.publicInputs_val {B n a l row tag start frame : ℕ} + (h : Capacity B n a l row tag start frame) (i : Fin 8) : + (publicInputs B n a l row tag start frame i).val = + inputValues n (addressBits B n) a l row tag start frame i := + Nat.mod_eq_of_lt (h.public_lt i) + +/-- The two native bursts install the scheduler row from encoded public inputs +at every sufficiently large length. The threshold is independent of the lane +split, the entry state and the initial contents of memory. -/ +theorem eventually_scheduler_prefix (B a : ℕ) (hB : 1 ≤ B) {row tag start frame : ℕ → ℕ} + (hr : PolynomiallyBounded row) (ht : PolynomiallyBounded tag) + (hs : PolynomiallyBounded start) (hf : PolynomiallyBounded frame) : + ∀ᶠ n : ℕ in atTop, ∀ l ≤ virtualBits B n, ∀ (state : Word (wordBits B n)) (m : Memory (wordBits B n)), + PrefixCorrect (publicInputs B n a l (row n) (tag n) (start n) (frame n)) state m B n a l := by + filter_upwards [eventually_capacity B a hB hr ht hs hf] with n hc + intro l hl state m + have h := hc l hl + apply scheduler_prefix state m hB ((by decide : 2 ≤ 3).trans h.length_ge) rfl + (h.publicInputs_val 0) (h.publicInputs_val 1) (h.publicInputs_val 2) (h.publicInputs_val 3) + h.degree_lt hl + · rw [h.publicInputs_val]; exact h.frame_end.le + · rw [h.publicInputs_val]; exact h.row_end.le + +end CompressorRecords.CursorRAM.ParametersInit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCursorParameters.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorParameters.lean new file mode 100644 index 0000000000..724ced9bc6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorParameters.lean @@ -0,0 +1,298 @@ +import OAI.Computability.VPVNP.CompressorRecordsCursorInit +import OAI.Computability.VPVNP.CompressorRecordsCursorCapacity +import OAI.Computability.VPVNP.CompressorRecordFrame +import OAI.Computability.VPVNP.RAMVirtualParametersCode +import OAI.Computability.VPVNP.PrimedInputRAMFlowComplete + +/-! +# Producing the cursor initializer's parameter frame + +The virtual-parameter program leaves the site exponent, bucket capacity and +live address width in registers. A fixed suffix splits the exponent, computes +the RAM arc width, and writes the eight words consumed by the scheduler-row +initializer. It uses the integer identity +`width = D * w * (8 + 10 * (D + 1) * H)` for the two mask systems. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CursorRAM.ParametersInit + +open BurstRAM BurstRAM.PrivateRAM PrimedInputRAM PrimedStackRAM CursorBounds Compression +open scoped Fin.CommRing + +variable {w : ℕ} + +private def emit (r : Fin 12) : List (Op 12 8) := [.write 8 r, .binary .add 8 8 0] + +/-- Slots are the input length, live address bits, degree exponent, lane +bits, scheduler row address, worker tag, array start and destination frame. -/ +def finish : Flow 12 8 := + straight (.constant 0 1) + ([.constant 1 2, .binary .add 2 1 1, .binary .add 3 2 2, .binary .add 4 3 1, + .binary .add 5 5 4, .binary .mul 5 5 5, .binary .mul 5 5 5, + .binary .add 6 10 0, .binary .mul 6 6 4, .binary .mul 6 6 7, + .binary .add 6 6 3, .binary .mul 6 6 10, .binary .mul 6 6 5, + .publicWord 2 2, .binary .shiftLeft 2 0 2, .publicWord 5 3, + .binary .sub 4 10 5, .binary .shiftLeft 4 0 4, .binary .shiftLeft 5 0 5, + .publicWord 8 7, .publicWord 1 4, .publicWord 3 5, .publicWord 7 6, + .stateWord 9, .binary .add 9 9 0] ++ [1,3,2,10,4,5,6,7].flatMap emit) + +/-- Run the virtual-parameter calculation, then split the site exponent and write the cursor +scheduler's eight parameter words. -/ +def program : Flow 12 8 := .seq (VirtualParameters.program 0 1) finish + +private def bank (pub : Fin 8 → Word w) (rs : Regs w 12) : Fin 8 → Word w := + let four := (2 : Word w) + 2 + let eight := four + four + let ten := eight + 2 + let x := rs 5 + ten + let z := x * x + let width := ((rs 10 + 1) * ten * rs 7 + eight) * rs 10 * (z*z) + let pow2 := @BinaryOp.eval w .shiftLeft 1 + ![pub 4, pub 5, pow2 (pub 2), rs 10, pow2 (rs 10 - pub 3), pow2 (pub 3), width, pub 6] + +private def writeLog (base : Word w) : List (Word w) → List (Event w) + | [] => [] + | x :: xs => .write base x :: .tick :: writeLog (base+1) xs + +/-- The local calculation ticks followed by the eight parameter-frame writes at the supplied +base address. -/ +def events (n : ℕ) (base : Word w) (fields : Fin 8 → Word w) : List (Event w) := + List.replicate (VirtualParameters.ticks n + 26) .tick ++ writeLog base (List.ofFn fields) + +set_option maxRecDepth 8192 in +set_option maxHeartbeats 900000 in +private theorem finish_run (pub : Fin 8 → Word w) (s : Word w) (m : Memory w) (rs : Regs w 12) : + let vs := List.ofFn (bank pub rs) + ∃ out, Flow.Exec pub s finish rs m (List.replicate 26 .tick ++ writeLog (pub 7) vs) + out (Greedy.writeRow m (pub 7) vs) ∧ out 9 = s+1 := by + dsimp only + have h : ∃ out, Flow.once pub s false finish rs m = some + (List.replicate 26 .tick ++ writeLog (pub 7) (List.ofFn (bank pub rs)), out, + Greedy.writeRow m (pub 7) (List.ofFn (bank pub rs))) ∧ out 9 = s+1 := by + simp (config := {decide := true}) [finish, straight, emit, Flow.once, Op.effect, + Function.update, BinaryOp.eval, bank, writeLog, Greedy.writeRow, List.replicate_succ] + obtain ⟨out, he, hr⟩ := h + exact ⟨out, (Flow.once_sound pub s false finish rs m he).1, hr⟩ + +private theorem eq_word {x : Word w} {v : ℕ} (h : x.val = v) : x = (v : Word w) := by + subst v + exact Fin.ext (Nat.mod_eq_of_lt x.isLt).symm + +private theorem power (u : Word w) (h : u.val < w) : + BinaryOp.shiftLeft.eval (1 : Word w) u = (2^u.val : ℕ) := by + have small : (1 : ℕ) < 2^w := by have := Nat.lt_two_pow_self (n := w); omega + have one : (1 : Word w).val = 1 := Nat.mod_eq_of_lt small + simp only [BinaryOp.eval, ite_eq_left h, one, Nat.shiftLeft_eq, one_mul, Fin.ofNat_eq_cast] + +/-- The triangular layer count cancels the factor two in each pair of sort blocks. -/ +theorem arc_width (D H w : ℕ) : + (∑ s : CursorRouting.RAMSystem D, CursorRouting.ramFieldBits H w s) = + ((D+1)*10*H+8)*D*w := by + have ht : RAMLayout.layerCount D * 2 = (D+1)*D := by + rw [RAMLayout.layerCount, Nat.choose_two_right, Nat.div_two_mul_two_of_even + (Nat.even_mul_pred_self (D+1)), Nat.add_sub_cancel] + rw [CursorRouting.ramArcWidth, RAMLayout.blockBits] + calc + _ = D*(8*w) + RAMLayout.layerCount D * 2 * (10*H*w) := by ring + _ = _ := by rw [ht]; ring + +private theorem bank_exact {pub : Fin 8 → Word w} {rs : Regs w 12} {B n a l : ℕ} + (r : VirtualParameters.Result n (addressBits B n) rs) + (ha : (pub 2).val = a) (hl : (pub 3).val = l) + (hA : a < w) (hL : l ≤ virtualBits B n) : + bank pub rs = ScheduleInit.inputs (pub 4) (pub 5) (virtualBits B n-l) l a + (initialWidth B n) (pub 6).val := by + let D := virtualBits B n + have hd : (rs 10).val = D := r.siteBits + have hp : (rs 11).val = 2^D := r.sites + have hD : D < w := (Nat.pow_lt_pow_iff_right Nat.one_lt_two).mp (hp ▸ (rs 11).isLt) + have hsub : (rs 10 - pub 3).val = D-l := by + rw [Fin.sub_val_of_le (by change (pub 3).val ≤ (rs 10).val; rwa [hl, hd]), hd, hl] + have hh : (rs 7).val = virtualBucket n := by + simpa [virtualBucket, roundedUp_eq] using r.bucket + have hsite : D-l+l = D := Nat.sub_add_cancel hL + have hwidth : initialWidth B n = ((D+1)*10*virtualBucket n+8)*D*wordBits B n := arc_width D _ _ + funext i + fin_cases i + all_goals first | rfl | skip + · change BinaryOp.shiftLeft.eval 1 (pub 2) = _ + rw [power _ (by omega), ha]; rfl + · change rs 10 = encode w (D-l+l) + rw [hsite]; exact eq_word hd + · change BinaryOp.shiftLeft.eval 1 (rs 10-pub 3) = _ + rw [power _ (by omega), hsub]; rfl + · change BinaryOp.shiftLeft.eval 1 (pub 3) = _ + rw [power _ (by omega), hl]; rfl + · let eight : Word w := (2+2)+(2+2) + let ten := eight+2 + change ((rs 10+1)*ten*rs 7+eight)*rs 10*((rs 5+ten)*(rs 5+ten)*((rs 5+ten)*(rs 5+ten))) = + encode w (initialWidth B n) + simp [hwidth, eq_word hd, eq_word r.addressBits, eq_word hh, encode, CursorBounds.wordBits, eight, ten] + ring + · exact eq_word rfl + +private theorem ticks_props (t : ℕ) (es : List (Event w)) : + countProbes (List.replicate t .tick ++ es) = countProbes es ∧ + choiceBits (List.replicate t .tick ++ es) = choiceBits es := by + induction t with + | zero => exact ⟨rfl,rfl⟩ + | succ t ih => simpa only [List.replicate_succ, List.cons_append, countProbes, choiceBits] using ih + +theorem work (n : ℕ) (base : Word w) (fields : Fin 8 → Word w) : + (events n base fields).length = VirtualParameters.ticks n + 42 ∧ + countProbes (events n base fields) = 8 ∧ choiceBits (events n base fields) = [] := by + unfold events + rw [List.length_append, List.length_replicate] + exact ⟨by change _ + 16 = _; omega, (ticks_props ..).1, (ticks_props ..).2⟩ + +/-- At normal call entry the virtual program and the parameter suffix compute +the eight scheduler inputs using one deterministic burst. -/ +theorem native {pub : Fin 8 → Word w} (state : Word w) (m : Memory w) {B n a l : ℕ} + (hB : 1 ≤ B) (hn : 2 ≤ n) (hw : w = wordBits B n) + (hpN : (pub 0).val = n) (hpR : (pub 1).val = addressBits B n) + (hpA : (pub 2).val = a) (hpL : (pub 3).val = l) (ha : a < w) (hl : l ≤ virtualBits B n) : + let fields := ScheduleInit.inputs (pub 4) (pub 5) (virtualBits B n-l) l a (initialWidth B n) (pub 6).val + let es := events n (pub 7) fields + let M := (program.template (some 9)).instantiate w pub + execute M.program (VirtualParameters.ticks n+43) (M.program.start state) m [] = + some ⟨es,some (state+1)⟩ := by + intro fields es M + obtain ⟨mid,run,hmid⟩ := VirtualParameters.programRun pub 0 1 state m (fun _ ↦ 0) B n hB hn hw hpN hpR + have he : bank pub mid = fields := bank_exact hmid hpA hpL ha hl + obtain ⟨out, finishRun, hret⟩ := finish_run pub state m mid + rw [he] at finishRun + have hwork := work n (pub 7) fields + apply (Flow.template_execute_iff program (some 9) pub state (fun _ ↦ 0) (fun _ ↦ 0) m _ _ _).mpr + refine ⟨out, Greedy.writeRow m (pub 7) (List.ofFn fields), ?_, by simp [hret], by change es.length < _; dsimp [es]; omega, hwork.2.2⟩ + simpa only [program, es, events, List.replicate_add, List.append_assoc] using run.seq finishRun + +private theorem after_writeLog (m : Memory w) (base : Word w) (xs : List (Word w)) : + after m (writeLog base xs) = Greedy.writeRow m base xs := by + induction xs generalizing m base with + | nil => rfl + | cons x xs ih => exact ih (writeMemory m base x) (base+1) + +private theorem after_events (m : Memory w) (n : ℕ) (base : Word w) (fields : Fin 8 → Word w) : + after m (events n base fields) = Greedy.writeRow m base (List.ofFn fields) := by + have ticks (t : ℕ) (es : List (Event w)) : after m (List.replicate t .tick ++ es) = after m es := by + induction t with + | zero => rfl + | succ t ih => simpa only [List.replicate_succ, List.cons_append, after, List.foldl_cons, update] using ih + rw [events, ticks, after_writeLog] + +private theorem read_stored (m : Memory w) (xs : List (Word w)) (base : Word w) + (h : Greedy.Stores m base xs) (i : ℕ) (hi : i < xs.length) : + m (base + (i : Word w)).val = xs[i] := by + induction xs generalizing base i with + | nil => simp at hi + | cons x xs ih => + cases i with + | zero => simpa using h.1 + | succ i => + have ht := ih (base+1) h.2 i (by simpa using hi) + rw [Nat.cast_succ, ← add_assoc, add_right_comm base (i : Word w) 1] + exact ht + +/-- Readback through the real frame loader. Every address outside these eight +cells retains its original word. -/ +theorem frame_ready (m : Memory w) (n : ℕ) (base : Word w) (fields : Fin 8 → Word w) + (fit : base.val+8 ≤ 2^w) : + let m' := after m (events n base fields) + Frame.data base m' = fields ∧ ∀ addr, addr < base.val ∨ base.val+8 ≤ addr → m' addr = m addr := by + dsimp only + rw [after_events] + have hfit : base.val+(List.ofFn fields).length ≤ 2^w := by simpa using fit + refine ⟨?_, fun addr h ↦ Greedy.writeRow_outside _ _ _ addr hfit (by simpa using h)⟩ + funext j + have hs := Greedy.writeRow_stores m base (List.ofFn fields) hfit + have hj : j.val < (List.ofFn fields).length := by simpa only [List.length_ofFn] using j.isLt + exact (read_stored _ _ _ hs j.val hj).trans (List.getElem_ofFn hj) + +/-- The next burst loads the generated frame, runs the existing row initializer +and returns the incremented state. Its memory has the exact loop bound and +all eleven cursor-worker parameters, and the framed call costs 22 probes. -/ +theorem initialize_from_frame (m : Memory w) (n : ℕ) (base row tag state : Word w) (b l a W start : ℕ) + (frameFit : base.val+8 ≤ 2^w) (rowFit : row.val+14 ≤ 2^w) : + let fields := ScheduleInit.inputs row tag b l a W start + let m' := after m (events n base fields) + let T := template ScheduleInit.ops 16 + let M := Frame.machine T base + let r := LiveStageLink.prependLog (Frame.loadEvents base m' 0 8) + (⟨ScheduleInit.events fields,some (state+1)⟩ : Report w) + let final := after m' r.events + execute M.program (1+ScheduleInit.ops.length+4*8) (M.program.start state) m' [] = some r ∧ + final row.val = tag ∧ final (row.val+1) = 0 ∧ final (row.val+2) = encode w (rowCount b l a) ∧ + (∀ j : Fin 11, final (row.val+3+j.val) = publicWords w b l a W start j) ∧ + (∀ addr, (addr < base.val ∨ base.val+8 ≤ addr) → (addr < row.val ∨ row.val+14 ≤ addr) → + final addr = m addr) ∧ r.events.length = 80 ∧ countProbes r.events = 22 := by + intro fields m' T M r final + obtain ⟨hfields, hpres⟩ := frame_ready m n base fields frameFit + change Frame.data base m' = fields at hfields + let s : Report w := ⟨ScheduleInit.events fields,some (state+1)⟩ + obtain ⟨hcall, htag, hzero, hbound, hparams, hout, hlen, hprobes, _⟩ := + ScheduleInit.initialize_row row tag state b l a W start m' rowFit + have hc := Frame.frame_cost base m' 0 8 s + have hfinal : final = after m' (ScheduleInit.events fields) := hc.2.2.2.1 + refine ⟨?_, hfinal ▸ htag, hfinal ▸ hzero, hfinal ▸ hbound, hfinal ▸ hparams, ?_, ?_, ?_⟩ + · change execute (Frame.machine T base).program _ _ _ _ = _ + rw [Frame.execute_frame, hfields, hcall] + rfl + · intro addr hbase hrow + rw [hfinal, hout addr hrow] + exact hpres addr hbase + · have hh : s.events.length = 48 := hlen + exact hc.1.trans (by rw [hh]) + · change r.probes = _ + have hh : s.probes = 14 := hprobes + exact hc.2.1.trans (by rw [hh]) + +/-- Two successive native bursts, with their actual external memory transfer +and the fields of the installed cursor scheduler row. -/ +def PrefixCorrect (pub : Fin 8 → Word w) (state : Word w) (m : Memory w) (B n a l : ℕ) : Prop := + let b := virtualBits B n-l + let W := initialWidth B n + let row := pub 4 + let fields := ScheduleInit.inputs row (pub 5) b l a W (pub 6).val + let es := events n (pub 7) fields + let m' := after m es + let M := (program.template (some 9)).instantiate w pub + let S := Frame.machine (template ScheduleInit.ops 16) (pub 7) + let r := LiveStageLink.prependLog (Frame.loadEvents (pub 7) m' 0 8) + (⟨ScheduleInit.events fields,some (state+1+1)⟩ : Report w) + let out := after m' r.events + execute M.program (VirtualParameters.ticks n+43) (M.program.start state) m [] = some ⟨es,some (state+1)⟩ ∧ + execute S.program (1+ScheduleInit.ops.length+4*8) (S.program.start (state+1)) m' [] = some r ∧ + out row.val = pub 5 ∧ out (row.val+1) = 0 ∧ out (row.val+2) = encode w (rowCount b l a) ∧ + (∀ j : Fin 11, out (row.val+3+j.val) = publicWords w b l a W (pub 6).val j) ∧ + (∀ addr, (addr < (pub 7).val ∨ (pub 7).val+8 ≤ addr) → (addr < row.val ∨ row.val+14 ≤ addr) → + out addr = m addr) ∧ countProbes es + countProbes r.events = 30 ∧ + es.length + r.events.length ≤ 12*Nat.clog 2 n+141 + +/-- The parameter prefix starts from the live length and address-width words. +Its two bursts make thirty external probes and use logarithmically many steps. -/ +theorem scheduler_prefix {pub : Fin 8 → Word w} (state : Word w) (m : Memory w) {B n a l : ℕ} + (hB : 1 ≤ B) (hn : 2 ≤ n) (hw : w = wordBits B n) + (hpN : (pub 0).val = n) (hpR : (pub 1).val = addressBits B n) + (hpA : (pub 2).val = a) (hpL : (pub 3).val = l) (ha : a < w) (hl : l ≤ virtualBits B n) + (frameFit : (pub 7).val+8 ≤ 2^w) (rowFit : (pub 4).val+14 ≤ 2^w) : + PrefixCorrect pub state m B n a l := by + let b := virtualBits B n-l + let W := initialWidth B n + let fields := ScheduleInit.inputs (pub 4) (pub 5) b l a W (pub 6).val + obtain ⟨hc, ht, hz, hb, hparams, hkeep, hlen, hprobes⟩ := + initialize_from_frame m n (pub 7) (pub 4) (pub 5) (state+1) b l a W (pub 6).val frameFit rowFit + refine ⟨native state m hB hn hw hpN hpR hpA hpL ha hl, hc, ht, hz, hb, hparams, hkeep, ?_, ?_⟩ + · rw [(work n (pub 7) fields).2.1, hprobes] + · rw [(work n (pub 7) fields).1, hlen] + have := VirtualParameters.ticks_le n + omega + +end CompressorRecords.CursorRAM.ParametersInit + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCursorRAM.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorRAM.lean new file mode 100644 index 0000000000..cc68c00473 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorRAM.lean @@ -0,0 +1,132 @@ +import OAI.Computability.VPVNP.PrimedStackRAMCode +import OAI.Computability.VPVNP.RAMChain +import OAI.Computability.VPVNP.RAMRecords + +/-! +# Native initialization of cursor incidence records + +A call visits one actual outgoing port in site-major order. The two address blocks +are numbered by the ordinary binary values of the corresponding bits of the physical +address. The call advances the cursor and translates the appropriate block on port one. +It writes the inverse incidence at the computed destination. Parallel copies retain +their own slot numbers. Lanes over a common base arc repeat the same three base writes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CursorRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- Public words are the degree, cursor count, two binary radices, real arc width, +and the six column starts. The persistent word is the site-major outgoing port. -/ +def visit : List (Op 20 11) := + [.stateWord 0, .publicWord 1 0, .publicWord 2 1, .publicWord 3 2, .publicWord 4 3, + .binary .div 5 0 1, .binary .mod 6 0 1, + .binary .mod 7 5 4, .binary .div 8 5 4, .binary .mod 9 8 3, .binary .div 10 8 3, + .constant 11 1, .constant 12 2, + .binary .add 13 6 11, .binary .div 13 12 13, .binary .mod 14 13 12, + .binary .shiftLeft 14 14 10, .binary .mod 15 14 3, .binary .div 16 14 3, + .binary .bitXor 9 9 15, .binary .bitXor 7 7 16, + .binary .add 10 10 11, .binary .mod 10 10 2, .binary .mul 10 10 3, .binary .add 10 10 9, + .binary .mul 8 8 1, .binary .add 8 8 6, .binary .mul 15 10 1, .binary .add 15 15 6, + .binary .mul 10 10 4, .binary .add 10 10 7, .binary .mul 10 10 1, .binary .add 10 10 6, + .binary .add 13 13 11, .binary .div 13 13 12, .publicWord 14 4, .binary .mul 13 13 14, + .publicWord 17 5, .binary .add 17 17 8, .write 17 15, + .publicWord 17 6, .binary .add 17 17 15, .write 17 8, + .publicWord 17 7, .binary .add 17 17 8, .write 17 16, + .publicWord 17 8, .binary .add 17 17 0, .write 17 10, + .publicWord 17 9, .binary .add 17 17 10, .write 17 0, + .publicWord 17 10, .binary .add 17 17 0, .write 17 13, + .binary .add 0 0 11] + +/-- Values appearing in the six writes. -/ +structure Row (α : Type) where + /-- Outgoing port index at the source base vertex, before the residual lane is included. -/ + sourceBase : α + /-- Incoming port index at the destination base vertex, used for the inverse base-incidence + write. -/ + targetBase : α + /-- The mask XORed into the residual lane when lifting this base arc to its actual + destination. -/ + displacement : α + /-- Destination port index after the cursor advance and lane translation, including the + actual site's residual lane. -/ + targetActual : α + /-- Number of payload bits carried by the outgoing port, with zero width for padding. -/ + width : α + +/-- Decode one site-major outgoing port using word arithmetic and compute its base endpoints, +lane translation, actual destination and payload width. -/ +def wordRow (p : Fin 11 → Word w) (i : Word w) : Row (Word w) := + let div := @BinaryOp.eval w .div + let mod := @BinaryOp.eval w .mod + let xor := @BinaryOp.eval w .bitXor + let site := div i (p 0) + let port := mod i (p 0) + let base := div site (p 3) + let cursor := div base (p 2) + let gate := div 2 (port + 1) + let mask := BinaryOp.shiftLeft.eval (mod gate 2) cursor + let shift := div mask (p 2) + let dest := mod (cursor + 1) (p 1) * p 2 + xor (mod base (p 2)) (mod mask (p 2)) + ⟨base * p 0 + port, dest * p 0 + port, shift, + (dest * p 3 + xor (mod site (p 3)) shift) * p 0 + port, div (gate + 1) 2 * p 4⟩ + +/-- Directly addressed outgoing and incoming columns, followed by the payload column +at each of the two granularities. -/ +def writes (p : Fin 11 → Word w) (i : Word w) (r : Row (Word w)) : List (Word w × Word w) := + [(p 5 + r.sourceBase, r.targetBase), (p 6 + r.targetBase, r.sourceBase), + (p 7 + r.sourceBase, r.displacement), (p 8 + i, r.targetActual), + (p 9 + r.targetActual, i), (p 10 + i, r.width)] + +/-- The native trace for one outgoing port, with the arithmetic ticks and six writes populating +the base and actual incidence columns. -/ +def events (p : Fin 11 → Word w) (i : Word w) : List (Event w) := + let r := wordRow p i + List.replicate 39 .tick ++ [.write (p 5 + r.sourceBase) r.targetBase, + .tick, .tick, .write (p 6 + r.targetBase) r.sourceBase, + .tick, .tick, .write (p 7 + r.sourceBase) r.displacement, + .tick, .tick, .write (p 8 + i) r.targetActual, + .tick, .tick, .write (p 9 + r.targetActual) i, + .tick, .tick, .write (p 10 + i) r.width, .tick] + +theorem events_after (p : Fin 11 → Word w) (i : Word w) (m : Memory w) : + after m (events p i) = + (writes p i (wordRow p i)).foldl (fun mem av ↦ writeMemory mem av.1 av.2) m := rfl + +theorem events_work (p : Fin 11 → Word w) (i : Word w) : + (events p i).length = visit.length ∧ countProbes (events p i) = 6 := ⟨rfl, rfl⟩ + +set_option maxRecDepth 8192 in +set_option maxHeartbeats 800000 in +private theorem visit_trace (p : Fin 11 → Word w) (m : Memory w) (i : Word w) (rs : Regs w 20) : + ∃ rs', trace p i visit rs m = some (events p i, rs', after m (events p i)) ∧ rs' 0 = i + 1 := by + simp (config := {decide := true}) [visit, events, wordRow, trace, Op.effect, BinaryOp.eval, + Function.update, after, update] + have h1 : (Fin.ofNat (2 ^ w) (1 : Word 2).val) = (1 : Word w) := by apply Fin.ext; rfl + simp only [Fin.ofNat_eq_cast, Fin.val_one] at h1 + simp only [h1] + repeat' apply And.intro + all_goals first | rfl | trivial + +/-- The same instruction table runs at every input length and visits every slot. -/ +theorem visit_native (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program (1 + visit.length) (M.program.start i) m [] = + some ⟨events p i, some (i + 1)⟩ := by + obtain ⟨rs, ht, hr⟩ := visit_trace p m i (fun _ ↦ 0) + let M := (template visit 0).instantiate w p + change execute M.program (1 + visit.length) ⟨M.entry, i, fun _ ↦ 0, fun _ ↦ 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hr] + +end CompressorRecords.CursorRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCursorScan.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorScan.lean new file mode 100644 index 0000000000..663448acff --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorScan.lean @@ -0,0 +1,163 @@ +import OAI.Computability.VPVNP.CompressorRecordsCursorRAM +import OAI.Computability.VPVNP.RAMBuckets + +/-! +# Native scan of the initial cursor graph + +One burst call writes the six forward, inverse, displacement and width cells +for one numbered outgoing slot. This scan allows repeated visits to the same +base cell from different lanes. Agreement with a common specification suffices +for every visited cell to contain its specified value at the end of the scan. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CursorRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- Six address/value pairs written by the call with natural index `j`. -/ +def rowWrites (p : Fin 11 → Word w) (j : ℕ) : List (Word w × Word w) := + let i := Fin.ofNat (2 ^ w) j + writes p i (wordRow p i) + +/-- Addresses visited in the half-open interval of row indices `[k,k+n)`. -/ +def Touches (p : Fin 11 → Word w) (k n addr : ℕ) : Prop := + ∃ j, k ≤ j ∧ j < k + n ∧ ∃ av ∈ rowWrites p j, av.1.val = addr + +/-- The complete trace with one report per row, including the persistent +index for the next call. -/ +def scanReports (p : Fin 11 → Word w) (k : ℕ) : ℕ → List (Report w) + | 0 => [] + | n+1 => ⟨events p (Fin.ofNat _ k), some (Fin.ofNat _ (k+1))⟩ :: scanReports p (k+1) n + +private theorem word_succ (k : ℕ) : + Fin.ofNat (2 ^ w) k + 1 = Fin.ofNat (2 ^ w) (k + 1) := by + apply Fin.ext + simp [Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + +/-- Execution of precisely the calls whose initial indices are in the interval. -/ +theorem scan_native (p : Fin 11 → Word w) (k n : ℕ) (m : Memory w) : + let M := (template visit 0).instantiate w p + runSegment M.program (1 + visit.length) (some (Fin.ofNat _ k)) m (List.replicate n []) = + some (scanReports p k n) := by + induction n generalizing k m with + | zero => rfl + | succ n ih => + dsimp only + rw [List.replicate_succ, runSegment, visit_native, word_succ] + simp only [ih, Option.map_some, scanReports] + +/-- The returned state can be used as the starting cursor of a following segment. -/ +theorem scanReports_endState (p : Fin 11 → Word w) (k n : ℕ) : + endState (some (Fin.ofNat _ k)) (scanReports p k n) = some (Fin.ofNat _ (k+n)) := by + induction n generalizing k with + | zero => rfl + | succ n ih => + rw [scanReports, endState, ih] + congr 2 + omega + +private theorem fold_writes_at (xs : List (Word w × Word w)) (m spec : Memory w) + (agree : ∀ av ∈ xs, spec av.1.val = av.2) (addr : ℕ) : + (xs.foldl (fun mem av ↦ writeMemory mem av.1 av.2) m) addr = + if ∃ av ∈ xs, av.1.val = addr then spec addr else m addr := by + induction xs generalizing m with + | nil => simp + | cons av xs ih => + rw [List.foldl_cons, ih _ (fun u hu ↦ agree u (List.mem_cons_of_mem _ hu))] + by_cases ht : ∃ u ∈ xs, u.1.val = addr + · simp [ht] + · by_cases he : addr = av.1.val + · subst addr + simp [ht, writeMemory, agree av (List.mem_cons_self ..)] + · simp [ht, he, Ne.symm he, writeMemory] + +private theorem touches_succ (p : Fin 11 → Word w) (k n addr : ℕ) : + Touches p k (n + 1) addr ↔ (∃ av ∈ rowWrites p k, av.1.val = addr) ∨ + Touches p (k+1) n addr := by + constructor + · rintro ⟨j, hj, hlt, h⟩ + rcases eq_or_lt_of_le hj with he | he + · exact .inl (he ▸ h) + · exact .inr ⟨j, by omega, by omega, h⟩ + · rintro (h | ⟨j,hj,hlt,h⟩) + · exact ⟨k, le_rfl, by omega, h⟩ + · exact ⟨j, by omega, by omega, h⟩ + +private theorem scan_after (p : Fin 11 → Word w) (k n : ℕ) (m spec : Memory w) + (agree : ∀ j, k ≤ j → j < k + n → ∀ av ∈ rowWrites p j, spec av.1.val = av.2) + (addr : ℕ) : + letI := Classical.propDecidable + after m (eventLog (scanReports p k n)) addr = + if Touches p k n addr then spec addr else m addr := by + classical + induction n generalizing k m with + | zero => + have h : ¬ Touches p k 0 addr := by rintro ⟨j,hj,hlt,_⟩; omega + simp [h, scanReports, eventLog, after] + | succ n ih => + let es := events p (Fin.ofNat _ k) + have hlog : after m (eventLog (scanReports p k (n+1))) = + after (after m es) (eventLog (scanReports p (k+1) n)) := by + simp only [scanReports, eventLog, List.flatMap_cons, after, List.foldl_append, es] + have hrow : after m es addr = + if ∃ av ∈ rowWrites p k, av.1.val = addr then spec addr else m addr := by + rw [events_after] + exact fold_writes_at (rowWrites p k) m spec (agree k le_rfl (by omega)) addr + rw [hlog, ih (k+1) (after m es) (fun j hj hlt ↦ agree j (by omega) (by omega))] + by_cases ht : Touches p (k+1) n addr <;> + simp [ht, hrow, touches_succ] + +theorem scanReports_length (p : Fin 11 → Word w) (k n : ℕ) : + (scanReports p k n).length = n := by + induction n generalizing k with + | zero => rfl + | succ n ih => simp [scanReports, ih] + +theorem scanReports_work (p : Fin 11 → Word w) (k n : ℕ) : + ∀ r ∈ scanReports p k n, r.events.length = visit.length ∧ countProbes r.events = 6 := by + induction n generalizing k with + | zero => simp [scanReports] + | succ n ih => + intro r hr + rcases List.mem_cons.mp hr with rfl | h + · exact events_work p _ + · exact ih (k+1) r h + +/-- One call plus six probes per slot, with six matching writes even when +multiple lanes visit the same base incidence. -/ +theorem scan_cost (p : Fin 11 → Word w) (k n : ℕ) : + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) (scanReports p k n) = 7 * n := by + induction n generalizing k with + | zero => rfl + | succ n ih => + rw [scanReports, RAMBuckets.cost, (events_work p _).2, ih, Nat.mul_succ] + omega + +/-- All native calls, their exact work, the contents of each constructed +record, and preservation of every address outside the six scanned columns. -/ +theorem scan_run (p : Fin 11 → Word w) (k n : ℕ) (m spec : Memory w) + (agree : ∀ j, k ≤ j → j < k + n → ∀ av ∈ rowWrites p j, spec av.1.val = av.2) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program (1 + visit.length) (some (Fin.ofNat _ k)) m (List.replicate n []) = + some rs ∧ rs.length = n ∧ (∀ r ∈ rs, r.events.length = visit.length ∧ countProbes r.events = 6) ∧ + (∀ addr, Touches p k n addr → after m (eventLog rs) addr = spec addr) ∧ + (∀ addr, ¬ Touches p k n addr → after m (eventLog rs) addr = m addr) := by + classical + refine ⟨scanReports p k n, scan_native p k n m, scanReports_length p k n, + scanReports_work p k n, ?_, ?_⟩ + · intro addr h + simpa only [h, ite_true] using scan_after p k n m spec agree addr + · intro addr h + simpa only [h, ite_false] using scan_after p k n m spec agree addr + +end CompressorRecords.CursorRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsCursorWords.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorWords.lean new file mode 100644 index 0000000000..d00ba6ce56 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsCursorWords.lean @@ -0,0 +1,160 @@ +import OAI.Computability.VPVNP.CompressorRecordsCursorRAM +import OAI.Computability.VPVNP.CompressorRecordsCursorCoordinates + +/-! +# Exact binary arithmetic of a level-zero descriptor visit + +Decode the three mixed-radix quotients of the persistent row. The two integer +divisions of the slot gate select respectively the flip slot and the genuine +payload slots. Splitting the one-bit mask by the low-block radix gives the +base translation and the remaining-lane displacement in the cursor state. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.CursorRAM + +open BurstRAM BurstRAM.PrivateRAM CursorNetwork + +variable {w : ℕ} + +/-- Encode a natural cursor parameter as a machine word by reduction modulo the word modulus. -/ +abbrev encode (w : ℕ) (n : ℕ) : Word w := Fin.ofNat (2 ^ w) n + +private theorem enc_add (x y : ℕ) : + encode w x + encode w y = encode w (x+y) := by + apply Fin.ext + simp only [Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod, Nat.mod_add_mod] + +private theorem enc_mul (x y : ℕ) : + encode w x * encode w y = encode w (x*y) := by + apply Fin.ext + simp only [Fin.val_mul, Fin.val_ofNat, Nat.mul_mod_mod, Nat.mod_mul_mod] + +private theorem enc_div {x y : ℕ} (hx : x < 2^w) (hy : y < 2^w) : + BinaryOp.div.eval (encode w x) (encode w y) = encode w (x/y) := by + change encode w (x % (2^w) / (y % (2^w))) = _ + rw [Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hy] + +private theorem enc_mod {x y : ℕ} (hx : x < 2^w) (hy : y < 2^w) : + BinaryOp.mod.eval (encode w x) (encode w y) = encode w (x%y) := by + change encode w (x % (2^w) % (y % (2^w))) = _ + rw [Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hy] + +private theorem enc_xor {x y : ℕ} (hx : x < 2^w) (hy : y < 2^w) : + BinaryOp.bitXor.eval (encode w x) (encode w y) = encode w (x ^^^ y) := by + change encode w ((x % (2^w)) ^^^ (y % (2^w))) = _ + rw [Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hy] + +private theorem enc_shift {x j : ℕ} (hx : x < 2^w) (hj : j < w) : + BinaryOp.shiftLeft.eval (encode w x) (encode w j) = encode w (x * 2^j) := by + have hj' : j < 2^w := hj.trans Nat.lt_two_pow_self + simp [BinaryOp.eval, encode, Nat.mod_eq_of_lt hj', Nat.mod_eq_of_lt hx, hj, Nat.shiftLeft_eq] + +theorem packed_lt {v x m n : ℕ} (hv : v < m) (hx : x < n) : v*n + x < m*n := by + have h := Nat.mul_le_mul_right n (Nat.succ_le_of_lt hv) + rw [Nat.succ_mul] at h + omega + +private theorem unpack_div {v x n : ℕ} (hx : x < n) : (v*n+x)/n = v := by + rw [Nat.mul_comm, Nat.mul_add_div (by omega), Nat.div_eq_of_lt hx, Nat.add_zero] + +private theorem gate (s : ℕ) : 2 / (s+1) % 2 = (if s = 1 then 1 else 0) ∧ + (2 / (s+1) + 1) / 2 = (if s < 2 then 1 else 0) := by + rcases s with _ | _ | s + · decide + · decide + · simp [Nat.div_eq_of_lt (show 2 < s+2+1 by omega)] + +private theorem mask_split (b j s : ℕ) : + ((if s = 1 then 1 else 0) * 2^j) % 2^b = (if s = 1 ∧ j < b then 2^j else 0) ∧ + ((if s = 1 then 1 else 0) * 2^j) / 2^b = cursorLaneMask b j s := by + by_cases hs : s = 1 + · by_cases hj : j < b + · have h := Nat.pow_lt_pow_right Nat.one_lt_two hj + simp [hs, hj, Nat.not_le.mpr hj, cursorLaneMask, Nat.mod_eq_of_lt h, Nat.div_eq_of_lt h] + · have hbj : b ≤ j := by omega + have he : 2^j = 2^(j-b)*2^b := by rw [← pow_add, Nat.sub_add_cancel hbj] + simp [hs, hj, hbj, cursorLaneMask, he] + · simp [hs, cursorLaneMask] + +/-- The first five public words are shared by all six column writes. -/ +structure Parameters (p : Fin 11 → Word w) (b l a W : ℕ) : Prop where + degree : p 0 = encode w (2^a) + cursors : p 1 = encode w (b+l) + low : p 2 = encode w (2^b) + lanes : p 3 = encode w (2^l) + width : p 4 = encode w W + +/-- Number of scanned source slots including the parallel padding. -/ +def rowCount (b l a : ℕ) := ((b+l) * 2^b * 2^l) * 2^a + +private theorem radix_bounds {b l a : ℕ} (hD : 1 < b+l) + (fit : rowCount b l a < 2^w) : + b+l ≤ w ∧ b+l < 2^w ∧ 2^a < 2^w ∧ 2^b < 2^w ∧ 2^l < 2^w ∧ + 2^(b+l) < 2^w ∧ (b+l)*2^b < 2^w ∧ (b+l)*2^b*2^l < 2^w := by + have ha := Nat.two_pow_pos a + have hb := Nat.two_pow_pos b + have hl := Nat.two_pow_pos l + unfold rowCount at fit + have hBL := (Nat.le_mul_of_pos_right _ ha).trans_lt fit + have hB := (Nat.le_mul_of_pos_right _ hl).trans_lt hBL + have hDc := (Nat.le_mul_of_pos_right _ hb).trans_lt hB + have hB' := (Nat.le_mul_of_pos_left _ (by omega : 0 < b+l)).trans_lt hB + have hL' := (Nat.le_mul_of_pos_left _ (Nat.mul_pos (by omega) hb)).trans_lt hBL + have ha' := (Nat.le_mul_of_pos_left _ (Nat.mul_pos (Nat.mul_pos (by omega) hb) hl)).trans_lt fit + have hpow : 2^(b+l) < 2^w := by + rw [pow_add] + exact (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_left _ (by omega : 0 < b+l))).trans_lt hBL + exact ⟨((Nat.pow_lt_pow_iff_right Nat.one_lt_two).mp hpow).le, hDc, ha', hB', hL', hpow, hB, hBL⟩ + +/-- All arithmetic in the native template agrees with the cursor's endpoint, lane +shift and width formulas. The room hypothesis is on the number of actual rows. -/ +theorem wordRow_exact {p : Fin 11 → Word w} {b l a W : ℕ} + (hparam : Parameters p b l a W) (hD : 1 < b+l) (hd : 2 ≤ 2^a) + (fit : rowCount b l a < 2^w) + {j x g s : ℕ} (hj : j < b+l) (hx : x < 2^b) (hg : g < 2^l) (hs : s < 2^a) : + wordRow p (encode w (((j*2^b+x)*2^l+g)*2^a+s)) = + ⟨encode w ((j*2^b+x)*2^a+s), + encode w (cursorNextBase b l j x s * 2^a+s), encode w (cursorLaneMask b j s), + encode w ((cursorNextBase b l j x s * 2^l+(g ^^^ cursorLaneMask b j s))*2^a+s), + encode w (if s < 2 then W else 0)⟩ := by + obtain ⟨hdw, hcw, haw, hbw, hlw, hpw, hbn, hsn⟩ := radix_bounds hD fit + have hbase := packed_lt hj hx + have hsite := packed_lt hbase hg + have hrow := packed_lt hsite hs + have hsw : s + 1 < 2^w := (Nat.succ_le_of_lt hs).trans_lt haw + have hjw : j + 1 < 2^w := (Nat.succ_le_of_lt hj).trans_lt hcw + have h2w : 2 < 2^w := hd.trans_lt haw + have h3w : 3 < 2^w := by + have h := Nat.pow_le_pow_right Nat.zero_lt_two (show 2 ≤ b+l by omega) + omega + have hquot : 2/(s+1) ≤ 2 := Nat.div_le_self .. + have hmask : (if s=1 then 1 else 0)*2^j < 2^w := by + split <;> simp [((Nat.pow_lt_pow_right Nat.one_lt_two hj).trans hpw)] + have hm := mask_split b j s + have hlow : (if s=1 ∧ j simp [((Nat.pow_lt_pow_right Nat.one_lt_two hj).trans hpw)] + have hlane : cursorLaneMask b j s < 2^w := by + rw [← hm.2]; exact (Nat.div_le_self ..).trans_lt hmask + have h1 : (1 : Word w) = encode w 1 := rfl + have h2 : (2 : Word w) = encode w 2 := rfl + unfold wordRow + simp only [hparam.degree, hparam.low, hparam.cursors, hparam.lanes, hparam.width, h1, h2, + enc_div (hrow.trans fit) haw, enc_mod (hrow.trans fit) haw, unpack_div hs, Nat.mul_add_mod_of_lt hs, + enc_div (hsite.trans hsn) hlw, enc_mod (hsite.trans hsn) hlw, unpack_div hg, Nat.mul_add_mod_of_lt hg, + enc_div (hbase.trans hbn) hbw, enc_mod (hbase.trans hbn) hbw, unpack_div hx, Nat.mul_add_mod_of_lt hx, + enc_add, enc_div h2w hsw, enc_mod (hquot.trans_lt h2w) h2w, (gate s).1, + enc_shift (show (if s = 1 then 1 else 0) < 2^w by split <;> omega) (hj.trans_le hdw), + enc_div hmask hbw, enc_mod hmask hbw, hm.1, hm.2, enc_xor (hx.trans hbw) hlow, + enc_xor (hg.trans hlw) hlane, enc_mod hjw hcw, enc_mul, cursorNextBase, + enc_div (show 2/(s+1)+1 < 2^w by omega) h2w, (gate s).2] + by_cases h : s < 2 <;> simp [h] + +end CompressorRecords.CursorRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsDemandOutput.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandOutput.lean new file mode 100644 index 0000000000..3db943940b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandOutput.lean @@ -0,0 +1,173 @@ +import OAI.Computability.VPVNP.CompressorRecordsDemandScan + +/-! +# Constructing the genuine old-arc inputs of the slot compiler + +Starting with the previous level's incidence and the selected layout's placement +columns, scan every directed old port once. The output occupies four consecutive +words per absolute old-arc ID. The CD flag and selected role cells then have exactly +the types and indexing read by the genuine-slot worker. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DemandRAM + +open Compression Compression.SurvivingSlots BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {w a g : ℕ} (X : State a (packingLaneBits a g)) + +/-- Number of directed old slots visited in site-major order, counting every base vertex, +packing lane and outgoing port. -/ +abbrev oldCount := Fintype.card X.Base * 2^(packingLaneBits a g) * 2^a +/-- Size of the absolute old-arc directory, counting all base arc identifiers across the +residual lanes. -/ +abbrev absoluteCount := Slots.oldBaseArcCount (Fintype.card X.Base) (2^(Shrink.J a)) (2^a) (Shrink.colors a) * 2^g +/-- The bijection that assigns each old arc its absolute directory index with the residual lane +as the least significant coordinate. -/ +abbrev absoluteIndex := Slots.oldArcIndex X.packingData X.baseIndex (bitWordFinEquiv (Shrink.J a)) (bitWordFinEquiv g) + +theorem count_eq : oldCount X = absoluteCount X := by + have h := Fintype.card_congr ((BundleKeys.oldArcOrder X.baseIndex).symm.trans (absoluteIndex X)) + simpa using h + +private theorem fieldAddr_word (p : Fin 11 → Word w) (i : Word w) (t : Fin 4) : + fieldAddr p i t = (address p i + (t.val : Word w)).val := by + fin_cases t <;> simp [fieldAddr] <;> congr 1 <;> ring + +theorem fieldAddr_exact {p : Fin 11 → Word w} {B : ℕ} (hp : BundleRAM.Params p a (Shrink.colors a) (Shrink.J a) g B) + (room : (p 10).val + 4*absoluteCount X ≤ 2^w) (e : BundleKeys.OldArc X.Base a g) {i : Word w} + (hi : i.val = (BundleKeys.oldArcOrder X.baseIndex e).val) (t : Fin 4) : + fieldAddr p i t = (p 10).val+4*(absoluteIndex X e).val+t.val := by + rw [fieldAddr_word, address_exact X.slots X.baseIndex hp e hi] + have fit : (p 10).val+4*(absoluteIndex X e).val+t.val < 2^w := by + have h : (absoluteIndex X e).val < absoluteCount X := (absoluteIndex X e).isLt + have ht := t.isLt + omega + have eqw : p 10 + 4 * ((absoluteIndex X e).val : Word w) + (t.val : Word w) = + (((p 10).val + 4*(absoluteIndex X e).val + t.val : ℕ) : Word w) := by + rw [Nat.cast_add, Nat.cast_add, Nat.cast_mul] + have h : ((p 10).val : Word w) = p 10 := Fin.ext (Nat.mod_eq_of_lt (p 10).isLt) + simp [h] + rw [eqw] + exact Nat.mod_eq_of_lt fit + +/-- The old-site port order and absolute arc order are two bijections of the same +finite space. Consequently the four-word output rows are disjoint in memory. -/ +theorem regions {p : Fin 11 → Word w} {B : ℕ} (hp : BundleRAM.Params p a (Shrink.colors a) (Shrink.J a) g B) + (old : Memory w) (room : (p 10).val + 4*absoluteCount X ≤ 2^w) + (outside : ∀ (i : Word w) (c : Fin 6), i.val < oldCount X → + inputAddr p old i c < (p 10).val ∨ (p 10).val+4*absoluteCount X ≤ inputAddr p old i c) : + Regions p old (oldCount X) := by + let E := BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex + let src (i : Word w) (h : i.val (E e).val) es).trans (idx j hj).symm)), + Fin.ext (by omega)⟩ + · rintro ⟨rfl,rfl⟩; rfl + · intro i j c t hi hj + have h₀ := outside i c hi + have h₁ := bound j hj t + rw [fieldAddr_exact X hp room _ (idx j hj)] at * + omega + +/-- The exact two data predicates consumed by the surviving-slot generator. -/ +structure RoleColumns (layout : Bool) (base : ℕ) (m : Memory w) : Prop where + cd : ∀ e, (m (base+4*(absoluteIndex X e).val+3)).val = if Slots.isCD X.packingData e then 1 else 0 + packed : ∀ (e : X.packingData.Motif) (r : PackedRole), + (m (base+4*(absoluteIndex X e.val).val+SlotOwners.roleOffset r)).val = + (SlotSchedule.siteIndex X.baseIndex (bitWordFinEquiv (Shrink.J a)) (bitWordFinEquiv g) + (X.packingData.survivingRole layout r e)).val + +theorem run_roles (T : IncidenceDirectory w) {p : Fin 11 → Word w} {shr : Fin 14 → Word w} + {m : Memory w} {layout : Bool} {B : ℕ} (hp : BundleRAM.Params p a (Shrink.colors a) (Shrink.J a) g B) + (h : Inputs p shr T) (inc : T.ActualColumns X m) (place : ShrinkRAM.PlacementColumns X.slots X.baseIndex shr layout m) + (room : (p 10).val+4*absoluteCount X ≤ 2^w) + (outside : ∀ (i : Word w) (c : Fin 6), i.val first | exact h1 | rfl + · intro e r + let v := X.packingData.survivingRole layout r e + have hv : Shrink.packedNumber X.baseIndex v < 2^w := by + have hsite := (Shrink.packedIndex X.baseIndex v).isLt + rw [Shrink.packedIndex_val] at hsite + have hcard : Fintype.card X.Base*(2^(Shrink.J a)*2^g) ≤ oldCount X := by + rw [← pow_add] + apply (Nat.mul_le_mul_left _ (Nat.pow_le_pow_right (by decide : 1 ≤ 2) + (show Shrink.J a+g ≤ packingLaneBits a g by unfold Shrink.J packingLaneBits; omega))).trans + exact Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _) + exact hsite.trans_le (hcard.trans reg.fits) + have hslot : (SlotSchedule.siteIndex X.baseIndex (bitWordFinEquiv (Shrink.J a)) (bitWordFinEquiv g) v).val = + Shrink.packedNumber X.baseIndex v := Shrink.packedIndex_val X.baseIndex v + rw [hslot] + have H := (sem e.val).2 e.prop + have hrole : mem ((p 10).val+4*(absoluteIndex X e.val).val+SlotOwners.roleOffset r) = + (Shrink.packedNumber X.baseIndex v : Word w) := by + cases r with + | a => exact (out e.val 0).trans H.1 + | b => exact (out e.val 1).trans H.2.1 + | d => exact (out e.val 2).trans H.2.2 + change (mem _).val = _ + rw [hrole]; exact Nat.mod_eq_of_lt hv + · intro x hx + apply hout.frame + intro i t hi + let e := E.symm ⟨i.val,by simpa only [Nat.zero_add] using hi⟩ + have hidx : i.val=(E e).val := by simp [e] + rw [fieldAddr_exact X hp room _ hidx] + have h₀ : (absoluteIndex X e).val < absoluteCount X := (absoluteIndex X e).isLt + have := t.isLt + omega + +end CompressorRecords.DemandRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsDemandRAM.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandRAM.lean new file mode 100644 index 0000000000..c2cdfc0fbc --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandRAM.lean @@ -0,0 +1,140 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleWords +import OAI.Computability.VPVNP.CompressorSlotOwnerAgreement + +/-! +# Materializing the selected roles of each old shrinking arc + +The scan cursor uses the old physical outgoing-port order. The output record address +uses the old arc's absolute ID in the surviving-slot directory, which moves the tag +and port ahead of the mask and keeps the residual lane least significant. Read both +thickness bits, follow the thin C endpoint for A and B, and read the opposite +endpoint's chosen owner for D. All arcs have a CD indicator, including thick–thick +arcs that occupy unused addresses of the genuine slot range. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DemandRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open ShrinkRAM (div mod select) +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Straight-line instruction lists for the demand worker, which uses 24 registers and 11 +public operands. -/ +abbrev Ops := List (Op 24 11) + +/-- Degree, residual/tag/mask radices, an unused offset, the actual outgoing, +thickness, owner, assigned and target columns, and the absolute arc-record base. -/ +def visit : Ops := + [.stateWord 0,.publicWord 1 0,.publicWord 2 1,.publicWord 3 2,.publicWord 4 3, + .constant 23 1,.binary .div 5 0 1,.binary .mod 6 0 1, + .publicWord 13 5,.binary .add 13 13 0,.read 7 13,.binary .div 7 7 1, + .publicWord 13 6,.binary .add 14 13 5,.read 8 14,.binary .add 14 13 7,.read 9 14, + .binary .sub 10 7 5,.binary .mul 10 8 10,.binary .add 11 5 10,.binary .sub 12 7 10, + .publicWord 13 8,.binary .add 13 13 11,.read 15 13,.binary .div 15 15 1, + .publicWord 13 9,.binary .add 13 13 11,.read 16 13, + .publicWord 13 7,.binary .add 13 13 12,.read 17 13, + .binary .mul 18 8 9,.binary .sub 18 23 18, + .binary .mod 19 5 2,.binary .div 5 5 2,.binary .mod 20 5 3,.binary .div 5 5 3, + .binary .mod 21 5 1,.binary .div 5 5 1,.binary .mod 22 5 4,.binary .div 5 5 4, + .binary .mul 5 5 3,.binary .add 5 5 20,.binary .mul 5 5 1,.binary .add 5 5 6, + .binary .mul 5 5 4,.binary .add 5 5 22,.binary .mul 5 5 1,.binary .add 5 5 21, + .binary .mul 5 5 2,.binary .add 5 5 19,.constant 22 2,.binary .add 22 22 22,.binary .mul 5 22 5, + .publicWord 13 10,.binary .add 13 13 5,.write 13 15, + .binary .add 13 13 23,.write 13 16,.binary .add 13 13 23,.write 13 17, + .binary .add 13 13 23,.write 13 18,.binary .add 0 0 23] + +/-- Address of an old arc's four-word demand record, obtained by permuting the scan index into +absolute arc order and adding the output table base. -/ +def address (p : Fin 11 → Word w) (i : Word w) : Word w := + let f := BundleRAM.decode p i + let hi := (((f.base*p 2+f.tag)*p 0+f.slot)*p 3+f.mask)*p 0+f.label + let lane := mod (BundleRAM.sourceSite p i) (p 1) + p 10 + 4*(hi*p 1+lane) + +/-- Order the physical source and target according to the source's thickness bit, putting the C +endpoint first on a CD arc. -/ +def endpoints (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : Word w × Word w := + let src := BundleRAM.sourceSite p i + let dst := BundleRAM.targetSite p m i + let thick := m (p 6+src).val + let delta := thick*(dst-src) + (src+delta,dst-delta) + +/-- The demand record of an old arc, storing its packed A, B and D site numbers and the CD +indicator. -/ +structure Roles (α : Type) where + /-- Packed source site of the bundle assigned to the thin C endpoint on a CD arc. -/ + A : α + /-- Packed target site of the bundle assigned to the thin C endpoint on a CD arc. -/ + B : α + /-- Packed site selected by the placement for the opposite, D endpoint on a CD arc. -/ + D : α + /-- The CD indicator, set to one unless both endpoints of the old arc are thick. -/ + cd : α + +/-- Read the placement data at the two endpoints to compute A, B and D, and use their thickness +bits to compute the CD flag. -/ +def roles (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : Roles (Word w) := + let s := BundleRAM.sourceSite p i + let t := BundleRAM.targetSite p m i + let z := endpoints p m i + ⟨div (m (p 8+z.1).val) (p 0),m (p 9+z.1).val,m (p 7+z.2).val,1-m (p 6+s).val * m (p 6+t).val⟩ + +/-- Trace of one demand visit, reading the old target, endpoint thicknesses and selected +placement data before writing the four demand fields. -/ +def events (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + let s := BundleRAM.sourceSite p i + let t := BundleRAM.targetSite p m i + let z := endpoints p m i + let v := roles p m i + let a := address p i + List.replicate 10 .tick ++ [.read (p 5+i) (m (p 5+i).val),.tick,.tick,.tick, + .read (p 6+s) (m (p 6+s).val),.tick,.read (p 6+t) (m (p 6+t).val)] ++ + List.replicate 6 .tick ++ [.read (p 8+z.1) (m (p 8+z.1).val),.tick,.tick,.tick, + .read (p 9+z.1) v.B,.tick,.tick,.read (p 7+z.2) v.D] ++ List.replicate 25 .tick ++ + [.write a v.A,.tick,.write (a+1) v.B,.tick,.write (a+1+1) v.D,.tick, + .write (a+1+1+1) v.cd,.tick] + +/-- Write the computed A, B, D and CD words to the four consecutive cells of the old arc's +demand record. -/ +def store (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : Memory w := + let a := address p i + let v := roles p m i + writeMemory (writeMemory (writeMemory (writeMemory m a v.A) (a+1) v.B) + (a+1+1) v.D) (a+1+1+1) v.cd + +theorem visit_after (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : + after m (events p m i) = store p m i := rfl + +theorem visit_work (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : + (events p m i).length = 64 ∧ countProbes (events p m i) = 10 := ⟨rfl,rfl⟩ + +set_option maxHeartbeats 1400000 in +set_option maxRecDepth 8192 in +private theorem visit_trace (p : Fin 11 → Word w) (m : Memory w) (i : Word w) (rs : Regs w 24) : + ∃ rs', trace p i visit rs m = some (events p m i, rs', store p m i) ∧ rs' 0 = i+1 := by + simp (config := {decide := true}) [visit, trace, Op.effect, Function.update, BinaryOp.eval, + events, roles, address, endpoints, BundleRAM.decode, BundleRAM.sourceSite, BundleRAM.targetSite, + div, mod, store] + repeat' apply And.intro + all_goals first | rfl | (norm_num1; rfl) + +theorem visit_native (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program 65 (M.program.start i) m [] = some ⟨events p m i,some (i+1)⟩ := by + obtain ⟨rs, ht, hr⟩ := visit_trace p m i (fun _ => 0) + let M := (template visit 0).instantiate w p + change execute M.program (1+visit.length) ⟨M.entry,i,fun _=>0,fun _=>0⟩ m [] = _ + rw [execute_template,run_eq_trace,ht]; simp [hr] + +end CompressorRecords.DemandRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsDemandRoles.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandRoles.lean new file mode 100644 index 0000000000..903429a7c4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandRoles.lean @@ -0,0 +1,146 @@ +import OAI.Computability.VPVNP.CompressorRecordsDemandRAM +import OAI.Computability.VPVNP.CompressorRecordsBundleInputs +import OAI.Computability.VPVNP.CompressorRecordsBundleRoleIndex + +/-! +# Absolute shrinking arc records and the selected role sites + +The native demand pass reads a site-major old arc and writes in the +lane-minor old arc order of the surviving-slot compiler. The two orders are +permutations of all directed old slots, including parallel and zero-width slots. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DemandRAM + +open Compression BurstRAM VPVNP.CompressorRecords.Shrink +open scoped Fin.CommRing + +variable {w a g : ℕ} + +private theorem of_val {x : Word w} {n : ℕ} (h : x.val = n) : x = (n : Word w) := by + subst n + exact Fin.ext (Nat.mod_eq_of_lt x.isLt).symm + +private theorem div_val (x y : Word w) : (ShrinkRAM.div x y).val = x.val / y.val := + Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt) + +private theorem old_low {V : Type} {N : ℕ} (order : V ≃ Fin N) (s : Old V a g) : + oldNumber order s % 2^g = (bitWordFinEquiv g s.1.2.2).val := by + let b := join a (join (colors a) (order s.1.1).val (bitWordFinEquiv (colors a) s.2.1).val) + (bitWordFinEquiv a s.2.2).val + have h : oldNumber order s = (b*2^(J a)+(bitWordFinEquiv (J a) s.1.2.1).val)*2^g + + (bitWordFinEquiv g s.1.2.2).val := by + change b*2^(J a+g)+((bitWordFinEquiv (J a) s.1.2.1).val*2^g+(bitWordFinEquiv g s.1.2.2).val) = _ + rw [pow_add]; ring + rw [h, Nat.mul_add_mod_of_lt (Fin.isLt _)] + +theorem address_exact {V : Type} {n : ℕ} (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) + (order : V ≃ Fin n) {p : Fin 11 → Word w} {B : ℕ} + (hp : BundleRAM.Params p a (colors a) (J a) g B) (e : BundleKeys.OldArc V a g) + {i : Word w} (hi : i.val = (BundleKeys.oldArcOrder order e).val) : + address p i = p 10 + 4 * ((Slots.oldArcIndex (orderedDyadicPacking G order) order + (bitWordFinEquiv (J a)) (bitWordFinEquiv g) e).val : Word w) := by + have ho := BundleKeys.oldArcOrder_val order e + have hq : i.val/2^a = oldNumber order (sourcePosition e) := by + rw [hi,ho, Nat.mul_comm, Nat.mul_add_div (Nat.two_pow_pos _), Nat.div_eq_of_lt e.1.2.isLt, Nat.add_zero] + have hs : i.val%2^a = e.1.2.val := by rw [hi,ho, Nat.mul_add_mod_of_lt e.1.2.isLt] + have hl : ShrinkRAM.mod (BundleRAM.sourceSite p i) (p 1) = ((bitWordFinEquiv g e.1.1.2.2).val : Word w) := by + change (((ShrinkRAM.div i (p 0)).val % (p 1).val : ℕ) : Word w) = _ + rw [div_val, hp.degree,hp.residual,hq,old_low] + rfl + unfold address + rw [BundleRAM.decode_exact hp, hq, hs, hl, BundleKeys.oldArcIndex_eq_key_lane G order] + simp only [BundleKeys.keyAt, BundleKeys.numericKey, Bool.false_eq_true, ite_false, + of_val hp.degree, of_val hp.mask, of_val hp.tag, of_val hp.residual, Nat.cast_add, Nat.cast_mul] + +/-- Physical source and destination site numbers in the preceding placement directory. -/ +theorem site_inputs (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) + {p : Fin 11 → Word w} {m : Memory w} (inc : T.ActualColumns X m) (hd : (p 0).val = 2^a) + (hOut : p 5 = T.actualOut) (fit : Fintype.card X.Base*2^(packingLaneBits a g)*2^a ≤ 2^w) + (e : BundleKeys.OldArc X.Base a g) {i : Word w} (hi : i.val = (BundleKeys.oldArcOrder X.baseIndex e).val) : + BundleRAM.sourceSite p i = ShrinkRAM.word w (oldNumber X.baseIndex (sourcePosition e)) ∧ + BundleRAM.targetSite p m i = ShrinkRAM.word w (oldNumber X.baseIndex (sourcePosition (X.packingData.actual e))) := by + have num (u : BundleKeys.OldArc X.Base a g) : + IncidenceDirectory.actualPort (w := w) X (packingInputEdges X.Base a g u) = + ShrinkRAM.word w (BundleKeys.oldArcOrder X.baseIndex u).val := by + rw [BundleKeys.oldArcOrder_val, Shrink.oldNumber_original]; rfl + have src : i = IncidenceDirectory.actualPort X (packingInputEdges X.Base a g e) := by + rw [num]; exact of_val hi + constructor + · exact BundleRAM.site_quotient X _ hd e _ hi + · apply BundleRAM.site_quotient X _ hd (X.packingData.actual e) + rw [hOut, src, inc.actualOut, ← BundleRAM.input_target, num] + exact Nat.mod_eq_of_lt ((BundleKeys.oldArcOrder X.baseIndex (X.packingData.actual e)).isLt.trans_le fit) + +/-- The demand worker's public inputs point to the old outgoing incidence and the shrink pass's +thickness, owner, assigned-bundle and target columns. -/ +structure Inputs (p : Fin 11 → Word w) (shr : Fin 14 → Word w) (T : IncidenceDirectory w) : Prop where + incidence : p 5 = T.actualOut + thick : p 6 = shr 11 + owner : p 7 = shr 10 + assigned : p 8 = shr 12 + target : p 9 = shr 13 + +/-- All four values of the selected demand role record. The CD flag is defined +on every old arc; the other three outputs agree with A, B, D on every actual motif. -/ +theorem roles_exact (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) + {p : Fin 11 → Word w} {shr : Fin 14 → Word w} {m : Memory w} {layout : Bool} + (h : Inputs p shr T) (inc : T.ActualColumns X m) + (place : ShrinkRAM.PlacementColumns X.slots X.baseIndex shr layout m) (hd : (p 0).val = 2^a) + (fit : Fintype.card X.Base * 2^(packingLaneBits a g) * 2^a ≤ 2^w) + (e : BundleKeys.OldArc X.Base a g) {i : Word w} (hi : i.val = (BundleKeys.oldArcOrder X.baseIndex e).val) : + let P := X.packingData + let z := roles p m i + z.cd = (if Slots.isCD P e then 1 else 0) ∧ + ∀ hm : Slots.isCD P e, z.A = (packedNumber X.baseIndex (P.roleA ⟨e,hm⟩) : Word w) ∧ + z.B = (packedNumber X.baseIndex (P.roleB ⟨e,hm⟩) : Word w) ∧ + z.D = (packedNumber X.baseIndex (P.roleD layout ⟨e,hm⟩) : Word w) := by + let P := X.packingData + let s := sourcePosition e + let t := sourcePosition (P.actual e) + let code (x : Old X.Base a g) := ShrinkRAM.word w (oldNumber X.baseIndex x) + obtain ⟨hs,ht⟩ := site_inputs X T inc hd h.incidence fit e hi + have reads (x : Old X.Base a g) : + m (p 6+code x).val = ((decide (P.thick x)).toNat : Word w) ∧ + ShrinkRAM.div (m (p 8+code x).val) (p 0) = (packedNumber X.baseIndex (P.assignedBundle x).1 : Word w) ∧ + m (p 9+code x).val = (packedNumber X.baseIndex (P.siteGraph.target (P.assignedBundle x)).1 : Word w) ∧ + m (p 7+code x).val = (packedNumber X.baseIndex (P.placement layout x) : Word w) := by + have ⟨ho,hth,ha,hb⟩ := Prod.mk.inj (place.atSite x) |>.imp_right Prod.mk.inj |>.imp_right (And.imp_right Prod.mk.inj) + change (m (shr 10+code x).val).val = _ at ho + change (m (shr 11+code x).val).val = _ at hth + change (m (shr 12+code x).val).val = _ at ha + change (m (shr 13+code x).val).val = _ at hb + rw [h.thick,h.owner,h.assigned,h.target] + refine ⟨of_val hth, ?_, of_val hb, of_val ho⟩ + apply of_val + rw [div_val, ha, hd, Shrink.join, Nat.mul_comm, Nat.mul_add_div (Nat.two_pow_pos _), + Nat.div_eq_of_lt (P.assignedBundle x).2.isLt, Nat.add_zero] + let cPos := if P.thick s then t else s + let dPos := if P.thick s then s else t + have ends : endpoints p m i = (code cPos, code dPos) := by + unfold endpoints + rw [hs,ht] + change (code s + m (p 6+code s).val*(code t-code s),code t-m (p 6+code s).val*(code t-code s)) = _ + rw [(reads s).1] + by_cases hts : P.thick s <;> simp [hts,cPos,dPos] + dsimp only + constructor + · change 1 - m (p 6+BundleRAM.sourceSite p i).val*m (p 6+BundleRAM.targetSite p m i).val = + if ¬(P.thick s ∧ P.thick t) then 1 else 0 + rw [hs,ht,(reads s).1,(reads t).1] + by_cases h₁ : P.thick s <;> by_cases h₂ : P.thick t <;> simp [h₁,h₂] + · intro hm + change ShrinkRAM.div (m (p 8+(endpoints p m i).1).val) (p 0) = _ ∧ + m (p 9+(endpoints p m i).1).val = _ ∧ m (p 7+(endpoints p m i).2).val = _ + rw [ends] + exact ⟨(reads cPos).2.1,(reads cPos).2.2.1,(reads dPos).2.2.2⟩ + +end CompressorRecords.DemandRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsDemandScan.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandScan.lean new file mode 100644 index 0000000000..633271752f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandScan.lean @@ -0,0 +1,145 @@ +import OAI.Computability.VPVNP.CompressorRecordsDemandRoles + +/-! +# Full scan of selected A, B, D and CD records + +The scan follows each old outgoing slot. The first probe finds its opposite site, +and later probes follow its selected C and D positions. Old directory cells remain +readable throughout. Each row is written at its own permuted absolute arc ID. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DemandRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Address and value of one output component. -/ +def fieldAddr (p : Fin 11 → Word w) (i : Word w) (t : Fin 4) : ℕ := + let a := address p i + ![a.val,(a+1).val,(a+1+1).val,(a+1+1+1).val] t + +/-- Select a field from a demand record in storage order A, B, D, CD. -/ +def Roles.field {α : Type} (r : Roles α) (t : Fin 4) : α := ![r.A,r.B,r.D,r.cd] t + +/-- The address of each of the six reads needed for one demand record, including the three +placement reads at its ordered endpoints. -/ +def inputAddr (p : Fin 11 → Word w) (m : Memory w) (i : Word w) (c : Fin 6) : ℕ := + let src := BundleRAM.sourceSite p i + let dst := BundleRAM.targetSite p m i + let ends := endpoints p m i + ![(p 5+i).val,(p 6+src).val,(p 6+dst).val,(p 8+ends.1).val,(p 9+ends.1).val,(p 7+ends.2).val] c + +/-- The output family can occupy any disjoint region of the external workspace. -/ +structure Regions (p : Fin 11 → Word w) (old : Memory w) (N : ℕ) : Prop where + fits : N ≤ 2^w + unique : ∀ (i j : Word w) (t u : Fin 4), i.val ShrinkRAM.div v (p 0)) (hr 0) + have hs : m (p 6+BundleRAM.sourceSite p i).val = old (p 6+BundleRAM.sourceSite p i).val := hr 1 + have he : endpoints p m i = endpoints p old i := by simp only [endpoints,hd,hs] + unfold roles + dsimp only + rw [he,hd,hs] + rw [show m (p 8+(endpoints p old i).1).val = _ from hr 3, + show m (p 9+(endpoints p old i).1).val = _ from hr 4, + show m (p 7+(endpoints p old i).2).val = _ from hr 5, + show m (p 6+BundleRAM.targetSite p old i).val = _ from hr 2] + rfl + +private theorem store_outside (p : Fin 11 → Word w) (m : Memory w) (i : Word w) (x : ℕ) + (h : ∀ t, x ≠ fieldAddr p i t) : store p m i x = m x := by + change (if x = fieldAddr p i 3 then _ else if x = fieldAddr p i 2 then _ else + if x = fieldAddr p i 1 then _ else if x = fieldAddr p i 0 then _ else m x) = _ + simp [h] + +private theorem store_field {p : Fin 11 → Word w} {old m : Memory w} {N : ℕ} + (reg : Regions p old N) (i : Word w) (hi : i.val rfl + +/-- The finished prefix contains precisely the rows for the visited source arcs. -/ +structure Written (p : Fin 11 → Word w) (old m : Memory w) (k : ℕ) : Prop where + row : ∀ (i : Word w) (t : Fin 4), i.val False.elim (Nat.not_lt_zero _ h), fun _ _ => rfl⟩ + +private theorem Written.step {p : Fin 11 → Word w} {old m : Memory w} {N : ℕ} {i : Word w} + (reg : Regions p old N) (hi : i.val + h.frame _ fun j t hj => reg.input i j c t hi (hj.trans hi) + constructor + · intro j t hj + by_cases he : j=i + · subst j; rw [store_field reg i hi,hr] + · rw [store_outside] + · exact h.row j t (by have := Fin.val_ne_of_ne he; omega) + · intro u hu; exact he ((reg.unique j i t u (by omega) hi).mp hu).1 + · intro x hx + rw [store_outside p m i x (fun t => hx i t (by omega))] + exact h.frame x (fun j t hj => hx j t (by omega)) + +/-- Sequential native execution with four exact output columns, all unrelated cells +framed, and ten probes per directed old port. -/ +theorem scan_run {p : Fin 11 → Word w} {old m : Memory w} {N k n : ℕ} + (reg : Regions p old N) (h : Written p old m k) (bound : k+n ≤ N) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 65 (some (ShrinkRAM.word w k)) m (List.replicate n []) = some rs ∧ + Written p old (after m (eventLog rs)) (k+n) ∧ rs.length = n ∧ + (∀ r ∈ rs, r.events.length = 64 ∧ countProbes r.events = 10) ∧ + RAMBuckets.cost Report.probes rs = 11*n := by + let M := (template visit 0).instantiate w p + induction n generalizing k m with + | zero => exact ⟨[],rfl,h,rfl,by simp,rfl⟩ + | succ n ih => + let i := ShrinkRAM.word w k + have hi : i.val=k := Nat.mod_eq_of_lt (by have := reg.fits; omega) + have hr : Written p old (store p m i) (k+1) := hi ▸ Written.step reg (hi ▸ (by omega)) (hi ▸ h) + obtain ⟨rs, he, hw, hl, hc, hcost⟩ := ih hr (by omega) + let rep : Report w := ⟨events p m i, some (i+1)⟩ + have hnext : i+1 = ShrinkRAM.word w (k+1) := by + change (k : Word w) + 1 = ((k+1 : ℕ) : Word w) + simp + have hmem : after m (eventLog (rep :: rs)) = after (store p m i) (eventLog rs) := by + change after m (events p m i ++ eventLog rs) = _ + rw [show after m (events p m i ++ eventLog rs) = after (after m (events p m i)) (eventLog rs) from List.foldl_append, + visit_after] + refine ⟨rep :: rs, ?_, ?_, by simp [hl], ?_, ?_⟩ + · change runSegment M.program 65 (some i) m (List.replicate (n+1) []) = _ + rw [List.replicate_succ, runSegment, visit_native p m i] + simp only [M,rep,visit_after,hnext,he,Option.map_some] + · rw [hmem]; simpa [Nat.add_assoc,Nat.add_comm 1 n] using hw + · intro r hx + rcases List.mem_cons.mp hx with rfl | hx + · exact visit_work p m i + · exact hc r hx + · change 1+countProbes (events p m i)+RAMBuckets.cost Report.probes rs = _ + rw [(visit_work p m i).2,hcost]; omega + +end CompressorRecords.DemandRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsDemandWidths.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandWidths.lean new file mode 100644 index 0000000000..22c1d69e96 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsDemandWidths.lean @@ -0,0 +1,235 @@ +import OAI.Computability.VPVNP.CompressorRecordsABGraph +import OAI.Computability.VPVNP.CompressorRecordsBundlePrefixGraph + +/-! +# Simultaneous demand and thick-wire width columns + +After the sorted-width scatter and the two old-field prefix scans, one native +balanced-piece scan materializes all AB widths. It preserves the sorted CD +widths, the original thick-wire widths, and the starts of both old field +families. Thus the AB and CD words for a single term share a bundle and rank. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.DemandWidths + +open Compression Compression.PackingData BurstRAM PrimedStackRAM BundleLists +open BundlePrefixGraph (Widths Starts thickWidth motifWidth) + +variable {w B : ℕ} + +private theorem out_bounds {p : Fin 5 → Word w} (L : ABWidths.Layout p B) + (t : Fin 2) (i : ℕ) (hi : i omega + +private theorem slot_bound {b j B s k : ℕ} (hb : b first + | change (p 3).val+B*(p 1).val ≤ _; rw [h₃,h₁]; omega + | change (p 4).val+B*(p 1).val ≤ _; rw [h₄,h₁]; omega + · intro t; left + fin_cases t <;> first + | change total.val+B ≤ (p 3).val; rw [h₃]; exact afterTotals + | change total.val+B ≤ (p 4).val; rw [h₄]; omega + · left; rw [h₁,h₃,h₄] + +theorem packedOutside (total : Word w) {B k start base length : ℕ} + (before : base+length ≤ start) (fit : start+2*(B*k) < 2^w) : + Outside (packedPublic total B k start) B base length := by + let p := packedPublic total B k start + have h₃ : (p 3).val = start := Nat.mod_eq_of_lt (by omega) + have h₄ : (p 4).val = start+B*k := Nat.mod_eq_of_lt (by omega) + intro t; left + fin_cases t <;> first + | change base+length ≤ (p 3).val; rw [h₃]; exact before + | change base+length ≤ (p 4).val; rw [h₄]; omega + +variable {V H T L : Type} {d c n : ℕ} [AddCommGroup H] [AddCommGroup T] [AddCommGroup L] +variable [Fintype V] [Fintype H] [Fintype T] [Fintype L] +variable [DecidableEq V] [DecidableEq T] [DecidableEq L] +variable (P : PackingData V H T L d c) (site : Site V T L ≃ Fin n) (old : Arc V H T L d c → ℕ) +variable (dd : P.ThickNumbering) (cd : P.BundleNumbering) + +/-- All demand widths and all old and AB field offsets in one memory snapshot. -/ +structure Stored (thick cdRows ab : Fin 5 → Word w) (mem : Memory w) : Prop where + thickWidths : Widths (portIndex site) dd (thickWidth P old) thick mem + cdWidths : Widths (portIndex site) cd (motifWidth P old) cdRows mem + thickStarts : Starts (portIndex site) dd (thickWidth P old) thick mem + cdStarts : Starts (portIndex site) cd (motifWidth P old) cdRows mem + ab : ABWidths.ABColumns P cd site old ab mem + +/-- A fixed scan gives both sides of the input to every demand motif and the +two orderings needed by the AB-copy kernel at its endpoints. -/ +theorem complete (t u p : Fin 5 → Word w) (initial : Memory w) {ts us : List (Report w)} + (h : BundlePrefixGraph.Completed P site old dd cd t u initial ts us) + (layout : ABWidths.Layout p (n*d)) (count : (p 0).val = pieceCount d c) + (total : p 2 = t 4) + (thickStride : 2^c*d/4 ≤ (t 1).val) (cdStride : pieceCount d c ≤ (u 1).val) + (apart : ∀ z ∈ [t,u], ∀ i ∈ ([2,3] : List (Fin 5)), Outside p (n*d) (z i).val ((n*d)*(z 1).val)) : + let mem := after (after initial (eventLog ts)) (eventLog us) + let N := n*d*pieceCount d c + let M := (template ABWidths.visit 0).instantiate w p + ∃ rs, runSegment M.program 30 (some (Fin.ofNat _ 0)) mem (List.replicate N []) = some rs ∧ + Stored P site old dd cd t u p (after mem (eventLog rs)) ∧ rs.length = N ∧ + RAMBuckets.cost Report.probes rs = 4*N := by + intro mem N M + have totals : ∀ b, (mem ((p 2).val+(portIndex site b).val)).val = P.bundleWidth old b := total ▸ h.thickTotals + obtain ⟨rs,hr,hab,hf,hl,cost⟩ := ABWidths.graph_run P cd site old p mem layout count totals + have hf' : ABWidths.Filled p mem (after mem (eventLog rs)) (n*d*(p 0).val) := count ▸ hf + have keep (z : Fin 5 → Word w) (hz : z ∈ [t,u]) (i : Fin 5) (hi : i ∈ ([2,3] : List (Fin 5))) + (b : Site V T L × Fin d) (j : ℕ) (hj : j < (z 1).val) : + after mem (eventLog rs) ((z i).val+(portIndex site b).val*(z 1).val+j) = + mem ((z i).val+(portIndex site b).val*(z 1).val+j) := by + apply frame layout hf' (apart z hz i hi) + · omega + · have hb := slot_bound (portIndex site b).isLt hj le_rfl + omega + refine ⟨rs,hr,⟨?_,?_,?_,?_,hab⟩,hl,cost⟩ + · intro b j; rw [keep t (by simp) 2 (by simp) b j.val (j.isLt.trans_le thickStride)]; exact h.thickWidths b j + · intro b j; rw [keep u (by simp) 2 (by simp) b j.val (j.isLt.trans_le cdStride)]; exact h.motifWidths b j + · intro b x + rw [keep t (by simp) 3 (by simp) b (dd b x).val ((dd b x).isLt.trans_le thickStride)] + exact h.thickStarts b x + · intro b x + rw [keep u (by simp) 3 (by simp) b (cd b x).val ((cd b x).isLt.trans_le cdStride)] + exact h.motifStarts b x + +/-- Scatter the ranked actual widths, compute both old-field prefix rectangles, and +then materialize the AB widths. These four segments use one post-memory after +another. Their combined cost is ten units per old port plus four per motif. -/ +theorem from_ranked_input {A : ℕ} (arcs : Arc V H T L d c ≃ Fin A) (hc : 2 ≤ c) + (s t u p : Fin 5 → Word w) (oldLayout : BundlePrefixGraph.RowLayout s t u A n d c) + (m : Memory w) (ranked : BundleWidthScatter.RankedInput P cd dd arcs site s m old) + (W : ℕ) (bound : ∀ e, old e ≤ W) (fit : pieceCount d c*W < 2^w) + (layout : ABWidths.Layout p (n*d)) (count : (p 0).val = pieceCount d c) (total : p 2=t 4) + (apart : ∀ z ∈ [t,u], ∀ i ∈ ([2,3] : List (Fin 5)), Outside p (n*d) (z i).val ((n*d)*(z 1).val)) : + let S := (template BundleWidthScatter.visit 0).instantiate w s + let M := (template ABWidths.visit 0).instantiate w p + ∃ ws ts us rs, let scattered := after m (eventLog ws) + let prefixed := after (after scattered (eventLog ts)) (eventLog us) + runSegment S.program 19 (some 0) m (List.replicate A []) = some ws ∧ + BundlePrefixGraph.Completed P site old dd cd t u scattered ts us ∧ + runSegment M.program 30 (some (Fin.ofNat _ 0)) prefixed (List.replicate (n*d*pieceCount d c) []) = some rs ∧ + Stored P site old dd cd t u p (after prefixed (eventLog rs)) ∧ + RAMBuckets.cost Report.probes ws + RAMBuckets.cost Report.probes ts + + RAMBuckets.cost Report.probes us + RAMBuckets.cost Report.probes rs = + 10*A + 4*(n*d*pieceCount d c) := by + intro S M + obtain ⟨ws,ts,us,hr,_,_,_,_,done,hcost⟩ := + BundlePrefixGraph.scatter_prefix_runs P site old dd cd arcs hc s t u oldLayout m ranked W bound fit + have ht : 2^c*d/4 ≤ (t 1).val := oldLayout.thickSize ▸ oldLayout.thick.size_le_stride + have hu : pieceCount d c ≤ (u 1).val := oldLayout.motifSize ▸ oldLayout.motif.size_le_stride + obtain ⟨rs,hab,stored,_,habcost⟩ := + complete P site old dd cd t u p _ done layout count total ht hu apart + exact ⟨ws,ts,us,rs,hr,done,hab,stored,congrArg₂ (·+·) hcost habcost⟩ + +/-- Following the old sorted-width rectangle, reserve the two old-start +rectangles, the two old-total columns, and finally the AB width and start +rectangles. One last-address bound suffices for all three subsequent scans. -/ +theorem allocation {A n d c : ℕ} (s : Fin 5 → Word w) (start : ℕ) (hc : 2 ≤ c) (hd : 0 < d) + (scatter : BundleWidthScatter.Layout s A n d c) + (afterWidths : (s 4).val + 2*((n*d)*(s 3).val) ≤ start) + (room : start+2*((n*d)*(s 3).val)+2*(n*d)+2*((n*d)*pieceCount d c) < 2^w) : + let B := n*d + let Q := pieceCount d c + let t := BundlePrefixGraph.prefixPublic s B d c start false + let u := BundlePrefixGraph.prefixPublic s B d c start true + let base := start+2*(B*(s 3).val)+2*B + let p := packedPublic (t 4) B Q base + BundlePrefixGraph.RowLayout s t u A n d c ∧ ABWidths.Layout p B ∧ (p 0).val = Q ∧ p 2 = t 4 ∧ + ∀ z ∈ [t,u], ∀ i ∈ ([2,3] : List (Fin 5)), Outside p B (z i).val (B*(z 1).val) := by + intro B Q t u base p + let size := B*(s 3).val + change start+2*size+2*B+2*(B*Q) < 2^w at room + change (s 4).val+2*size ≤ start at afterWidths + have fit : start+2*size+2*B < 2^w := by omega + have tables := BundlePrefixGraph.RowLayout.packed s A n d c start hc hd scatter afterWidths fit + have hw : Q < 2^w := scatter.slots.trans_lt (s 3).isLt + have hpos : 0 < Q := by + obtain ⟨j,rfl⟩ := Nat.exists_eq_add_of_le hc + change 0 < 3*(2^(2+j)*d)/4 + rw [pow_add, show 2^2 = 4 by decide] + have := Nat.mul_pos (Nat.two_pow_pos j) hd + rw [Nat.mul_assoc 4] + omega + have tStart : (t 3).val = start := by + change start % (2^w) = start; exact Nat.mod_eq_of_lt (by omega) + have uStart : (u 3).val = start+size := by + change (start+size) % (2^w) = _; exact Nat.mod_eq_of_lt (by omega) + have tTotal : (t 4).val = start+2*size := by + change (start+2*size) % (2^w) = _; exact Nat.mod_eq_of_lt (by omega) + have tWidth : (t 2).val = (s 4).val := congrArg Fin.val tables.thickBase + have uWidth : (u 2).val = (s 4).val+size := tables.motifBase + have tStride : (t 1).val = (s 3).val := rfl + have uStride : (u 1).val = (s 3).val := rfl + have htotal : (t 4).val+B ≤ base := by change _ ≤ start+2*size+2*B; omega + refine ⟨tables, packedLayout _ _ _ _ hpos hw htotal room,Nat.mod_eq_of_lt hw,rfl,?_⟩ + intro z hz i hi + apply packedOutside _ _ room + simp only [List.mem_cons, List.not_mem_nil, or_false] at hz hi + rcases hz with rfl|rfl <;> rcases hi with rfl|rfl + all_goals + first | rw [tStride] | rw [uStride] + first | rw [tWidth] | rw [uWidth] | rw [tStart] | rw [uStart] + change _ + size ≤ start+2*size+2*B + omega + +end CompressorRecords.DemandWidths + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsDirectory.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsDirectory.lean new file mode 100644 index 0000000000..0b292e5615 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsDirectory.lean @@ -0,0 +1,311 @@ +import OAI.Computability.VPVNP.CompressorRecordsSchedule +import OAI.Computability.VPVNP.CompressorRecordsController + +/-! +# Native execution of a level-major descriptor directory + +Every row supplies a worker tag, a starting cursor, an exclusive stop, and +a fixed-pitch parameter bank. The dispatcher executes the controller, then +the chosen worker for all its data calls, and then returns to the controller. +The row theorem composes an actual verified source run with any remaining +directory. Its cost is linear in the source calls plus probes and the row +count, with constants fixed by the catalog. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Directory + +open BurstRAM BurstRAM.PrivateRAM +open scoped Fin.CommRing + +variable {d w : ℕ} (C : Catalog d) (ports : Ports w) + +/-- A fixed number of pass slots per level. An optional initial segment, +such as the level-zero cursor construction, precedes the repeated levels. -/ +def levelOrdinal {slots : ℕ} (first level : ℕ) (slot : Fin slots) : ℕ := + first + level*slots + slot.val + +/-- Natural address of a field in the fixed-pitch directory, indexed by row ordinal and field +offset. -/ +def address (base arity ordinal : ℕ) (field : Fin (arity + 3)) : ℕ := + base + ordinal*(arity+3) + field.val + +theorem address_injective (base arity : ℕ) : + Function.Injective (fun p : ℕ × Fin (arity+3) ↦ address base arity p.1 p.2) := by + rintro ⟨i,a⟩ ⟨j,b⟩ h + change base + i*(arity+3) + a.val = base + j*(arity+3) + b.val at h + have he : i*(arity+3)+a.val = j*(arity+3)+b.val := by omega + have ha := congrArg (· % (arity+3)) he + simp only [Nat.mul_add_mod_self_right, Nat.mod_eq_of_lt a.isLt, Nat.mod_eq_of_lt b.isLt] at ha + obtain rfl : a = b := Fin.ext ha + have hx := Nat.add_right_cancel he + exact Prod.ext (Nat.eq_of_mul_eq_mul_right (by omega) hx) rfl + +/-- A descriptor program with one finite table independent of the number +of repetitions, directory rows, address width, and live input length. -/ +abbrev table := Schedule.template C (Controller.table (arity C)) + +/-- The native program that dispatches between the fixed-arity directory controller and the +catalog's data workers. -/ +abbrev program := (Schedule.machine C (Controller.table (arity C)) ports).program + +/-- The current directory row's word address, computed from the published directory base, row +ordinal and catalog arity. -/ +def rowBase (m : Memory w) := Controller.rowBase (arity C) ports.data m + +theorem rowBase_val (m : Memory w) + (fit : ports.directory.val + (m ports.ordinal.val).val * (arity C + 3) < 2 ^ w) : + (rowBase C ports m).val = ports.directory.val + (m ports.ordinal.val).val*(arity C+3) := by + exact Controller.rowBase_val (arity C) ports.data m fit + +/-- The linked controller report that snapshots the active row and starts its selected worker +at the stored cursor. -/ +def launchReport (m : Memory w) := + LiveStageLink.linkedReport handoff ports.tag (0 : Fin (d+1)) (Controller.rowReport + (arity C) ports.data m) + +/-- The linked accepting controller report emitted when the directory ordinal has reached the +total row count. -/ +def terminalReport (m : Memory w) := + LiveStageLink.linkedReport (handoff (d := d)) ports.tag 0 (Controller.doneReport ports.data m) + +/-- Memory after the controller launches an active row, with its worker operands and stop bound +installed in the active frame. -/ +def prepared (m : Memory w) := after m (Controller.rowReport (arity C) ports.data m).events + +/-- The worker's initial cursor, read from offset one of the current directory row. -/ +def start (m : Memory w) := m (rowBase C ports m + 1).val +/-- The worker's exclusive stopping cursor, read from offset two of the current directory row. -/ +def bound (m : Memory w) := m (rowBase C ports m + 2).val +/-- The public parameter words of the selected worker, read in order immediately after the +row's stop bound. -/ +def words (i : Fin d) (m : Memory w) : Fin (C i).params → Word w := + fun j ↦ Controller.field (rowBase C ports m + 2) m (j.val+1) + +/-- Internal controller memory effects and the precise next cursor. -/ +theorem launch_effect (m : Memory w) : + (launchReport C ports m).result = some (start C ports m) ∧ + after m (launchReport C ports m).events = prepared C ports m ∧ + (launchReport C ports m).probes = 7+2*(arity C+1) ∧ + choiceBits (launchReport C ports m).events = [] := by + let q := Controller.rowReport (arity C) ports.data m + have hn : handoff (0 : Fin (d+1)) = none := rfl + have hq : q.result = some (start C ports m) := rfl + have hc := Controller.rowReport_cost (arity C) ports.data m + refine ⟨?_,?_,?_,?_⟩ + · change (LiveStageLink.linkedReport handoff ports.tag 0 q).result = _ + simp [LiveStageLink.linkedReport, LiveStageLink.prependLog, LiveStageLink.exitReport, hq] + · rw [launchReport, LiveStageLink.linkedReport_after, hn] + rfl + · rw [launchReport, LiveStageLink.linkedReport_probes, hn] + change q.probes + 1 + (if q.result = none ∧ _ then 1 else 0) = _ + have hp : q.probes = 6+2*(arity C+1) := hc.2.1 + simp [hp,hq] + omega + · rw [launchReport, LiveStageLink.linkedReport_choiceBits] + exact hc.2.2 + +theorem terminal_effect (m : Memory w) : + (terminalReport (d := d) ports m).result = none ∧ after m (terminalReport (d := + d) ports m).events = m ∧ + (terminalReport (d := d) ports m).probes = 3 ∧ choiceBits (terminalReport (d := + d) ports m).events = [] := by + have hn : handoff (0 : Fin (d+1)) = none := rfl + refine ⟨?_,?_,?_,?_⟩ + · rfl + · rw [terminalReport, LiveStageLink.linkedReport_after, hn]; rfl + · rw [terminalReport, LiveStageLink.linkedReport_probes, hn]; rfl + · rw [terminalReport, LiveStageLink.linkedReport_choiceBits]; rfl + +theorem launch (m : Memory w) (st : Word w) (htag : m ports.tag.val = 0) (fits : d + 1 ≤ 2 ^ w) + (active : m ports.ordinal.val < m ports.rows.val) {cap : ℕ} + (hcap : 20 + 6 * (arity C + 1) + 2 * (d + 1) + 5 ≤ cap) : + execute (program C ports) cap ((program C ports).start st) m [] = some + (launchReport C ports m) := by + apply controller_call C (Controller.table (arity C)) ports st m [] htag fits hcap + exact Controller.execute_row (arity C) ports.data st m [] _ active le_rfl + +theorem terminate (m : Memory w) (st : Word w) (htag : m ports.tag.val = 0) (fits : d + 1 ≤ 2 ^ w) + (closed : m ports.rows.val ≤ m ports.ordinal.val) {cap : ℕ} (hcap : 6 + 2 * + (d + 1) + 5 ≤ cap) : + execute (program C ports) cap ((program C ports).start st) m [] = some (terminalReport (d := + d) ports m) := by + apply controller_call C (Controller.table (arity C)) ports st m [] htag fits hcap + exact Controller.execute_done (arity C) ports.data st m [] _ closed le_rfl + +/-- Separation of the active parameter bank from the two mutable control +cells. The controller snapshots the full source row before writing the bank. -/ +def FrameFits : Prop := + arity C+1 ≤ 2^w ∧ ∀ j : Fin (arity C+1), + ports.activeFrame + (j.val : Word w) ≠ ports.ordinal ∧ ports.activeFrame + (j.val : Word w) + ≠ ports.tag + +theorem ready (m : Memory w) (i : Fin d) (fits : FrameFits C ports) + (rowTag : m (rowBase C ports m).val = LiveStageLink.tagWord w i.succ) : + Ready C i ports (words C ports i m) (bound C ports m) (prepared C ports m) := by + have h (j : Fin (arity C+1)) : prepared C ports m (ports.activeFrame+(j.val : Word w)).val = + Controller.field (rowBase C ports m+2) m j.val := + Controller.after_row_frame (arity C) ports.data m j fits.1 (fits.2 j).1 (fits.2 j).2 + refine ⟨(Controller.after_row_tag (arity C) ports.data m).trans rowTag, ?_, ?_⟩ + · simpa [stopWord, bound, Controller.field] using h 0 + · funext j + exact h ⟨j.val+1, Nat.succ_lt_succ (j.isLt.trans_le (params_le_arity C i))⟩ + +/-- One scheduled worker invocation. Its operand words, starting state, +and bound are read from its row in the entry memory. -/ +structure Row (d w : ℕ) where + /-- Entry memory in which the directory controller finds the row and reads its operands. -/ + input : Memory w + /-- Catalog index of the worker selected for this row. -/ + worker : Fin d + /-- Instruction fuel supplied to each call of the row's source worker. -/ + fuel : ℕ + /-- The ordered choice-bit streams supplied to the source worker's data calls. -/ + choices : List (List Bool) + /-- The source worker reports for the row's data calls, in execution order. -/ + reports : List (Report w) + +namespace Row + +/-- Surround the worker choice streams with empty streams for the controller launch and closing +call. -/ +def choicesWithControl (row : Row d w) : List (List Bool) := [] :: (row.choices ++ [[]]) + +/-- Memory passed to the first worker data call after the controller has installed this row's +active frame. -/ +def dataMemory (row : Row d w) := prepared C ports row.input + +/-- Memory after replaying all source worker reports from the prepared data memory. -/ +def endMemory (row : Row d w) := after (row.dataMemory C ports) (eventLog row.reports) + +/-- Memory after the row finishes and restores the controller stage tag to zero. -/ +def post (row : Row d w) := writeMemory (row.endMemory C ports) ports.tag 0 + +/-- The complete linked report list for a directory row, from the controller launch through all +data calls and the closing handoff. -/ +def log (row : Row d w) : List (Report w) := + launchReport C ports row.input :: + (linkedRows C row.worker ports (row.dataMemory C ports) row.reports ++ + [closedLinkedReport C row.worker ports (row.endMemory C ports)]) + +/-- The active row starts under the controller tag, has positive fuel, and its source reports +form an actual run respecting the loaded frame and cursor bound. -/ +structure Valid (row : Row d w) : Prop where + controllerTag : row.input ports.tag.val = 0 + active : row.input ports.ordinal.val < row.input ports.rows.val + positiveFuel : 0 < row.fuel + sourceRun : runSegment ((C row.worker).table.instantiate w + (words C ports row.worker row.input)).program + row.fuel (some (start C ports row.input)) (row.dataMemory C ports) row.choices = + some row.reports + frame : ValidTrace C row.worker ports (words C ports row.worker row.input) + (bound C ports row.input) + (start C ports row.input) (row.dataMemory C ports) row.reports + +/-- A per-call fuel bound covering the controller, the row's source worker and active-frame +loads, and the outer stage dispatch. -/ +def capNeeded (row : Row d w) := + max (20+6*(arity C+1)) (row.fuel+3+4*((C row.worker).params+1)) + 2*(d+1)+5 + +/-- From controller entry through the full original pass and its handoff. +The tail can itself start another pass with newly computed parameters. -/ +theorem segment (row : Row d w) (v : row.Valid C ports) (fits : d + 1 ≤ 2 ^ w) {cap : ℕ} + (hc : capNeeded C row ≤ cap) (tail : List (List Bool)) : + runSegment (program C ports) cap (some 0) row.input (row.choicesWithControl ++ tail) = + (runSegment (program C ports) cap (some 0) (row.post C ports) tail).map (row.log C ports + ++ ·) := by + unfold capNeeded at hc + have hr := launch C ports row.input 0 v.controllerTag fits v.active (cap := cap) (by omega) + have h := launch_effect C ports row.input + simp only [choicesWithControl, List.cons_append, List.append_assoc, List.nil_append, runSegment, + hr, h.1, h.2.1] + change (runSegment (Schedule.machine C (Controller.table (arity C)) ports).program cap + (some (start C ports row.input)) (row.dataMemory C ports) (row.choices ++ [] :: tail)).map _ = _ + rw [worker_segment C (Controller.table (arity C)) row.worker ports _ _ _ _ _ _ row.fuel cap + v.positiveFuel fits + (by omega) v.sourceRun v.frame tail] + simp only [log, post, endMemory, dataMemory, Option.map_map, Function.comp_def, + List.cons_append, List.append_assoc, + List.nil_append] + +/-- Exact source and scheduler charges through one full row, including the +controller launch, active data calls, and the empty-choice closing call. -/ +theorem cost (row : Row d w) (v : row.Valid C ports) : + RAMBuckets.cost Report.probes (row.log C ports) = + RAMBuckets.cost Report.probes row.reports + row.reports.length*((C row.worker).params+2) + + ((C row.worker).params+4) + (8+2*(arity C+1)) := by + rw [log, endMemory, RAMBuckets.cost, (launch_effect C ports row.input).2.2.1, + linkedPass_cost C row.worker ports + (words C ports row.worker row.input) (bound C ports row.input) (start C ports row.input) + _ _ v.frame] + omega + +end Row + +/-- Memory at the terminal controller, after the last worker handoff. -/ +def finalMemory (m : Memory w) : List (Row d w) → Memory w + | [] => m + | row :: rest => finalMemory (row.post C ports) rest + +/-- Compatibility at every native row boundary, with directory exhaustion +checked at the terminal controller. A worker may write later rows. -/ +def Valid (cap : ℕ) (m : Memory w) : List (Row d w) → Prop + | [] => m ports.tag.val = 0 ∧ m ports.rows.val ≤ m ports.ordinal.val + | row :: rest => row.input = m ∧ row.Valid C ports ∧ row.capNeeded C ≤ cap ∧ Valid cap + (row.post C ports) rest + +/-- The native full directory run accepts these exact streams and computes +the indicated reports for all the selected rows. -/ +theorem run (rows : List (Row d w)) (m : Memory w) (cap : ℕ) (fits : d + 1 ≤ 2 ^ w) + (hcap : 6 + 2 * (d + 1) + 5 ≤ cap) (v : Valid C ports cap m rows) : + runSegment (program C ports) cap (some 0) m (rows.flatMap Row.choicesWithControl ++ [[]]) = + some (rows.flatMap (Row.log C ports) ++ [terminalReport (d := d) ports + (finalMemory C ports m rows)]) := by + induction rows generalizing m with + | nil => + obtain ⟨htag,closed⟩ := v + rw [List.flatMap_nil, List.nil_append, runSegment, terminate C ports m 0 htag fits closed hcap] + rfl + | cons row rest ih => + obtain ⟨rfl, hrow, hrowCap, hrest⟩ := v + rw [List.flatMap_cons, List.append_assoc, row.segment C ports hrow fits hrowCap, ih _ hrest] + simp [finalMemory] + +/-- The total linked charge depends only on native source charges and +the row count. The constants depend on the fixed worker catalog. -/ +theorem cost_bound (rows : List (Row d w)) (m : Memory w) (cap : ℕ) (v : Valid C ports cap m rows) : + RAMBuckets.cost Report.probes + (rows.flatMap (Row.log C ports) ++ [terminalReport (d := d) ports + (finalMemory C ports m rows)]) ≤ + (rows.map fun row ↦ RAMBuckets.cost Report.probes row.reports).sum * (arity C+3) + + rows.length*(3*arity C+14) + 4 := by + induction rows generalizing m with + | nil => + simp only [List.flatMap_nil, List.nil_append, finalMemory, List.map_nil, List.sum_nil, + List.length_nil, Nat.zero_mul, Nat.zero_add, RAMBuckets.cost, (terminal_effect (d := + d) ports m).2.2.1] + decide + | cons row rest ih => + obtain ⟨rfl,hrow,_,hrest⟩ := v + have prev := ih _ hrest + have len : row.reports.length ≤ RAMBuckets.cost Report.probes row.reports := by + rw [RAMBuckets.cost_eq_length_add_probes]; omega + have hk := params_le_arity C row.worker + have hm := Nat.mul_le_mul len (Nat.add_le_add_right hk 2) + rw [List.flatMap_cons, finalMemory, List.append_assoc, RAMBuckets.cost_append, + row.cost C ports hrow, + List.map_cons, List.sum_cons, Nat.add_mul, List.length_cons, Nat.add_mul, Nat.one_mul] + have hmul : RAMBuckets.cost Report.probes row.reports * (arity C+3) = + RAMBuckets.cost Report.probes row.reports * (arity C+2) + RAMBuckets.cost Report.probes + row.reports := by + rw [show arity C+3 = (arity C+2)+1 by omega, Nat.mul_succ] + omega + +end CompressorRecords.Schedule.Directory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsDirectoryCursor.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsDirectoryCursor.lean new file mode 100644 index 0000000000..57a52c6e2a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsDirectoryCursor.lean @@ -0,0 +1,219 @@ +import OAI.Computability.VPVNP.CompressorRecordsDirectory +import OAI.Computability.VPVNP.CompressorRecordsScheduleCursor +import OAI.Computability.VPVNP.CompressorRecordsCursorInit + +/-! +# Launching the level-zero cursor pass from an initialized directory + +The first directory row is produced by the fourteen-write initializer. +The controller snapshots the row, installs the active frame, and launches +the cursor worker at row zero. The last worker call restores the controller +tag while preserving the constructed graph directory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Directory.Cursor + +open BurstRAM BurstRAM.PrivateRAM +open CursorNetwork Compression +open scoped Fin.CommRing + +variable {w b l a pad columns : ℕ} {S : Type} [Fintype S] + +/-- The first scheduler row uses the tag for catalog worker zero. -/ +def initWords (ports : Ports w) (b l a width columns : ℕ) : Fin 8 → Word w := + CursorRAM.ScheduleInit.inputs ports.directory (LiveStageLink.tagWord w (0 : Fin 2).succ) b l a width columns + +/-- Memory after the cursor initializer writes the first directory row for the specified +radices, degree, width and incidence columns. -/ +def installed (ports : Ports w) (b l a width columns : ℕ) (m : Memory w) : Memory w := + after m (CursorRAM.ScheduleInit.events (initWords ports b l a width columns)) + +/-- The row object includes the exact reports of the source worker. The +directory dispatcher derives its tag, cursor and operand bank from RAM. -/ +def row (m : Memory w) (b l a width columns : ℕ) : Row 2 w where + input := m + worker := 0 + fuel := 1+CursorRAM.visit.length + choices := List.replicate (CursorRAM.rowCount b l a) [] + reports := CursorRAM.scanReports (CursorRAM.publicWords w b l a width columns) 0 (CursorRAM.rowCount b l a) + +/-- The address lies before the cursor initializer's directory row or at least fourteen words +past its start. -/ +def OutsideRow (ports : Ports w) (addr : Word w) : Prop := + addr.val < ports.directory.val ∨ ports.directory.val + 14 ≤ addr.val + +/-- The active controller row launches the cursor worker at zero with the exact row count and +public operands for the initial graph. -/ +structure Header (ports : Ports w) (b l a width columns : ℕ) (m : Memory w) : Prop where + controllerTag : m ports.tag.val = 0 + active : m ports.ordinal.val < m ports.rows.val + rowTag : m (rowBase cursorRefresh ports m).val = LiveStageLink.tagWord w (0 : Fin 2).succ + initial : start cursorRefresh ports m = 0 + exclusive : bound cursorRefresh ports m = CursorRAM.encode w (CursorRAM.rowCount b l a) + publicWords : words cursorRefresh ports 0 m = CursorRAM.publicWords w b l a width columns + +private theorem addr_val (base : Word w) (j : ℕ) (h : base.val+j < 2^w) : + (base + (j : Word w)).val = base.val+j := by + rw [Fin.val_add, Fin.val_natCast, Nat.mod_eq_of_lt (by omega : j < 2^w), Nat.mod_eq_of_lt h] + +/-- The actual initializer produces every operand used by the controller. +The only hypotheses about incoming RAM concern the three controller cells. +Their addresses lie outside the fourteen consecutive writes. -/ +theorem install (ports : Ports w) (b l a width columns : ℕ) (m : Memory w) + (state : Word w) (rowRoom : ports.directory.val+14 ≤ 2^w) + (tagOutside : OutsideRow ports ports.tag) (ordinalOutside : OutsideRow ports ports.ordinal) + (countOutside : OutsideRow ports ports.rows) + (tag : m ports.tag.val = 0) (ordinal : m ports.ordinal.val = 0) (count : 0 < m ports.rows.val) : + let pub := initWords ports b l a width columns + let M := (PrimedStackRAM.template CursorRAM.ScheduleInit.ops 16).instantiate w pub + execute M.program (1+CursorRAM.ScheduleInit.ops.length) (M.program.start state) m [] = + some ⟨CursorRAM.ScheduleInit.events pub, some (state+1)⟩ ∧ + Header ports b l a width columns (installed ports b l a width columns m) := by + let out := installed ports b l a width columns m + obtain ⟨hn,hr,hs,hb,hp,keep,_⟩ := CursorRAM.ScheduleInit.initialize_row ports.directory + (LiveStageLink.tagWord w (0 : Fin 2).succ) state b l a width columns m rowRoom + have hor : out ports.ordinal.val = 0 := (keep _ ordinalOutside).trans ordinal + have hbase : rowBase cursorRefresh ports out = ports.directory := by + change ports.directory + out ports.ordinal.val * _ = ports.directory + rw [hor,zero_mul,add_zero] + refine ⟨hn, (keep _ tagOutside).trans tag, ?_, ?_, ?_, ?_, ?_⟩ + · change out ports.ordinal.val < out ports.rows.val + rwa [hor, show out ports.rows.val = m ports.rows.val from keep _ countOutside] + · change out (rowBase cursorRefresh ports out).val = _ + rwa [hbase] + · change out (rowBase cursorRefresh ports out+1).val = _ + rw [hbase, show (ports.directory+1).val = ports.directory.val+1 from + addr_val ports.directory 1 (by omega)] + exact hs + · change out (rowBase cursorRefresh ports out+2).val = _ + rw [hbase, show (ports.directory+2).val = ports.directory.val+2 from + addr_val ports.directory 2 (by omega)] + exact hb + · funext j + change out ((rowBase cursorRefresh ports out+2) + ((j.val+1 : ℕ) : Word w)).val = _ + have hj : j.val < 11 := j.isLt + have haddr : (ports.directory+2) + ((j.val+1 : ℕ) : Word w) = + ports.directory + ((3+j.val : ℕ) : Word w) := by push_cast; ring + rw [hbase, haddr, addr_val ports.directory _ (by omega), ← Nat.add_assoc] + exact hp j + +local notation "N₀" => CursorRAM.rowCount b l a + + +/-- Once the controller has read the first row, the guard and parameters +come from its computed frame. Every subsequent reload sees the same values. -/ +theorem valid (ports : Ports w) (hD : 1 < b+l) (hd : 2+pad = 2^a) (bits : S → ℕ) + (m : Memory w) (h : Header ports b l a (∑ s, bits s) columns m) + (room : columns + 6*N₀ ≤ 2^w) (frameOk : FrameFits cursorRefresh ports) + (tag : ports.tag.val < columns ∨ columns + 6*N₀ ≤ ports.tag.val) + (frame : ports.activeFrame.val + 12 ≤ columns ∨ columns + 6*N₀ ≤ ports.activeFrame.val) + (frameRoom : ports.activeFrame.val + 12 ≤ 2^w) : + (row m b l a (∑ s, bits s) columns).Valid cursorRefresh ports := by + have hp : 0 < N₀ := by unfold CursorRAM.rowCount; positivity + have hv : (CursorRAM.encode w N₀).val = N₀ := Nat.mod_eq_of_lt (by omega) + have hr := ready cursorRefresh ports m 0 frameOk h.rowTag + rw [h.publicWords, h.exclusive] at hr + refine ⟨h.controllerTag, h.active, (by change 0 < 57; decide), ?_, ?_⟩ + · change runSegment (((cursorRefresh 0).table.instantiate w (words cursorRefresh ports 0 m)).program) + _ (some (start cursorRefresh ports m)) _ _ = _ + rw [h.publicWords, h.initial] + let pub := CursorRAM.publicWords w b l a (∑ s, bits s) columns + change runSegment ((PrimedStackRAM.template CursorRAM.visit 0).instantiate w pub).program + (1+CursorRAM.visit.length) (some 0) (prepared cursorRefresh ports m) (List.replicate N₀ []) = + some (CursorRAM.scanReports pub 0 N₀) + simpa only [Fin.ofNat_eq_cast, Nat.cast_zero] using + CursorRAM.scan_native (CursorRAM.publicWords w b l a (∑ s, bits s) columns) 0 N₀ (prepared cursorRefresh ports m) + · change ValidTrace cursorRefresh 0 ports (words cursorRefresh ports 0 m) + (bound cursorRefresh ports m) (start cursorRefresh ports m) _ _ + rw [h.publicWords, h.exclusive, h.initial] + have he := cursor_valid_trace ports (CursorRAM.publicWords w b l a (∑ s, bits s) columns) 0 N₀ + (prepared cursorRefresh ports m) (CursorRAM.encode w N₀) (by omega) hr + (cursor_disjoint_layout hD hd bits ports room tag frame frameRoom) + simpa only [row, Row.dataMemory, Fin.ofNat_eq_cast, Nat.cast_zero] using he + +/-- A level-zero row, including its controller launch, has the source +cursor pass's six writes per slot and a fixed dispatcher overhead. -/ +theorem row_effect (ports : Ports w) (m : Memory w) (b l a width columns : ℕ) + (initial : start cursorRefresh ports m = 0) : + let R := row m b l a width columns + after m (eventLog (R.log cursorRefresh ports)) = R.post cursorRefresh ports ∧ + endState (some 0) (R.log cursorRefresh ports) = some 0 ∧ + RAMBuckets.cost Report.probes (R.log cursorRefresh ports) = 20*CursorRAM.rowCount b l a + 47 := by + let pub := CursorRAM.publicWords w b l a width columns + let n := CursorRAM.rowCount b l a + let pre := prepared cursorRefresh ports m + let rs := cursorPassReports ports pub 0 n pre + let head := launchReport cursorRefresh ports m + have he := launch_effect cursorRefresh ports m + have ht := cursor_pass_effect ports pub 0 n pre + change after m (eventLog (head :: rs)) = _ ∧ endState (some 0) (head :: rs) = _ ∧ + RAMBuckets.cost Report.probes (head :: rs) = _ + refine ⟨?_, ?_, ?_⟩ + · simp only [eventLog, List.flatMap_cons, after, List.foldl_append] + change after (after m head.events) (eventLog rs) = _ + rw [he.2.1] + exact ht.1 + · change endState head.result rs = some 0 + rw [he.1, initial] + exact ht.2.1 + · rw [RAMBuckets.cost, he.2.2.1, ht.2.2.2] + have harity : arity cursorRefresh = 11 := by decide + rw [harity] + omega + +/-- Execute the native row producer, launch the controller from the resulting +RAM, run the full incidence scan, and splice any following rows at the exact +post-state. The resulting external memory represents the typed cursor graph. -/ +theorem initialize_and_launch (ports : Ports w) (hD : 1 < b+l) (hd : 2+pad = 2^a) + (bits : S → ℕ) (m : Memory w) (state : Word w) + (rowRoom : ports.directory.val+14 ≤ 2^w) + (tagOutside : OutsideRow ports ports.tag) (ordinalOutside : OutsideRow ports ports.ordinal) + (countOutside : OutsideRow ports ports.rows) + (tagZero : m ports.tag.val = 0) (ordinal : m ports.ordinal.val = 0) (count : 0 < m ports.rows.val) + (room : columns + 6*N₀ ≤ 2^w) (widthFits : (∑ s, bits s) < 2^w) + (frameOk : FrameFits cursorRefresh ports) + (tag : ports.tag.val < columns ∨ columns + 6*N₀ ≤ ports.tag.val) + (frame : ports.activeFrame.val + 12 ≤ columns ∨ columns + 6*N₀ ≤ ports.activeFrame.val) + (frameRoom : ports.activeFrame.val + 12 ≤ 2^w) {cap : ℕ} (hcap : 119 ≤ cap) + (tail : List (List Bool)) : + let init := initWords ports b l a (∑ s, bits s) columns + let M := (PrimedStackRAM.template CursorRAM.ScheduleInit.ops 16).instantiate w init + let input := installed ports b l a (∑ s, bits s) columns m + let R := row input b l a (∑ s, bits s) columns + let D := program cursorRefresh ports + let mem := R.post cursorRefresh ports + let rs := R.log cursorRefresh ports + let X := cursorState (cursorCoordinateLabels b l) hD hd bits + execute M.program (1+CursorRAM.ScheduleInit.ops.length) (M.program.start state) m [] = + some ⟨CursorRAM.ScheduleInit.events init, some (state+1)⟩ ∧ + R.Valid cursorRefresh ports ∧ + runSegment D cap (some 0) input (R.choicesWithControl ++ tail) = + (runSegment D cap (some 0) mem tail).map (rs ++ ·) ∧ + after input (eventLog rs) = mem ∧ endState (some 0) rs = some 0 ∧ + mem ports.tag.val = 0 ∧ (CursorRAM.directory w b l a columns).Represents X mem ∧ + RAMBuckets.cost Report.probes rs = 20*N₀+47 := by + let input := installed ports b l a (∑ s, bits s) columns m + let R := row input b l a (∑ s, bits s) columns + obtain ⟨hi, hh⟩ := install ports b l a (∑ s, bits s) columns m state rowRoom tagOutside ordinalOutside + countOutside tagZero ordinal count + have hv := valid ports hD hd bits input hh room frameOk tag frame frameRoom + obtain ⟨hm,hr,hc⟩ := row_effect ports input b l a (∑ s, bits s) columns hh.initial + have hbound : Row.capNeeded cursorRefresh R = 119 := by + unfold Row.capNeeded + rw [show arity cursorRefresh = 11 by decide] + rfl + have hs := Row.segment cursorRefresh ports R hv (by omega) (hbound ▸ hcap) tail + refine ⟨hi, hv, hs, hm, hr, ?_, ?_, hc⟩ + · simp [Row.post, writeMemory] + · apply cursor_directory_write_tag hD hd bits room ports.tag 0 tag + exact (CursorRAM.initialize_cursor hD hd bits room widthFits (prepared cursorRefresh ports input)).2.1 + +end CompressorRecords.Schedule.Directory.Cursor + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsLevelCalendar.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsLevelCalendar.lean new file mode 100644 index 0000000000..0433438ef6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsLevelCalendar.lean @@ -0,0 +1,471 @@ +import OAI.Computability.VPVNP.CompressorRecordsSchedule + +/-! +# Online controller for repeated descriptor phases + +The finite controller contains the planner tags for an initial sequence and +for one compression block. On each entry it reads the current ordinal and +the total number of phases. A quotient and remainder recover the current +block and its phase. The controller writes the planner tag and returns the address of the +current block header. The subsequent row launch increments the ordinal. +At the total it accepts. The same finite instruction table serves every block count. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.LevelCalendar + +open BurstRAM BurstRAM.PrivateRAM +open scoped Fin.CommRing + +variable {w d : ℕ} + +/-- The initial and repeated tags are operands in the program text. -/ +structure Calendar (d : ℕ) where + /-- Planner tags visited once before the first repeated compression block. -/ + initial : List (Fin d) + /-- Planner tags traversed in order for each repetition of a compression block. -/ + block : List (Fin d) + /-- Words reserved per directory row when locating the level headers after the directory. -/ + rowPitch : ℕ + /-- Number of level-header strides from the start of one compression block to the next. -/ + levelsPerBlock : ℕ + +/-- Number of distinct phase slots in the initial sequence and one copy of the repeated block. -/ +def Calendar.size (A : Calendar d) := A.initial.length + A.block.length +/-- Number of scheduled phases for the given block count, including the initial phases exactly +once. -/ +def Calendar.total (A : Calendar d) (blocks : ℕ) := A.initial.length + blocks*A.block.length +/-- Convert a chronological ordinal to a finite phase slot, using the remainder within the +repeated block after the initial sequence. -/ +def Calendar.phase (A : Calendar d) (j : ℕ) := + if j < A.initial.length then j else A.initial.length + (j-A.initial.length)%A.block.length +/-- The zero-based block number containing a repeated phase, with initial phases assigned to +block zero. -/ +def Calendar.level (A : Calendar d) (j : ℕ) := + if j < A.initial.length then 0 else (j-A.initial.length)/A.block.length + +theorem Calendar.phase_lt (A : Calendar d) {j blocks : ℕ} (h : j < A.total blocks) : + A.phase j < A.size := by + unfold Calendar.phase Calendar.size + split_ifs with hj + · omega + · have hn : 0 < A.block.length := by + by_contra! he + have hzero : A.block.length = 0 := by omega + simp [Calendar.total, hzero] at h + omega + exact Nat.add_lt_add_left (Nat.mod_lt _ hn) _ + +theorem Calendar.block_phase (A : Calendar d) (t : ℕ) (i : Fin A.block.length) : + A.phase (A.initial.length + t*A.block.length+i.val) = A.initial.length+i.val ∧ + A.level (A.initial.length + t*A.block.length+i.val) = t := by + have hi := i.isLt + simp only [Calendar.phase, Calendar.level, Nat.add_assoc, Nat.add_sub_cancel_left, Nat.mul_add_mod_of_lt hi] + simp only [show ¬ A.initial.length+(t*A.block.length+i.val) < A.initial.length by omega, ↓reduceIte] + rw [Nat.mul_comm t, Nat.mul_add_div (by omega), Nat.div_eq_of_lt hi, Nat.add_zero] + trivial + +theorem Calendar.level_lt (A : Calendar d) {j blocks : ℕ} (h : j < A.total blocks) + (hblock : A.initial.length ≤ j) : A.level j < blocks := by + have hn : 0 < A.block.length := by + by_contra! he + simp [Calendar.total, show A.block.length = 0 by omega] at h + omega + rw [Calendar.level, ite_eq_right (not_lt.mpr hblock), Nat.div_lt_iff_lt_mul hn] + unfold Calendar.total at h + omega + +/-- The planner tag at a phase slot in the concatenation of the initial sequence and one +repeated block. -/ +def Calendar.planner (A : Calendar d) (i : Fin A.size) : Fin d := + (A.initial ++ A.block)[i.val]'(by simpa [Calendar.size] using i.isLt) + +/-- Number of native calendar instruction labels, with 31 shared rows and three lookup rows per +phase slot. -/ +abbrev PCs (A : Calendar d) := 31 + A.size*3 +private def labels (A : Calendar d) : Fin 31 ⊕ (Fin A.size × Fin 3) ≃ Fin (PCs A) := + ((Equiv.refl _).sumCongr finProdFinEquiv).trans finSumFinEquiv +private def head (A : Calendar d) (i : Fin 31) := labels A (.inl i) +private def slot (A : Calendar d) (i : Fin A.size) (q : Fin 3) := labels A (.inr (i,q)) +private def lookup (A : Calendar d) (n : ℕ) := + if h : n < A.size then slot A ⟨n,h⟩ 0 else head A 25 + +/-- Enough bits to represent the tags, phase indices, row pitch and number +of levels per block. The level size is read from RAM. -/ +def literalWidth (A : Calendar d) := Nat.clog 2 (A.size+d+A.rowPitch+A.levelsPerBlock+2) +private def lit (A : Calendar d) (n : ℕ) : Word (literalWidth A) := Fin.ofNat _ n + +private def headCode (A : Calendar d) : Fin 31 → Instr (literalWidth A) (PCs A) 11 5 + | 0 => .publicWord 0 2 (head A 1) + | 1 => .readExternal 1 0 (head A 2) + | 2 => .publicWord 2 3 (head A 3) + | 3 => .readExternal 2 2 (head A 4) + | 4 => .jumpLt 1 2 (head A 5) (head A 24) + | 5 => .constant 3 (lit A A.initial.length) (head A 6) + | 6 => .jumpLt 1 3 (head A 7) (head A 9) + | 7 => .copy 4 1 (head A 8) + | 8 => .constant 5 (lit A 0) (head A 14) + | 9 => .binary .sub 6 1 3 (head A 10) + | 10 => .constant 7 (lit A A.block.length) (head A 11) + | 11 => .binary .div 5 6 7 (head A 12) + | 12 => .binary .mod 4 6 7 (head A 13) + | 13 => .binary .add 4 3 4 (head A 14) + | 14 => .publicWord 8 1 (head A 15) + | 15 => .constant 9 (lit A A.rowPitch) (head A 16) + | 16 => .binary .mul 9 9 2 (head A 17) + | 17 => .binary .add 8 8 9 (head A 18) + | 18 => .publicWord 9 1 (head A 26) + | 19 => .binary .mul 9 9 5 (head A 20) + | 20 => .binary .add 8 8 9 (head A 21) + | 21 => .publicWord 7 4 (lookup A 0) + | 22 => .writeExternal 7 10 (head A 23) + | 23 => .returnState 8 + | 24 => .accept + | 25 => .reject + | 26 => .constant 10 (lit A 1) (head A 27) + | 27 => .binary .sub 9 9 10 (head A 28) + | 28 => .readExternal 9 9 (head A 29) + | 29 => .constant 10 (lit A A.levelsPerBlock) (head A 30) + | _ => .binary .mul 9 9 10 (head A 19) + +private def slotCode (A : Calendar d) (i : Fin A.size) : Fin 3 → Instr (literalWidth A) (PCs A) 11 5 + | 0 => .constant 10 (lit A i.val) (slot A i 1) + | 1 => .jumpEq 4 10 (slot A i 2) (lookup A (i.val+1)) + | 2 => .constant 10 (lit A (A.planner i).succ.val) (head A 22) + +/-- Finite instruction table that reads the current ordinal, locates its block header and +dispatches its planner, or accepts at the schedule end. -/ +def table (A : Calendar d) : Template (PCs A) 11 5 where + literalWidth := literalWidth A + entry := head A 0 + code pc := match (labels A).symm pc with + | .inl i => headCode A i + | .inr (i,q) => slotCode A i q + +/-- Instantiate the level calendar's instruction table at the chosen word width and five public +operands. -/ +abbrev machine (A : Calendar d) (pub : Fin 5 → Word w) := (table A).instantiate w pub + +private theorem code_head (A : Calendar d) (pub : Fin 5 → Word w) (i : Fin 31) : + (machine A pub).code (head A i) = (headCode A i).resize w := by + simp [machine, table, Template.instantiate, head] +private theorem code_slot (A : Calendar d) (pub : Fin 5 → Word w) (i : Fin A.size) (q : Fin 3) : + (machine A pub).code (slot A i q) = (slotCode A i q).resize w := by + simp [machine, table, Template.instantiate, slot] + +private theorem lit_val (A : Calendar d) (n : ℕ) (hn : n < A.size+d+A.rowPitch+A.levelsPerBlock+2) : + (lit A n).val = n := Nat.mod_eq_of_lt (hn.trans_le (Nat.le_pow_clog (by decide) _)) + +private theorem step (A : Calendar d) (pub : Fin 5 → Word w) (pc : Fin (PCs A)) (s : Word w) + (rs : Fin 11 → Word w) (priv : Word w → Word w) : + (machine A pub).program.step ⟨pc,s,rs,priv⟩ = ((machine A pub).code pc).run pub ⟨pc,s,rs,priv⟩ := rfl + +private def boot (pub : Fin 5 → Word w) (m : Memory w) : List (Event w) := + [.tick,.read (pub 2) (m (pub 2).val),.tick,.read (pub 3) (m (pub 3).val),.tick] + +/-- The accepting calendar report after reading the ordinal and total phase count, with no +continuation state. -/ +def closedReport (pub : Fin 5 → Word w) (m : Memory w) : Report w := ⟨boot pub m,none⟩ + +private def lookedUp (A : Calendar d) (i : Fin A.size) (rs : Fin 11 → Word w) (n : ℕ) : Report w := + ⟨List.replicate (2*n+3) .tick ++ [.write (rs 7) (LiveStageLink.tagWord w (A.planner i).succ)],some (rs 8)⟩ + +private theorem scan (A : Calendar d) (pub : Fin 5 → Word w) (s : Word w) + (m : Memory w) (bs : List Bool) (f : ℕ) (i : Fin A.size) (room : A.size ≤ 2^w) + (rs : Fin 11 → Word w) (hr : rs 4 = (i.val : Word w)) (k n : ℕ) (hn : k+n = i.val) : + execute (machine A pub).program (f+5+2*n) ⟨lookup A k,s,rs,fun _ ↦ 0⟩ m bs = + if bs = [] then some (lookedUp A i rs n) else none := by + induction n generalizing k rs with + | zero => + have hk : k = i.val := by omega + subst k + rw [show lookup A i.val = slot A i 0 by simp [lookup,i.isLt]] + have hidx := lit_val A i.val (by have := i.isLt; omega) + have htag := lit_val A ((A.planner i).val+1) (by have := (A.planner i).isLt; omega) + by_cases hb : bs = [] <;> + simp (config := {decide := true}) [execute, step, code_slot, slotCode, code_head, headCode, + Instr.resize, Instr.run, Config.put, hidx, htag, hr, hb, lookedUp, + LiveStageLink.tagWord, Report.prepend] + | succ n ih => + have hk : k < i.val := by omega + let j : Fin A.size := ⟨k,hk.trans i.isLt⟩ + have he : lookup A k = slot A j 0 := by simp [lookup,j,j.isLt] + have hne : (i.val : Word w) ≠ (k : Word w) := by + intro h + have hv := congrArg Fin.val h + simp only [Fin.val_natCast, Nat.mod_eq_of_lt (hk.trans_le (i.isLt.trans_le room).le), + Nat.mod_eq_of_lt (i.isLt.trans_le room)] at hv + omega + have hidx := lit_val A j.val (by have := j.isLt; omega) + let rs' := Function.update rs (10 : Fin 11) (k : Word w) + have hrest := ih rs' (by simpa [rs'] using hr) (k+1) (by omega) + rw [show f+5+2*(n+1) = (f+5+2*n)+2 by omega, he] + simp (config := {decide := true}) only [execute, step, code_slot, slotCode, Instr.resize, + Instr.run, Config.put, hidx, Fin.ofNat_eq_cast, Function.update_self, Function.update_of_ne (show (4:Fin 11) ≠ 10 by decide), + hr, hne, ↓reduceIte, j] + rw [hrest] + by_cases hb : bs = [] <;> simp (config := {decide := true}) [hb,lookedUp,rs', + Report.prepend, show 2*(n+1)+3 = (2*n+3)+2 by omega, List.replicate_succ] + +private def finishing (A : Calendar d) (pub : Fin 5 → Word w) (i : Fin A.size) + (rs : Fin 11 → Word w) (m : Memory w) : Report w := + let gap := pub 1-1 + ⟨List.replicate 7 .tick ++ [.read gap (m gap.val)] ++ + List.replicate (2*i.val+3+5) .tick ++ [.write (pub 4) (LiveStageLink.tagWord w (A.planner i).succ)], + some (pub 1 + (A.rowPitch : Word w)*rs 2 + (m gap.val*(A.levelsPerBlock : Word w))*rs 5)⟩ + +set_option maxRecDepth 8192 in +private theorem finish (A : Calendar d) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (f : ℕ) (i : Fin A.size) (room : A.size ≤ 2^w) + (rs : Fin 11 → Word w) (hr : rs 4 = (i.val : Word w)) : + execute (machine A pub).program ((f+5+2*i.val)+13) ⟨head A 14,s,rs,fun _ ↦ 0⟩ m bs = + if bs = [] then some (finishing A pub i rs m) else none := by + have hp := lit_val A A.levelsPerBlock (by omega) + have hrow := lit_val A A.rowPitch (by omega) + have hone := lit_val A 1 (by omega) + simp (config := {decide := true}) [execute, step, code_head, headCode, Instr.resize, Instr.run, + Config.put, hp, hrow, hone, BinaryOp.eval] + rw [scan A pub s m bs f i room _ (by simpa using hr) 0 i.val (by omega)] + by_cases hb : bs = [] <;> simp (config := {decide := true}) [hb,finishing,lookedUp, + Report.prepend, Function.comp_def, List.replicate_succ] + +/-- Level headers immediately follow the directory with one fixed-pitch row +per ordinal. The planner receives the address of the current header. -/ +def header (A : Calendar d) (pub : Fin 5 → Word w) (m : Memory w) := + pub 1 + (A.rowPitch : Word w)*m (pub 3).val + + (m (pub 1-1).val*(A.levelsPerBlock : Word w))*(A.level (m (pub 2).val).val : Word w) + +/-- Planner tag and current header selected by the cursor calculation. -/ +def dispatchReport (A : Calendar d) (pub : Fin 5 → Word w) (m : Memory w) (i : Fin A.size) : Report w := + let ord := m (pub 2).val + let steps := if ord.val < A.initial.length then 4 else 7 + let gap := pub 1-1 + ⟨boot pub m ++ List.replicate (7+steps) .tick ++ [.read gap (m gap.val)] ++ + List.replicate (2*i.val+3+5) .tick ++ + [.write (pub 4) (LiveStageLink.tagWord w (A.planner i).succ)], some (header A pub m)⟩ + +private theorem atStart (A : Calendar d) (pub : Fin 5 → Word w) (s : Word w) : + (machine A pub).program.start s = ⟨head A 0,s,fun _ ↦ 0,fun _ ↦ 0⟩ := rfl + +/-- The capacity test consumes two reads and accepts at or beyond the +exclusive bound. Nonempty branch strings are rejected. -/ +theorem execute_closed (A : Calendar d) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (closed : m (pub 3).val ≤ m (pub 2).val) {cap : ℕ} (hc : 6 ≤ cap) : + execute (machine A pub).program cap ((machine A pub).program.start s) m bs = + if bs = [] then some (closedReport pub m) else none := by + obtain ⟨f,rfl⟩ : ∃ f, cap = f+6 := ⟨cap-6,by omega⟩ + rw [atStart] + by_cases hb : bs = [] <;> + simp (config := {decide := true}) [execute, step, code_head, headCode, Instr.resize, Instr.run, + Config.put, not_lt_of_ge closed, hb, closedReport, boot, Report.prepend] + +set_option maxRecDepth 8192 in +/-- The ordinal selects a planner from the finite program text. The bound, ordinal and level-stride +reads are followed by the planner tag write. The return word points +to the current header for the planner to read on the next call. -/ +theorem execute_dispatch (A : Calendar d) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (active : m (pub 2).val < m (pub 3).val) + (i : Fin A.size) (hi : A.phase (m (pub 2).val).val = i.val) + (room : A.size < 2^w) {cap : ℕ} (hc : 30+2*A.size ≤ cap) : + execute (machine A pub).program cap ((machine A pub).program.start s) m bs = + if bs = [] then some (dispatchReport A pub m i) else none := by + let ord := m (pub 2).val + change A.phase ord.val = i.val at hi + have hord : (ord.val : Word w) = ord := Fin.ext (Nat.mod_eq_of_lt ord.isLt) + have hpre : A.initial.length < 2^w := by unfold Calendar.size at room; omega + have hblock : A.block.length < 2^w := by unfold Calendar.size at room; omega + have hp := lit_val A A.initial.length (by unfold Calendar.size; omega) + have hb := lit_val A A.block.length (by unfold Calendar.size; omega) + have hz := lit_val A 0 (by omega) + have hcmp : ord < (A.initial.length : Word w) ↔ ord.val < A.initial.length := by + change ord.val < A.initial.length % (2^w) ↔ _ + rw [Nat.mod_eq_of_lt hpre] + rw [atStart] + by_cases init : ord.val < A.initial.length + · have hc' : 27+2*i.val ≤ cap := by have := i.isLt; omega + obtain ⟨f,hf⟩ : ∃ f, cap = ((f+5+2*i.val)+13)+9 := ⟨cap-(27+2*i.val),by omega⟩ + have hw := hcmp.mpr init + have hidx : ord = (i.val : Word w) := by + have hx : ord.val = i.val := by simpa only [Calendar.phase, init, ↓reduceIte] using hi + exact hord.symm.trans (congrArg (fun n : ℕ ↦ (n : Word w)) hx) + rw [hf] + generalize hfuel : (f+5+2*i.val)+13 = rest + simp (config := {decide := true}) [execute, step, code_head, headCode, Instr.resize, Instr.run, + Config.put, hp, hz, active, show m (pub 2).val < (A.initial.length : Word w) from hw] + rw [← hfuel, finish A pub s m bs f i room.le _ (by simpa using hidx)] + by_cases hs : bs = [] <;> simp (config := {decide := true}) [hs,dispatchReport,boot,finishing, + header, Report.prepend, Function.comp_def, List.replicate_succ, Calendar.level, + show (m (pub 2).val).val < A.initial.length from init] + · have hc' : 30+2*i.val ≤ cap := by have := i.isLt; omega + obtain ⟨f,hf⟩ : ∃ f, cap = ((f+5+2*i.val)+13)+12 := ⟨cap-(30+2*i.val),by omega⟩ + have hw := mt hcmp.mp init + have hsub : (ord-(A.initial.length : Word w)).val = ord.val-A.initial.length := by + have hx : ord - (A.initial.length : Word w) = ((ord.val-A.initial.length : ℕ) : Word w) := by + rw [Nat.cast_sub (Nat.le_of_not_gt init), hord] + rw [hx, Fin.val_natCast, Nat.mod_eq_of_lt ((Nat.sub_le _ _).trans_lt ord.isLt)] + have hidx : (A.initial.length : Word w) + ((ord.val-A.initial.length)%A.block.length : ℕ) = + (i.val : Word w) := by + rw [← Nat.cast_add] + exact congrArg (fun n : ℕ ↦ (n : Word w)) (by simpa only [Calendar.phase, init, ↓reduceIte] using hi) + rw [hf] + generalize hfuel : (f+5+2*i.val)+13 = rest + simp (config := {decide := true}) [execute, step, code_head, headCode, Instr.resize, Instr.run, + Config.put, hp, hb, active, show ¬m (pub 2).val < (A.initial.length : Word w) from hw, BinaryOp.eval] + rw [← hfuel, finish A pub s m bs f i room.le _ (by + simpa (config := {decide := true}) [show (m (pub 2).val-(A.initial.length : Word w)).val = + (m (pub 2).val).val-A.initial.length from hsub, Nat.mod_eq_of_lt hblock] using hidx)] + by_cases hs : bs = [] <;> simp (config := {decide := true}) [hs,dispatchReport,boot,finishing, + header, Report.prepend, Function.comp_def, List.replicate_succ, Calendar.level, + show ¬(m (pub 2).val).val < A.initial.length from init, show (m (pub 2).val-(A.initial.length : Word w)).val = + (m (pub 2).val).val-A.initial.length from hsub, Nat.mod_eq_of_lt hblock] + +theorem Calendar.planner_initial (A : Calendar d) (i : Fin A.initial.length) : + A.planner (i.castAdd A.block.length) = A.initial[i.val] := by + change (A.initial ++ A.block)[i.val]'(by simp; omega) = A.initial[i.val] + rw [List.getElem_append_left i.isLt] + +theorem Calendar.planner_block (A : Calendar d) (i : Fin A.block.length) : + A.planner (i.natAdd A.initial.length) = A.block[i.val] := by + unfold Calendar.planner + rw [List.getElem_append_right (by simp)] + simp + +/-- Stage zero launches the row, the next stages are the data workers, +and the calendar follows them. The recipe tags follow the calendar in +initial-then-block order. -/ +def recipeCalendar (workers initial phases rowPitch levelsPerBlock : ℕ) : + Calendar (workers+1+(initial+phases)) where + initial := List.ofFn fun i : Fin initial ↦ (i.castAdd phases).natAdd (workers+1) + block := List.ofFn fun i : Fin phases ↦ (i.natAdd initial).natAdd (workers+1) + rowPitch := rowPitch + levelsPerBlock := levelsPerBlock + +theorem recipe_tag (workers initial phases rowPitch levelsPerBlock : ℕ) + (i : Fin (recipeCalendar workers initial phases rowPitch levelsPerBlock).size) : + ((recipeCalendar workers initial phases rowPitch levelsPerBlock).planner i).succ.val = workers+2+i.val := by + unfold Calendar.planner + simp only [recipeCalendar, Fin.val_succ] + by_cases h : i.val < initial + · rw [List.getElem_append_left (by simpa using h)] + simp + omega + · rw [List.getElem_append_right (by simpa using Nat.le_of_not_gt h)] + simp + omega + +/-- For every block count and every active ordinal the phase index exists. +The read-only phase table has only one copy of the repeated block. -/ +theorem execute_active (A : Calendar d) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (blocks : ℕ) (total : (m (pub 3).val).val = A.total blocks) + (active : m (pub 2).val < m (pub 3).val) + (room : A.size < 2^w) {cap : ℕ} (hc : 30+2*A.size ≤ cap) : + let i : Fin A.size := ⟨A.phase (m (pub 2).val).val,A.phase_lt (total ▸ Fin.lt_def.mp active)⟩ + ∀ bs, execute (machine A pub).program cap ((machine A pub).program.start s) m bs = + if bs = [] then some (dispatchReport A pub m i) else none := by + intro i bs + exact execute_dispatch A pub s m bs active i rfl room hc + +private theorem ticks (m : Memory w) (n : ℕ) : + after m (List.replicate n .tick) = m ∧ countProbes (List.replicate n (.tick : Event w)) = 0 ∧ + choiceBits (List.replicate n (.tick : Event w)) = [] := by + induction n with + | zero => exact ⟨rfl,rfl,rfl⟩ + | succ n ih => simpa only [List.replicate_succ, after, List.foldl_cons, update, countProbes, + choiceBits] using ih + +private theorem ticks_write (n : ℕ) (a v : Word w) : + countProbes (List.replicate n .tick ++ [.write a v]) = 1 ∧ + choiceBits (List.replicate n .tick ++ [.write a v]) = [] := by + induction n with + | zero => exact ⟨rfl,rfl⟩ + | succ n ih => simpa only [List.replicate_succ, List.cons_append, countProbes, choiceBits] using ih + +/-- The selected recipe sees the original ordinal and directory. There are +three reads, one tag write, and zero nondeterministic choices. -/ +theorem dispatch_effect (A : Calendar d) (pub : Fin 5 → Word w) (m : Memory w) (i : Fin A.size) : + let rep := dispatchReport A pub m i + after m rep.events = writeMemory m (pub 4) (LiveStageLink.tagWord w (A.planner i).succ) ∧ + rep.result = some (header A pub m) ∧ rep.probes = 4 ∧ choiceBits rep.events = [] := by + let n := 2*i.val+3+5 + let v := LiveStageLink.tagWord w (A.planner i).succ + have ho := ticks_write n (pub 4) v + dsimp only + by_cases h : (m (pub 2).val).val < A.initial.length <;> + simp (config := {decide := true}) only [dispatchReport, h, ↓reduceIte, boot, List.cons_append, + List.nil_append, List.append_assoc, List.replicate_succ, after, List.foldl_append, List.foldl_cons, + update, List.foldl_nil, Report.probes, countProbes, choiceBits, true_and] + all_goals change writeMemory (after m (List.replicate n .tick)) (pub 4) v = _ ∧ + 1+(1+(1+countProbes (List.replicate n .tick ++ [.write (pub 4) v]))) = _ ∧ + choiceBits (List.replicate n .tick ++ [.write (pub 4) v]) = [] + all_goals rw [(ticks m n).1,ho.1,ho.2]; exact ⟨rfl,rfl,rfl⟩ + +theorem closed_effect (pub : Fin 5 → Word w) (m : Memory w) : + let rep := closedReport pub m + after m rep.events = m ∧ rep.result = none ∧ rep.probes = 2 ∧ choiceBits rep.events = [] := + ⟨rfl,rfl,rfl,rfl⟩ + +/-- The planner can emit row `o` and the row launcher can read that same +row. The launcher subsequently advances the ordinal. -/ +theorem dispatch_ordinal (A : Calendar d) (pub : Fin 5 → Word w) (m : Memory w) (i : Fin A.size) + (ordTag : pub 2 ≠ pub 4) (totalTag : pub 3 ≠ pub 4) : + let out := after m (dispatchReport A pub m i).events + out (pub 2).val = m (pub 2).val ∧ out (pub 3).val = m (pub 3).val ∧ + out (pub 4).val = LiveStageLink.tagWord w (A.planner i).succ := by + dsimp only + rw [(dispatch_effect A pub m i).1] + simp [writeMemory, Fin.val_ne_of_ne ordTag, Fin.val_ne_of_ne totalTag] + +/-- The level pointer is an exact natural RAM address when the header fits. +The word before the directory stores the number of words in one level. -/ +theorem header_address (A : Calendar d) (pub : Fin 5 → Word w) (m : Memory w) + (room : (pub 1).val + A.rowPitch*(m (pub 3).val).val + (m (pub 1-1).val).val*A.levelsPerBlock*A.level (m (pub 2).val).val < 2^w) : + (header A pub m).val = + (pub 1).val + A.rowPitch*(m (pub 3).val).val + (m (pub 1-1).val).val*A.levelsPerBlock*A.level (m (pub 2).val).val := by + have hv : ((pub 1).val : Word w) = pub 1 := Fin.ext (Nat.mod_eq_of_lt (pub 1).isLt) + have ht : ((m (pub 3).val).val : Word w) = m (pub 3).val := Fin.ext (Nat.mod_eq_of_lt (m (pub 3).val).isLt) + have hg : ((m (pub 1-1).val).val : Word w) = m (pub 1-1).val := Fin.ext (Nat.mod_eq_of_lt (m (pub 1-1).val).isLt) + unfold header + conv_lhs => rw [← hg,← hv,← ht,← Nat.cast_mul,← Nat.cast_add,← Nat.cast_mul,← Nat.cast_mul,← Nat.cast_add,Fin.val_natCast,hv,Nat.mod_eq_of_lt room] + +/-- For each block below the repetition bound, each slot dispatches to +its own compiled recipe and receives that block's header. -/ +theorem execute_block (A : Calendar d) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (blocks t : ℕ) (ht : t < blocks) (i : Fin A.block.length) + (total : (m (pub 3).val).val = A.total blocks) + (ord : (m (pub 2).val).val = A.initial.length+t*A.block.length+i.val) + (room : A.size < 2^w) {cap : ℕ} (hc : 30+2*A.size ≤ cap) : + let rep := dispatchReport A pub m (i.natAdd A.initial.length) + execute (machine A pub).program cap ((machine A pub).program.start s) m [] = some rep ∧ + rep.result = some (pub 1+(A.rowPitch : Word w)*m (pub 3).val+(m (pub 1-1).val*(A.levelsPerBlock : Word w))*(t : Word w)) ∧ + after m rep.events = writeMemory m (pub 4) (LiveStageLink.tagWord w A.block[i.val].succ) := by + have hlt : m (pub 2).val < m (pub 3).val := by + rw [Fin.lt_def, ord, total, Calendar.total] + have hi := i.isLt + have h := Nat.mul_le_mul_right A.block.length (Nat.succ_le_of_lt ht) + rw [Nat.succ_mul] at h + omega + obtain ⟨hp,hl⟩ := A.block_phase t i + have he := execute_dispatch A pub s m [] hlt (i.natAdd A.initial.length) (ord ▸ hp) room hc + have hm := (dispatch_effect A pub m (i.natAdd A.initial.length)).1 + refine ⟨he,?_,?_⟩ + · change some (header A pub m) = _ + rw [header, ord, hl] + · rwa [Calendar.planner_block] at hm + +/-- When the last row launcher has advanced the ordinal to the prescribed +total, the next calendar call terminates after two reads. -/ +theorem execute_at_total (A : Calendar d) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (blocks : ℕ) (total : (m (pub 3).val).val = A.total blocks) + (ord : (m (pub 2).val).val = A.total blocks) {cap : ℕ} (hc : 6 ≤ cap) : + execute (machine A pub).program cap ((machine A pub).program.start s) m [] = + some (closedReport pub m) := + execute_closed A pub s m [] (Fin.le_def.mpr (total.trans ord.symm).le) hc + +end CompressorRecords.Schedule.LevelCalendar + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsLevelFields.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsLevelFields.lean new file mode 100644 index 0000000000..305c1a3df8 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsLevelFields.lean @@ -0,0 +1,187 @@ +import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +import OAI.Computability.VPVNP.CompressorDescriptorSpace +import OAI.Computability.VPVNP.CompressorLevelCounts +import OAI.Computability.VPVNP.CompressorRecordsLevelCalendar + +/-! +# Physical header operands for online compressor recipes + +Each recipe enters at the first level of its block. A fixed substep offset +and the runtime level stride select the input or output header. Scalar, +incidence, and scratch-array operands use the published pointer cells. The +directory holds exactly the rows visited by the calendar, which may occupy +less space than the polynomial bound reserved in the capacity calculation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.LevelFields + +open BurstRAM BurstRAM.PrivateRAM Compression PhaseRecipe DescriptorSpace +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Recipe expression that loads the level-header stride from the cell immediately preceding +the directory. -/ +def stride := Expr.load ((Expr.publicWord 1).sub (.lit 1)) +/-- Address expression for the header a fixed number of level strides after the block's entry +state. -/ +def atLevel (step : ℕ) := Expr.state.add ((Expr.lit step).mul stride) +/-- Address of a field at the specified offset in a header selected relative to the block's +first level. -/ +def address (step offset : ℕ) := (atLevel step).add (.lit offset) +/-- Recipe expression that loads one word from the selected level header. -/ +def scalar (step offset : ℕ) := Expr.load (address step offset) +/-- Load the published pointer to one of the six incidence columns following the level's scalar +fields. -/ +def incidence (shape : Shape) (step : ℕ) (c : Fin 6) := scalar step (shape.scalarFields+c.val) +/-- Load a table's published base pointer from the level header after the six incidence +pointers. -/ +def table (shape : Shape) (step : ℕ) (j : Fin shape.tables) := scalar step + (shape.scalarFields+6+j.val) + +/-- Read the number of input base vertices from scalar zero of the selected level. -/ +def vertices (step : ℕ) := scalar step 0 +/-- Read the input slot degree from scalar one of the selected level. -/ +def degree (step : ℕ) := scalar step 1 +/-- Read the number of input lanes per base vertex from scalar two of the selected level. -/ +def lanes (step : ℕ) := scalar step 2 +/-- Read the number of residual lanes from scalar three of the selected level. -/ +def residualLanes (step : ℕ) := scalar step 3 +/-- Read the next level's slot degree from scalar four of the current level. -/ +def nextDegree (step : ℕ) := scalar step 4 +/-- Read the refresh expander's degree from scalar five of the selected level. -/ +def expanderDegree (step : ℕ) := scalar step 5 +/-- Compute the level's input site count by multiplying the base-vertex count by the lanes per +vertex. -/ +def sites (step : ℕ) := (vertices step).mul (lanes step) +/-- Compute the number of input ports visited in a level by multiplying its site count by its +slot degree. -/ +def slots (step : ℕ) := (sites step).mul (degree step) + +/-- Runtime metadata identifying the first level in this block. -/ +structure Entry (L : DescriptorSpace.Layout) (first : ℕ) (pub : Fin 5 → Word w) + (state : Word w) (m : Memory w) : Prop where + pointer : state = ((levelStart L) first : Word w) + pitch : m (pub 1-1).val = ((levelWords L) : Word w) + +variable {L : DescriptorSpace.Layout} {first : ℕ} {pub : Fin 5 → Word w} {state : Word w} + {m : Memory w} + +theorem eval_stride (e : Entry L first pub state m) : stride.eval pub state m = ((levelWords L) + : Word w) := + e.pitch + +theorem eval_atLevel (e : Entry L first pub state m) (step : ℕ) : + (atLevel step).eval pub state m = ((levelStart L) (first+step) : Word w) := by + change state + (step : Word w) * stride.eval pub state m = _ + rw [eval_stride e,e.pointer] + simp [levelStart, Nat.add_mul, add_assoc] + +theorem eval_address (e : Entry L first pub state m) (step offset : ℕ) : + (address step offset).eval pub state m = ((levelStart L) (first+step)+offset : ℕ) := by + change (atLevel step).eval pub state m + (offset : Word w) = _ + rw [eval_atLevel e]; simp + +theorem eval_scalar (e : Entry L first pub state m) (step offset : ℕ) + (room : (levelStart L) (first + step) + offset < 2 ^ w) : + (scalar step offset).eval pub state m = m ((levelStart L) (first+step)+offset) := by + change m ((address step offset).eval pub state m).val = _ + rw [eval_address e, Fin.val_natCast, Nat.mod_eq_of_lt room] + +theorem eval_incidence (e : Entry L first pub state m) (step : ℕ) (c : Fin 6) + (room : (incidenceHead L) (first + step) c < 2 ^ w) : + (incidence L.shape step c).eval pub state m = m ((incidenceHead L) (first+step) c) := by + simpa only [incidence,incidenceHead,Nat.add_assoc] using eval_scalar e step + (L.shape.scalarFields+c.val) + (by simpa only [incidenceHead,Nat.add_assoc] using room) + +theorem eval_table (e : Entry L first pub state m) (step : ℕ) (j : Fin L.shape.tables) + (room : (tableHead L) (first + step) j < 2 ^ w) : + (table L.shape step j).eval pub state m = m ((tableHead L) (first+step) j) := by + simpa only [table,tableHead,Nat.add_assoc] using eval_scalar e step (L.shape.scalarFields+6+j.val) + (by simpa only [tableHead,Nat.add_assoc] using room) + +theorem eval_calendar_entry {d : ℕ} (A : Schedule.LevelCalendar.Calendar d) (pub : Fin 5 → Word w) + (m : Memory w) (L : DescriptorSpace.Layout) + (dir : pub 1 = ((directoryBase L) : Word w)) (pitch : A.rowPitch = L.shape.arity + 3) + (total : m (pub 3).val = ((directoryRows L) : Word w)) + (strideEq : m (pub 1 - 1).val = ((levelWords L) : Word w)) : + Entry L (A.levelsPerBlock*A.level (m (pub 2).val).val) pub + (Schedule.LevelCalendar.header A pub m) m := by + refine ⟨?_,strideEq⟩ + unfold Schedule.LevelCalendar.header + rw [dir, pitch, total, ← dir, strideEq, dir] + simp only [levelStart, levelsBase, Nat.cast_add, Nat.cast_mul] + ring + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + +/-- The first five persistent scalars describe the actual selected step, including +its residual lanes and next degree. The sixth scalar is the fixed expander degree +for a refresh. -/ +structure Published (L : DescriptorSpace.Layout) (i : ℕ) (v : SelectedLevel B f hf) (dH : ℕ) + (m : Memory w) : Prop where + room : (levelStart L) i + 5 < 2^w + vertices : m ((levelStart L) i+0) = (Fintype.card v.input.Base : Word w) + degree : m ((levelStart L) i+1) = ((2^v.inputExponent : ℕ) : Word w) + lanes : m ((levelStart L) i+2) = ((2^v.inputLanes : ℕ) : Word w) + residual : m ((levelStart L) i+3) = ((2^v.outputLanes : ℕ) : Word w) + nextDegree : m ((levelStart L) i+4) = ((2^v.outputExponent : ℕ) : Word w) + expander : m ((levelStart L) i+5) = (dH : Word w) + +theorem eval_dimensions {step dH : ℕ} {v : SelectedLevel B f hf} (e : Entry L first pub state m) + (h : Published L (first + step) v dH m) : + (sites step).eval pub state m = (v.input.positions : Word w) ∧ + (slots step).eval pub state m = (v.oldSlots : Word w) ∧ + (residualLanes step).eval pub state m = ((2^v.outputLanes : ℕ) : Word w) ∧ + (nextDegree step).eval pub state m = ((2^v.outputExponent : ℕ) : Word w) ∧ + (expanderDegree step).eval pub state m = (dH : Word w) := by + have room := h.room + have hv := (eval_scalar e step 0 (by omega)).trans h.vertices + have hd := (eval_scalar e step 1 (by omega)).trans h.degree + have hl := (eval_scalar e step 2 (by omega)).trans h.lanes + have hs : (sites step).eval pub state m = (v.input.positions : Word w) := by + change (scalar step 0).eval pub state m * (scalar step 2).eval pub state m = _ + have hc := (Fintype.card_congr (bitWordFinEquiv v.inputLanes)).trans (Fintype.card_fin _) + rw [hv,hl,State.positions,Fintype.card_prod,hc,Nat.cast_mul] + refine ⟨hs,?_, (eval_scalar e step 3 (by omega)).trans h.residual, + (eval_scalar e step 4 (by omega)).trans h.nextDegree, + (eval_scalar e step 5 room).trans h.expander⟩ + change (sites step).eval pub state m * (scalar step 1).eval pub state m = _ + rw [hs, hd, SelectedLevel.oldSlots, Nat.cast_mul] + +/-- Pack the actual chronological directory before the headers. Capacities of +all persistent per-level arrays and the relative field offsets are preserved. -/ +def tightDirectory (L : DescriptorSpace.Layout) (rows : ℕ) : DescriptorSpace.Layout := + { L with shape := { L.shape with initialRows := rows, levelPasses := 0, sitePasses := 0 } } + +theorem tight_rows (L : DescriptorSpace.Layout) (rows : ℕ) : (directoryRows + (tightDirectory L rows)) = rows := by + simp [tightDirectory, directoryRows, passesPerLevel] + +theorem tight_stride (L : DescriptorSpace.Layout) (rows : ℕ) : (levelWords + (tightDirectory L rows)) = (levelWords L) := rfl + +theorem tight_end (L : DescriptorSpace.Layout) (rows : ℕ) (h : rows ≤ (directoryRows L)) : + (endAddress (tightDirectory L rows)) ≤ (endAddress L) := by + change (directoryBase L) + (directoryRows (tightDirectory L rows))*(L.shape.arity+3) + + L.levels*(levelWords L) ≤ + (directoryBase L) + (directoryRows L)*(L.shape.arity+3) + L.levels*(levelWords L) + rw [tight_rows] + exact Nat.add_le_add_right (Nat.add_le_add_left (Nat.mul_le_mul_right _ h) _) _ + +theorem calendar_capacity (L : DescriptorSpace.Layout) (initial phases blocks : ℕ) + (hi : initial ≤ L.shape.initialRows) (hb : blocks ≤ L.levels) + (hp : phases ≤ (passesPerLevel L)) : initial+blocks*phases ≤ (directoryRows L) := + Nat.add_le_add hi (Nat.mul_le_mul hb hp) + +end CompressorRecords.LevelFields + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsOnline.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsOnline.lean new file mode 100644 index 0000000000..07d1d8d305 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsOnline.lean @@ -0,0 +1,619 @@ +import OAI.Computability.VPVNP.CompressorRecordsLevelCalendar +import OAI.Computability.VPVNP.CompressorRecordsDirectory +import OAI.Computability.VPVNP.CompressorRecordsRowRecipe + +/-! +# Native online descriptor program + +Stage zero launches the freshly constructed row. The data workers come +next, followed by the calendar and the row recipes. A data worker's +closing call returns to the calendar. A recipe's accepting call returns +to stage zero, which snapshots its actual output row. The calendar is the +only accepting terminal stage of the scheduled path. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online + +open BurstRAM BurstRAM.PrivateRAM +open scoped Fin.CommRing + +variable {d initial phases w : ℕ} {C : Catalog d} + +/-- The finite plan of row-building recipes for the initial and repeated phases, together with +the number of levels advanced by each block. -/ +structure Config (C : Catalog d) (initial phases : ℕ) where + /-- How many level headers the calendar advances when it moves to the next block. -/ + levelsPerBlock : ℕ + /-- The recipe and its register count at each initial or repeated phase, producing a + directory row of the catalog's fixed arity. -/ + recipes : Fin (initial+phases) → Σ r, RowRecipe.Recipe r 5 (arity C) + +variable (plan : Config C initial phases) + +/-- Total number of linked online stages, including a launcher, the data workers, a calendar +and the row recipes. -/ +abbrev N (d q : ℕ) := (d+1)+(q+1) +local notation "q₀" => initial+phases +local notation "D₀" => N d q₀ + +/-- Build the planner calendar for this configuration using the catalog's row pitch and the +configured number of levels per block. -/ +def calendar := LevelCalendar.recipeCalendar d initial phases (arity C+3) plan.levelsPerBlock + +/-- Stage zero, where the controller snapshots the directory row and launches its data worker. -/ +def launchIndex (d q : ℕ) : Fin (N d q) := (0 : Fin (d+1)).castAdd (q+1) +/-- The linked stage of a data worker, immediately following the launcher in catalog order. -/ +def workerIndex (q : ℕ) (i : Fin d) : Fin (N d q) := i.succ.castAdd (q+1) +/-- The stage after the data-worker bank that selects the next planner recipe. -/ +def calendarIndex (d q : ℕ) : Fin (N d q) := (0 : Fin (q+1)).natAdd (d+1) +/-- The linked stage of a row-building recipe, numbered after the calendar. -/ +def recipeIndex (d : ℕ) {q : ℕ} (j : Fin q) : Fin (N d q) := j.succ.natAdd (d+1) + +private def fullSlot {p r : ℕ} (T : Template p r 5) : Slot := ⟨⟨p,r,5,T⟩,id⟩ +private def dataSlot (P : Pass) : Slot := ⟨worker P,fun _ ↦ 0⟩ + +/-- The stage slots and their operand mappings, ordered as launcher, data workers, calendar and +row recipes. -/ +def slots : Fin D₀ → Slot := + Fin.addCases (Fin.cons (fullSlot (Controller.table (arity C))) (fun i ↦ dataSlot (C i))) + (Fin.cons (fullSlot (LevelCalendar.table (calendar plan))) (fun j ↦ fullSlot (plan.recipes j).2.acceptTable)) + +private def regs := Finset.univ.sup fun s ↦ (slots plan s).regs +private def embedRegs (s : Fin D₀) : Fin (slots plan s).regs ↪ Fin (regs plan) := + Fin.castLEEmb (Finset.le_sup (f := fun t ↦ (slots plan t).regs) (Finset.mem_univ s)) + +/-- Embed each stage's instructions into the online program's shared register bank and public +operand table. -/ +def tables (s : Fin D₀) := LiveStageLink.widen (slots plan s).table (embedRegs plan s) (slots plan s).publicIndex + +/-- The continuation on stage acceptance. A completed worker goes to the calendar and a +completed recipe goes to the launcher. -/ +def handoff (d q : ℕ) : Fin (N d q) → Option (Fin (N d q)) := + Fin.addCases (Fin.cons none (fun _ ↦ some (calendarIndex d q))) (Fin.cons none (fun _ ↦ some (launchIndex d q))) + +/-- The fixed online RAM template linking the widened stage tables with their accepting +handoffs. -/ +def template := LiveStageLink.linked (tables plan) (handoff d q₀) + +/-- Instantiate the linked online stages with the runtime workspace ports and stage-tag +address. -/ +def program (ports : Ports w) := (LiveStageLink.machine (tables plan) (handoff d q₀) ports.data ports.tag).program + +/-- Wrap a source-stage report in the online dispatcher's events and apply the accepting +handoff for its stage. -/ +def linked (ports : Ports w) (s : Fin D₀) (rep : Report w) := + LiveStageLink.linkedReport (handoff d q₀) ports.tag s rep + +private def source (slot : Slot) (ports : Ports w) (state : Word w) (m : Memory w) (bs : List Bool) (f : ℕ) := + let P := (slot.table.instantiate w (ports.data ∘ slot.publicIndex)).program + execute P f (P.start state) m bs + +private theorem call (ports : Ports w) (s : Fin D₀) (state : Word w) (m : Memory w) (bs : List Bool) + (htag : m ports.tag.val = LiveStageLink.tagWord w s) (fits : D₀ ≤ 2^w) + {f cap : ℕ} (hcap : f+2*D₀+5 ≤ cap) {rep : Report w} + (hr : source (slots plan s) ports state m bs f = some rep) : + execute (program plan ports) cap ((program plan ports).start state) m bs = + some (linked ports s rep) := by + apply LiveStageLink.execute_linked_of_stage _ _ _ _ s fits hcap _ _ htag bs rep + rw [tables, LiveStageLink.execute_widen_start] + exact hr + +theorem phase_count : (calendar plan).size = q₀ := by + simp [calendar, LevelCalendar.recipeCalendar, LevelCalendar.Calendar.size] + +/-- Identify a recipe's configuration index with its slot in the constructed planner calendar. -/ +def phaseIndex (j : Fin q₀) : Fin (calendar plan).size := Fin.cast (phase_count plan).symm j + +theorem phase_tag (j : Fin q₀) : + LiveStageLink.tagWord w ((calendar plan).planner (phaseIndex plan j)).succ = + LiveStageLink.tagWord w (recipeIndex d j) := by + apply congrArg (Fin.ofNat (2^w)) + apply (LevelCalendar.recipe_tag d initial phases (arity C+3) plan.levelsPerBlock (phaseIndex plan j)).trans + simp [phaseIndex,recipeIndex] + omega + +/-- One real calendar call selects the next row recipe in the shared tag +cell and returns the header pointer to it. -/ +theorem calendar_call (ports : Ports w) (state : Word w) (m : Memory w) (j : Fin q₀) + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (fits : D₀ ≤ 2^w) + (active : m ports.ordinal.val < m ports.rows.val) + (hj : (calendar plan).phase (m ports.ordinal.val).val = j.val) + {cap : ℕ} (hcap : 30+2*q₀+2*D₀+5 ≤ cap) : + execute (program plan ports) cap ((program plan ports).start state) m [] = + some (linked ports (calendarIndex d q₀) + (LevelCalendar.dispatchReport (calendar plan) ports.data m (phaseIndex plan j))) := by + apply call plan ports _ state m [] htag fits hcap + simp only [slots, calendarIndex, Fin.addCases_right, Fin.cons_zero] + apply LevelCalendar.execute_dispatch (calendar plan) ports.data state m [] active (phaseIndex plan j) hj + · rw [phase_count]; unfold N at fits; omega + · rw [phase_count] + +theorem calendar_stop (ports : Ports w) (state : Word w) (m : Memory w) + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (fits : D₀ ≤ 2^w) + (stop : m ports.rows.val ≤ m ports.ordinal.val) {cap : ℕ} (hcap : 6+2*D₀+5 ≤ cap) : + execute (program plan ports) cap ((program plan ports).start state) m [] = + some (linked ports (calendarIndex d q₀) (LevelCalendar.closedReport ports.data m)) := by + apply call plan ports _ state m [] htag fits hcap + simp only [slots, calendarIndex, Fin.addCases_right, Fin.cons_zero] + exact LevelCalendar.execute_closed (calendar plan) ports.data state m [] stop le_rfl + +/-- The accepting source report of a row recipe, using the write events computed from the block +header state and entry memory. -/ +def recipeSource (ports : Ports w) (j : Fin q₀) (state : Word w) (m : Memory w) : Report w := + ⟨((plan.recipes j).2.report ports.data state m).events,none⟩ + +/-- A fixed recipe runs on the returned header pointer and transfers to the +row launcher. -/ +theorem recipe_call (ports : Ports w) (j : Fin q₀) (state : Word w) (m : Memory w) + (htag : m ports.tag.val = LiveStageLink.tagWord w (recipeIndex d j)) (fits : D₀ ≤ 2^w) + {cap : ℕ} (hcap : (plan.recipes j).2.code.length+1+2*D₀+5 ≤ cap) : + execute (program plan ports) cap ((program plan ports).start state) m [] = + some (linked ports (recipeIndex d j) (recipeSource plan ports j state m)) := by + apply call plan ports _ state m [] htag fits hcap + simp only [slots,recipeIndex,Fin.addCases_right,Fin.cons_succ] + exact RowRecipe.execute_accept (plan.recipes j).2 ports.data state m [] _ (Nat.lt_succ_self _) + +/-- Stage zero loads the currently addressed row and installs its worker's +parameter frame. -/ +theorem launch_call (ports : Ports w) (state : Word w) (m : Memory w) + (htag : m ports.tag.val = 0) (fits : D₀ ≤ 2^w) + (active : m ports.ordinal.val < m ports.rows.val) {cap : ℕ} + (hcap : 20+6*(arity C+1)+2*D₀+5 ≤ cap) : + execute (program plan ports) cap ((program plan ports).start state) m [] = + some (linked ports (launchIndex d q₀) (Controller.rowReport (arity C) ports.data m)) := by + apply call plan ports (launchIndex d q₀) state m [] htag fits hcap + simp only [slots,launchIndex,Fin.addCases_left,Fin.cons_zero] + exact Controller.execute_row (arity C) ports.data state m [] _ active le_rfl + +/-- The data worker's closing source report, including the active-frame loads for its bound and +parameters before acceptance. -/ +def closedSource (P : Pass) (ports : Ports w) (m : Memory w) := + LiveStageLink.prependLog (Frame.loadEvents ports.activeFrame m 0 (P.params+1)) (LiveHeaderBounded.closedReport w) + +theorem worker_active (ports : Ports w) (i : Fin d) (state : Word w) (m : Memory w) (bs : List Bool) + (htag : m ports.tag.val = LiveStageLink.tagWord w i.succ) (fits : D₀ ≤ 2^w) + (guard : state < stopWord ports.activeFrame m) {f cap : ℕ} + (hcap : f+3+4*((C i).params+1)+2*D₀+5 ≤ cap) (rep : Report w) + (hr : let S := ((C i).table.instantiate w (parameters ports.activeFrame m)).program + execute S f (S.start state) m bs = some rep) : + execute (program plan ports) cap ((program plan ports).start state) m bs = + some (linked ports (workerIndex q₀ i) (workerReport (C i) ports.activeFrame m rep)) := by + apply call plan ports _ state m bs htag fits hcap + simp only [slots,workerIndex,Fin.addCases_left,Fin.cons_succ] + change execute (((worker (C i)).table.instantiate w (fun _ ↦ ports.activeFrame)).program) _ + (((worker (C i)).table.instantiate w (fun _ ↦ ports.activeFrame)).program.start state) m bs = _ + rw [execute_worker _ _ _ _ _ guard,hr] + rfl + +theorem worker_stop (ports : Ports w) (i : Fin d) (state : Word w) (m : Memory w) + (htag : m ports.tag.val = LiveStageLink.tagWord w i.succ) (fits : D₀ ≤ 2^w) + (guard : stopWord ports.activeFrame m ≤ state) {cap : ℕ} + (hcap : 4+4*((C i).params+1)+2*D₀+5 ≤ cap) : + execute (program plan ports) cap ((program plan ports).start state) m [] = + some (linked ports (workerIndex q₀ i) (closedSource (C i) ports m)) := by + apply call plan ports _ state m [] htag fits hcap + simp only [slots,workerIndex,Fin.addCases_left,Fin.cons_succ] + exact execute_worker_stop (C i) ports.activeFrame state m [] guard 0 + +private theorem returned (ports : Ports w) (index : Fin D₀) (m : Memory w) (rep : Report w) + {st : Word w} (hs : rep.result = some st) : + let out := linked ports index rep + out.result = some st ∧ after m out.events = after m rep.events ∧ + out.probes = rep.probes+1 ∧ choiceBits out.events = choiceBits rep.events := by + refine ⟨?_,?_,?_,LiveStageLink.linkedReport_choiceBits ..⟩ + · simp [linked, LiveStageLink.linkedReport, LiveStageLink.prependLog, LiveStageLink.exitReport, hs] + · rw [linked,LiveStageLink.linkedReport_after,hs] + · rw [linked,LiveStageLink.linkedReport_probes,hs]; simp + +private theorem transferred (ports : Ports w) (index dest : Fin D₀) (m : Memory w) (rep : Report w) + (hs : rep.result = none) (hd : handoff d q₀ index = some dest) : + let out := linked ports index rep + out.result = some 0 ∧ after m out.events = writeMemory (after m rep.events) ports.tag + (LiveStageLink.tagWord w dest) ∧ out.probes = rep.probes+2 ∧ choiceBits out.events = choiceBits rep.events := by + refine ⟨?_,?_,?_,LiveStageLink.linkedReport_choiceBits ..⟩ + · simp [linked, LiveStageLink.linkedReport, LiveStageLink.prependLog, LiveStageLink.exitReport, hs, hd] + · rw [linked, LiveStageLink.linkedReport_after,hs,hd] + · rw [linked, LiveStageLink.linkedReport_probes,hs,hd]; simp + +/-- The linked calendar report dispatching the recipe for the specified phase. -/ +def calendarReport (ports : Ports w) (m : Memory w) (j : Fin q₀) := + linked ports (calendarIndex d q₀) (LevelCalendar.dispatchReport (calendar plan) ports.data m (phaseIndex plan j)) + +/-- The linked report of a recipe that writes its row and hands control to the launcher. -/ +def recipeReport (ports : Ports w) (j : Fin q₀) (state : Word w) (m : Memory w) := + linked ports (recipeIndex d j) (recipeSource plan ports j state m) + +/-- The linked controller report that installs the newly prepared row and dispatches its data +worker. -/ +def launchReport (C : Catalog d) (q : ℕ) (ports : Ports w) (m : Memory w) := + LiveStageLink.linkedReport (handoff d q) ports.tag (launchIndex d q) (Controller.rowReport (arity C) ports.data m) + +/-- Wrap one successful data call with its active-frame loads and the online stage dispatch. -/ +def activeReport (C : Catalog d) (q : ℕ) (ports : Ports w) (i : Fin d) (m : Memory w) (rep : Report w) := + LiveStageLink.linkedReport (handoff d q) ports.tag (workerIndex q i) (workerReport (C i) ports.activeFrame m rep) + +/-- The linked closing report at the worker's exclusive bound, handing control back to the +calendar. -/ +def stopReport (C : Catalog d) (q : ℕ) (ports : Ports w) (i : Fin d) (m : Memory w) := + LiveStageLink.linkedReport (handoff d q) ports.tag (workerIndex q i) (closedSource (C i) ports m) + +theorem calendar_effect (ports : Ports w) (m : Memory w) (j : Fin q₀) : + let out := calendarReport plan ports m j + out.result = some (LevelCalendar.header (calendar plan) ports.data m) ∧ + after m out.events = writeMemory m ports.tag (LiveStageLink.tagWord w (recipeIndex d j)) ∧ + out.probes = 5 ∧ choiceBits out.events = [] := by + obtain ⟨hm,hr,hp,hb⟩ := LevelCalendar.dispatch_effect (calendar plan) ports.data m (phaseIndex plan j) + obtain ⟨hs,he,hc,hk⟩ := returned ports (calendarIndex d q₀) m _ hr + rw [phase_tag plan] at hm + exact ⟨hs,he.trans hm,hc.trans (by rw [hp]),hk.trans hb⟩ + +theorem recipe_effect (ports : Ports w) (j : Fin q₀) (s : Word w) (m : Memory w) : + let R := (plan.recipes j).2 + let out := recipeReport plan ports j s m + out.result = some 0 ∧ after m out.events = + writeMemory (Greedy.writeRow m (R.address ports.data s m) (R.words ports.data s m)) ports.tag 0 ∧ + out.probes = R.reads+(arity C+3)+2 ∧ choiceBits out.events = [] := by + obtain ⟨hs,he,hp,hb⟩ := transferred ports (recipeIndex d j) (launchIndex d q₀) m + (recipeSource plan ports j s m) rfl (by simp [handoff,recipeIndex]) + obtain ⟨_,hc,hk⟩ := RowRecipe.report_cost (plan.recipes j).2 ports.data s m + exact ⟨hs, he.trans (congrArg (fun mem ↦ writeMemory mem ports.tag 0) (RowRecipe.after_row ..)), + hp.trans (congrArg (·+2) hc), hb.trans hk⟩ + +theorem launch_effect (ports : Ports w) (m : Memory w) : + let out := launchReport C q₀ ports m + out.result = some (Directory.start C ports m) ∧ after m out.events = Directory.prepared C ports m ∧ + out.probes = 7+2*(arity C+1) ∧ choiceBits out.events = [] := by + obtain ⟨hr,hm,hp,hb⟩ := returned ports (launchIndex d q₀) m (Controller.rowReport (arity C) ports.data m) rfl + obtain ⟨_,hc,hk⟩ := Controller.rowReport_cost (arity C) ports.data m + exact ⟨hr,hm,hp.trans (by change countProbes _+1 = _; rw [hc]; omega),hb.trans hk⟩ + +theorem active_effect (ports : Ports w) (i : Fin d) (m : Memory w) (rep : Report w) + {s : Word w} (h : rep.result = some s) : + let out := activeReport C q₀ ports i m rep + out.result = some s ∧ after m out.events = after m rep.events ∧ + out.probes = rep.probes+(C i).params+2 ∧ choiceBits out.events = choiceBits rep.events := by + have cost := Frame.frame_cost ports.activeFrame m 0 ((C i).params+1) (LiveHeaderBounded.activeReport rep) + obtain ⟨hr,hm,hp,hb⟩ := returned ports (workerIndex q₀ i) m (workerReport (C i) ports.activeFrame m rep) h + exact ⟨hr, hm.trans cost.2.2.2.1, hp.trans (by rw [workerReport,cost.2.1]; change _ + rep.probes + 1 = _; omega), + hb.trans cost.2.2.1⟩ + +theorem stop_effect (ports : Ports w) (i : Fin d) (m : Memory w) : + let out := stopReport C q₀ ports i m + out.result = some 0 ∧ after m out.events = writeMemory m ports.tag (LiveStageLink.tagWord w (calendarIndex d q₀)) ∧ + out.probes = (C i).params+3 ∧ choiceBits out.events = [] := by + have cost := Frame.frame_cost ports.activeFrame m 0 ((C i).params+1) (LiveHeaderBounded.closedReport w) + obtain ⟨hr,hm,hp,hb⟩ := transferred ports (workerIndex q₀ i) (calendarIndex d q₀) m + (closedSource (C i) ports m) rfl (by simp [workerIndex,handoff]) + exact ⟨hr,hm.trans (congrArg (fun mem ↦ writeMemory mem ports.tag _) cost.2.2.2.1), + hp.trans (by rw [closedSource,cost.2.1]; rfl), hb.trans cost.2.2.1⟩ + +theorem terminal_effect (ports : Ports w) (m : Memory w) : + let out := linked ports (calendarIndex d q₀) (LevelCalendar.closedReport ports.data m) + out.result = none ∧ after m out.events = m ∧ out.probes = 3 ∧ choiceBits out.events = [] := by + have hn : handoff d q₀ (calendarIndex d q₀) = none := by simp [handoff,calendarIndex] + dsimp only + refine ⟨?_,?_,?_,LiveStageLink.linkedReport_choiceBits ..⟩ + · simp [linked,LiveStageLink.linkedReport, LiveStageLink.prependLog, LiveStageLink.exitReport, hn] + rfl + · rw [linked,LiveStageLink.linkedReport_after,hn]; rfl + · rw [linked,LiveStageLink.linkedReport_probes,hn]; rfl + +/-- Wrap the worker reports in execution order, advancing the source memory after each call so +the next frame is read from its actual entry memory. -/ +def workerRows (C : Catalog d) (q : ℕ) (ports : Ports w) (i : Fin d) : + Memory w → List (Report w) → List (Report w) + | _, [] => [] + | m, rep :: rs => activeReport C q ports i m rep :: workerRows C q ports i (after m rep.events) rs + +/-- Run all the source calls of a data worker, acknowledge its stop, and +continue at the calendar tag. Each read of the bounded frame uses the +memory left by the preceding source call. -/ +theorem worker_segment (ports : Ports w) (i : Fin d) (pub : Fin (C i).params → Word w) + (bound st : Word w) (m : Memory w) (bits : List (List Bool)) (rs : List (Report w)) + (f cap : ℕ) (hf : 0 < f) (fits : D₀ ≤ 2^w) + (hcap : f+3+4*((C i).params+1)+2*D₀+5 ≤ cap) + (hr : runSegment ((C i).table.instantiate w pub).program f (some st) m bits = some rs) + (hv : ValidTrace C i ports pub bound st m rs) (tail : List (List Bool)) : + let D := program plan ports + let finalMem := after m (eventLog rs) + runSegment D cap (some st) m (bits ++ [] :: tail) = + (runSegment D cap (some 0) (writeMemory finalMem ports.tag (LiveStageLink.tagWord w (calendarIndex d q₀))) tail).map + (fun more ↦ workerRows C q₀ ports i m rs ++ stopReport C q₀ ports i finalMem :: more) := by + dsimp only + induction bits generalizing st m rs with + | nil => + obtain rfl : rs = [] := (Option.some.inj hr).symm + obtain ⟨⟨htag,hbound,_⟩,hle⟩ := hv + have hc := worker_stop plan ports i st m htag fits (hbound ▸ hle) (cap := cap) (by omega) + have he := stop_effect (C := C) (initial := initial) (phases := phases) ports i m + change runSegment _ _ _ _ ([] :: tail) = _ + rw [runSegment,hc] + change (runSegment _ _ (stopReport C q₀ ports i m).result (after m (stopReport C q₀ ports i m).events) tail).map _ = _ + rw [he.1,he.2.1]; rfl + | cons bs rest ih => + rw [runSegment] at hr + let S := ((C i).table.instantiate w pub).program + cases hs : execute S f (S.start st) m bs with + | none => rw [hs] at hr; contradiction + | some rep => + rw [hs] at hr + obtain ⟨reps,hr',rfl⟩ := Option.map_eq_some_iff.mp hr + obtain ⟨⟨htag,hbound,hpub⟩,hlt,next,hn,hv'⟩ := hv + have hsource : let P := ((C i).table.instantiate w (parameters ports.activeFrame m)).program + execute P f (P.start st) m bs = some rep := by rw [hpub]; exact hs + have hc := worker_active plan ports i st m bs htag fits (hbound ▸ hlt) hcap rep hsource + have he := active_effect (initial := initial) (phases := phases) ports i m rep hn (C := C) + rw [List.cons_append,runSegment,hc] + change (runSegment _ _ (activeReport C q₀ ports i m rep).result + (after m (activeReport C q₀ ports i m rep).events) _).map _ = _ + rw [he.1,he.2.1,ih next (after m rep.events) reps (hn ▸ hr') hv'] + simp only [workerRows, List.cons_append, Option.map_map, Function.comp_def, eventLog, + List.flatMap_cons, after, List.foldl_append] + rfl + +/-- Memory after calendar dispatch has written the selected recipe's stage tag. -/ +def calendarMemory (ports : Ports w) (m : Memory w) (j : Fin q₀) := + writeMemory m ports.tag (LiveStageLink.tagWord w (recipeIndex d j)) + +/-- Memory after the selected recipe writes its row at the computed address and sets the +launcher tag. -/ +def rowInput (ports : Ports w) (m : Memory w) (j : Fin q₀) : Memory w := + let pre := calendarMemory (d := d) ports m j + let s := LevelCalendar.header (calendar plan) ports.data m + let R := (plan.recipes j).2 + writeMemory (Greedy.writeRow pre (R.address ports.data s pre) (R.words ports.data s pre)) ports.tag 0 + +/-- The calendar dispatch, recipe execution and worker launch reports that precede the data +calls of one online row. -/ +def preparation (ports : Ports w) (m : Memory w) (j : Fin q₀) : List (Report w) := + [calendarReport plan ports m j, + recipeReport plan ports j (LevelCalendar.header (calendar plan) ports.data m) (calendarMemory (d := d) ports m j), + launchReport C q₀ ports (rowInput plan ports m j)] + +/-- Execute the calendar, its selected recipe, and the launcher, then enter +the data worker selected by the computed row. The launcher reads the +actual output memory of the selected recipe. -/ +theorem prepare_segment (ports : Ports w) (state : Word w) (m : Memory w) (j : Fin q₀) + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (fits : D₀ ≤ 2^w) + (active : m ports.ordinal.val < m ports.rows.val) + (hj : (calendar plan).phase (m ports.ordinal.val).val = j.val) + (activeRow : rowInput plan ports m j ports.ordinal.val < rowInput plan ports m j ports.rows.val) + {cap : ℕ} (calCap : 30+2*q₀+2*D₀+5 ≤ cap) + (recipeCap : (plan.recipes j).2.code.length+1+2*D₀+5 ≤ cap) + (launchCap : 20+6*(arity C+1)+2*D₀+5 ≤ cap) (tail : List (List Bool)) : + let input := rowInput plan ports m j + let D := program plan ports + runSegment D cap (some state) m ([] :: [] :: [] :: tail) = + (runSegment D cap (some (Directory.start C ports input)) (Directory.prepared C ports input) tail).map + (preparation plan ports m j ++ ·) := by + let pre := calendarMemory (d := d) ports m j + let s := LevelCalendar.header (calendar plan) ports.data m + let input := rowInput plan ports m j + have cal := calendar_call plan ports state m j htag fits active hj calCap + have recp := recipe_call plan ports j s pre (by simp [pre,calendarMemory,writeMemory]) fits recipeCap + have launch := launch_call plan ports 0 input (by simp [input,rowInput,writeMemory]) fits activeRow launchCap + have hc := calendar_effect plan ports m j + have hr := recipe_effect plan ports j s pre + have hl := launch_effect (C := C) (initial := initial) (phases := phases) ports input + change runSegment _ _ _ _ (_ :: _ :: _ :: tail) = _ + rw [runSegment,cal] + change (runSegment _ _ (calendarReport plan ports m j).result (after m (calendarReport plan ports m j).events) _).map _ = _ + rw [hc.1,hc.2.1] + change (runSegment _ _ (some s) pre ([] :: [] :: tail)).map _ = _ + rw [runSegment,recp] + change ((runSegment _ _ (recipeReport plan ports j s pre).result (after pre (recipeReport plan ports j s pre).events) _).map _).map _ = _ + rw [hr.1,hr.2.1] + change ((runSegment _ _ (some 0) input ([] :: tail)).map _).map _ = _ + rw [runSegment,launch] + change (((runSegment _ _ (launchReport C q₀ ports input).result (after input (launchReport C q₀ ports input).events) tail).map _).map _).map _ = _ + rw [hl.1,hl.2.1] + simp only [Option.map_map,preparation,List.cons_append,List.nil_append,Function.comp_def] + rfl + +/-- All reports for one online row, including preparation, the ordered data calls and the +closing return to the calendar. -/ +def rowLog (ports : Ports w) (m : Memory w) (j : Fin q₀) (row : Directory.Row d w) := + preparation plan ports m j ++ workerRows C q₀ ports row.worker (row.dataMemory C ports) row.reports ++ + [stopReport C q₀ ports row.worker (row.endMemory C ports)] + +/-- The row's final worker memory with the stage tag set to resume the calendar. -/ +def post (C : Catalog d) (q : ℕ) (ports : Ports w) (row : Directory.Row d w) := + writeMemory (row.endMemory C ports) ports.tag (LiveStageLink.tagWord w (calendarIndex d q)) + +/-- The complete choice-stream list for the row, with empty streams for its three preparation +calls and its closing call. -/ +def rowChoices (row : Directory.Row d w) := [] :: [] :: [] :: (row.choices ++ [[]]) + +/-- A complete phase begins and ends at the calendar. The original source +call sequence consumes exactly its own branch choices. The recipe and row +launcher operate on the memory computed by the preceding phase. -/ +theorem row_segment (ports : Ports w) (state : Word w) (m : Memory w) (j : Fin q₀) + (row : Directory.Row d w) (input : row.input = rowInput plan ports m j) + (v : row.Valid C ports) + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (fits : D₀ ≤ 2^w) + (active : m ports.ordinal.val < m ports.rows.val) (hj : (calendar plan).phase (m ports.ordinal.val).val = j.val) + {cap : ℕ} (calCap : 30+2*q₀+2*D₀+5 ≤ cap) + (recipeCap : (plan.recipes j).2.code.length+1+2*D₀+5 ≤ cap) + (launchCap : 20+6*(arity C+1)+2*D₀+5 ≤ cap) + (dataCap : row.fuel+3+4*((C row.worker).params+1)+2*D₀+5 ≤ cap) + (tail : List (List Bool)) : + let D := program plan ports + runSegment D cap (some state) m (rowChoices row ++ tail) = + (runSegment D cap (some 0) (post C q₀ ports row) tail).map (rowLog plan ports m j row ++ ·) := by + have prep := prepare_segment plan ports state m j htag fits active hj (input ▸ v.active) calCap recipeCap launchCap + (row.choices ++ [] :: tail) + rw [← input] at prep + have hw := worker_segment plan ports row.worker (Directory.words C ports row.worker row.input) + (Directory.bound C ports row.input) (Directory.start C ports row.input) (row.dataMemory C ports) + row.choices row.reports row.fuel cap v.positiveFuel fits dataCap v.sourceRun v.frame tail + change runSegment _ _ _ _ (rowChoices row ++ tail) = _ + simp only [rowChoices, List.cons_append, List.nil_append, List.append_assoc] + rw [prep] + change (runSegment _ _ _ (row.dataMemory C ports) _).map _ = _ + rw [hw] + simp only [rowLog,post,Directory.Row.endMemory,Option.map_map,Function.comp_def,List.append_assoc, + List.cons_append,List.nil_append] + +private theorem workerRows_cost (ports : Ports w) (i : Fin d) (pub : Fin (C i).params → Word w) + (bound st : Word w) (m : Memory w) (rs : List (Report w)) + (h : ValidTrace C i ports pub bound st m rs) : + RAMBuckets.cost Report.probes (workerRows C q₀ ports i m rs) = + RAMBuckets.cost Report.probes rs + rs.length*((C i).params+2) := by + induction rs generalizing m st with + | nil => simp [workerRows,RAMBuckets.cost] + | cons rep rs ih => + obtain ⟨_,_,s,hn,hv⟩ := h + rw [workerRows,RAMBuckets.cost,RAMBuckets.cost, + (active_effect (initial := initial) (phases := phases) ports i m rep hn (C := C)).2.2.1, + ih s _ hv,List.length_cons,Nat.add_mul,Nat.one_mul] + omega + +/-- Total calls plus probes for one online phase, charged against the raw +worker calls and the native row expression's metadata reads. -/ +theorem row_cost (ports : Ports w) (m : Memory w) (j : Fin q₀) (row : Directory.Row d w) + (v : row.Valid C ports) : + RAMBuckets.cost Report.probes (rowLog plan ports m j row) = + RAMBuckets.cost Report.probes row.reports + row.reports.length*((C row.worker).params+2) + + (plan.recipes j).2.reads + 3*arity C + (C row.worker).params + 26 := by + have hp := workerRows_cost (initial := initial) (phases := phases) ports row.worker _ _ _ _ _ v.frame + rw [rowLog, RAMBuckets.cost_append, RAMBuckets.cost_append,hp,preparation] + simp only [RAMBuckets.cost, (calendar_effect plan ports m j).2.2.1, + (recipe_effect plan ports j _ _).2.2.1, (launch_effect (C := C) (initial := initial) (phases := phases) ports _).2.2.1, + (stop_effect (C := C) (initial := initial) (phases := phases) ports row.worker _).2.2.1] + omega + +private theorem workerRows_after (ports : Ports w) (i : Fin d) (pub : Fin (C i).params → Word w) + (bound st : Word w) (m : Memory w) (rs : List (Report w)) + (h : ValidTrace C i ports pub bound st m rs) : + after m (eventLog (workerRows C q₀ ports i m rs)) = after m (eventLog rs) := by + induction rs generalizing m st with + | nil => rfl + | cons rep rs ih => + obtain ⟨_,_,s,hn,hv⟩ := h + have he := (active_effect (initial := initial) (phases := phases) ports i m rep hn (C := C)).2.1 + simp only [workerRows,eventLog,List.flatMap_cons,after,List.foldl_append] + change after (after m (activeReport C q₀ ports i m rep).events) _ = after (after m rep.events) _ + rw [he] + exact ih s _ hv + +/-- Actual linked reports have the same memory and next state as the +continuation supplied to the phase composition theorem. -/ +theorem row_effect (ports : Ports w) (m : Memory w) (j : Fin q₀) (row : Directory.Row d w) + (input : row.input = rowInput plan ports m j) (v : row.Valid C ports) (state : Word w) : + after m (eventLog (rowLog plan ports m j row)) = post C q₀ ports row ∧ + endState (some state) (rowLog plan ports m j row) = some 0 := by + let pre := calendarMemory (d := d) ports m j + let s := LevelCalendar.header (calendar plan) ports.data m + have hc : after m (calendarReport plan ports m j).events = pre := (calendar_effect plan ports m j).2.1 + have hr : after pre (recipeReport plan ports j s pre).events = row.input := + (recipe_effect plan ports j s pre).2.1.trans input.symm + have hl := (launch_effect (C := C) (initial := initial) (phases := phases) ports row.input).2.1 + have hw := workerRows_after (initial := initial) (phases := phases) ports row.worker _ _ _ _ _ v.frame + have hs := stop_effect (C := C) (initial := initial) (phases := phases) ports row.worker (row.endMemory C ports) + constructor + · simp only [rowLog,preparation,eventLog,List.flatMap_append,List.flatMap_cons,List.flatMap_nil, + List.append_nil,after,List.foldl_append] + change after (after (after (after (after m (calendarReport plan ports m j).events) + (recipeReport plan ports j s pre).events) (launchReport C q₀ ports (rowInput plan ports m j)).events) + (eventLog (workerRows C q₀ ports row.worker (row.dataMemory C ports) row.reports))) + (stopReport C q₀ ports row.worker (row.endMemory C ports)).events = _ + rw [hc,hr,← input,hl] + change after (after (row.dataMemory C ports) (eventLog (workerRows C q₀ ports row.worker _ row.reports))) _ = _ + rw [hw] + exact hs.2.1 + · rw [rowLog,endState_append]; exact hs.1 + +private theorem stored_field {m : Memory w} {base : Word w} {xs : List (Word w)} + (h : Greedy.Stores m base xs) (i : Fin xs.length) : m (base+(i.val : Word w)).val = xs[i.val] := by + induction xs generalizing base with + | nil => exact Fin.elim0 i + | cons x xs ih => + cases i using Fin.cases with + | zero => simpa using h.1 + | succ i => + simpa only [Fin.val_succ,Nat.cast_add,Nat.cast_one,add_assoc,add_comm (1 : Word w) (i.val : Word w), + List.getElem_cons_succ] using ih h.2 i + +/-- From a recipe's actual destination and field values, the launcher +installs the computed start, stop and parameters. Address separation +protects the row and the two controller counters through the tag transfer. -/ +theorem computed_ready (ports : Ports w) (m : Memory w) (j : Fin q₀) (i : Fin d) + (st stop : Word w) (params : Fin (arity C) → Word w) (frame : Directory.FrameFits C ports) + (ordTag : ports.ordinal ≠ ports.tag) (totalTag : ports.rows ≠ ports.tag) + (dest : let pre := calendarMemory (d := d) ports m j + (plan.recipes j).2.address ports.data (LevelCalendar.header (calendar plan) ports.data m) pre = + Directory.rowBase C ports pre) + (fields : let pre := calendarMemory (d := d) ports m j + (plan.recipes j).2.words ports.data (LevelCalendar.header (calendar plan) ports.data m) pre = + LiveStageLink.tagWord w i.succ :: st :: stop :: List.ofFn params) + (room : (Directory.rowBase C ports m).val + (arity C+3) ≤ 2^w) + (away : ∀ addr ∈ [ports.tag,ports.ordinal,ports.rows], addr.val < (Directory.rowBase C ports m).val ∨ + (Directory.rowBase C ports m).val + (arity C+3) ≤ addr.val) : + let input := rowInput plan ports m j + input ports.ordinal.val = m ports.ordinal.val ∧ input ports.rows.val = m ports.rows.val ∧ + Directory.start C ports input = st ∧ + Ready C i ports (fun u ↦ params (Fin.castLE (params_le_arity C i) u)) stop (Directory.prepared C ports input) := by + let base := Directory.rowBase C ports m + let pre := calendarMemory (d := d) ports m j + let xs := LiveStageLink.tagWord w i.succ :: st :: stop :: List.ofFn params + let data := Greedy.writeRow pre base xs + let input := rowInput plan ports m j + have hord : pre ports.ordinal.val = m ports.ordinal.val := by + simp [pre,calendarMemory,writeMemory,Fin.val_ne_of_ne ordTag] + have hcount : pre ports.rows.val = m ports.rows.val := by + simp [pre,calendarMemory,writeMemory,Fin.val_ne_of_ne totalTag] + have same {mem : Memory w} (he : mem ports.ordinal.val = m ports.ordinal.val) : + Directory.rowBase C ports mem = base := by + change ports.directory + mem ports.ordinal.val * _ = ports.directory + m ports.ordinal.val * _ + rw [he] + have hd : input = writeMemory data ports.tag 0 := by + dsimp only [input,rowInput,data,pre,xs] + rw [dest,fields,same hord] + have hlen : xs.length = arity C+3 := by simp [xs] + have fit : base.val + xs.length ≤ 2^w := hlen ▸ room + have keep (a : Word w) (ha : a ∈ [ports.tag,ports.ordinal,ports.rows]) : + data a.val = pre a.val := + Greedy.writeRow_outside pre base xs a.val fit (hlen ▸ away a ha) + have hiord : input ports.ordinal.val = m ports.ordinal.val := by + rw [hd,writeMemory,ite_eq_right (Fin.val_ne_of_ne ordTag),keep _ (by simp),hord] + have hitot : input ports.rows.val = m ports.rows.val := by + rw [hd,writeMemory,ite_eq_right (Fin.val_ne_of_ne totalTag),keep _ (by simp),hcount] + have stores : Greedy.Stores data base xs := Greedy.writeRow_stores pre base xs fit + have read (k : ℕ) (hk : k < xs.length) : input (base+(k : Word w)).val = xs[k] := by + have hsum : (base+(k : Word w)).val = base.val+k := by + rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : k < 2^w),Nat.mod_eq_of_lt (by omega)] + have ha := away ports.tag (by simp) + change ports.tag.val < base.val ∨ base.val + (arity C+3) ≤ ports.tag.val at ha + have hn : (base+(k : Word w)).val ≠ ports.tag.val := by rw [hsum]; omega + rw [hd,writeMemory,ite_eq_right hn] + exact stored_field stores ⟨k,hk⟩ + have hbase := same hiord + have htag : input (Directory.rowBase C ports input).val = LiveStageLink.tagWord w i.succ := by + rw [hbase]; simpa [xs] using read 0 (by omega) + have hstart : Directory.start C ports input = st := by + rw [Directory.start,hbase]; simpa [xs] using read 1 (by omega) + have hstop : Directory.bound C ports input = stop := by + rw [Directory.bound,hbase]; simpa [xs] using read 2 (by omega) + have hp : Directory.words C ports i input = fun u ↦ params (Fin.castLE (params_le_arity C i) u) := by + funext u + have hu := u.isLt.trans_le (params_le_arity C i) + change input ((Directory.rowBase C ports input + 2) + ((u.val+1 : ℕ) : Word w)).val = _ + rw [hbase, show (base+2)+((u.val+1 : ℕ) : Word w) = base+((u.val+3 : ℕ) : Word w) by push_cast; ring] + have hk := read (u.val+3) (by omega) + change input (base+((u.val+3 : ℕ) : Word w)).val = + (LiveStageLink.tagWord w i.succ :: st :: stop :: List.ofFn params)[u.val.succ.succ.succ]'(by simp [hu]) at hk + simp only [List.getElem_cons_succ,List.getElem_ofFn] at hk + exact hk + have hr := Directory.ready C ports input i frame htag + rw [hp,hstop] at hr + exact ⟨hiord,hitot,hstart,hr⟩ + +end CompressorRecords.Schedule.Online + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsOnlineRun.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsOnlineRun.lean new file mode 100644 index 0000000000..670d21f3ba --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsOnlineRun.lean @@ -0,0 +1,201 @@ +import OAI.Computability.VPVNP.CompressorRecordsOnline + +/-! +# Chronological execution of the online descriptor program + +Each selected phase contributes the actual branch stream of its worker. +The row input is computed by the recipe in the memory left by the +preceding phase. One final empty-choice calendar call accepts at the +exclusive ordinal bound. The total work bound uses the maximum number +of metadata reads among the fixed recipes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule.Online.Run + +open BurstRAM + +variable {d initial phases w : ℕ} {C : Catalog d} +variable (plan : Config C initial phases) (ports : Ports w) +local notation "q₀" => initial+phases +local notation "D₀" => N d q₀ + +/-- The recipe and data worker on this actual path. -/ +structure Step (d q w : ℕ) where + /-- Index of the row recipe chosen by the calendar at this step's ordinal. -/ + phase : Fin q + /-- The selected worker's directory row, including its entry memory, fuel, branch streams and + source reports. -/ + row : Directory.Row d w + +/-- Each phase starts from actual RAM and has enough private fuel to +evaluate its recipe and to execute each source call. -/ +structure Step.Valid (cap : ℕ) (m : Memory w) (step : Step d q₀ w) : Prop where + phase : (calendar plan).phase (m ports.ordinal.val).val = step.phase.val + active : m ports.ordinal.val < m ports.rows.val + input : step.row.input = rowInput plan ports m step.phase + source : step.row.Valid C ports + recipeCap : (plan.recipes step.phase).2.code.length+1+2*D₀+5 ≤ cap + dataCap : step.row.fuel+3+4*((C step.row.worker).params+1)+2*D₀+5 ≤ cap + +/-- The next phase is verified in the previous worker's computed post-memory. -/ +def Valid (cap : ℕ) : Memory w → List (Step d q₀ w) → Prop + | m, [] => m ports.rows.val ≤ m ports.ordinal.val + | m, step :: rest => step.Valid plan ports cap m ∧ Valid cap (post C q₀ ports step.row) rest + +/-- Follow the scheduled rows in order and return the memory left when the last worker hands +control back to the calendar. An empty run returns its entry memory. -/ +def finalMemory : Memory w → List (Step d q₀ w) → Memory w + | m, [] => m + | _, step :: rest => finalMemory (post C q₀ ports step.row) rest + +/-- Concatenate the planner, launch, worker and stop reports for each row in its entry memory, +then append the calendar's closing report. -/ +def reports : Memory w → List (Step d q₀ w) → List (Report w) + | m, [] => [linked ports (calendarIndex d q₀) (LevelCalendar.closedReport ports.data m)] + | m, step :: rest => rowLog plan ports m step.phase step.row ++ reports (post C q₀ ports step.row) rest + +/-- Supply empty branch streams for row preparation and stopping, the worker's own streams for +its data calls, and one final empty stream for calendar acceptance. -/ +def choices (steps : List (Step d q₀ w)) : List (List Bool) := + steps.flatMap (fun step ↦ rowChoices step.row) ++ [[]] + +/-- Run the fixed instruction table from the calendar through the terminal +accept. Each phase may depend on choices made inside all earlier workers. -/ +theorem execute (steps : List (Step d q₀ w)) (m : Memory w) (state : Word w) (cap : ℕ) + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (fits : D₀ ≤ 2^w) + (calCap : 30+2*q₀+2*D₀+5 ≤ cap) (launchCap : 20+6*(arity C+1)+2*D₀+5 ≤ cap) + (v : Valid plan ports cap m steps) : + runSegment (program plan ports) cap (some state) m (choices steps) = some (reports plan ports m steps) := by + induction steps generalizing m state with + | nil => + rw [choices,List.flatMap_nil,List.nil_append,runSegment,calendar_stop plan ports state m htag fits v (by omega)] + rfl + | cons step rest ih => + obtain ⟨hr,ht⟩ := v + have htag' : post C q₀ ports step.row ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀) := by + simp [post,writeMemory] + change runSegment _ _ _ _ ((step :: rest).flatMap _ ++ [[]]) = _ + rw [List.flatMap_cons,List.append_assoc, row_segment plan ports state m step.phase step.row hr.input hr.source + htag fits hr.active hr.phase calCap hr.recipeCap launchCap hr.dataCap] + change (runSegment _ _ _ _ (choices rest)).map _ = _ + rw [ih _ 0 htag' ht] + rfl + +/-- The full reports leave exactly the memory of the last data worker +after its return to the calendar, and the final call halts. -/ +theorem effect (steps : List (Step d q₀ w)) (m : Memory w) (state : Word w) {cap : ℕ} + (v : Valid plan ports cap m steps) : + after m (eventLog (reports plan ports m steps)) = finalMemory (C := C) ports m steps ∧ + endState (some state) (reports plan ports m steps) = none := by + induction steps generalizing m state with + | nil => + have h := terminal_effect (initial := initial) (phases := phases) (d := d) ports m + exact ⟨by simpa only [reports, finalMemory, eventLog, List.flatMap_cons, List.flatMap_nil, + List.append_nil] using h.2.1,h.1⟩ + | cons step rest ih => + obtain ⟨hr,ht⟩ := v + obtain ⟨hm,hs⟩ := row_effect plan ports m step.phase step.row hr.input hr.source state + obtain ⟨hm',hs'⟩ := ih _ 0 ht + rw [reports, endState_append, hs, finalMemory] + refine ⟨?_,hs'⟩ + simp only [eventLog,List.flatMap_append,after,List.foldl_append] + change after (after m (eventLog (rowLog plan ports m step.phase step.row))) _ = _ + rw [hm] + exact hm' + +/-- Uniform metadata-read bound depends only on the finite set of recipes. -/ +def maxReads := Finset.univ.sup fun j ↦ (plan.recipes j).2.reads + +theorem reads_le (j : Fin q₀) : (plan.recipes j).2.reads ≤ maxReads plan := + Finset.le_sup (f := fun i ↦ (plan.recipes i).2.reads) (Finset.mem_univ j) + +/-- Sum the number of source-worker calls and their memory probes over all selected rows, +before charging for calendar and dispatch work. -/ +def sourceCost (steps : List (Step d q₀ w)) := + (steps.map fun step ↦ RAMBuckets.cost Report.probes step.row.reports).sum + +/-- Source calls and probes are charged with a catalog-wide constant. Each +scheduled row also pays for the calendar, recipe, frame launch, and closing +call. The final calendar call costs four units including its dispatch read. -/ +theorem cost_bound (steps : List (Step d q₀ w)) (m : Memory w) {cap : ℕ} + (v : Valid plan ports cap m steps) : + RAMBuckets.cost Report.probes (reports plan ports m steps) ≤ + sourceCost steps*(arity C+3) + steps.length*(maxReads plan+4*arity C+26) + 4 := by + induction steps generalizing m with + | nil => + rw [reports, RAMBuckets.cost, (terminal_effect (initial := initial) (phases := phases) (d := d) ports m).2.2.1] + simp [sourceCost,RAMBuckets.cost] + | cons step rest ih => + obtain ⟨hr,ht⟩ := v + have tail := ih _ ht + have hlen : step.row.reports.length ≤ RAMBuckets.cost Report.probes step.row.reports := by + rw [RAMBuckets.cost_eq_length_add_probes]; omega + have hk := params_le_arity C step.row.worker + have hm := Nat.mul_le_mul hlen (Nat.add_le_add_right hk 2) + have hreads := reads_le plan step.phase + rw [reports, RAMBuckets.cost_append, row_cost plan ports m step.phase step.row hr.source] + have split : sourceCost (step :: rest) = RAMBuckets.cost Report.probes step.row.reports + sourceCost rest := rfl + rw [split,Nat.add_mul,List.length_cons,Nat.add_mul,Nat.one_mul] + have mul : RAMBuckets.cost Report.probes step.row.reports * (arity C+3) = + RAMBuckets.cost Report.probes step.row.reports * (arity C+2) + RAMBuckets.cost Report.probes step.row.reports := + Nat.mul_succ .. + omega + +/-- Number of rows still to be launched from this calendar memory. -/ +def remaining (ports : Ports w) (m : Memory w) := + (m ports.rows.val).val - (m ports.ordinal.val).val + +/-- A per-phase construction can generate the entire path from its current +descriptor memory. It suffices to construct the next source row, preserve +the construction invariant, and account for the single ordinal increment. -/ +theorem exists_valid (I : Memory w → Prop) (cap : ℕ) + (next : ∀ m, I m → m ports.ordinal.val < m ports.rows.val → ∃ step : Step d q₀ w, + step.Valid plan ports cap m ∧ I (post C q₀ ports step.row) ∧ + remaining ports (post C q₀ ports step.row)+1 = remaining ports m) + (m : Memory w) (h : I m) : + ∃ steps, Valid plan ports cap m steps ∧ steps.length = remaining ports m ∧ + I (finalMemory (C := C) ports m steps) := by + generalize hn : remaining ports m = n + induction n generalizing m with + | zero => + have hclosed : m ports.rows.val ≤ m ports.ordinal.val := + Fin.le_def.mpr (Nat.sub_eq_zero_iff_le.mp hn) + exact ⟨[],hclosed,rfl,h⟩ + | succ n ih => + have hlt : m ports.ordinal.val < m ports.rows.val := Fin.lt_def.mpr (by + unfold remaining at hn; omega) + obtain ⟨step,hs,hI,hl⟩ := next m h hlt + obtain ⟨rest,hr,hcount,hfinal⟩ := ih _ hI (by omega) + exact ⟨step::rest, ⟨hs,hr⟩, by simp [hcount], hfinal⟩ + +/-- Acceptance, exact path choices, final invariant and work bound follow +from the next-row construction without a precomputed directory of rows. -/ +theorem exists_run (I : Memory w → Prop) (cap : ℕ) + (next : ∀ m, I m → m ports.ordinal.val < m ports.rows.val → ∃ step : Step d q₀ w, + step.Valid plan ports cap m ∧ I (post C q₀ ports step.row) ∧ + remaining ports (post C q₀ ports step.row)+1 = remaining ports m) + (m : Memory w) (h : I m) (state : Word w) + (htag : m ports.tag.val = LiveStageLink.tagWord w (calendarIndex d q₀)) (fits : D₀ ≤ 2^w) + (calCap : 30+2*q₀+2*D₀+5 ≤ cap) (launchCap : 20+6*(arity C+1)+2*D₀+5 ≤ cap) : + ∃ steps : List (Step d q₀ w), + let rs := reports plan ports m steps + steps.length = remaining ports m ∧ + runSegment (program plan ports) cap (some state) m (choices steps) = some rs ∧ + branchPaths rs = choices steps ∧ endState (some state) rs = none ∧ + I (after m (eventLog rs)) ∧ + RAMBuckets.cost Report.probes rs ≤ + sourceCost steps*(arity C+3) + steps.length*(maxReads plan+4*arity C+26) + 4 := by + obtain ⟨steps,hv,hlen,hfinal⟩ := exists_valid plan ports I cap next m h + have he := execute plan ports steps m state cap htag fits calCap launchCap hv + obtain ⟨hm,hs⟩ := effect plan ports steps m state hv + exact ⟨steps,hlen,he,((runSegment_iff ..).mp he).2.2,hs,hm ▸ hfinal,cost_bound plan ports steps m hv⟩ + +end CompressorRecords.Schedule.Online.Run + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsOnlineWorkspace.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsOnlineWorkspace.lean new file mode 100644 index 0000000000..10e153125c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsOnlineWorkspace.lean @@ -0,0 +1,345 @@ +import OAI.Computability.VPVNP.CompressorRecordsOnline +import OAI.Computability.VPVNP.CompressorRecordsWorkspace +import OAI.Computability.VPVNP.CompressorDescriptorStride +import OAI.Computability.VPVNP.CompressorCalendarRows + +/-! +# The online descriptor scheduler on the pair program's native ABI + +The outer program gives the pair workspace in public word two. Every +descriptor call snapshots six pointer words there, then runs the same online +calendar, planner, launch, or worker stage that the internal tag selected. +The snapshot preserves the persistent result and all branch choices. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.OnlineWorkspace + +open BurstRAM BurstRAM.PrivateRAM Schedule +open scoped Fin.CommRing + +variable {w d initial phases : ℕ} {C : Catalog d} (plan : Online.Config C initial phases) + +/-- Compile the online scheduler with a workspace-pointer snapshot at entry and expose it +through the pair program's eleven public words. Public word two supplies the workspace +base. -/ +def table := LiveStageLink.widen (Frame.compile (Online.template plan)) (Function.Embedding.refl _) + (fun _ : Fin 1 ↦ (2 : Fin 11)) + +/-- Instantiate the framed online scheduler with the actual eleven public words of the pair +program. -/ +abbrev program (pub : Fin 11 → Word w) := ((table plan).instantiate w pub).program +/-- Addresses used by the online scheduler for this catalog, computed from its maximum operand +count and the workspace base in public word two. -/ +abbrev ports (pub : Fin 11 → Word w) := Workspace.ports (arity C) (pub 2) + +theorem execute_dispatch (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bits : List Bool) (cap : ℕ) (h : Workspace.Installed (arity C) (pub 2) m) : + execute (program plan pub) cap ((program plan pub).start s) m bits = + (execute (Online.program plan (ports (C := C) pub)) (cap-24) + ((Online.program plan (ports (C := C) pub)).start s) m bits).map (Workspace.report (pub 2) m) := by + unfold program table + rw [LiveStageLink.execute_widen_start] + change execute (Frame.machine (Online.template plan) (pub 2)).program cap + ((Frame.machine (Online.template plan) (pub 2)).program.start s) m bits = _ + rw [Frame.execute_cap, show (Frame.data (pub 2) m : Fin 6 → Word w) = _ from h] + rfl + +/-- Six external reads and eighteen private ticks precede each native linked +source report, including the reports that switch from a planner to a worker. -/ +theorem execute_linked (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) (bs : List Bool) + (h : Workspace.Installed (arity C) (pub 2) m) (fuel : ℕ) (rep : Report w) + (run : let S := Online.program plan (ports (C := C) pub) + execute S fuel (S.start s) m bs = some rep) : + let out := Workspace.report (pub 2) m rep + execute (program plan pub) (fuel+24) ((program plan pub).start s) m bs = some out ∧ + out.events.length = 24+rep.events.length ∧ out.probes = 6+rep.probes ∧ + choiceBits out.events = choiceBits rep.events ∧ after m out.events = after m rep.events ∧ + out.result = rep.result := by + refine ⟨?_, Workspace.report_effect _ _ _⟩ + dsimp only at run ⊢ + rw [execute_dispatch plan pub s m bs _ h, Nat.add_sub_cancel, run] + rfl + +/-- The native linker's data tag is inside the pair workspace. It is distinct +from the enclosing stage tag whenever that tag precedes the workspace. -/ +theorem tag_ne_outer (g : ℕ) (base outer : Word w) (h : outer.val < base.val) + (fit : base.val+6 < 2^w) : (Workspace.ports g base).tag ≠ outer := by + have v : (base+6 : Word w).val = base.val+6 := by + change (base+((6 : ℕ) : Word w)).val = _ + rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (show 6 < 2^w by omega),Nat.mod_eq_of_lt fit] + intro eqn + have hx := congrArg Fin.val eqn + change (base+6 : Word w).val = _ at hx + omega + +/-- Prepend the workspace-pointer snapshot to each source report, reading the pointer bank in +the memory left by preceding reports. -/ +def framed (base : Word w) : Memory w → List (Report w) → List (Report w) + | _, [] => [] + | m, rep :: rest => Workspace.report base m rep :: framed base (after m rep.events) rest + +/-- Only the pointer bank must be available at call boundaries. The active +frame, stage tag, ordinal and all level records may change across calls. -/ +def Banks (g : ℕ) (base : Word w) : Memory w → List (Report w) → Prop + | _, [] => True + | m, rep :: rest => Workspace.Installed g base m ∧ Banks g base (after m rep.events) rest + +theorem run_framed (pub : Fin 11 → Word w) (fuel : ℕ) (st : Option (Word w)) (m : Memory w) + (bits : List (List Bool)) (rs : List (Report w)) + (hr : runSegment (Online.program plan (ports (C := C) pub)) fuel st m bits = some rs) + (hb : Banks (arity C) (pub 2) m rs) : + runSegment (program plan pub) (fuel+24) st m bits = some (framed (pub 2) m rs) := by + induction bits generalizing st m rs with + | nil => + have : rs = [] := (Option.some.inj hr).symm + subst rs; rfl + | cons b bits ih => + cases st with + | none => contradiction + | some s => + let S := Online.program plan (ports (C := C) pub) + cases hc : execute S fuel (S.start s) m b with + | none => simp [runSegment, ← show S = Online.program plan (ports (C := C) pub) by rfl, hc] at hr + | some rep => + simp only [runSegment, ← show S = Online.program plan (ports (C := C) pub) by rfl, hc, + Option.map_eq_some_iff] at hr + obtain ⟨tail,ht,rfl⟩ := hr + obtain ⟨he,_,_,_,hm,hs⟩ := execute_linked plan pub s m b hb.1 fuel rep hc + rw [runSegment, he] + simp only [hs,hm,ih _ _ _ ht hb.2,Option.map_some,framed] + +theorem framed_effect (base : Word w) (m : Memory w) (rs : List (Report w)) (st : Option (Word w)) : + endState st (framed base m rs) = endState st rs ∧ + after m (eventLog (framed base m rs)) = after m (eventLog rs) ∧ + RAMBuckets.cost Report.probes (framed base m rs) = 6*rs.length + RAMBuckets.cost Report.probes rs := by + induction rs generalizing m st with + | nil => exact ⟨rfl,rfl,rfl⟩ + | cons x xs ih => + obtain ⟨_,hp,_,hm,hs⟩ := Workspace.report_effect base m x + obtain ⟨h₁,h₂,h₃⟩ := ih (after m x.events) x.result + refine ⟨?_,?_,?_⟩ + · simpa only [framed,endState,hs] using h₁ + · simp only [framed,eventLog,List.flatMap_cons,after,List.foldl_append] + change after (after m (Workspace.report base m x).events) (eventLog (framed base (after m x.events) xs)) = _ + rw [hm]; exact h₂ + · simp only [framed,RAMBuckets.cost,hp,h₃,List.length_cons] + omega + +/-- The calendar's level stride occupies the word immediately before the +first directory row. -/ +def gap (g : ℕ) (base : Word w) : Word w := base + ((10+g : ℕ) : Word w) + +theorem gap_eq (g : ℕ) (base : Word w) : (Workspace.ports g base).directory-1 = gap g base := by + simp only [Workspace.ports,gap,Nat.cast_add,Nat.cast_ofNat] + ring + +/-- Ready state of the workspace on the first calendar call. -/ +structure Ready (d g : ℕ) (base rows stride : Word w) (m : Memory w) : Prop where + bank : Workspace.Installed g base m + tag : m (Workspace.ports g base).tag.val = ((d+1 : ℕ) : Word w) + ordinal : m (Workspace.ports g base).ordinal.val = 0 + count : m (Workspace.ports g base).rows.val = rows + pitch : m ((Workspace.ports g base).directory-1).val = stride + +private theorem address_ne (base : Word w) {i j : ℕ} (hi : i < 2^w) (hj : j < 2^w) (e : i ≠ j) : + (base+(i : Word w)).val ≠ (base+(j : Word w)).val := by + intro he + have hv := congrArg Fin.val (show (i : Word w) = (j : Word w) from add_left_cancel (Fin.ext he)) + simp only [Fin.val_natCast,Nat.mod_eq_of_lt hi,Nat.mod_eq_of_lt hj] at hv + exact e hv + +/-- Memory after the setup reports install the workspace pointer bank, reset the ordinal, and +select the calendar as the next stage. -/ +def armed (d g : ℕ) (base : Word w) (m : Memory w) : Memory w := + after (after m (Workspace.initReport g base).events) (Workspace.calendarReport d base).events + +/-- Two native accepting setup calls install the pointer bank and select the +calendar. The earlier row-count and stride computations survive both calls. -/ +theorem arm (d g : ℕ) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (rows stride : Word w) (fit : 10+g < 2^w) + (hr : m (Workspace.ports g (pub 2)).rows.val = rows) (hp : m (gap g (pub 2)).val = stride) : + let base := pub 2 + let A := (Workspace.initMachine g pub).program + let B := ((Workspace.calendarStart d).instantiate w pub).program + let mid := after m (Workspace.initReport g base).events + execute A 42 (A.start s) m [] = some (Workspace.initReport g base) ∧ + execute B 6 (B.start 0) mid [] = some (Workspace.calendarReport d base) ∧ + Ready d g base rows stride (armed d g base m) := by + let base := pub 2 + let mid := after m (Workspace.initReport g base).events + have room : 8 < 2^w := by omega + have mg : mid (gap g base).val = stride := by + apply Eq.trans (Workspace.init_outside g base m (gap g base).val _) hp + intro i + exact address_ne base fit (i.isLt.trans room) (by have := i.isLt; omega) + have me := (Workspace.calendar_effect d g base mid).1 + have eqn : armed d g base m = writeMemory mid (Workspace.ports g base).tag ((d+1 : ℕ) : Word w) := me + refine ⟨Workspace.execute_init g pub s m [] 42 le_rfl, + Workspace.execute_calendarStart d pub 0 mid [] 6 le_rfl, ?_⟩ + constructor + · exact Workspace.calendar_installed d g base mid (Workspace.init_installed _ _ _ room.le) (by omega) + · change armed d g base m (Workspace.ports g base).tag.val = _ + rw [eqn]; simp [writeMemory] + · have hn : (base+7).val ≠ (base+6).val := address_ne base (i := 7) (j := 6) (by omega) (by omega) (by decide) + change armed d g base m (base+7).val = 0 + rw [eqn] + change (if (base+7).val = (base+6).val then _ else mid (base+7).val) = _ + rw [ite_eq_right hn] + exact (Workspace.init_controls g base m room.le).2 + · have hn : (base+8).val ≠ (base+6).val := address_ne base (i := 8) (j := 6) (by omega) (by omega) (by decide) + change armed d g base m (base+8).val = _ + rw [eqn] + change (if (base+8).val = (base+6).val then _ else mid (base+8).val) = _ + rw [ite_eq_right hn] + exact (Workspace.init_rowCount g base m room).trans hr + · rw [gap_eq] + change armed d g base m (gap g base).val = _ + rw [eqn] + change (if (gap g base).val = (base+6).val then _ else mid (gap g base).val) = _ + have hn : (gap g base).val ≠ (base+6).val := address_ne base fit (j := 6) (by omega) (by omega) + rw [ite_eq_right hn] + exact mg + +theorem frame_after_count (base count : Word w) (m : Memory w) (fit : 16 < 2^w) : + (Frame.data (base+9) (writeMemory m (base+8) count) : Fin 8 → Word w) = Frame.data (base+9) m := by + funext i + have haddr : base+9+(i.val : Word w) = base+((9+i.val : ℕ) : Word w) := by + rw [Nat.cast_add,Nat.cast_ofNat,add_assoc] + have h : (base+9+(i.val : Word w)).val ≠ (base+8).val := by + rw [haddr] + exact address_ne base (i := 9+i.val) (j := 8) (by have := i.isLt; omega) (by omega) (by omega) + change writeMemory m (base+8) count (base+9+(i.val : Word w)).val = _ + exact ite_eq_right h + +/-- The stride computation is a one-call outer setup stage. Its original +persistent return is closed by the existing single-call stage wrapper. -/ +def strideTable (F : DescriptorSpace.Shape) := LiveOneShot.oneShot (DescriptorStride.table F) + +theorem stride_and_arm (d : ℕ) (L : DescriptorSpace.Layout) (pub : Fin 11 → Word w) + (s : Word w) (m : Memory w) (rows : Word w) {row tag : Word w} {b l a W start : ℕ} + (frame : Frame.data (pub 2+9) m = CursorRAM.ScheduleInit.inputs row tag b l a W start) + (positions : (b+l)*2^b*2^l = L.positions) (fit : 10+L.shape.arity < 2^w) + (count : m (pub 2+8).val = rows) : + let g := L.shape.arity + let base := pub 2 + let S := ((strideTable L.shape).instantiate w pub).program + let es := (DescriptorStride.report L.shape pub s m).events + let m' := after m es + let A := (Workspace.initMachine g pub).program + let B := ((Workspace.calendarStart d).instantiate w pub).program + execute S (1+DescriptorStride.cost L.shape) (S.start s) m [] = some ⟨es,none⟩ ∧ + execute A 42 (A.start 0) m' [] = some (Workspace.initReport g base) ∧ + execute B 6 (B.start 0) (after m' (Workspace.initReport g base).events) [] = + some (Workspace.calendarReport d base) ∧ + Ready d g base rows (DescriptorSpace.levelWords L : Word w) (armed d g base m') := by + obtain ⟨hs,_,hm,_,_⟩ := DescriptorStride.native L pub s m frame positions + have hr : after m (DescriptorStride.report L.shape pub s m).events (pub 2+8).val = rows := by + rw [hm] + have h : (pub 2+8).val ≠ (pub 2+((10+L.shape.arity : ℕ) : Word w)).val := + address_ne (pub 2) (i := 8) (by omega) fit (by omega) + simpa only [writeMemory,h,↓reduceIte] using count + have hp : after m (DescriptorStride.report L.shape pub s m).events (gap L.shape.arity (pub 2)).val = + (DescriptorSpace.levelWords L : Word w) := by rw [hm]; simp [gap, writeMemory] + refine ⟨?_, arm d L.shape.arity pub 0 _ _ _ fit hr hp⟩ + dsimp only [strideTable] + rw [LiveOneShot.execute_oneShot] + change (execute _ _ (((DescriptorStride.table L.shape).instantiate w pub).program.start s) m []).map _ = _ + rw [hs] + rfl + +theorem tag_is_calendar (q d g : ℕ) {base rows stride : Word w} {m : Memory w} + (ready : Ready d g base rows stride m) : + m (Workspace.ports g base).tag.val = LiveStageLink.tagWord w (Online.calendarIndex d q) := by + rw [ready.tag] + simp [Online.calendarIndex, LiveStageLink.tagWord] + +/-- The calendar runs one fixed prefix and one fixed phase block for each of the +paper's logarithmically many compression blocks. -/ +def rowsSpec (initial phases p q : ℕ) : CalendarRows.Spec := ⟨p,q,initial,phases⟩ + +/-- Run all four native metadata stages in the pair ABI. The cursor-parameter +producer has already installed its eight-word frame. The row counter reads +the input length, the stride stage reads the cursor frame, and the final two +stages publish the six pointers and select the calendar. -/ +theorem bootstrap (p q : ℕ) (L : DescriptorSpace.Layout) (pub : Fin 11 → Word w) + (s : Word w) (m : Memory w) (n : ℕ) (arityEq : L.shape.arity = arity C) + (hq : 0 < q) (hn : (pub 6).val = n) (hp : p < 2^w) (hpow : n^p < 2^w) (hr : 2^q < 2^w) + {row tag : Word w} {b l a W start : ℕ} + (frame : Frame.data (pub 2+9) m = CursorRAM.ScheduleInit.inputs row tag b l a W start) + (positions : (b+l)*2^b*2^l = L.positions) (fit : 10+arity C < 2^w) (frameFit : 16 < 2^w) : + let g := arity C + let base := pub 2 + let D := rowsSpec initial phases p q + let Q := ((CalendarRows.table D).instantiate w pub).program + let qrep := CalendarRows.report D pub n + let m₁ := after m qrep.events + let S := ((strideTable L.shape).instantiate w pub).program + let es := (DescriptorStride.report L.shape pub 0 m₁).events + let m₂ := after m₁ es + let A := (Workspace.initMachine g pub).program + let B := ((Workspace.calendarStart d).instantiate w pub).program + execute Q (CalendarRows.ticks D n + 2) (Q.start s) m [] = some qrep ∧ + execute S (1+DescriptorStride.cost L.shape) (S.start 0) m₁ [] = some ⟨es,none⟩ ∧ + execute A 42 (A.start 0) m₂ [] = some (Workspace.initReport g base) ∧ + execute B 6 (B.start 0) (after m₂ (Workspace.initReport g base).events) [] = + some (Workspace.calendarReport d base) ∧ + Ready d g base ((initial+phases*Compression.blockCount ((p : ℝ)/q) n : ℕ) : Word w) + (DescriptorSpace.levelWords L : Word w) (armed d g base m₂) := by + let D := rowsSpec initial phases p q + let m₁ := after m (CalendarRows.report D pub n).events + have hm : m₁ = writeMemory m (pub 2+8) (CalendarRows.rows D n) := CalendarRows.after_report D pub n m + have frame' : Frame.data (pub 2+9) m₁ = CursorRAM.ScheduleInit.inputs row tag b l a W start := by + rw [hm,frame_after_count _ _ _ frameFit,frame] + have cnt : m₁ (pub 2+8).val = (CalendarRows.rows D n : Word w) := by rw [hm]; simp [writeMemory] + have hs := stride_and_arm d L pub 0 m₁ _ frame' positions (by rwa [arityEq]) cnt + rw [arityEq,CalendarRows.rows_eq] at hs + exact ⟨CalendarRows.execute_native D pub s m [] n hq hn hp hr hpow le_rfl,hs⟩ + +/-- At ordinal zero the calendar passes the first actual level header to +its planner, directly after the last reserved directory row. -/ +theorem first_header (pub : Fin 11 → Word w) (m : Memory w) (rows stride : Word w) + (ready : Ready d (arity C) (pub 2) rows stride m) : + LevelCalendar.header (Online.calendar plan) (ports (C := C) pub).data m = + (ports (C := C) pub).directory + ((arity C+3 : ℕ) : Word w)*rows := by + let A := Online.calendar plan + have level : A.level 0 = 0 := by + unfold LevelCalendar.Calendar.level + split <;> simp + change _ + ((A.rowPitch : ℕ) : Word w)*m (Workspace.ports (arity C) (pub 2)).rows.val + + _*(A.level (m (Workspace.ports (arity C) (pub 2)).ordinal.val).val : Word w) = _ + rw [ready.count, ready.ordinal] + simp only [Fin.val_zero,level,Nat.cast_zero,mul_zero,add_zero] + rfl + +/-- The first nonempty calendar call executes on the enclosing eleven-word +table with the complete pointer-loading and stage-selection transcripts. -/ +theorem first_dispatch (pub : Fin 11 → Word w) (state : Word w) (m : Memory w) (rows stride : Word w) + (ready : Ready d (arity C) (pub 2) rows stride m) (nonempty : 0 < rows) + (j : Fin (initial+phases)) (hj : j.val = 0) (fits : Online.N d (initial+phases) ≤ 2^w) + {cap : ℕ} (budget : 30+2*(initial+phases)+2*Online.N d (initial+phases)+5 ≤ cap) : + let P := ports (C := C) pub + let rep := Online.linked P (Online.calendarIndex d (initial+phases)) + (LevelCalendar.dispatchReport (Online.calendar plan) P.data m (Online.phaseIndex plan j)) + execute (program plan pub) (cap+24) ((program plan pub).start state) m [] = + some (Workspace.report (pub 2) m rep) := by + let P := ports (C := C) pub + have active : m P.ordinal.val < m P.rows.val := by rw [ready.ordinal,ready.count]; exact nonempty + have phase : (Online.calendar plan).phase (m P.ordinal.val).val = j.val := by + rw [ready.ordinal,hj] + simp only [Fin.val_zero,LevelCalendar.Calendar.phase] + by_cases h : 0 < (Online.calendar plan).initial.length + · simp [h] + · have hz : (Online.calendar plan).initial.length = 0 := by omega + simp [hz] + have hc := Online.calendar_call plan P state m j (tag_is_calendar _ _ _ ready) fits active phase budget + exact (execute_linked plan pub state m [] ready.bank cap _ hc).1 + +end CompressorRecords.OnlineWorkspace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsOrdinalFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsOrdinalFootprint.lean new file mode 100644 index 0000000000..786ce500fc --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsOrdinalFootprint.lean @@ -0,0 +1,73 @@ +import OAI.Computability.VPVNP.CompressorRecordsOrdinalRun +import OAI.Computability.VPVNP.CompressorSourceTransport + +/-! +# External addresses of complete ordinal scans + +Read and write bounds verified on individual source calls are preserved +when the calls run consecutively. The resulting bounds allow the online +dispatcher to replay a pass after changing its own control words. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.OrdinalRun + +open BurstRAM SourceTransport + +variable {w : ℕ} {Q : Type*} + +/-- A native scan reads and writes only the union of its rows' data cells. -/ +theorem footprint (P : BurstRAM.Program w Q) (fuel : ℕ) (cursor : ℕ → Word w) + (N : ℕ) (I : ℕ → Memory w → Prop) (readable writable : ℕ → Prop) + (advance : ∀ j < N, ∀ m, I j m → ∀ bits rep, execute P fuel (P.start (cursor j)) m bits = some rep → + rep.result = some (cursor (j+1)) ∧ I (j+1) (after m rep.events) ∧ + Reads readable rep.events ∧ Writes writable rep.events) + (j : ℕ) (bs : List (List Bool)) (m : Memory w) (rs : List (Report w)) + (size : j+bs.length ≤ N) (inv : I j m) (run : runSegment P fuel (some (cursor j)) m bs = some rs) : + Reads readable (eventLog rs) ∧ Writes writable (eventLog rs) := by + induction bs generalizing j m rs with + | nil => + change some [] = some rs at run + cases Option.some.inj run + exact ⟨fun _ _ h => (List.not_mem_nil h).elim,fun _ _ h => (List.not_mem_nil h).elim⟩ + | cons b bs ih => + cases h : execute P fuel (P.start (cursor j)) m b with + | none => simp [runSegment,h] at run + | some rep => + have hj : j ?_,fun a v he => ?_⟩ + · exact (List.mem_append.mp he).elim (rd a v) (tr a v) + · exact (List.mem_append.mp he).elim (wr a v) (tw a v) + +/-- The report list records every successor cursor in visit order. -/ +theorem successors (P : BurstRAM.Program w Q) (fuel : ℕ) (cursor : ℕ → Word w) (N : ℕ) + (advance : ∀ j < N, ∀ m bits rep, execute P fuel (P.start (cursor j)) m bits = some rep → + rep.result = some (cursor (j+1))) + (j : ℕ) (bs : List (List Bool)) (m : Memory w) (rs : List (Report w)) + (size : j+bs.length ≤ N) (run : runSegment P fuel (some (cursor j)) m bs = some rs) : + rs.map Report.result = (List.range' (j+1) bs.length).map (fun l => some (cursor l)) := by + induction bs generalizing j m rs with + | nil => change some [] = some rs at run; cases Option.some.inj run; rfl + | cons b bs ih => + cases h : execute P fuel (P.start (cursor j)) m b with + | none => simp [runSegment,h] at run + | some rep => + have hj : j + change some [] = some rs at run + cases Option.some.inj run + change j+0 = N at size + have e : j=N := by omega + subst j + exact ⟨⟨ready,closed⟩,inv,fun _ _ => rfl⟩ + | cons b bs ih => + cases h : execute P fuel (P.start (cursor j)) mem b with + | none => simp [runSegment,h] at run + | some rep => + have hj : j (frame x hx).trans (keep x hx)⟩ + +/-- Specialization to an already prepared physical directory row. -/ +theorem row_valid (row : Directory.Row d w) (cursor : ℕ → Word w) (I : ℕ → Memory w → Prop) + (start : Directory.start C ports row.input = cursor 0) + (active : ∀ j < row.choices.length, cursor j < Directory.bound C ports row.input) + (closed : Directory.bound C ports row.input ≤ cursor row.choices.length) + (tag : row.input ports.tag.val = 0) (live : row.input ports.ordinal.val < row.input ports.rows.val) + (fuel : 0 < row.fuel) + (ready : Ready C row.worker ports (Directory.words C ports row.worker row.input) + (Directory.bound C ports row.input) (row.dataMemory C ports)) + (inv : I 0 (row.dataMemory C ports)) + (run : let P := ((C row.worker).table.instantiate w (Directory.words C ports row.worker row.input)).program + runSegment P row.fuel (some (cursor 0)) (row.dataMemory C ports) row.choices = some row.reports) + (advance : let P := ((C row.worker).table.instantiate w (Directory.words C ports row.worker row.input)).program + ∀ j < row.choices.length, ∀ mem, I j mem → ∀ bits rep, execute P row.fuel (P.start (cursor j)) mem bits = some rep → + rep.result = some (cursor (j+1)) ∧ I (j+1) (after mem rep.events) ∧ + Preserved (C row.worker).params ports mem (after mem rep.events)) : + row.Valid C ports ∧ I row.choices.length (row.endMemory C ports) ∧ + Preserved (C row.worker).params ports (row.dataMemory C ports) (row.endMemory C ports) := by + let P := ((C row.worker).table.instantiate w (Directory.words C ports row.worker row.input)).program + obtain ⟨frame,last,keep⟩ := validTrace C row.worker ports P row.fuel _ _ cursor _ I active closed advance 0 _ _ _ + (Nat.zero_add _) inv ready run + exact ⟨⟨tag,live,fuel,start ▸ run,start ▸ frame⟩,last,keep⟩ + +end CompressorRecords.OrdinalRun + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsPhaseRecipe.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsPhaseRecipe.lean new file mode 100644 index 0000000000..8078cd923e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsPhaseRecipe.lean @@ -0,0 +1,504 @@ +import OAI.Computability.VPVNP.CompressorRecordsRowRecipe +import OAI.Computability.VPVNP.CompressorRecordsController +import Mathlib.Algebra.BigOperators.Fin + +/-! +# Compiling current-level formulas to native row planners + +Expressions can read the level pointer, the five controller ports, and memory +at computed addresses. The compiler allocates disjoint output registers and +reuses a bounded scratch interval between formulas. Natural literals are +synthesized from their binary digits using word additions. Every read finishes +before the row writer installs its first field. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PhaseRecipe + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM RowRecipe +open scoped Fin.CommRing + +variable {w r g : ℕ} + +/-- A word formula for planning a directory row from constants, the controller's five public +words, the current level pointer, memory loads and RAM binary operations. -/ +inductive Expr where + | lit (value : ℕ) + | publicWord (index : Fin 5) + | state + | load (address : Expr) + | binary (op : BinaryOp) (left right : Expr) + +/-- Compute the formula's machine word in the current level and entry memory. A load reads +memory at the address obtained by evaluating its subexpression. -/ +def Expr.eval (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) : Expr → Word w + | .lit n => (n : Word w) + | .publicWord i => pub i + | .state => state + | .load a => m (a.eval pub state m).val + | .binary op a b => op.eval (a.eval pub state m) (b.eval pub state m) + +/-- Form the sum of two planner expressions using machine-word addition. -/ +def Expr.add := Expr.binary .add +/-- Form the product of two planner expressions using machine-word multiplication. -/ +def Expr.mul := Expr.binary .mul +/-- Subtract the second planner expression from the first at the machine's word width. -/ +def Expr.sub := Expr.binary .sub +/-- Form the unsigned integer quotient of the two word values computed by planner expressions. -/ +def Expr.div := Expr.binary .div +/-- Form the unsigned remainder of the first planner expression's value modulo the second's. -/ +def Expr.mod := Expr.binary .mod +/-- Address expression for field offset `i` from the current level header, whose base is +carried in persistent state. -/ +def Expr.headerAddress (i : ℕ) := Expr.state.add (.lit i) +/-- Load a level-header field at the given word offset from the current state pointer. -/ +def Expr.header (i : ℕ) := Expr.load (Expr.headerAddress i) +/-- Address of the directory row to publish, computed as the directory base plus the stored +ordinal times the row width `g + 3`. -/ +def Expr.rowBase (g : ℕ) := (Expr.publicWord 1).add ((Expr.load (.publicWord 2)).mul (.lit (g+3))) + +theorem eval_rowBase (g : ℕ) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + (Expr.rowBase g).eval pub s m = Controller.rowBase g pub m := rfl + +/-- Number of consecutive scratch registers used to compile this expression. Binary operations +keep the left result while compiling the right operand one register later. -/ +def Expr.slots : Expr → ℕ + | .lit _ => 2 + | .publicWord _ | .state => 1 + | .load a => a.slots + | .binary _ a b => max a.slots (1+b.slots) + +theorem Expr.slots_pos (e : Expr) : 0 < e.slots := by induction e <;> simp_all [Expr.slots] + +private def run (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (ls : List (Assign r 5)) (rs : Regs w r) := (evaluate pub s m ls rs).2 + +private theorem run_append (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (as bs : List (Assign r 5)) (rs : Regs w r) : + run pub s m (as++bs) rs = run pub s m bs (run pub s m as rs) := by + induction as generalizing rs with + | nil => rfl + | cons a as ih => exact ih _ + +private theorem run_single (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (a : Assign r 5) (rs : Regs w r) : + run pub s m [a] rs = Function.update rs a.dst (a.rhs.value pub s m rs) := rfl + +private def digits (dst one : Fin r) (n : ℕ) : List (Assign r 5) := + if n = 0 then [⟨dst,.literal 0⟩] + else digits dst one (n/2) ++ [⟨dst,.binary .add dst dst⟩] ++ + (if n%2 = 0 then [] else [⟨dst,.binary .add dst one⟩]) +termination_by n +decreasing_by omega + +private theorem digits_keep (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (dst one : Fin r) (n : ℕ) (rs : Regs w r) (j : Fin r) (hj : j ≠ dst) : + run pub s m (digits dst one n) rs j = rs j := by + induction n using Nat.strong_induction_on with + | h n ih => + rw [digits] + by_cases hn : n = 0 + · simp [hn, run_single, Function.update_of_ne hj] + · have hl := ih (n/2) (by omega) + by_cases hb : n%2 = 0 <;> simp only [hn,hb,↓reduceIte,List.append_nil,run_append,run_single,Function.update_of_ne hj,hl] + +private theorem digits_value (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (dst one : Fin r) (ne : one ≠ dst) (n : ℕ) (rs : Regs w r) (ho : rs one = 1) : + run pub s m (digits dst one n) rs dst = (n : Word w) := by + induction n using Nat.strong_induction_on with + | h n ih => + rw [digits] + by_cases hn : n = 0 + · subst n; simp [run_single, RHS.value] + have hv := ih (n/2) (by omega) + have keep := digits_keep pub s m dst one (n/2) rs one ne + by_cases hb : n%2 = 0 + · simp only [hn, hb, ↓reduceIte, List.append_nil, run_append, run_single, RHS.value, BinaryOp.eval, + Function.update_self, hv] + rw [← Nat.cast_add, show n/2+n/2 = n by omega] + · simp only [hn, hb, ↓reduceIte, run_append, run_single, RHS.value, BinaryOp.eval, Function.update_self, + Function.update_of_ne ne, hv, keep, ho] + rw [← Nat.cast_add, ← Nat.cast_one (R := Word w), ← Nat.cast_add, show n/2+n/2+1 = n by omega] + +/-- The scratch register at `start` holds the result. A right subexpression +begins one register later and may reuse the left subexpression's temporaries. -/ +def Expr.compile (slot : ℕ → Fin r) (start : ℕ) : Expr → List (Assign r 5) + | .lit n => [⟨slot (start+1),.literal 1⟩] ++ digits (slot start) (slot (start+1)) n + | .publicWord i => [⟨slot start,.publicWord i⟩] + | .state => [⟨slot start,.state⟩] + | .load a => a.compile slot start ++ [⟨slot start,.read (slot start)⟩] + | .binary op a b => a.compile slot start ++ b.compile slot (start+1) ++ + [⟨slot start,.binary op (slot start) (slot (start+1))⟩] + +private theorem compile_keep (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) (e : Expr) + (slot : ℕ → Fin r) (start : ℕ) (rs : Regs w r) (j : Fin r) + (free : ∀ i, start ≤ i → i < start+e.slots → j ≠ slot i) : + run pub s m (e.compile slot start) rs j = rs j := by + induction e generalizing start rs with + | lit n => + have h0 := free start le_rfl (by simp [Expr.slots]) + have h1 := free (start+1) (by omega) (by simp [Expr.slots]) + rw [Expr.compile, run_append, digits_keep _ _ _ _ _ _ _ _ h0, run_single, Function.update_of_ne h1] + | state | publicWord _ => + simp [Expr.compile, run_single, Function.update_of_ne (free start le_rfl (by simp [Expr.slots]))] + | load a ih => + have h0 := free start le_rfl (by have := a.slots_pos; simp [Expr.slots, this]) + simp [Expr.compile, run_append, run_single, Function.update_of_ne h0, ih start rs free] + | binary op a b ha hb => + have fL : ∀ i, start ≤ i → i < start+a.slots → j ≠ slot i := + fun i lo hi ↦ free i lo (by change i < start+max a.slots (1+b.slots); omega) + have fR : ∀ i, start+1 ≤ i → i < start+1+b.slots → j ≠ slot i := + fun i lo hi ↦ free i (by omega) (by change i < start+max a.slots (1+b.slots); omega) + have h0 := fL start le_rfl (by have := a.slots_pos; omega) + rw [Expr.compile, run_append, run_append, run_single, Function.update_of_ne h0, hb _ _ fR, ha _ _ fL] + +private theorem compile_value (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) (e : Expr) + (slot : ℕ → Fin r) (cap start : ℕ) (rs : Regs w r) + (room : start+e.slots ≤ cap) (inj : ∀ i < cap, ∀ j < cap, slot i = slot j → i = j) : + run pub s m (e.compile slot start) rs (slot start) = e.eval pub s m := by + induction e generalizing start rs with + | lit n => + have span : start+2 ≤ cap := room + have ne : slot (start+1) ≠ slot start := fun h ↦ by have := inj _ (by omega) _ (by omega) h; omega + rw [Expr.compile, run_append] + exact digits_value _ _ _ _ _ ne _ _ (by simp [run_single, RHS.value]) + | state | publicWord _ => simp [Expr.compile, run_single, Expr.eval, RHS.value] + | load a ih => + simp [Expr.compile, run_append, run_single, Expr.eval, RHS.value, ih start rs room] + | binary op a b ha hb => + have span : start+max a.slots (1+b.slots) ≤ cap := room + have hL := ha start rs (by omega) + let mid := run pub s m (a.compile slot start) rs + have hR := hb (start+1) mid (by omega) + have keep : run pub s m (b.compile slot (start+1)) mid (slot start) = mid (slot start) := by + apply compile_keep + intro i lo hi he + have := inj start (by omega) i (by omega) he + omega + rw [Expr.compile, run_append, run_append, run_single, Function.update_self] + change op.eval (run pub s m (b.compile slot (start+1)) mid (slot start)) + (run pub s m (b.compile slot (start+1)) mid (slot (start+1))) = _ + rw [keep, hR, show mid (slot start) = _ from hL] + rfl + +/-- Number of external reads when evaluating an expression. Repeated occurrences +are counted separately, including repeated loads of the same header field. -/ +def Expr.loads : Expr → ℕ + | .lit _ | .publicWord _ | .state => 0 + | .load a => a.loads+1 + | .binary _ a b => a.loads+b.loads + +private def readCount (ls : List (Assign r 5)) := (ls.map fun a ↦ a.rhs.reads).sum + +private theorem readCount_append (a b : List (Assign r 5)) : readCount (a++b) = readCount a + readCount b := by + simp [readCount] + +private theorem digits_reads (dst one : Fin r) (n : ℕ) : readCount (digits dst one n) = 0 := by + induction n using Nat.strong_induction_on with + | h n ih => + rw [digits] + by_cases hn : n = 0 + · simp [hn,readCount,RHS.reads] + · have h := ih (n/2) (by omega) + by_cases hb : n%2 = 0 <;> simp only [hn,hb,↓reduceIte,readCount_append,h] <;> rfl + +theorem Expr.compile_reads (e : Expr) (slot : ℕ → Fin r) (start : ℕ) : + ((e.compile slot start).map fun a ↦ a.rhs.reads).sum = e.loads := by + change readCount _ = _ + induction e generalizing start with + | lit n => rw [Expr.compile,readCount_append,digits_reads]; rfl + | state | publicWord _ => rfl + | load a ih => rw [Expr.compile,readCount_append,ih]; rfl + | binary op a b ha hb => rw [Expr.compile,readCount_append,readCount_append,ha,hb]; rfl + +/-- Parameters occupy a full catalog-width row, including any padding. -/ +structure Phase (g : ℕ) where + /-- Numeric worker tag written at the start of the directory row so the launcher can select + the pass. -/ + tag : ℕ + /-- Expression for the worker's first cursor, stored immediately after its tag. -/ + initial : Expr + /-- Expression for the exclusive cursor bound at which the worker scan returns to the + controller. -/ + stop : Expr + /-- Expressions for the worker's public operands in directory order, including any padding to + the catalog width. -/ + params : Fin g → Expr + +/-- Pad a worker's finite operand vector at the high end of the row. -/ +def Phase.ofParams {k g : ℕ} (_ : k ≤ g) (tag : ℕ) (initial stop : Expr) (params : Fin k → Expr) : Phase g := + ⟨tag,initial,stop,fun i ↦ if h : i.val < k then params ⟨i.val,h⟩ else .lit 0⟩ + +private def Phase.formulas (P : Phase g) : Fin (g+4) → Expr := + Fin.cons (.rowBase g) (Fin.cons (.lit P.tag) (Fin.cons P.initial (Fin.cons P.stop P.params))) + +private def Phase.scratch (P : Phase g) := Finset.univ.sup fun j ↦ (P.formulas j).slots +/-- Number of planner registers needed for the row address, its `g + 3` fields and the largest +scratch interval used by any one formula. -/ +def Phase.registerCount (P : Phase g) := P.scratch + g + 4 + +private def Phase.out (P : Phase g) (j : Fin (g+4)) : Fin P.registerCount := + ⟨j.val,by have := j.isLt; unfold Phase.registerCount; omega⟩ + +private def Phase.slot (P : Phase g) (i : ℕ) : Fin P.registerCount := + ⟨(g+4+i) % P.registerCount, Nat.mod_lt _ (by unfold Phase.registerCount; omega)⟩ + +private theorem slot_val (P : Phase g) {i : ℕ} (hi : i < P.scratch) : (P.slot i).val = g+4+i := + Nat.mod_eq_of_lt (by unfold Phase.registerCount; omega) + +private theorem room (P : Phase g) (i : Fin (g+4)) : (P.formulas i).slots ≤ P.scratch := + Finset.le_sup (f := fun j ↦ (P.formulas j).slots) (Finset.mem_univ i) + +private def Phase.emit (P : Phase g) (i : Fin (g+4)) : List (Assign P.registerCount 5) := + (P.formulas i).compile P.slot 0 ++ [⟨P.out i,.copy (P.slot 0)⟩] + +private theorem emit_value (P : Phase g) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (rs : Regs w P.registerCount) (i j : Fin (g+4)) : + run pub s m (P.emit i) rs (P.out j) = + if i = j then (P.formulas i).eval pub s m else rs (P.out j) := by + have enough := room P i + rw [Phase.emit, run_append, run_single] + by_cases hij : i = j + · subst j + simp only [↓reduceIte, Function.update_self, RHS.value] + apply compile_value _ _ _ _ _ P.scratch _ _ (by omega) + intro x hx y hy he + have eqn := congrArg Fin.val he + rw [slot_val P hx,slot_val P hy] at eqn + omega + · have hne : P.out j ≠ P.out i := fun e ↦ hij (Fin.ext (congrArg (fun t : Fin P.registerCount ↦ t.val) e.symm)) + simp only [hij,↓reduceIte,Function.update_of_ne hne] + apply compile_keep + intro t _ h e + have eqn := congrArg Fin.val e + rw [slot_val P (by omega)] at eqn + change j.val = g+4+t at eqn + have := j.isLt + omega + +private theorem emit_list (P : Phase g) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (rs : Regs w P.registerCount) (ls : List (Fin (g+4))) (j : Fin (g+4)) : + run pub s m (ls.flatMap P.emit) rs (P.out j) = + if j ∈ ls then (P.formulas j).eval pub s m else rs (P.out j) := by + induction ls generalizing rs with + | nil => simp [run,evaluate] + | cons i ls ih => + rw [List.flatMap_cons, run_append, ih, emit_value] + by_cases e : i = j + · subst i; simp + · by_cases h : j ∈ ls <;> simp [h,e,Ne.symm e] + +/-- One fixed finite native recipe for a phase of the online calendar. -/ +def Phase.recipe (P : Phase g) : Recipe P.registerCount 5 g where + lines := (List.finRange (g+4)).flatMap P.emit + dest := P.out 0 + tag := P.out (0 : Fin (g+3)).succ + start := P.out (0 : Fin (g+2)).succ.succ + stop := P.out (0 : Fin (g+1)).succ.succ.succ + params i := P.out i.succ.succ.succ.succ + +private theorem emit_reads (P : Phase g) (i : Fin (g+4)) : + readCount (P.emit i) = (P.formulas i).loads := by + rw [Phase.emit,readCount_append,show readCount ((P.formulas i).compile P.slot 0) = _ from + Expr.compile_reads _ _ _] + rfl + +/-- The row address contributes one ordinal read. All remaining reads arise +from the starting cursor, stopping cursor, and padded public operands. -/ +theorem Phase.recipe_reads (P : Phase g) : + P.recipe.reads = 1 + P.initial.loads + P.stop.loads + (List.ofFn fun i ↦ (P.params i).loads).sum := by + have fold (ls : List (Fin (g+4))) : + readCount (ls.flatMap P.emit) = (ls.map fun i ↦ (P.formulas i).loads).sum := by + induction ls with + | nil => rfl + | cons i ls ih => rw [List.flatMap_cons,readCount_append,emit_reads,ih]; rfl + change readCount ((List.finRange (g+4)).flatMap P.emit) = _ + rw [fold, ← List.ofFn_eq_map] + simp only [Phase.formulas,List.ofFn_succ,Fin.cons_zero,Fin.cons_succ,Expr.loads,Expr.rowBase, + Expr.add,Expr.mul,List.sum_cons] + omega + +/-- Evaluate the directory row in the current header and memory, yielding the tag, starting +cursor, exclusive stop and all parameter words in storage order. -/ +def Phase.words (P : Phase g) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) := + (P.tag : Word w) :: P.initial.eval pub s m :: P.stop.eval pub s m :: + List.ofFn (fun i ↦ (P.params i).eval pub s m) + +private theorem eval_out (P : Phase g) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) (i : Fin (g+4)) : + P.recipe.values pub s m (P.out i) = (P.formulas i).eval pub s m := by + change run pub s m ((List.finRange _).flatMap P.emit) _ _ = _ + rw [emit_list] + simp + +theorem recipe_address (P : Phase g) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + P.recipe.address pub s m = Controller.rowBase g pub m := by + change P.recipe.values pub s m (P.out 0) = _ + rw [eval_out] + simp [Phase.formulas, eval_rowBase] + +theorem recipe_words (P : Phase g) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + P.recipe.words pub s m = P.words pub s m := by + simp only [Recipe.words, Recipe.fields, Phase.words, List.map_cons, List.map_ofFn] + change P.recipe.values pub s m (P.out (0 : Fin (g+3)).succ) :: + P.recipe.values pub s m (P.out (0 : Fin (g+2)).succ.succ) :: + P.recipe.values pub s m (P.out (0 : Fin (g+1)).succ.succ.succ) :: + List.ofFn (fun i : Fin g ↦ P.recipe.values pub s m (P.out i.succ.succ.succ.succ)) = _ + simp only [eval_out, Phase.formulas, Fin.cons_succ, Fin.cons_zero, Expr.eval] + +/-- A completed native planner accepts with the computed worker row installed in +the current directory slot. All expression loads see the input memory. -/ +theorem execute_phase (P : Phase g) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (cap : ℕ) (budget : P.recipe.code.length < cap) + (fit : (Controller.rowBase g pub m).val + (g+3) ≤ 2^w) : + let M := P.recipe.acceptTable.instantiate w pub + let es := (P.recipe.report pub s m).events + execute M.program cap (M.program.start s) m [] = some ⟨es,none⟩ ∧ + Greedy.Stores (after m es) (Controller.rowBase g pub m) (P.words pub s m) ∧ + (∀ a, a < (Controller.rowBase g pub m).val ∨ (Controller.rowBase g pub m).val + (g+3) ≤ a → + after m es a = m a) ∧ + countProbes es = P.recipe.reads+(g+3) ∧ choiceBits es = [] := by + refine ⟨execute_accept P.recipe pub s m [] cap budget, ?_, ?_, (report_cost ..).2⟩ + · rw [← recipe_address P pub s m, ← recipe_words] + exact row_stores _ _ _ _ (by rwa [recipe_address]) + · intro a ha + exact row_outside P.recipe pub s m (by rwa [recipe_address]) a (by rwa [recipe_address]) + +private theorem stored_at (m : Memory w) (dest : Word w) (xs : List (Word w)) + (stored : Greedy.Stores m dest xs) (j : ℕ) (hj : j < xs.length) : + m (dest+(j : Word w)).val = xs[j] := by + induction xs generalizing dest j with + | nil => simp at hj + | cons x xs ih => + cases j with + | zero => simpa using stored.1 + | succ j => + have h := ih (dest+1) stored.2 j (by simpa using hj) + have eqn : dest+((j+1 : ℕ) : Word w) = (dest+1)+(j : Word w) := by + rw [Nat.cast_add,Nat.cast_one]; ac_rfl + simpa only [eqn,List.getElem_cons_succ] using h + +/-- Pointwise interface to the launcher's row reader. The last equality uses +the same origin and offset as the worker parameter frame. -/ +theorem row_fields (P : Phase g) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (fit : (Controller.rowBase g pub m).val + (g+3) ≤ 2^w) : + let base := Controller.rowBase g pub m + let out := after m (P.recipe.report pub s m).events + out base.val = (P.tag : Word w) ∧ out (base+1).val = P.initial.eval pub s m ∧ + out (base+2).val = P.stop.eval pub s m ∧ + ∀ j : Fin g, Controller.field (base+2) out (j.val+1) = (P.params j).eval pub s m := by + let base := Controller.rowBase g pub m + let out := after m (P.recipe.report pub s m).events + have st := row_stores P.recipe pub s m (by rwa [recipe_address]) + rw [recipe_address,recipe_words] at st + change Greedy.Stores out base ((P.tag : Word w) :: P.initial.eval pub s m :: P.stop.eval pub s m :: + List.ofFn (fun i ↦ (P.params i).eval pub s m)) at st + have two : base+1+1 = base+2 := by rw [add_assoc, one_add_one_eq_two] + refine ⟨st.1,st.2.1,?_,?_⟩ + · simpa only [two] using st.2.2.1 + · intro j + have h := stored_at out (base+1+1+1) _ st.2.2.2 j.val (by simp) + have he : base+2+((j.val+1 : ℕ) : Word w) = (base+1+1+1)+(j.val : Word w) := by + rw [two, Nat.cast_add, Nat.cast_one]; ac_rfl + change out (base+2+((j.val+1 : ℕ) : Word w)).val = _ + rw [he] + simpa only [List.getElem_ofFn] using h + +theorem ofParams_value {k : ℕ} (hk : k ≤ g) (tag : ℕ) (initial stop : Expr) + (v : Fin k → Expr) (i : Fin k) : + (Phase.ofParams hk tag initial stop v).params (i.castLE hk) = v i := by + simp [Phase.ofParams,i.isLt] + +theorem ofParams_padding {k : ℕ} (hk : k ≤ g) (tag : ℕ) (initial stop : Expr) + (v : Fin k → Expr) (i : Fin g) (hi : k ≤ i.val) : + (Phase.ofParams hk tag initial stop v).params i = .lit 0 := by + simp [Phase.ofParams,not_lt_of_ge hi] + +/-- The seven pointer fields are in the native refresh visitor's public order: +old widths, bundle targets, port shifts, bundle totals, outgoing offsets, +incoming offsets, and incoming widths. -/ +structure RefreshHeader where + /-- Offset in the current level header of the vertex-count word used to compute the refresh + scan length. -/ + vertices : ℕ + /-- Offset of the degree word used both as the first refresh operand and to compute the + numbers of bundles and slots. -/ + degree : ℕ + /-- Offset of the residual-lane count used to expand each vertex and port into refresh + bundles. -/ + residualLanes : ℕ + /-- Offsets of the seven array pointers for old widths, bundle targets, port shifts, bundle + totals, outgoing offsets, incoming offsets and incoming widths, in worker order. -/ + heads : Fin 7 → ℕ + +/-- Planner expression multiplying the header's vertex count, degree and residual-lane count to +obtain the number of refresh bundles. -/ +def RefreshHeader.bundles (H : RefreshHeader) := + ((Expr.header H.vertices).mul (.header H.degree)).mul (.header H.residualLanes) + +/-- Planner expression for the exclusive end of the refresh scan, one degree-sized block of +slots per bundle. -/ +def RefreshHeader.slots (H : RefreshHeader) := H.bundles.mul (.header H.degree) + +/-- Plan a refresh scan from cursor zero to the slot count computed from the header. Its eight +public operands are the degree and the seven array pointers. -/ +def refresh (tag : ℕ) (H : RefreshHeader) : Phase 8 where + tag := tag + initial := .lit 0 + stop := H.slots + params := Fin.cons (.header H.degree) (fun i ↦ Expr.header (H.heads i)) + +/-- Read the machine word at offset `i` from the level header pointed to by the persistent +state. -/ +def headerCell (m : Memory w) (s : Word w) (i : ℕ) := m (s+(i : Word w)).val + +/-- Read the refresh worker's eight public words from the current header, placing the degree +first and the seven array pointers after it. -/ +def refreshPublic (H : RefreshHeader) (m : Memory w) (s : Word w) : Fin 8 → Word w := + Fin.cons (headerCell m s H.degree) (fun i ↦ headerCell m s (H.heads i)) + +theorem refresh_words (tag : ℕ) (H : RefreshHeader) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) : + let V := headerCell m s H.vertices + let D := headerCell m s H.degree + let R := headerCell m s H.residualLanes + let B := V*D*R + (refresh tag H).recipe.words pub s m = (tag : Word w) :: 0 :: B*D :: List.ofFn (refreshPublic H m s) := by + rw [recipe_words] + change _ :: _ :: _ :: List.ofFn _ = _ :: _ :: _ :: List.ofFn _ + congr 3 + +/-- With the physical slot count in range the word multiplication computes the +natural exclusive stop, including zero vertices, degree or residual lanes. -/ +theorem refresh_stop_val (tag : ℕ) (H : RefreshHeader) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (fit : (headerCell m s H.vertices).val * (headerCell m s H.degree).val * + (headerCell m s H.residualLanes).val * (headerCell m s H.degree).val < 2^w) : + ((refresh tag H).stop.eval pub s m).val = (headerCell m s H.vertices).val * (headerCell m s H.degree).val * + (headerCell m s H.residualLanes).val * (headerCell m s H.degree).val := by + change (headerCell m s H.vertices * headerCell m s H.degree * headerCell m s H.residualLanes * + headerCell m s H.degree).val = _ + simp only [Fin.val_mul, Nat.mod_mul_mod, Nat.mod_eq_of_lt fit] + +/-- The accepting planner for the refresh worker constructs the actual eight +public operands directly from the header and supplies the computed segment count. -/ +theorem execute_refresh (tag : ℕ) (H : RefreshHeader) (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (cap : ℕ) (budget : (refresh tag H).recipe.code.length < cap) + (fit : (Controller.rowBase 8 pub m).val + 11 ≤ 2^w) : + let R := (refresh tag H).recipe + let M := R.acceptTable.instantiate w pub + let D := headerCell m s H.degree + let B := headerCell m s H.vertices * D * headerCell m s H.residualLanes + execute M.program cap (M.program.start s) m [] = some ⟨(R.report pub s m).events, none⟩ ∧ + Greedy.Stores (after m (R.report pub s m).events) (Controller.rowBase 8 pub m) + ((tag : Word w) :: 0 :: B*D :: List.ofFn (refreshPublic H m s)) := by + obtain ⟨he,hs,_⟩ := execute_phase (refresh tag H) pub s m cap budget fit + refine ⟨he,?_⟩ + rw [← recipe_words, refresh_words] at hs + exact hs + +end CompressorRecords.PhaseRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsPortRankRAM.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsPortRankRAM.lean new file mode 100644 index 0000000000..56ca4cd0bb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsPortRankRAM.lean @@ -0,0 +1,246 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleRank + +/-! +# Fixed-degree rank worker indexed by the old outgoing port + +The burst call loads the port's classified owner, its key, and its owner's +count. It scans a fixed number of cells in the owner's key row. A saturating +countdown masks the unused tail of a thick row, so the initial contents of the +tail cells are immaterial. The resulting rank is written at the old port's +absolute address, and the returned cursor advances to the next port. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRankRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- Straight-line instructions for the old-port rank worker, with nine private registers and +six public operands. -/ +abbrev Ops := List (Op 9 6) + +/-- Read the classified owner of old port `i` from the owner column addressed by public operand +zero. -/ +def owner (p : Fin 6 → Word w) (m : Memory w) (i : Word w) := m (p 0+i).val +/-- Read the key of old port `i` that the worker compares with keys belonging to the same +owner. -/ +def pivot (p : Fin 6 → Word w) (m : Memory w) (i : Word w) := m (p 1+i).val +/-- Read the number of valid entries in the old port owner's key row from the count column. -/ +def lengthAt (p : Fin 6 → Word w) (m : Memory w) (i : Word w) := m (p 4+owner p m i).val +/-- Address of the first key in the old port owner's row, computed from the key-array base, +owner index and row stride. -/ +def start (p : Fin 6 → Word w) (m : Memory w) (i : Word w) := p 2+owner p m i*p 3 + +private def samples (m : Memory w) (ptr : Word w) : ℕ → List (Word w) + | 0 => [] + | n+1 => m ptr.val :: samples m (ptr+1) n + +/-- Sample `cap` consecutive key words beginning at the old port owner's row, including any +unused tail cells. -/ +def row (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (cap : ℕ) := + samples m (start p m i) cap + +private theorem word_succ (k : ℕ) : Fin.ofNat (2^w) (k+1) = Fin.ofNat _ k+1 := by + apply Fin.ext + simp [Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + +private theorem samples_eq_ofFn (m : Memory w) (ptr : Word w) (n : ℕ) : + samples m ptr n = List.ofFn (fun j : Fin n ↦ m (ptr + Fin.ofNat _ j.val).val) := by + induction n generalizing ptr with + | zero => rfl + | succ n ih => + rw [samples, List.ofFn_succ, ih] + simp only [Fin.val_zero, Fin.ofNat_zero, add_zero, Fin.val_succ, word_succ] + congr 2 + funext j + rw [add_right_comm, add_assoc] + +theorem row_eq_map (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (cap : ℕ) : + row p m i cap = (List.range cap).map fun j ↦ m (start p m i + Fin.ofNat _ j).val := by + rw [row, samples_eq_ofFn] + apply List.ext_getElem <;> simp + +/-- Rank of the old port's key as a machine word. Count strictly smaller keys in the sampled +row prefix limited by the owner's stored count. -/ +def result (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (cap : ℕ) : Word w := + Fin.ofNat _ (((row p m i cap).take (lengthAt p m i).val).countP fun x ↦ decide (x < pivot p m i)) + +private def setup : Ops := + [.stateWord 0, .publicWord 6 0, .binary .add 6 6 0, .read 8 6, + .publicWord 6 1, .binary .add 6 6 0, .read 2 6, + .publicWord 6 4, .binary .add 6 6 8, .read 3 6, + .publicWord 6 3, .binary .mul 1 8 6, .publicWord 6 2, + .binary .add 1 6 1, .constant 5 1] + +private def step : Ops := + [.read 6 1, .binary .add 6 6 5, .binary .div 6 2 6, .binary .div 6 6 6, + .binary .div 7 3 3, .binary .sub 3 3 7, .binary .mul 6 7 6, + .binary .add 4 4 6, .binary .add 1 1 5] + +private def walk : ℕ → Ops + | 0 => [] + | n+1 => step ++ walk n + +private def finish : Ops := + [.publicWord 6 5, .binary .add 6 6 0, .write 6 4, .binary .add 0 0 5] + +/-- One straight-line template for all old ports of the same fixed degree. -/ +def visit (cap : ℕ) : Ops := setup ++ walk cap ++ finish + +theorem visit_length (cap : ℕ) : (visit cap).length = 19 + 9*cap := by + have h (n : ℕ) : (walk n).length = 9*n := by + induction n with + | zero => rfl + | succ n ih => simp [walk, step, ih]; omega + simp [visit, setup, finish, h]; omega + +private abbrev div (x y : Word w) := BinaryOp.div.eval x y + +private theorem div_val (x y : Word w) : (div x y).val = x.val / y.val := + Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt) + +private theorem active (x : Word w) : div x x = if x = 0 then 0 else 1 := by + by_cases hx : x = 0 + · simp [hx, div, BinaryOp.eval] + · rw [ite_eq_right hx] + change Fin.ofNat _ (x.val / x.val) = _ + rw [Nat.div_self (Nat.pos_of_ne_zero (fun h ↦ hx (Fin.ext h)))] + rfl + +private theorem lessIndicator (x pivot : Word w) : + div (div pivot (x+1)) (div pivot (x+1)) = if x < pivot then 1 else 0 := by + rw [active] + have hs : (x+1).val = (x.val+1) % (2^w) := by + simp [Fin.val_add, Nat.add_mod_mod] + by_cases h : x < pivot + · have lt : x.val < pivot.val := h + have hs' := Nat.mod_eq_of_lt (show x.val+1 < 2^w by have := pivot.isLt; omega) + have hn : div pivot (x+1) ≠ 0 := by + intro hz + have := congrArg Fin.val hz + rw [div_val, hs, hs'] at this + exact (Nat.ne_of_gt (Nat.div_pos lt (Nat.zero_lt_succ _))) this + simp [h, hn] + · have le : pivot.val ≤ x.val := le_of_not_gt h + have hz : div pivot (x+1) = 0 := by + apply Fin.ext + rw [div_val, hs] + by_cases fit : x.val+1 < 2^w + · rw [Nat.mod_eq_of_lt fit, Nat.div_eq_of_lt (by omega)]; rfl + · have top : x.val+1 = 2^w := by have := x.isLt; omega + rw [top, Nat.mod_self, Nat.div_zero]; rfl + simp [h, hz] + +private def preEvents (p : Fin 6 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + [.tick,.tick,.tick,.read (p 0+i) (owner p m i),.tick,.tick,.read (p 1+i) (pivot p m i), + .tick,.tick,.read (p 4+owner p m i) (lengthAt p m i),.tick,.tick,.tick,.tick,.tick] + +private theorem setup_trace (p : Fin 6 → Word w) (m : Memory w) (i : Word w) : + ∃ r, trace p i setup (fun _ ↦ 0) m = some (preEvents p m i,r,m) ∧ + r 0 = i ∧ r 1 = start p m i ∧ r 2 = pivot p m i ∧ r 3 = lengthAt p m i ∧ + r 4 = 0 ∧ r 5 = 1 := by + simp (config := {decide := true}) [setup, preEvents, owner, pivot, start, lengthAt, + trace, Op.effect, BinaryOp.eval, Function.update] + rfl + +private def walkEvents (m : Memory w) (ptr : Word w) : ℕ → List (Event w) + | 0 => [] + | n+1 => [.read ptr (m ptr.val),.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick] ++ walkEvents m (ptr+1) n + +private theorem step_trace (p : Fin 6 → Word w) (m : Memory w) (i : Word w) + (r : Regs w 9) (h1 : r 5 = 1) : + let live := if r 3 = 0 then 0 else (1 : Word w) + let lt := if m (r 1).val < r 2 then (1 : Word w) else 0 + ∃ s, trace p i step r m = + some ([.read (r 1) (m (r 1).val),.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick],s,m) ∧ + s 0 = r 0 ∧ s 1 = r 1+1 ∧ s 2 = r 2 ∧ s 3 = r 3-live ∧ + s 4 = r 4+live*lt ∧ s 5 = 1 := by + dsimp only + simp (config := {decide := true}) [step, trace, Op.effect, Function.update, h1, + BinaryOp.eval] at * + refine ⟨active (r 3), ?_⟩ + change div (r 3) (r 3) * div (div (r 2) (m (r 1).val + 1)) (div (r 2) (m (r 1).val + 1)) = _ + rw [active, lessIndicator] + split <;> simp_all + +private theorem walk_trace (p : Fin 6 → Word w) (m : Memory w) (i : Word w) + (cap : ℕ) (r : Regs w 9) (hone : r 5 = 1) : + ∃ s, trace p i (walk cap) r m = some (walkEvents m (r 1) cap,s,m) ∧ + s 0 = r 0 ∧ s 5 = 1 ∧ s 4 = r 4 + + Fin.ofNat _ (((samples m (r 1) cap).take (r 3).val).countP fun x ↦ decide (x < r 2)) := by + induction cap generalizing r with + | zero => exact ⟨r, rfl, rfl, hone, by simp [samples]⟩ + | succ n ih => + obtain ⟨s, hs, h0, hptr, hpiv, hrem, hacc, hu⟩ := step_trace p m i r hone + obtain ⟨t, ht, h0', hu', hv⟩ := ih s hu + refine ⟨t, ?_, h0'.trans h0, hu', ?_⟩ + · simp [walk, trace_append, hs, ht, walkEvents, hptr] + rw [hv, hacc, hptr, hpiv, hrem] + by_cases hr : r 3 = 0 + · simp [hr] + · obtain ⟨k,hk⟩ := Nat.exists_eq_succ_of_ne_zero (fun h ↦ hr (Fin.ext h)) + have hleft : (r 3-1).val = k := by rw [Fin.val_sub_one_of_ne_zero hr, hk]; omega + simp only [hr, ite_false, hleft, samples, hk, List.take_succ_cons, one_mul, List.countP_cons] + by_cases hlt : m (r 1).val < r 2 + · simp only [hlt, decide_true, ite_true, word_succ] + ac_rfl + · simp [hlt] + +private def finalEvents (p : Fin 6 → Word w) (i rank : Word w) : List (Event w) := + [.tick,.tick,.write (p 5+i) rank,.tick] + +private theorem finish_trace (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (r : Regs w 9) + (h0 : r 0 = i) (hu : r 5 = 1) : + ∃ s, trace p i finish r m = some (finalEvents p i (r 4),s,writeMemory m (p 5+i) (r 4)) ∧ + s 0 = i+1 := by + simp (config := {decide := true}) [finish, trace, Op.effect, BinaryOp.eval, + finalEvents, Function.update, h0, hu] + +private theorem walk_stats (m : Memory w) (ptr : Word w) (cap : ℕ) (tail : List (Event w)) : + countProbes (walkEvents m ptr cap ++ tail) = cap + countProbes tail ∧ + (walkEvents m ptr cap ++ tail).length = 9*cap + tail.length ∧ + after m (walkEvents m ptr cap ++ tail) = after m tail := by + induction cap generalizing ptr with + | zero => simp [walkEvents] + | succ n ih => + obtain ⟨hp,hl,hm⟩ := ih (ptr+1) + refine ⟨?_, ?_, hm⟩ + · change 1 + countProbes (walkEvents m (ptr+1) n ++ tail) = _; omega + · change (walkEvents m (ptr+1) n ++ tail).length + 9 = _; omega + +/-- Actual native execution on arbitrary external words, including unused row +cells equal to the largest representable word. -/ +theorem run_one (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (cap : ℕ) : + let M := (template (visit cap) 0).instantiate w p + ∃ es, execute M.program (1+(visit cap).length) (M.program.start i) m [] = some ⟨es,some (i+1)⟩ ∧ + after m es = writeMemory m (p 5+i) (result p m i cap) ∧ countProbes es = cap+4 ∧ + es.length = (visit cap).length := by + obtain ⟨r,hs,h0,hptr,hpiv,hrem,hacc,hu⟩ := setup_trace p m i + obtain ⟨s,hw,hs0,hsu,hs4⟩ := walk_trace p m i cap r hu + obtain ⟨t,hf,hret⟩ := finish_trace p m i s (hs0.trans h0) hsu + have heq : s 4 = result p m i cap := by simpa only [result,row,hptr,hpiv,hrem,hacc,zero_add] using hs4 + rw [heq] at hf + let tail := finalEvents p i (result p m i cap) + obtain ⟨hp,hl,hm⟩ := walk_stats m (r 1) cap tail + refine ⟨preEvents p m i ++ (walkEvents m (r 1) cap ++ tail), ?_, hm, ?_, ?_⟩ + · change execute ((template (visit cap) 0).instantiate w p).program (1+(visit cap).length) + ⟨_, i, fun _ ↦ 0, fun _ ↦ 0⟩ m [] = _ + rw [execute_template, run_eq_trace, visit, trace_append, trace_append, hs] + simp [hw,hf,hret,List.append_assoc,tail] + · change 1+(1+(1+countProbes (walkEvents m (r 1) cap ++ tail))) = _ + change countProbes (walkEvents m (r 1) cap ++ tail) = cap+1 at hp + omega + · rw [List.length_append, visit_length, hl] + change 15+(9*cap+4) = _ + omega + +end CompressorRecords.PortRankRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsPortRankScan.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsPortRankScan.lean new file mode 100644 index 0000000000..58baba4637 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsPortRankScan.lean @@ -0,0 +1,159 @@ +import OAI.Computability.VPVNP.CompressorRecordsPortRankRAM +import OAI.Computability.VPVNP.CompressorSlotOwnerRuns + +/-! +# Filling the absolute-port rank table + +The classifier's owner and pivot columns, the bundle counts and the rectangular +key table are read-only throughout the scan. The output column is indexed by +the original arc's full outgoing-port ID, including the residual lane. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRankRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- All addresses that can be read by the call at this port in its input memory. -/ +def inputs (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (cap : ℕ) : List (Word w) := + [p 0+i, p 1+i, p 4+owner p m i] ++ (List.range cap).map (fun j ↦ start p m i + Fin.ofNat _ j) + +private theorem result_congr (p : Fin 6 → Word w) (i : Word w) (cap : ℕ) {m init : Memory w} + (eqv : ∀ a ∈ inputs p init i cap, m a.val = init a.val) : + result p m i cap = result p init i cap := by + have ho : owner p m i = owner p init i := eqv (p 0+i) (by simp [inputs]) + have hp : pivot p m i = pivot p init i := eqv (p 1+i) (by simp [inputs]) + have hlen : lengthAt p m i = lengthAt p init i := by + simp only [lengthAt, ho] + exact eqv _ (by simp [inputs]) + have hs : start p m i = start p init i := by simp only [start, ho] + have hrow : row p m i cap = row p init i cap := by + simp only [row_eq_map, hs] + apply List.map_congr_left + intro j hj + exact eqv _ (List.mem_append_right _ (List.mem_map.mpr ⟨j,hj,rfl⟩)) + simp only [result, hp, hlen, hrow] + +/-- Regions for a full absolute-port scan. Input arrays may be placed in +arbitrary order and used by other phases of the compressor. -/ +structure Regions (p : Fin 6 → Word w) (m : Memory w) (cap A : ℕ) : Prop where + outputFits : (p 5).val + A ≤ 2^w + reads : ∀ i < A, ∀ a ∈ inputs p m (Fin.ofNat _ i) cap, + a.val < (p 5).val ∨ (p 5).val + A ≤ a.val + +private theorem visit_segment {p : Fin 6 → Word w} {initial : Memory w} {cap A : ℕ} + (reg : Regions p initial cap A) (k n : ℕ) (hk : k+n ≤ A) : + SlotOwnerPass.Visit ((template (visit cap) 0).instantiate w p).program (1+(visit cap).length) + (cap+4) (visit cap).length (p 5).val k n (fun i ↦ result p initial (Fin.ofNat _ i) cap) initial := by + intro j _ hj m frame + let i := Fin.ofNat (2^w) j + have heq := result_congr p i cap (m := m) (init := initial) + (fun a ha ↦ frame a.val (by have := reg.reads j (by omega) a ha; omega)) + obtain ⟨es,he,hm,hp,hl⟩ := run_one p m i cap + have hs : i+1 = Fin.ofNat (2^w) (j+1) := by + apply Fin.ext + simp [i, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + have hd : p 5+i = Fin.ofNat (2^w) ((p 5).val+j) := by + apply Fin.ext + simp [i, Fin.val_add, Nat.add_mod_mod] + exact ⟨es, hs ▸ he, by rw [hm,hd,heq], hp,hl⟩ + +/-- The native segment visits exactly the requested subinterval of the old IDs. -/ +theorem interval_run (p : Fin 6 → Word w) (initial : Memory w) (cap A k n : ℕ) + (reg : Regions p initial cap A) (hk : k+n ≤ A) : + let M := (template (visit cap) 0).instantiate w p + ∃ rs, runSegment M.program (1+(visit cap).length) (some (Fin.ofNat _ k)) initial + (List.replicate n []) = some rs ∧ + endState (some (Fin.ofNat _ k)) rs = some (Fin.ofNat _ (k+n)) ∧ + (∀ j, k ≤ j → j < k+n → after initial (eventLog rs) ((p 5).val+j) = + result p initial (Fin.ofNat _ j) cap) ∧ + (∀ a, a < (p 5).val+k ∨ (p 5).val+k+n ≤ a → after initial (eventLog rs) a = initial a) ∧ + rs.length = n ∧ (∀ r ∈ rs, r.probes = cap+4 ∧ r.events.length = (visit cap).length) ∧ + RAMBuckets.cost Report.probes rs = (1+(cap+4))*n := by + apply SlotOwnerPass.run + · have := reg.outputFits + omega + · exact visit_segment reg k n hk + +/-- The complete increasing-cursor rank scan has one call per old port, +`cap+4` probes per call, and a frame covering every other external array. -/ +theorem scan_run (p : Fin 6 → Word w) (initial : Memory w) (cap A : ℕ) + (reg : Regions p initial cap A) : + let M := (template (visit cap) 0).instantiate w p + ∃ rs, SlotOwners.FilledRun M.program (1+(visit cap).length) (cap+4) (visit cap).length + A (p 5) (fun j ↦ result p initial (Fin.ofNat _ j) cap) initial rs := by + apply SlotOwners.filled_run _ _ _ _ _ _ _ initial reg.outputFits + exact visit_segment reg 0 A (by omega) + +/-- Contents of the cells read for one genuine port. The live keys can +occupy any prefix of the uniform-stride row. -/ +structure StoredRow {E : Type*} {K : ℕ} (p : Fin 6 → Word w) (m : Memory w) (i : Word w) + (cap : ℕ) (key : E → Fin K) (fit : K ≤ 2^w) (e : E) (ids : List E) : Prop where + count : (lengthAt p m i).val = ids.length + capacity : ids.length ≤ cap + pivot_eq : pivot p m i = (key e).castLE fit + rowFits : (start p m i).val + ids.length ≤ 2^w + keys : ∀ j : Fin ids.length, m ((start p m i).val + j.val) = (key ids[j.val]).castLE fit + +theorem StoredRow.result {E : Type*} {K : ℕ} {p : Fin 6 → Word w} {m : Memory w} {i : Word w} + {cap : ℕ} {key : E → Fin K} {fit : K ≤ 2^w} {e : E} {ids : List E} + (h : StoredRow p m i cap key fit e ids) : + result p m i cap = Fin.ofNat _ (ids.countP (fun a ↦ decide (key a < key e))) := by + let word := fun a ↦ (key a).castLE fit + have he : (row p m i cap).take (lengthAt p m i).val = ids.map word := by + rw [row_eq_map, h.count] + apply List.ext_getElem + · simp [h.capacity] + · intro j hj hk + have hi : j < ids.length := by simpa using hk + have hp := h.rowFits + have ha : (start p m i + Fin.ofNat _ j).val = (start p m i).val+j := by + rw [Fin.val_add, Fin.val_ofNat, Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)] + simp only [List.getElem_take, List.getElem_map, List.getElem_range, ha] + exact h.keys ⟨j,hi⟩ + rw [PortRankRAM.result, he, h.pivot_eq, List.countP_map] + rfl + +open Compression Compression.PackingData Slots BundleRank + +variable {V H Tag L : Type} {N J A d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) (arcs : Arc V H Tag L d c ≃ Fin A) +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] [DecidableEq V] [DecidableEq Tag] [DecidableEq L] + +/-- From the two materialized key tables, a single fixed template fills the +entire rank column. Its entries are the exact piece numbers and concatenation +numbers of the packed graph, including distinct old wires with shared endpoints. -/ +theorem graph_scan (p : Fin 6 → Word w) (initial : Memory w) (cap : ℕ) + (reg : Regions p initial cap A) (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (hc : 2 ≤ c) + (fitM : N*(J*(d*(2^c*d))) ≤ 2^w) (fitT : 2^c*d ≤ 2^w) + (motifs : ∀ b (x : P.MotifFiber b), ∃ r : IncidentRow P.bundle b, + StoredRow p initial (Fin.ofNat _ (arcs x.1.1).val) cap (motifKey P vertices tags) + fitM x.1 r.ids) + (thick : ∀ b (x : P.ThickFiber b), ∃ r : IncidentRow (fun a : P.ThickWire ↦ a.1.1) b, + StoredRow p initial (Fin.ofNat _ (arcs x.1.1).val) cap (thickKey P) fitT x.1 r.ids) : + let M := (template (visit cap) 0).instantiate w p + ∃ rs, SlotOwners.FilledRun M.program (1+(visit cap).length) (cap+4) (visit cap).length + A (p 5) (fun j ↦ result p initial (Fin.ofNat _ j) cap) initial rs ∧ + (∀ b (x : P.MotifFiber b), after initial (eventLog rs) ((p 5).val+(arcs x.1.1).val) = + Fin.ofNat _ (P.sortedBundleNumbering vertices tags hc b x).val) ∧ + (∀ b (x : P.ThickFiber b), after initial (eventLog rs) ((p 5).val+(arcs x.1.1).val) = + Fin.ofNat _ (P.sortedThickNumbering hc b x).val) := by + obtain ⟨rs,run⟩ := scan_run p initial cap A reg + refine ⟨rs,run,?_,?_⟩ + · intro b x + obtain ⟨r,h⟩ := motifs b x + rw [run.filled _ (arcs _).isLt, h.result, motif_rank P vertices tags hc b r x] + · intro b x + obtain ⟨r,h⟩ := thick b x + rw [run.filled _ (arcs _).isLt, h.result, thick_rank P hc b r x] + +end CompressorRecords.PortRankRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsRankedDirectory.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsRankedDirectory.lean new file mode 100644 index 0000000000..7358aa6369 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsRankedDirectory.lean @@ -0,0 +1,157 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundlePass +import OAI.Computability.VPVNP.CompressorBundleRankedTable +import OAI.Computability.VPVNP.ShrinkStatePass + +/-! +# The first four native passes for a shrinking state + +Starting with the incidence and placement directories, the four passes classify +the arcs, append their IDs, gather their sorting keys, and write their ranks. +The output rank and original width of every port are now both directly +addressed by its actual outgoing ID. Each pass starts in the post-memory of +the preceding one. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BundleRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.PackingData BundleKeys +open BundleGather BundleRank + +variable {w a g : ℕ} +variable (X : State a (packingLaneBits a g)) +local notation "N" => Fintype.card X.Base +local notation "A" => N * 2^(packingLaneBits a g) * 2^a +local notation "D" => (2:ℕ)^a +local notation "C" => Shrink.colors a +local notation "J" => Shrink.J a +local notation "cap" => pieceCount D C +local notation "P" => X.packingData +local notation "arcs" => oldArcOrder (a := a) (g := g) X.baseIndex +local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex + +variable (T : IncidenceDirectory w) (p : Fin 11 → Word w) (q : Fin 6 → Word w) +variable (out dest : Word w) +local notation "K" => KeyTable.dyadic (q 5) (p 10) out T.width (Fin.val (q 4)) N a g +local notation "R" => rankPublic q (p 10) out dest + +/-- Post-memory at each pass boundary is computed from the preceding reports. -/ +structure RankedDirectoryRun (m : Memory w) (cs ls gs rs : List (Report w)) : Prop where + classify : runSegment ((template visit 0).instantiate w p).program (1+visit.length) + (some 0) m (List.replicate A []) = some cs + append : runSegment ((template collectPreimage 3).instantiate w q).program 23 (some 0) + (after m (eventLog cs)) (List.replicate A []) = some ls + lists : PreimagesAt q (BundleLists.wordOwner P arcs sites) (after (after m (eventLog cs)) (eventLog ls)) A + gather : runSegment ((template Fixed.visit 0).instantiate w (Fixed.parameters K)).program 29 (some 0) + (after (after m (eventLog cs)) (eventLog ls)) (List.replicate A []) = some gs + gatherCursor : endState (some 0) gs = some (Fin.ofNat _ A) + gatherWork : ∀ r ∈ gs, r.events.length = 28 ∧ r.probes = 3 + rank : let f := after (after (after m (eventLog cs)) (eventLog ls)) (eventLog gs) + let v := PortRankRAM.visit cap + SlotOwners.FilledRun ((template v 0).instantiate w R).program (1+v.length) (cap+4) v.length A dest + (fun j ↦ PortRankRAM.result R f (Fin.ofNat _ j) cap) f rs + keys : let f := after (after (after (after m (eventLog cs)) (eventLog ls)) (eventLog gs)) (eventLog rs) + ∀ e : OldArc X.Base a g, f ((p 10).val+(arcs e).val) = + Fin.ofNat _ (keyAt X.baseIndex (bothThick X.slots X.baseIndex e) e) + frame : ∀ addr, + (∀ (t : Fin 2) (i : Word w), i.val < A → addr ≠ outAddr p t i) → + OutsidePreimageWrites q addr → addr < out.val → addr < dest.val → + after (after (after (after m (eventLog cs)) (eventLog ls)) (eventLog gs)) (eventLog rs) addr = m addr + cost : RAMBuckets.cost Report.probes cs + RAMBuckets.cost Report.probes ls + + RAMBuckets.cost Report.probes gs + RAMBuckets.cost Report.probes rs = (cap+23)*A + +private theorem key_sizes (ha : A ≤ 2^w) : N*(2^J*(D*(2^C*D))) ≤ 2^w ∧ 2^C*D ≤ 2^w := by + have arith : A = N*(2^J*(D*(2^C*D)))*2^g := by + simp only [packingLaneBits, Shrink.J, Shrink.colors,pow_add]; ring + have h := (Nat.le_mul_of_pos_right (N*(2^J*(D*(2^C*D)))) (Nat.two_pow_pos g)).trans (arith ▸ ha) + have hN : 0 < N := Fintype.card_pos + exact ⟨h,((Nat.le_mul_of_pos_left _ (Nat.two_pow_pos a)).trans + ((Nat.le_mul_of_pos_left _ (Nat.two_pow_pos J)).trans (Nat.le_mul_of_pos_left _ hN))).trans h⟩ + +/-- All four native report sequences, their combined cost, and the final +`shrinkNumber`, `shrinkOrder` and width entries. -/ +theorem ranked_directory (shrPub : Fin 14 → Word w) (layout : Bool) (m : Memory w) + (inc : T.ActualColumns X m) (placement : ShrinkRAM.PlacementColumns X.slots X.baseIndex shrPub layout m) + (hp : Params p a C J g (numBundles N a g)) (reg : Regions p m A) + (hOut : p 5 = T.actualOut) (hThick : p 6 = shrPub 11) (hOwner : p 7 = shrPub 10) + (hAssigned : p 8 = shrPub 12) (qreg : RowRegions q) (hinput : q 1 = p 9) (hA : (q 0).val = A) + (hcount : (q 2).val = numBundles N a g + numBundles N a g) + (zero : ∀ u : Word w, u < q 2 → m (countAt q u).val = 0) + (apart : ∀ u : Word w, u < q 2 → ∀ t : Fin 2, ∀ i : Word w, i.val < A → + (countAt q u).val ≠ outAddr p t i) + (kreg : (K).Layout) (rreg : RankLayout q (p 10) out dest A (2*numBundles N a g)) + (keysOutside : ∀ j < A, OutsidePreimageWrites q ((p 10).val+j)) + (widthFits : T.width.val+A ≤ 2^w) + (widthClass : ∀ e : OldArc X.Base a g, ∀ t : Fin 2, ∀ i : Word w, i.val < A → + (T.width + Fin.ofNat _ (arcs e).val).val ≠ outAddr p t i) + (widthAppend : ∀ j < A, OutsidePreimageWrites q (T.width.val+j)) + (widthRank : separated T.width.val A dest.val A) : + ∃ cs ls gs rs, RankedDirectoryRun X T p q out dest m cs ls gs rs ∧ + let f := after (after (after (after m (eventLog cs)) (eventLog ls)) (eventLog gs)) (eventLog rs) + (∀ b (x : (P).MotifFiber b), f (dest.val+(arcs x.val.val).val) = Fin.ofNat _ (X.shrinkNumber b x).val) ∧ + (∀ b (x : (P).ThickFiber b), f (dest.val+(arcs x.val.val).val) = Fin.ofNat _ (X.shrinkOrder b x).val) ∧ + (∀ e : OldArc X.Base a g, f (T.width.val+(arcs e).val) = Fin.ofNat _ (X.packingWidth e)) ∧ + ∀ e : OldArc X.Base a g, f ((q 1).val+(arcs e).val) = + Fin.ofNat _ (BundleLists.bucketIndex sites (BundleLists.bucketOf P e)).val := by + classical + obtain ⟨cs,ls,hc,hl,scan,cls,pre,frame,_,cost⟩ := classify_and_collect X T p shrPub layout m inc + placement hp reg hOut hThick hOwner hAssigned q qreg hinput hA hcount kreg.motifFits zero apart + let classMem := after m (eventLog cs) + let lists := after classMem (eventLog ls) + obtain ⟨fitM,fitT⟩ := key_sizes X reg.fits + have lookup (e : OldArc X.Base a g) : + lists ((p 10).val+(arcs e).val) = classMem (p 10+Fin.ofNat _ (arcs e).val).val := by + have fit := kreg.keysFit + change (p 10).val+A ≤ 2^w at fit + rw [Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt (by have := (arcs e).isLt; omega)] + exact frame _ (keysOutside _ (arcs e).isLt) + have hkM (x : (P).Motif) : lists ((p 10).val+(arcs x.val).val) = + (motifKey P X.baseIndex (bitWordFinEquiv J) x).castLE fitM := by + rw [lookup]; exact Fin.ext (cls.motif_key X.slots X.baseIndex x) + have hkT (x : (P).ThickWire) : lists ((p 10).val+(arcs x.val).val) = (thickKey P x).castLE fitT := by + rw [lookup]; exact Fin.ext (cls.thick_key X.slots X.baseIndex x.val.1 ⟨x,rfl⟩) + obtain ⟨gs,rs,hg,done,rank,read,total⟩ := fixed_ranked_table P arcs sites q (p 10) out T.width dest + (State.two_le_packingColors a) X.baseIndex (bitWordFinEquiv J) fitM fitT kreg rreg qreg hA hcount lists pre hkM hkT + have count : Fixed.entryCount K = A := by + change numBundles N a g * (2^C*D/4+cap) = _ + rw [Nat.mul_add]; exact bundle_rows_total N a g + have gathered : runSegment ((template Fixed.visit 0).instantiate w (Fixed.parameters K)).program 29 + (some 0) lists (List.replicate A []) = some gs := count ▸ hg.executed + have gatherCursor : endState (some 0) gs = some (Fin.ofNat _ A) := count ▸ hg.cursor + refine ⟨cs,ls,gs,rs,⟨hc,hl,pre,gathered,gatherCursor,hg.work,rank,fun e ↦ ?_,?_,?_⟩,read.motif,read.thick,fun e ↦ ?_,fun e ↦ ?_⟩ + · have hi := (arcs e).isLt + have keep := rank.frame _ (rreg.keys.outside hi) + have keep' := (done.inputs K kreg (le_refl _)).2.1 _ hi + refine keep.trans (keep'.trans ((lookup e).trans ?_)) + exact Fin.ext ((cls.key e).trans (Nat.mod_eq_of_lt ((cls.key e) ▸ (classMem _).isLt)).symm) + · intro addr outside hrows hkeys hdest + exact (rank.frame addr (.inl hdest)).trans ((done.outside K kreg (le_refl _) addr (.inl hkeys)).trans + ((frame addr hrows).trans (scan.preserve addr (fun t i _ hi ↦ outside t i (by simpa only [Nat.zero_add] using hi))))) + · rw [cost,Nat.add_assoc,total,← Nat.add_mul]; congr 1; unfold Shrink.colors; omega + · let j := (arcs e).val + have keep := rank.frame (T.width.val+j) (widthRank.outside (arcs e).isLt) + have keep' := (done.inputs K kreg (le_refl _)).2.2 j (arcs e).isLt + have ht := scan.width_at X T inc widthClass e + rw [Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt (by have := (arcs e).isLt; omega)] at ht + exact keep.trans (keep'.trans ((frame _ (widthAppend j (arcs e).isLt)).trans ht)) + + · let i := Fin.ofNat (2^w) (arcs e).val + have hi := (arcs e).isLt + have hv : i.val = (arcs e).val := Nat.mod_eq_of_lt (hi.trans_le reg.fits) + have hown := pre.owners i (show i.val < (q 0).val by rw [hv,hA]; exact hi) + have hb : numBundles N a g+numBundles N a g ≤ 2^w := hcount ▸ (q 2).isLt.le + rw [BundleLists.wordOwner_at P arcs sites reg.fits hb e] at hown + have hfit := qreg.ownersBeforeCounts + change lists (q 1+i).val = _ at hown + rw [Fin.val_add,hv,Nat.mod_eq_of_lt (by have := (q 3).isLt; omega)] at hown + exact (rank.frame _ (rreg.owners.outside hi)).trans + ((done.outside K kreg (le_refl _) _ (rreg.keepOwners.outside hi)).trans hown) + +end CompressorRecords.BundleRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsRowRecipe.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsRowRecipe.lean new file mode 100644 index 0000000000..afcbf4b948 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsRowRecipe.lean @@ -0,0 +1,380 @@ +import OAI.Computability.VPVNP.CompressorRecordGreedyInit +import OAI.Computability.VPVNP.LiveOneShot +import Mathlib.Tactic.Ring + +/-! +# Computing a compressor worker row from a live level header + +A recipe is a finite straight-line word program. It may read a public word, +the current level pointer carried in persistent state, or external memory +through any computed address. Its assignments finish before it writes the +destination row, so its values describe the input memory even when a row +overlaps cells used to compute it. Two additional registers hold the output +cursor and the constant one. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RowRecipe + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {r k g w : ℕ} + +/-- Read-only assignments in the straight-line source program. The native +two-bit immediates may be combined by arithmetic to build larger constants. -/ +inductive RHS (r k : ℕ) where + | literal (v : Word 2) + | publicWord (i : Fin k) + | state + | copy (src : Fin r) + | binary (op : BinaryOp) (lhs rhs : Fin r) + | read (address : Fin r) + +/-- One straight-line planner instruction that evaluates a read-only right-hand side and stores +its word in a specified register. -/ +structure Assign (r k : ℕ) where + /-- Register overwritten by this assignment before the next recipe line executes. -/ + dst : Fin r + /-- Read-only operation that supplies the word assigned to the destination register. -/ + rhs : RHS r k + +/-- Compute an assignment's word from the public operands, persistent state, external memory +and current registers. -/ +def RHS.value (pub : Fin k → Word w) (s : Word w) (m : Memory w) (rs : Regs w r) : + RHS r k → Word w + | .literal v => Fin.ofNat _ v.val + | .publicWord i => pub i + | .state => s + | .copy src => rs src + | .binary op a b => op.eval (rs a) (rs b) + | .read a => m (rs a).val + +/-- The assignment's trace event, a memory read carrying its address and observed word for a +load, or one private tick for another operation. -/ +def RHS.event (m : Memory w) (rs : Regs w r) : RHS r k → Event w + | .read a => .read (rs a) (m (rs a).val) + | _ => .tick + +/-- Number of external reads charged for one right-hand side, one for a memory load and zero +for all register operations and inputs. -/ +def RHS.reads : RHS r k → ℕ + | .read _ => 1 + | _ => 0 + +/-- Execute the assignments in order against the same entry memory, returning the chronological +events and the final register values. -/ +def evaluate (pub : Fin k → Word w) (s : Word w) (m : Memory w) : + List (Assign r k) → Regs w r → List (Event w) × Regs w r + | [], rs => ([],rs) + | a :: rest, rs => + let next := evaluate pub s m rest (Function.update rs a.dst (a.rhs.value pub s m rs)) + (a.rhs.event m rs :: next.1, next.2) + +/-- The selected registers specify both the destination and the full padded row. -/ +structure Recipe (r k g : ℕ) where + /-- Straight-line assignments that compute the destination address and field values before + any directory word is written. -/ + lines : List (Assign r k) + /-- Register containing the address at which to write the first word of the directory row. -/ + dest : Fin r + /-- Register containing the stage tag that selects the worker for this row. -/ + tag : Fin r + /-- Register containing the cursor passed to the worker on its first call. -/ + start : Fin r + /-- Register containing the exclusive stopping cursor for the worker's scan. -/ + stop : Fin r + /-- Registers containing the worker's parameter words in their padded directory order. -/ + params : Fin g → Fin r + +/-- Output registers in the order their contents are stored, starting with the tag and both +cursor bounds and ending with the parameter bank. -/ +def Recipe.fields (R : Recipe r k g) := R.tag :: R.start :: R.stop :: List.ofFn R.params + +/-- The register file obtained by running the recipe's assignments from zeroed registers on the +supplied public words, state and entry memory. -/ +def Recipe.values (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) := + (evaluate pub s m R.lines (fun _ ↦ 0)).2 + +/-- The computed destination address read from the final register file before row storage +begins. -/ +def Recipe.address (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) := + R.values pub s m R.dest + +/-- The words written to the directory, read from the final registers in tag, start, stop and +parameter order. -/ +def Recipe.words (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) := + R.fields.map (R.values pub s m) + +private def low (i : Fin r) := i.castAdd 2 +private def ptr (r : ℕ) := (0 : Fin 2).natAdd r +private def one (r : ℕ) := (1 : Fin 2).natAdd r + +private def Assign.code (a : Assign r k) : Op (r+2) k := match a.rhs with + | .literal v => .constant (low a.dst) v + | .publicWord i => .publicWord (low a.dst) i + | .state => .stateWord (low a.dst) + | .copy i => .copy (low a.dst) (low i) + | .binary op i j => .binary op (low a.dst) (low i) (low j) + | .read i => .read (low a.dst) (low i) + +private def storeCode (i : Fin r) : List (Op (r+2) k) := + [.write (ptr r) (low i), .binary .add (ptr r) (ptr r) (one r)] + +/-- Compile the assignments, write the fields to consecutive cells, and put the incoming state +plus one in the return register. -/ +def Recipe.code (R : Recipe r k g) : List (Op (r+2) k) := + R.lines.map Assign.code ++ ([.copy (ptr r) (low R.dest), .constant (one r) 1] ++ + (R.fields.flatMap storeCode ++ [.stateWord (ptr r), .binary .add (ptr r) (ptr r) (one r)])) + +/-- Native instruction template for publishing one recipe row and returning the advanced state. -/ +def Recipe.table (R : Recipe r k g) := template R.code (ptr r) + +private def storeLog (dest : Word w) : List (Word w) → List (Event w) + | [] => [] + | v :: vs => .write dest v :: .tick :: storeLog (dest+1) vs + +/-- Trace of the recipe's assignment events, pointer setup, consecutive row writes and state +advance, with return value `s + 1`. -/ +def Recipe.report (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) : Report w := + ⟨(evaluate pub s m R.lines (fun _ ↦ 0)).1 ++ [.tick,.tick] ++ + storeLog (R.address pub s m) (R.words pub s m) ++ [.tick,.tick],some (s+1)⟩ + +/-- Total external reads performed by the computation lines before the row is written, counting +repeated loads separately. -/ +def Recipe.reads (R : Recipe r k g) : ℕ := (R.lines.map fun a ↦ a.rhs.reads).sum + +private theorem update_left {a b : ℕ} {α : Type*} (l : Fin a → α) (h : Fin b → α) + (i : Fin a) (v : α) : + Function.update (Fin.append l h) (i.castAdd b) v = Fin.append (Function.update l i v) h := by + funext t + cases t using Fin.addCases with + | left j => by_cases e : j = i <;> simp [Function.update, e] + | right j => + have e : j.natAdd a ≠ i.castAdd b := fun eqn ↦ by have := congrArg Fin.val eqn; simp at this; omega + simp [Function.update_of_ne e] + +private theorem update_right {a b : ℕ} {α : Type*} (l : Fin a → α) (h : Fin b → α) + (i : Fin b) (v : α) : + Function.update (Fin.append l h) (i.natAdd a) v = Fin.append l (Function.update h i v) := by + funext t + cases t using Fin.addCases with + | left j => + have e : j.castAdd b ≠ i.natAdd a := fun eqn ↦ by have := congrArg Fin.val eqn; simp at this; omega + simp [Function.update_of_ne e] + | right j => by_cases e : j = i <;> simp [Function.update, e] + +private theorem assign_effect (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (rs : Regs w r) (aux : Fin 2 → Word w) (a : Assign r k) : + a.code.effect pub s (Fin.append rs aux) m = some (a.rhs.event m rs, + Fin.append (Function.update rs a.dst (a.rhs.value pub s m rs)) aux, m) := by + obtain ⟨i,x⟩ := a + cases x <;> simp [Assign.code, RHS.value, RHS.event, Op.effect, low, update_left] + +private theorem lines_trace (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (ls : List (Assign r k)) (rs : Regs w r) (aux : Fin 2 → Word w) : + let out := evaluate pub s m ls rs + trace pub s (ls.map Assign.code) (Fin.append rs aux) m = some (out.1,Fin.append out.2 aux,m) := by + induction ls generalizing rs with + | nil => rfl + | cons a ls ih => simp [trace, assign_effect, ih, evaluate] + +private theorem store_trace (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (rs : Regs w r) (aux : Fin 2 → Word w) (h : aux 1 = 1) (fields : List (Fin r)) : + let words := fields.map rs + ∃ last : Fin 2 → Word w, last 1 = 1 ∧ + trace pub s (fields.flatMap storeCode) (Fin.append rs aux) m = + some (storeLog (aux 0) words,Fin.append rs last,Greedy.writeRow m (aux 0) words) := by + induction fields generalizing m aux with + | nil => exact ⟨aux,h,rfl⟩ + | cons i rest ih => + let aux' := Function.update aux 0 (aux 0+1) + have h' : aux' 1 = 1 := by simpa (config := {decide := true}) [aux'] + obtain ⟨last,hl,ht⟩ := ih (writeMemory m (aux 0) (rs i)) aux' h' + refine ⟨last,hl,?_⟩ + simp [storeCode, trace, Op.effect, ptr, low, one, update_right, BinaryOp.eval, h, ← show + Function.update aux 0 (aux 0+1) = aux' by rfl, ht, storeLog, Greedy.writeRow, aux'] + +private theorem zeros : (fun _ : Fin (r+2) ↦ (0 : Word w)) = + Fin.append (fun _ : Fin r ↦ 0) (fun _ : Fin 2 ↦ 0) := by + funext i; cases i using Fin.addCases <;> simp + +private theorem row_trace (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) : + ∃ out, trace pub s R.code (fun _ ↦ 0) m = some ((R.report pub s m).events,out, + Greedy.writeRow m (R.address pub s m) (R.words pub s m)) ∧ out (ptr r) = s+1 := by + let rs := R.values pub s m + let aux : Fin 2 → Word w := Function.update (Function.update (fun _ ↦ 0) 0 (rs R.dest)) 1 1 + have h : aux 1 = 1 := by simp [aux] + obtain ⟨last,hl,ht⟩ := store_trace pub s m rs aux h R.fields + unfold Recipe.code + rw [zeros, trace_append, lines_trace] + dsimp only [Option.bind_some] + change ∃ _, ((trace pub s _ (Fin.append rs _) m).map _) = _ ∧ _ + simp only [List.cons_append, List.nil_append, trace, Op.effect, ptr, low, one, Fin.append_left, + update_right, bind, Option.bind_some] + have lit : Fin.ofNat (2^w) (1 : Word 2).val = (1 : Word w) := by apply Fin.ext; rfl + rw [lit, trace_append, ht] + simp [trace, Op.effect, BinaryOp.eval, Fin.append_right, update_right, hl, + Recipe.report, Recipe.address, Recipe.words, rs, aux, List.append_assoc] + +private theorem eval_cost (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (ls : List (Assign r k)) (rs : Regs w r) : + (evaluate pub s m ls rs).1.length = ls.length ∧ + countProbes (evaluate pub s m ls rs).1 = (ls.map fun a ↦ a.rhs.reads).sum := by + induction ls generalizing rs with + | nil => exact ⟨rfl,rfl⟩ + | cons a ls ih => + obtain ⟨hl,hp⟩ := ih (Function.update rs a.dst (a.rhs.value pub s m rs)) + cases a with + | mk dst rhs => + cases rhs <;> simp [evaluate, RHS.event, RHS.reads, hl, hp, countProbes] + +private theorem store_cost (dest : Word w) (vs : List (Word w)) : + (storeLog dest vs).length = 2*vs.length ∧ countProbes (storeLog dest vs) = vs.length := by + induction vs generalizing dest with + | nil => exact ⟨rfl,rfl⟩ + | cons x xs ih => + obtain ⟨hl,hp⟩ := ih (dest+1) + simp [storeLog, countProbes, hl, hp, Nat.add_comm] + omega + +theorem fields_length (R : Recipe r k g) : R.fields.length = g+3 := by simp [Recipe.fields] + +private theorem storeCode_length (fs : List (Fin r)) : + (fs.flatMap (storeCode (k := k))).length = 2*fs.length := by + induction fs with + | nil => rfl + | cons x xs ih => simp [storeCode, ih, Nat.mul_succ] + +theorem code_length (R : Recipe r k g) : R.code.length = R.lines.length + 2*(g+3)+4 := by + simp only [Recipe.code, List.length_append, List.length_map, storeCode_length, fields_length, + List.length_cons, List.length_nil] + omega + +/-- Exact native execution, including the rejection of every nonempty branch stream. -/ +theorem execute_row (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (bits : List Bool) (cap : ℕ) (budget : R.code.length < cap) : + let M := R.table.instantiate w pub + execute M.program cap (M.program.start s) m bits = + if bits = [] then some (R.report pub s m) else none := by + obtain ⟨f,rfl⟩ : ∃ f, cap = (f+1) + R.code.length := ⟨cap-(1+R.code.length),by omega⟩ + let M := (template R.code (ptr r)).instantiate w pub + let bad : Fin (R.code.length+2) := ⟨R.code.length+1,by omega⟩ + let stop : Fin (R.code.length+2) := ⟨R.code.length,by omega⟩ + have hb : M.code bad = .reject := by + simp [M, bad, template, Template.instantiate, Instr.resize, show ¬R.code.length+1 < R.code.length by omega] + have hs : M.code stop = .returnState (ptr r) := by simp [M, stop, template, Template.instantiate, Instr.resize] + have step := (template_contains R.code (ptr r) pub).execute hb s (fun _ ↦ 0) (fun _ ↦ 0) m bits (f+1) + obtain ⟨out,ht,hv⟩ := row_trace R pub s m + change execute M.program _ ⟨⟨0,by omega⟩,s,fun _ ↦ 0,fun _ ↦ 0⟩ m bits = _ + rw [step, run_eq_trace] + change (trace pub s R.code (fun _ ↦ 0) m).bind _ = _ + rw [ht] + change (execute M.program (f+1) ⟨stop,s,out,fun _ ↦ 0⟩ _ bits).map _ = _ + by_cases h : bits = [] <;> simp [execute, Machine.program, hs, Instr.run, h, hv, Recipe.report] + +/-- One-shot version of the row publisher that accepts after the row is stored so the linked +launcher can take control. -/ +def Recipe.acceptTable (R : Recipe r k g) := LiveOneShot.oneShot R.table + +/-- Single-row planners transfer to a statically linked launch stage on acceptance. -/ +theorem execute_accept (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (bits : List Bool) (cap : ℕ) (budget : R.code.length < cap) : + let M := R.acceptTable.instantiate w pub + execute M.program cap (M.program.start s) m bits = + if bits = [] then some ⟨(R.report pub s m).events,none⟩ else none := by + dsimp only [Recipe.acceptTable] + rw [LiveOneShot.execute_oneShot] + change (execute (R.table.instantiate w pub).program cap ((R.table.instantiate w pub).program.start s) + m bits).map _ = _ + rw [execute_row R pub s m bits cap budget] + split <;> rfl + +theorem report_cost (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) : + (R.report pub s m).events.length = R.lines.length + 2*(g+3)+4 ∧ + (R.report pub s m).probes = R.reads+(g+3) ∧ choiceBits (R.report pub s m).events = [] := by + have he := execute_row R pub s m [] (R.code.length+1) (by omega) + have hchoice := (execute_spec (show execute _ _ _ _ [] = some (R.report pub s m) from he)).2.2 + obtain ⟨hl,hp⟩ := eval_cost pub s m R.lines (fun _ ↦ 0) + obtain ⟨wl,wp⟩ := store_cost (R.address pub s m) (R.words pub s m) + have wh : (R.words pub s m).length = g+3 := by simp [Recipe.words, fields_length] + refine ⟨?_,?_,hchoice⟩ + · simp only [Recipe.report, List.length_append, wl, wh, hl, List.length_cons, List.length_nil] + omega + · simp [Recipe.report, Report.probes, Greedy.probes_append, countProbes, wp, wh, hp, Recipe.reads] + +theorem after_row (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) : + after m (R.report pub s m).events = Greedy.writeRow m (R.address pub s m) (R.words pub s m) := by + obtain ⟨out,ht,_⟩ := row_trace R pub s m + exact Greedy.trace_after ht + +/-- Every field is computed from entry memory. No disjointness between metadata +and the destination row is needed to install the result. -/ +theorem row_stores (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (fit : (R.address pub s m).val + (g+3) ≤ 2^w) : + Greedy.Stores (after m (R.report pub s m).events) (R.address pub s m) (R.words pub s m) := by + rw [after_row] + exact Greedy.writeRow_stores _ _ _ (by simpa [Recipe.words, fields_length] using fit) + +theorem row_outside (R : Recipe r k g) (pub : Fin k → Word w) (s : Word w) (m : Memory w) + (fit : (R.address pub s m).val + (g+3) ≤ 2^w) (a : ℕ) + (free : a < (R.address pub s m).val ∨ (R.address pub s m).val + (g+3) ≤ a) : + after m (R.report pub s m).events a = m a := by + rw [after_row] + exact Greedy.writeRow_outside _ _ _ _ + (by simpa [Recipe.words, fields_length] using fit) (by simpa [Recipe.words, fields_length] using free) + +/-- The four consecutive live level-header words are the vertex count, degree, +replication factor, and directory row ordinal. Public word zero is the directory +base. The emitted row for tag one starts at zero and stops at the slot count. -/ +def sizeRecipe : Recipe 11 1 2 where + lines := + [⟨0,.state⟩, ⟨1,.literal 1⟩, ⟨2,.read 0⟩, ⟨0,.binary .add 0 1⟩, ⟨3,.read 0⟩, + ⟨0,.binary .add 0 1⟩, ⟨4,.read 0⟩, ⟨0,.binary .add 0 1⟩, ⟨5,.read 0⟩, + ⟨6,.binary .mul 2 3⟩, ⟨6,.binary .mul 6 4⟩, ⟨7,.binary .mul 6 3⟩, ⟨8,.publicWord 0⟩, + ⟨9,.literal 2⟩, ⟨10,.literal 3⟩, ⟨9,.binary .add 9 10⟩, ⟨9,.binary .mul 5 9⟩, + ⟨8,.binary .add 8 9⟩, ⟨10,.literal 0⟩] + dest := 8 + tag := 1 + start := 10 + stop := 7 + params := ![6,3] + +theorem sizeRecipe_values (pub : Fin 1 → Word w) (s : Word w) (m : Memory w) : + let V := m s.val + let D := m (s+1).val + let R := m (s+2).val + let B := V*D*R + let S := B*D + sizeRecipe.address pub s m = pub 0 + m (s+3).val * 5 ∧ + sizeRecipe.words pub s m = [1,0,S,B,D] := by + have two : (s+1+1 : Word w) = s+2 := by rw [add_assoc, one_add_one_eq_two] + have three : (s+2+1 : Word w) = s+3 := by ring + have five : (2+3 : Word w) = 5 := by ring + simp (config := {decide := true}) [Recipe.address, Recipe.words, Recipe.fields, Recipe.values, + sizeRecipe, evaluate, RHS.value, BinaryOp.eval, two, three, five] + +/-- Native construction of the slot-scan row using four metadata reads and five +writes. The row's stop and operands are evaluated from the original header. -/ +theorem sizeRecipe_row (pub : Fin 1 → Word w) (s : Word w) (m : Memory w) + (fit : (pub 0 + m (s+3).val * 5).val + 5 ≤ 2^w) : + let M := sizeRecipe.acceptTable.instantiate w pub + let B := m s.val * m (s+1).val * m (s+2).val + let es := (sizeRecipe.report pub s m).events + execute M.program 34 (M.program.start s) m [] = some ⟨es,none⟩ ∧ + Greedy.Stores (after m es) (pub 0 + m (s+3).val*5) [1,0,B*m (s+1).val,B,m (s+1).val] ∧ + countProbes es = 9 := by + obtain ⟨ha,hw⟩ := sizeRecipe_values pub s m + refine ⟨execute_accept sizeRecipe pub s m [] 34 (by decide), ?_, ?_⟩ + · rw [← ha, ← hw] + exact row_stores _ _ _ _ (by simpa only [ha] using fit) + · exact (report_cost sizeRecipe pub s m).2.1 + +end CompressorRecords.RowRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsSchedule.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsSchedule.lean new file mode 100644 index 0000000000..2f7b444f41 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsSchedule.lean @@ -0,0 +1,429 @@ +import OAI.Computability.VPVNP.CompressorRecordFrame +import OAI.Computability.VPVNP.LiveHeaderBoundedRun +import OAI.Computability.VPVNP.LiveStageLinkPaths +import OAI.Computability.VPVNP.CompressorRecordsCursorScan +import OAI.Computability.VPVNP.CompressorRecordRefreshRAM + +/-! +# A fixed dispatcher for the compressor descriptor passes + +The controller occupies tag zero. A worker has a finite native table and +its own public parameter format. On each worker call the active frame +supplies an exclusive cursor bound followed by the parameters. At the +bound the stage linker writes tag zero and returns to the controller. Thus +level counts and pass repetitions change memory and cursors while the +dispatcher table is fixed. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule + +open BurstRAM BurstRAM.PrivateRAM +open scoped Fin.CommRing + +/-- A worker with its actual finite register and parameter arities. -/ +structure Pass where + /-- Number of instruction labels in the pass’s native RAM table. -/ + pcs : ℕ + /-- Number of private registers available to instructions in this pass. -/ + regs : ℕ + /-- Number of public operand words expected by the native pass. A scheduled call loads these + words from the active frame after the stop word. -/ + params : ℕ + /-- The pass’s native instruction table, indexed by its own instruction labels, private + registers, and public operands. -/ + table : Template pcs regs params + +/-- An indexed family of native passes. The dispatcher assigns the pass at index `i` to tag `i ++ 1` and reserves tag zero for the controller. -/ +abbrev Catalog (d : ℕ) := Fin d → Pass + +/-- Native pass that writes six cursor-incidence entries for one outgoing port and returns the +next port index in register zero. -/ +def cursorPass : Pass := ⟨_,_,_,PrimedStackRAM.template CursorRAM.visit 0⟩ +/-- Native pass that writes a segment’s outgoing and incoming offsets and incoming width, +updates the bundle total, and returns the next segment index. -/ +def refreshPass : Pass := ⟨_,_,_,PrimedStackRAM.template RefreshRAM.visit 0⟩ + +/-- Small concrete catalog used to link the initial cursor and refresh scans. -/ +def cursorRefresh : Catalog 2 := ![cursorPass,refreshPass] + +/-- Maximum number of public operands among the catalog’s passes, or zero for an empty catalog. +This fixes the width of the directory’s parameter bank. -/ +def arity {d : ℕ} (C : Catalog d) : ℕ := Finset.univ.sup fun i ↦ (C i).params + +theorem params_le_arity {d : ℕ} (C : Catalog d) (i : Fin d) : (C i).params ≤ arity C := + Finset.le_sup (f := fun j ↦ (C j).params) (Finset.mem_univ i) + +variable {w d p r : ℕ} + +/-- The bounded-table library numbers its exclusive stop last. A directory +frame places it first, followed by the worker's original public words. -/ +private def field {k : ℕ} : Fin (k+1) → Fin (k+1) := Fin.lastCases 0 Fin.succ + +private def guarded (P : Pass) := + LiveStageLink.widen (LiveHeaderBounded.bounded P.table) (Function.Embedding.refl _) field + +/-- Wrap a native pass in a frame loader and a cursor guard. Its sole public word points to the +frame, whose first word is the exclusive stop and whose remaining words supply the pass +operands. -/ +def worker (P : Pass) : Pass := ⟨_,_,_,Frame.compile (guarded P)⟩ + +/-- Limit and original public words in the order seen by the running worker. -/ +def stopWord (base : Word w) (m : Memory w) : Word w := m base.val + +/-- Read native operand `j` at active-frame offset `j + 1`, immediately after the exclusive +stop stored at offset zero. -/ +def parameters {k : ℕ} (base : Word w) (m : Memory w) (j : Fin k) : Word w := + Frame.data base m (j.succ : Fin (k+1)) + +private theorem fields_correct (P : Pass) (base : Word w) (m : Memory w) : + (Frame.data base m : Fin (P.params+1) → Word w) ∘ field = + LiveHeaderBounded.publicData (parameters base m) (stopWord base m) := by + funext i + cases i using Fin.lastCases with + | last => simp [field, Frame.data, stopWord, LiveHeaderBounded.publicData ] + | cast j => simp [field, parameters, LiveHeaderBounded.publicData ] + +/-- Report for an active worker call. The frame loads and three cursor-guard ticks precede the +native pass events, and the call returns the native result. -/ +def workerReport (P : Pass) (base : Word w) (m : Memory w) (rep : Report w) : Report w := + LiveStageLink.prependLog (Frame.loadEvents base m 0 (P.params+1)) + (LiveHeaderBounded.activeReport rep) + +private theorem execute_guarded (P : Pass) (base state : Word w) (m : Memory w) (bits : List Bool) + (f : ℕ) : + let S := ((guarded P).instantiate w (Frame.data base m)).program + let B := (LiveHeaderBounded.machine P.table (parameters base m) (stopWord base m)).program + execute S f (S.start state) m bits = execute B f (B.start state) m bits := by + dsimp only + rw [show guarded P = LiveStageLink.widen (LiveHeaderBounded.bounded P.table) + (Function.Embedding.refl _) field from rfl, LiveStageLink.execute_widen_start, fields_correct] + +theorem execute_worker (P : Pass) (base state : Word w) (m : Memory w) (bits : List Bool) + (hlt : state < stopWord base m) (fuel : ℕ) : + let W := ((worker P).table.instantiate w (fun _ ↦ base)).program + let S := (P.table.instantiate w (parameters base m)).program + execute W (fuel+3+4*(P.params+1)) (W.start state) m bits = + (execute S fuel (S.start state) m bits).map (workerReport P base m) := by + dsimp only + change execute (Frame.machine (guarded P) base).program _ ((Frame.machine (guarded P) + base).program.start state) m bits = _ + rw [Frame.execute_frame (guarded P) base state (fuel+3) m bits, execute_guarded, + LiveHeaderBounded.execute_active P.table (parameters base m) (stopWord base m) fuel state hlt, + Option.map_map] + rfl + +private def stopReport (P : Pass) (base : Word w) (m : Memory w) := + LiveStageLink.prependLog (Frame.loadEvents base m 0 (P.params+1)) + (LiveHeaderBounded.closedReport w) + +theorem execute_worker_stop (P : Pass) (base state : Word w) (m : Memory w) (bits : List Bool) + (hle : stopWord base m ≤ state) (extra : ℕ) : + let W := ((worker P).table.instantiate w (fun _ ↦ base)).program + execute W (extra+4+4*(P.params+1)) (W.start state) m bits = + if bits = [] then some (stopReport P base m) else none := by + dsimp only + change execute (Frame.machine (guarded P) base).program _ ((Frame.machine (guarded P) + base).program.start state) m bits = _ + rw [Frame.execute_frame (guarded P) base state (extra+4) m bits, execute_guarded, + LiveHeaderBounded.execute_closed P.table (parameters base m) (stopWord base m) extra state hle] + cases bits <;> rfl + +/-- Shared public words of the enclosing stage linker. The internal tag is +separate from the enclosing live program's stage tag. -/ +structure Ports (w : ℕ) where + /-- Base address of the active worker frame, which stores the exclusive cursor bound followed + by the worker’s public operands. -/ + activeFrame : Word w + /-- Base address of the descriptor directory from which the controller loads each scheduled + row. -/ + directory : Word w + /-- Address of the control cell holding the index of the next directory row to launch. -/ + ordinal : Word w + /-- Address of the cell holding the directory row count. The controller finishes when the + ordinal reaches this count. -/ + rows : Word w + /-- Address of the internal dispatch tag. Zero selects the controller and tag `i + 1` selects + worker `i`. -/ + tag : Word w + +/-- The five shared public words in operand order are the active-frame base, directory base, +ordinal address, row-count address, and dispatch-tag address. -/ +def Ports.data (ports : Ports w) : Fin 5 → Word w := + ![ports.activeFrame,ports.directory,ports.ordinal,ports.rows,ports.tag] + +/-- A stage is widened only after its operand format and optional frame loader +have been chosen. This keeps the original worker register budgets independent. -/ +structure Slot extends Pass where + /-- Selects the shared public word for each operand of the slot. The controller uses all five + words in order, and a framed worker uses only the active-frame base. -/ + publicIndex : Fin params → Fin 5 + +private def workerSlot (P : Pass) : Slot := ⟨worker P, fun _ ↦ 0⟩ + +variable (C : Catalog d) (controller : Template p r 5) + +/-- Assign the controller to slot zero and the framed, guarded version of catalog pass `i` to +slot `i + 1`. -/ +def slots : Fin (d+1) → Slot := Fin.cons ⟨⟨p,r,5,controller⟩,id⟩ (fun i ↦ workerSlot (C i)) + +private def registerCount : ℕ := Finset.univ.sup fun s ↦ (slots C controller s).regs + +private def regEmbedding (s : Fin (d + 1)) : + Fin (slots C controller s).regs ↪ Fin (registerCount C controller) := + Fin.castLEEmb (Finset.le_sup (f := fun t ↦ (slots C controller t).regs) (Finset.mem_univ s)) + +/-- Widen a slot’s native table to the largest register count among all slots and map its +public operands into the dispatcher’s five shared words. -/ +def tables (s : Fin (d + 1)) : Template (slots C controller s).pcs (registerCount C controller) + 5 := + LiveStageLink.widen (slots C controller s).table (regEmbedding C controller s) + (slots C controller s).publicIndex + +/-- The controller explicitly writes the computed worker tag and returns +its initial cursor. An accepting worker transfers back to the controller. -/ +def handoff : Fin (d+1) → Option (Fin (d+1)) := Fin.cons none (fun _ ↦ some 0) + +/-- The linked dispatcher table for the controller and catalog workers. Accepting a worker +transfers control to slot zero, while accepting the controller finishes the schedule. -/ +def template := LiveStageLink.linked (tables C controller) handoff + +/-- Instantiate the linked dispatcher at word width `w` with the five port words and +`ports.tag` as the address from which the linker reads the active slot. -/ +def machine (ports : Ports w) := + LiveStageLink.machine (tables C controller) handoff ports.data ports.tag + +private theorem call_slot (ports : Ports w) (s : Fin (d + 1)) (state : Word w) (m : Memory w) + (htag : m ports.tag.val = LiveStageLink.tagWord w s) (fits : d + 1 ≤ 2 ^ w) + (bits : List Bool) {f cap : ℕ} (hcap : f + 2 * (d + 1) + 5 ≤ cap) {rep : Report w} + (hsource : let S := ((slots C controller s).table.instantiate w (ports.data ∘ + (slots C controller s).publicIndex)).program + execute S f (S.start state) m bits = some rep) : + let D := (machine C controller ports).program + execute D cap (D.start state) m bits = some (LiveStageLink.linkedReport handoff ports.tag s + rep) := by + apply LiveStageLink.execute_linked_of_stage _ _ _ _ s fits hcap _ _ htag bits rep + rw [tables, LiveStageLink.execute_widen_start] + exact hsource + +/-- One successful call of a source worker inside the actual finite +descriptor dispatcher. Its incoming tag and guard are read from RAM. -/ +theorem worker_active (ports : Ports w) (i : Fin d) (state : Word w) (m : Memory w) + (bits : List Bool) + (htag : m ports.tag.val = LiveStageLink.tagWord w i.succ) (fits : d + 1 ≤ 2 ^ w) + (hlt : state < stopWord ports.activeFrame m) {f cap : ℕ} + (hcap : f + 3 + 4 * ((C i).params + 1) + 2 * (d + 1) + 5 ≤ cap) (rep : Report w) + (hsource : let S := ((C i).table.instantiate w (parameters ports.activeFrame m)).program + execute S f (S.start state) m bits = some rep) : + let D := (machine C controller ports).program + execute D cap (D.start state) m bits = some + (LiveStageLink.linkedReport handoff ports.tag i.succ (workerReport + (C i) ports.activeFrame m rep)) := by + apply call_slot C controller ports i.succ state m htag fits bits hcap + change execute (((worker (C i)).table.instantiate w (fun _ ↦ ports.activeFrame)).program) _ + (((worker (C i)).table.instantiate w (fun _ ↦ ports.activeFrame)).program.start state) m bits + = _ + rw [execute_worker _ _ _ _ _ hlt, hsource] + rfl + +/-- The single empty-choice call at the exclusive bound transfers back to +the controller, which can select another pass or the next level. -/ +theorem worker_stop (ports : Ports w) (i : Fin d) (state : Word w) (m : Memory w) + (htag : m ports.tag.val = LiveStageLink.tagWord w i.succ) (fits : d + 1 ≤ 2 ^ w) + (hle : stopWord ports.activeFrame m ≤ state) {cap : ℕ} (hcap : 4 + 4 * ((C i).params + 1) + + 2 * (d + 1) + 5 + ≤ cap) : + let D := (machine C controller ports).program + execute D cap (D.start state) m [] = some + (LiveStageLink.linkedReport handoff ports.tag i.succ (stopReport + (C i) ports.activeFrame m)) := by + apply call_slot C controller ports i.succ state m htag fits [] hcap + change execute (((worker (C i)).table.instantiate w (fun _ ↦ ports.activeFrame)).program) _ + (((worker (C i)).table.instantiate w (fun _ ↦ ports.activeFrame)).program.start state) m [] = _ + exact execute_worker_stop _ _ _ _ [] hle 0 + +/-- Any successful call of the controller is also a native call in the +descriptor dispatcher. The controller's accepting exit terminates the schedule. -/ +theorem controller_call (ports : Ports w) (state : Word w) (m : Memory w) (bits : List Bool) + (htag : m ports.tag.val = 0) (fits : d + 1 ≤ 2 ^ w) {f cap : ℕ} (hcap : f + 2 * + (d + 1) + 5 ≤ cap) + (rep : Report w) (hc : let S := (controller.instantiate w ports.data).program + execute S f (S.start state) m bits = some rep) : + let D := (machine C controller ports).program + execute D cap (D.start state) m bits = some + (LiveStageLink.linkedReport handoff ports.tag (0 : Fin (d+1)) rep) := + call_slot C controller ports 0 state m htag fits bits hcap hc + +/-- Tagged reports of active data calls and of the single closing call. -/ +def activeLinkedReport (i : Fin d) (ports : Ports w) (m : Memory w) (rep : Report w) : Report w := + LiveStageLink.linkedReport handoff ports.tag i.succ (workerReport (C i) ports.activeFrame m rep) + +/-- Report of the closing call at or beyond worker `i`’s exclusive bound. It reads the dispatch +tag and frame, writes tag zero, and returns cursor zero to the controller. -/ +def closedLinkedReport (i : Fin d) (ports : Ports w) (m : Memory w) : Report w := + LiveStageLink.linkedReport handoff ports.tag i.succ (stopReport (C i) ports.activeFrame m) + +theorem activeLinkedReport_effect (i : Fin d) (ports : Ports w) (m : Memory w) (rep : Report w) + {st : Word w} (h : rep.result = some st) : + let out := activeLinkedReport C i ports m rep + out.result = some st ∧ after m out.events = after m rep.events ∧ + choiceBits out.events = choiceBits rep.events ∧ out.probes = rep.probes + + (C i).params + 2 := by + let q := workerReport (C i) ports.activeFrame m rep + have cost := Frame.frame_cost ports.activeFrame m 0 ((C i).params+1) + (LiveHeaderBounded.activeReport rep) + have hq : q.result = some st := h + dsimp only + change (LiveStageLink.linkedReport handoff ports.tag i.succ q).result = _ ∧ _ + refine ⟨?_, ?_, ?_, ?_⟩ + · simp [LiveStageLink.linkedReport, LiveStageLink.prependLog, LiveStageLink.exitReport, hq] + · rw [activeLinkedReport, LiveStageLink.linkedReport_after] + rw [show workerReport (C i) ports.activeFrame m rep = q from rfl, hq] + exact cost.2.2.2.1 + · rw [activeLinkedReport, LiveStageLink.linkedReport_choiceBits] + exact cost.2.2.1 + · rw [activeLinkedReport, LiveStageLink.linkedReport_probes] + change q.probes+1+(if q.result = none ∧ _ then 1 else 0) = _ + rw [hq] + have hp : q.probes = (C i).params+1+rep.probes := cost.2.1 + simp [hp] + omega + +/-- Finishing a pass writes precisely the internal controller tag and returns +cursor zero. There are two tag probes plus one read per active-frame word. -/ +theorem closedLinkedReport_effect (i : Fin d) (ports : Ports w) (m : Memory w) : + let out := closedLinkedReport C i ports m + out.result = some 0 ∧ after m out.events = writeMemory m ports.tag 0 ∧ + choiceBits out.events = [] ∧ out.probes = (C i).params + 3 := by + let q := stopReport (C i) ports.activeFrame m + have cost := Frame.frame_cost ports.activeFrame m 0 ((C i).params+1) + (LiveHeaderBounded.closedReport w) + have hq : q.result = none := rfl + have hn : handoff i.succ = some (0 : Fin (d+1)) := Fin.cons_succ .. + dsimp only + refine ⟨?_,?_,?_,?_⟩ + · change (LiveStageLink.linkedReport handoff ports.tag i.succ q).result = _ + simp [LiveStageLink.linkedReport, LiveStageLink.prependLog, LiveStageLink.exitReport, hq, hn] + · rw [closedLinkedReport, LiveStageLink.linkedReport_after] + rw [show stopReport (C i) ports.activeFrame m = q from rfl, hq, hn] + have hm : after m q.events = m := cost.2.2.2.1 + change writeMemory (after m q.events) ports.tag (LiveStageLink.tagWord w (0 : Fin (d+1))) = _ + rw [hm] + rfl + · rw [closedLinkedReport, LiveStageLink.linkedReport_choiceBits] + exact cost.2.2.1 + · rw [closedLinkedReport, LiveStageLink.linkedReport_probes] + change q.probes+1+(if q.result = none ∧ _ then 1 else 0) = _ + rw [hq, hn] + have hp : q.probes = (C i).params+1+0 := cost.2.1 + simp [hp] + +/-- Active-frame and dispatcher cells that must survive an ordinary pass. -/ +def Ready (i : Fin d) (ports : Ports w) (pub : Fin (C i).params → Word w) (bound : Word w) + (m : Memory w) : Prop := + m ports.tag.val = LiveStageLink.tagWord w i.succ ∧ + stopWord ports.activeFrame m = bound ∧ parameters ports.activeFrame m = pub + +/-- Each source report is below the stop and returns a new cursor. At the +end the native guard observes the stop. This allows arbitrary cursor steps. -/ +def ValidTrace (i : Fin d) (ports : Ports w) (pub : Fin (C i).params → Word w) (bound : Word w) : + Word w → Memory w → List (Report w) → Prop + | st, m, [] => Ready C i ports pub bound m ∧ bound ≤ st + | st, m, rep :: rs => Ready C i ports pub bound m ∧ st < bound ∧ + ∃ next, rep.result = some next ∧ ValidTrace i ports pub bound next (after m rep.events) rs + +/-- Wrap each active source report in its dispatcher report in execution order. The frame for +each call is read from the memory left by the preceding source events. -/ +def linkedRows (i : Fin d) (ports : Ports w) : Memory w → List (Report w) → List (Report w) + | _, [] => [] + | m, r::rs => activeLinkedReport C i ports m r :: linkedRows i ports (after m r.events) rs + +/-- Exact total charge of the linked data calls in an active source trace. -/ +theorem linkedRows_cost (i : Fin d) (ports : Ports w) (pub : Fin (C i).params → Word w) + (bound st : Word w) (m : Memory w) (rs : List (Report w)) (hv : ValidTrace C i ports pub bound + st m rs) : + RAMBuckets.cost Report.probes (linkedRows C i ports m rs) = + RAMBuckets.cost Report.probes rs + rs.length*((C i).params+2) := by + induction rs generalizing m st with + | nil => simp [linkedRows, RAMBuckets.cost] + | cons r rs ih => + obtain ⟨_,_,next,hn,hv'⟩ := hv + rw [linkedRows, RAMBuckets.cost, RAMBuckets.cost, (activeLinkedReport_effect C i ports m r + hn).2.2.2, + ih next _ hv', List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +/-- Exact cost through the handoff, excluding the controller call that +prepared this row. A zero-length scan still executes its closing call. -/ +theorem linkedPass_cost (i : Fin d) (ports : Ports w) (pub : Fin (C i).params → Word w) + (bound st : Word w) (m : Memory w) (rs : List (Report w)) (hv : ValidTrace C i ports pub bound + st m rs) : + RAMBuckets.cost Report.probes + (linkedRows C i ports m rs ++ [closedLinkedReport C i ports (after m (eventLog rs))]) = + RAMBuckets.cost Report.probes rs + rs.length*((C i).params+2) + ((C i).params+4) := by + rw [RAMBuckets.cost_append, linkedRows_cost C i ports pub bound st m rs hv, RAMBuckets.cost, + (closedLinkedReport_effect C i ports _).2.2.2] + change _ + ((1 + ((C i).params+3))+0) = _ + omega + +/-- Execute a verified source pass inside the finite dispatcher, consume its +closing call, and resume any remaining level schedule at controller tag zero. +The frame is loaded once per call, independently of the source's private work. -/ +theorem worker_segment (i : Fin d) (ports : Ports w) (pub : Fin (C i).params → Word w) + (bound st : Word w) (m : Memory w) (bits : List (List Bool)) (rs : List (Report w)) + (f cap : ℕ) (hf : 0 < f) (fits : d + 1 ≤ 2 ^ w) + (hcap : f + 3 + 4 * ((C i).params + 1) + 2 * (d + 1) + 5 ≤ cap) + (hr : runSegment ((C i).table.instantiate w pub).program f (some st) m bits = some rs) + (hv : ValidTrace C i ports pub bound st m rs) (tail : List (List Bool)) : + let D := (machine C controller ports).program + let finalMem := after m (eventLog rs) + runSegment D cap (some st) m (bits ++ [] :: tail) = + (runSegment D cap (some 0) (writeMemory finalMem ports.tag 0) tail).map + (fun more ↦ linkedRows C i ports m rs ++ closedLinkedReport C i ports finalMem :: + more) := by + dsimp only + induction bits generalizing st m rs with + | nil => + obtain rfl : rs = [] := (Option.some.inj hr).symm + obtain ⟨⟨htag, hbound, _⟩, hle⟩ := hv + have hstop := worker_stop C controller ports i st m htag fits (hbound ▸ hle) (cap := cap) + (by omega) + have hclosed := closedLinkedReport_effect C i ports m + change runSegment _ _ _ _ ([] :: tail) = _ + rw [runSegment, hstop] + change (runSegment _ _ (closedLinkedReport C i ports m).result (after m + (closedLinkedReport C i ports m).events) + tail).map _ = _ + rw [hclosed.1,hclosed.2.1] + rfl + | cons bs rest ih => + rw [runSegment] at hr + let S := ((C i).table.instantiate w pub).program + cases hs : execute S f (S.start st) m bs with + | none => rw [hs] at hr; contradiction + | some rep => + rw [hs] at hr + obtain ⟨reps,hr',rfl⟩ := Option.map_eq_some_iff.mp hr + obtain ⟨⟨htag, hbound, hpub⟩,hlt,next,hn,hv'⟩ := hv + have hsource : let P := ((C i).table.instantiate w (parameters ports.activeFrame m)).program + execute P f (P.start st) m bs = some rep := by rw [hpub]; exact hs + have hcall := worker_active C controller ports i st m bs htag fits (hbound ▸ hlt) + hcap rep hsource + have hlinked := activeLinkedReport_effect C i ports m rep hn + rw [List.cons_append, runSegment, hcall] + change (runSegment _ _ (activeLinkedReport C i ports m rep).result + (after m (activeLinkedReport C i ports m rep).events) _).map _ = _ + rw [hlinked.1, hlinked.2.1, ih next (after m rep.events) reps (hn ▸ hr') hv'] + simp only [linkedRows, List.cons_append, Option.map_map, Function.comp_def, eventLog, + List.flatMap_cons, after, List.foldl_append] + rfl + +end CompressorRecords.Schedule + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsScheduleCursor.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsScheduleCursor.lean new file mode 100644 index 0000000000..dcd55b856e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsScheduleCursor.lean @@ -0,0 +1,298 @@ +import OAI.Computability.VPVNP.CompressorRecordsSchedule +import OAI.Computability.VPVNP.CompressorRecordsCursor + +/-! +# Executing the cursor incidence scan in the descriptor dispatcher + +Each row writes six entries. The external tag and twelve frame cells therefore +retain their values throughout the scan when they are disjoint from the six +output columns. At the exclusive bound the linked worker writes the controller +tag and returns the initial cursor for the controller. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Schedule + +open BurstRAM BurstRAM.PrivateRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- All row writes in the scanned interval avoid the dispatch tag and the +twelve input cells (bound and eleven public words). -/ +def CursorDisjoint (ports : Ports w) (pub : Fin 11 → Word w) (k n : ℕ) : Prop := + ∀ j, k ≤ j → j < k + n → ∀ av ∈ CursorRAM.rowWrites pub j, + av.1 ≠ ports.tag ∧ ∀ u : Fin 12, av.1 ≠ ports.activeFrame + (u.val : Word w) + +private theorem fold_away (xs : List (Word w × Word w)) (m : Memory w) (addr : Word w) + (h : ∀ av ∈ xs, av.1 ≠ addr) : + xs.foldl (fun mem av ↦ writeMemory mem av.1 av.2) m addr.val = m addr.val := by + induction xs generalizing m with + | nil => rfl + | cons av xs ih => + rw [List.foldl_cons, ih _ (fun a ha ↦ h a (List.mem_cons_of_mem _ ha))] + exact ite_eq_right (fun he ↦ h av (List.mem_cons_self ..) (Fin.ext he.symm)) + +/-- A single visit leaves each protected address available to the next call, +regardless of earlier contents of the output columns. -/ +theorem cursor_row_preserves (ports : Ports w) (pub : Fin 11 → Word w) (j : ℕ) + (m : Memory w) + (h : ∀ av ∈ CursorRAM.rowWrites pub j, av.1 ≠ ports.tag ∧ + ∀ u : Fin 12, av.1 ≠ ports.activeFrame + (u.val : Word w)) : + let out := after m (CursorRAM.events pub (Fin.ofNat _ j)) + out ports.tag.val = m ports.tag.val ∧ + stopWord ports.activeFrame out = stopWord ports.activeFrame m ∧ + (parameters ports.activeFrame out : Fin 11 → Word w) = parameters ports.activeFrame m := by + dsimp only + rw [CursorRAM.events_after] + have keep (addr : Word w) (h' : ∀ av ∈ CursorRAM.rowWrites pub j, av.1 ≠ addr) := + fold_away (CursorRAM.rowWrites pub j) m addr h' + refine ⟨keep _ (fun av ha ↦ (h av ha).1), keep _ ?_, ?_⟩ + · intro av ha + simpa using (h av ha).2 0 + · funext i + exact keep _ (fun av ha ↦ (h av ha).2 i.succ) + +/-- Every cursor returned by the body is the next row number. Together with +frame preservation this gives the dispatch guard at every call boundary. -/ +theorem cursor_valid_trace (ports : Ports w) (pub : Fin 11 → Word w) + (k n : ℕ) (m : Memory w) (bound : Word w) + (hk : k+n = bound.val) (hready : Ready cursorRefresh 0 ports pub bound m) + (hsep : CursorDisjoint ports pub k n) : + ValidTrace cursorRefresh 0 ports pub bound (Fin.ofNat _ k) m (CursorRAM.scanReports pub k n) := by + induction n generalizing k m with + | zero => + have he : Fin.ofNat (2^w) k = bound := Fin.ext (by + simp only [Nat.add_zero] at hk + rw [Fin.val_ofNat, hk, Nat.mod_eq_of_lt bound.isLt]) + exact ⟨hready,he.ge⟩ + | succ n ih => + have hlt : k < bound.val := by omega + have hstate : Fin.ofNat (2^w) k < bound := by + change k % (2^w) < bound.val + rwa [Nat.mod_eq_of_lt (hlt.trans bound.isLt)] + obtain ⟨ht, hb, hp⟩ := cursor_row_preserves ports pub k m (hsep k le_rfl (by omega)) + refine ⟨hready,hstate,Fin.ofNat _ (k+1),rfl,ih (k+1) _ (by omega) + ⟨ht.trans hready.1, hb.trans hready.2.1, hp.trans hready.2.2⟩ ?_⟩ + exact fun j hj h ↦ hsep j (by omega) (by omega) + +/-- Chronological reports of all data calls and the final transfer. The +closing call reads the same frame and sends the next call to the controller. -/ +def cursorPassReports (ports : Ports w) (pub : Fin 11 → Word w) (k n : ℕ) + (m : Memory w) : List (Report w) := + let rs := CursorRAM.scanReports pub k n + linkedRows cursorRefresh 0 ports m rs ++ + [closedLinkedReport cursorRefresh 0 ports (after m (eventLog rs))] + +variable {p r : ℕ} + +/-- Execute all rows from the current cursor through the exclusive bound +and resume the controller with the exact new incidence columns. -/ +theorem cursor_segment (controller : Template p r 5) (ports : Ports w) + (pub : Fin 11 → Word w) (k n : ℕ) (m : Memory w) (bound : Word w) + (hk : k+n = bound.val) (hready : Ready cursorRefresh 0 ports pub bound m) + (hsep : CursorDisjoint ports pub k n) (fits : 3 ≤ 2^w) + {cap : ℕ} (hcap : 119 ≤ cap) (tail : List (List Bool)) : + let D := (machine cursorRefresh controller ports).program + let out := after m (eventLog (CursorRAM.scanReports pub k n)) + runSegment D cap (some (Fin.ofNat _ k)) m (List.replicate n [] ++ [] :: tail) = + (runSegment D cap (some 0) (writeMemory out ports.tag 0) tail).map + (fun more ↦ cursorPassReports ports pub k n m ++ more) := by + have h := worker_segment cursorRefresh controller 0 ports pub bound (Fin.ofNat _ k) m + (List.replicate n []) (CursorRAM.scanReports pub k n) (1+CursorRAM.visit.length) cap (by decide) + fits hcap (CursorRAM.scan_native pub k n m) (cursor_valid_trace ports pub k n m bound hk hready hsep) tail + simpa only [cursorPassReports, List.append_assoc, List.singleton_append] using h + +private theorem linked_cursor_rows (ports : Ports w) (pub : Fin 11 → Word w) (k n : ℕ) + (m : Memory w) : + let source := CursorRAM.scanReports pub k n + let rows := linkedRows cursorRefresh 0 ports m source + after m (eventLog rows) = after m (eventLog source) ∧ rows.length = n ∧ + RAMBuckets.cost Report.probes rows = 20*n := by + induction n generalizing k m with + | zero => exact ⟨rfl,rfl,rfl⟩ + | succ n ih => + let rep : Report w := ⟨CursorRAM.events pub (Fin.ofNat _ k), some (Fin.ofNat _ (k+1))⟩ + let out := after m rep.events + obtain ⟨_,hm,_,hp⟩ := activeLinkedReport_effect cursorRefresh 0 ports m rep rfl + have hprobe : (activeLinkedReport cursorRefresh 0 ports m rep).probes = 19 := hp + obtain ⟨hmem,hrows,hcost⟩ := ih (k+1) out + dsimp only + change after m (eventLog (activeLinkedReport cursorRefresh 0 ports m rep :: _)) = + after m (eventLog (rep :: _)) ∧ (_ :: _).length = _ ∧ RAMBuckets.cost _ (_ :: _) = _ + refine ⟨?_,?_,?_⟩ + · change after (after m (activeLinkedReport cursorRefresh 0 ports m rep).events) + (eventLog (linkedRows cursorRefresh 0 ports out (CursorRAM.scanReports pub (k+1) n))) = + after out (eventLog (CursorRAM.scanReports pub (k+1) n)) + rw [hm] + exact hmem + · rw [List.length_cons, hrows] + · rw [RAMBuckets.cost, hprobe, hcost, Nat.mul_succ] + omega + +/-- Nineteen probes per data call (six writes, twelve frame reads, one tag +read) and fourteen probes for the closing call. Only the latter writes the +tag, and it returns cursor zero. Costs include one unit per call. -/ +theorem cursor_pass_effect (ports : Ports w) (pub : Fin 11 → Word w) (k n : ℕ) + (m : Memory w) : + let rs := cursorPassReports ports pub k n m + let sourceMem := after m (eventLog (CursorRAM.scanReports pub k n)) + after m (eventLog rs) = writeMemory sourceMem ports.tag 0 ∧ + endState (some (Fin.ofNat _ k)) rs = some 0 ∧ rs.length = n+1 ∧ + RAMBuckets.cost Report.probes rs = 20*n+15 := by + let mem := after m (eventLog (CursorRAM.scanReports pub k n)) + let close := closedLinkedReport cursorRefresh 0 ports mem + obtain ⟨hm,hl,hcost⟩ := linked_cursor_rows ports pub k n m + obtain ⟨hresult,hmem,_,hp⟩ := closedLinkedReport_effect cursorRefresh 0 ports mem + dsimp only [cursorPassReports] + refine ⟨?_,?_,?_,?_⟩ + · simp only [eventLog, List.flatMap_append, after, List.foldl_append] + change after (after m (eventLog (linkedRows cursorRefresh 0 ports m _))) close.events = _ + rw [hm] + exact hmem + · rw [endState_append]; exact hresult + · rw [List.length_append,hl]; rfl + · rw [RAMBuckets.cost_append,hcost,RAMBuckets.cost,hp] + rfl + +private theorem column_address {start n t i : ℕ} (room : start + 6*n ≤ 2^w) + (ht : t < 6) (hi : i < n) : + start ≤ (CursorRAM.encode w (start+t*n) + CursorRAM.encode w i).val ∧ + (CursorRAM.encode w (start+t*n) + CursorRAM.encode w i).val < start + 6*n := by + have hoff := CursorRAM.packed_lt ht hi + have ha : start + t*n+i < 2^w := by omega + rw [Fin.val_add, Fin.val_ofNat, Fin.val_ofNat, Nat.mod_eq_of_lt (by omega : start+t*n < 2^w), + Nat.mod_eq_of_lt (by omega : i < 2^w), Nat.mod_eq_of_lt ha] + omega + +section Columns + +open CursorRAM CursorNetwork Compression + +variable {b l a pad start : ℕ} {S : Type} [Fintype S] +variable (hD : 1 < b+l) (hd : 2+pad = 2^a) (bits : S → ℕ) +local notation "X₀" => cursorState (cursorCoordinateLabels b l) hD hd bits +local notation "N₀" => rowCount b l a +local notation "P₀" => publicWords w b l a (∑ s, bits s) start + +private theorem base_address (room : start + 6*N₀ ≤ 2^w) (t : Fin 6) (e : BasePort b l a) : + let addr := encode w (start + t.val*N₀) + IncidenceDirectory.basePort X₀ e + start ≤ addr.val ∧ addr.val < start + 6*N₀ := by + have he : IncidenceDirectory.basePort (w := w) X₀ e = encode w (baseOrder b l a e).val := by + rw [baseOrder_val]; rfl + rw [he] + apply column_address room t.isLt + exact (baseOrder b l a e).isLt.trans_le + (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos l))) + +private theorem actual_address (room : start + 6*N₀ ≤ 2^w) (t : Fin 6) (e : ActualPort b l a) : + let addr := encode w (start + t.val*N₀) + IncidenceDirectory.actualPort X₀ e + start ≤ addr.val ∧ addr.val < start + 6*N₀ := by + have he : IncidenceDirectory.actualPort (w := w) X₀ e = encode w (actualOrder b l a e).val := by + rw [actualOrder_val, cursorActualSlotNumber, cursorActualIndex_val]; rfl + rw [he] + exact column_address room t.isLt (actualOrder b l a e).isLt + +include hD hd + +/-- The two base indices and the two actual indices used by a row are port +numbers of the typed graph. Hence even indirect inverse-column writes stay +inside the reserved output region. -/ +theorem cursor_write_address (room : start + 6*N₀ ≤ 2^w) {j : ℕ} (hj : j < N₀) + (av : Word w × Word w) (hav : av ∈ rowWrites P₀ j) : + start ≤ av.1.val ∧ av.1.val < start + 6*N₀ := by + let e := (actualOrder b l a).symm ⟨j,hj⟩ + have num : (actualOrder b l a e).val = j := congrArg Fin.val ((actualOrder b l a).apply_symm_apply ⟨j,hj⟩) + have fit : N₀ < 2^w := by omega + rw [← num, rowWrites, visit_row hD hd bits start fit e] at hav + simp only [writes, typedRow, List.mem_cons, List.not_mem_nil, or_false] at hav + rcases hav with rfl | rfl | rfl | rfl | rfl | rfl + · exact base_address hD hd bits room 0 _ + · exact base_address hD hd bits room 1 _ + · exact base_address hD hd bits room 2 _ + · exact column_address room (t := 3) (by decide) (actualOrder b l a e).isLt + · exact actual_address hD hd bits room 4 _ + · exact column_address room (t := 5) (by decide) (actualOrder b l a e).isLt + +/-- Natural-address layout conditions suffice for the complete cursor scan. +The frame may be placed on either side of the incidence columns. -/ +theorem cursor_disjoint_layout (ports : Ports w) (room : start + 6*N₀ ≤ 2^w) + (tag : ports.tag.val < start ∨ start + 6*N₀ ≤ ports.tag.val) + (frame : ports.activeFrame.val + 12 ≤ start ∨ start + 6*N₀ ≤ ports.activeFrame.val) + (frameFits : ports.activeFrame.val + 12 ≤ 2^w) : CursorDisjoint ports P₀ 0 N₀ := by + intro j _ hj av ha + obtain ⟨lo,hi⟩ := cursor_write_address hD hd bits room (by simpa using hj) av ha + refine ⟨fun he ↦ ?_, fun u he ↦ ?_⟩ + · rw [he] at lo hi + omega + · have hu := u.isLt + have hu' : (u.val : Word w).val = u.val := Nat.mod_eq_of_lt (by omega) + have haddr : (ports.activeFrame + (u.val : Word w)).val = ports.activeFrame.val + u.val := by + rw [Fin.val_add, hu', Nat.mod_eq_of_lt (by omega)] + rw [he, haddr] at lo hi + omega + +/-- The closing transfer can write its tag after the scan without changing +any of the six typed incidence tables. -/ +theorem cursor_directory_write_tag (room : start + 6*N₀ ≤ 2^w) (tag v : Word w) + (htag : tag.val < start ∨ start + 6*N₀ ≤ tag.val) {m : Memory w} + (rep : (directory w b l a start).Represents X₀ m) : + (directory w b l a start).Represents X₀ (writeMemory m tag v) := by + have eq (addr : Word w) (h : start ≤ addr.val ∧ addr.val < start + 6*N₀) : + writeMemory m tag v addr.val = m addr.val := ite_eq_right (by omega) + constructor + · intro e + exact (eq _ (base_address hD hd bits room 0 e)).trans (rep.baseOut e) + · intro e + exact (eq _ (base_address hD hd bits room 1 e)).trans (rep.baseIn e) + · intro e + exact (eq _ (base_address hD hd bits room 2 e)).trans (rep.shift e) + · intro e + exact (eq _ (actual_address hD hd bits room 3 e)).trans (rep.actualOut e) + · intro e + exact (eq _ (actual_address hD hd bits room 4 e)).trans (rep.actualIn e) + · intro e + exact (eq _ (actual_address hD hd bits room 5 e)).trans (rep.width e) + +/-- The native linked worker builds the level-zero cursor directory and +returns the dispatcher to its controller. The protected frame may be before +or after the columns. The tag and frame are read from the supplied memory. -/ +theorem initialize_linked_cursor (controller : Template p r 5) (ports : Ports w) (m : Memory w) + (room : start + 6*N₀ ≤ 2^w) (widthFits : (∑ s, bits s) < 2^w) + (tag : ports.tag.val < start ∨ start + 6*N₀ ≤ ports.tag.val) + (frame : ports.activeFrame.val + 12 ≤ start ∨ start + 6*N₀ ≤ ports.activeFrame.val) + (frameFits : ports.activeFrame.val + 12 ≤ 2^w) + (hready : Ready cursorRefresh 0 ports P₀ (encode w N₀) m) + {cap : ℕ} (hcap : 119 ≤ cap) : + let D := (machine cursorRefresh controller ports).program + let rs := cursorPassReports ports P₀ 0 N₀ m + let out := after m (eventLog rs) + runSegment D cap (some 0) m (List.replicate N₀ [] ++ [[]]) = some rs ∧ + (directory w b l a start).Represents X₀ out ∧ + out ports.tag.val = 0 ∧ endState (some 0) rs = some 0 ∧ + rs.length = N₀+1 ∧ RAMBuckets.cost Report.probes rs = 20*N₀+15 := by + have hp : 0 < N₀ := by unfold rowCount; positivity + have hv : (encode w N₀).val = N₀ := Nat.mod_eq_of_lt (by omega) + have hsep := cursor_disjoint_layout hD hd bits ports room tag frame frameFits + have hrun := cursor_segment controller ports P₀ 0 N₀ m (encode w N₀) (by omega) hready hsep + (by omega) hcap [] + have hrep := (initialize_cursor hD hd bits room widthFits m).2.1 + obtain ⟨hmem, hres, hlen, hcost⟩ := cursor_pass_effect ports P₀ 0 N₀ m + dsimp only + refine ⟨?_, ?_, ?_, hres, hlen, hcost⟩ + · simpa only [runSegment, Option.map_some, List.append_nil, Fin.ofNat_eq_cast, Nat.cast_zero] using hrun + · rw [hmem] + exact cursor_directory_write_tag hD hd bits room ports.tag 0 tag hrep + · rw [hmem] + simp [writeMemory] + +end Columns + +end CompressorRecords.Schedule + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedArena.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedArena.lean new file mode 100644 index 0000000000..f403d5e790 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedArena.lean @@ -0,0 +1,220 @@ +import OAI.Computability.VPVNP.CompressorRecordsSelectedScoreRun +import OAI.Computability.VPVNP.CompressorRecordsDemandOutput + +/-! # Consecutive score, placement and role arrays for a selected shrinking term + +The two scores and the chosen layout follow the actual motif term rows. +Four old-position columns then contain the selected placement, and four +words per absolute old arc contain its demand-role record. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.SelectedArena + +open Compression BurstRAM +open scoped Fin.CommRing + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) + +/-- Number of old packed positions in this shrinking state, one for each base vertex and +packing-lane address. -/ +abbrev positions := ShrinkRAM.PositionCount (Fintype.card X.Base) a g +/-- Number of selected motif term rows, counted in the physical motif order used by the score +pass. -/ +abbrev motifs := (SelectedScore.motifOrder X).length + +variable (termBase stride : Word w) + +/-- Address immediately after the fixed-stride motif term rows, where the first layout score is +stored. -/ +def origin := termBase.val + motifs X*stride.val +/-- Start of the placement columns, three words past the score origin to allow for two scores +and the chosen-layout bit. -/ +def placementBase := origin X termBase stride + 3 +/-- Start of the demand-role records after the four placement columns of one word per old +position. -/ +def roleBase := placementBase X termBase stride + 4*positions X +/-- Exclusive end of the selected arena, after four role words for each absolute old arc. -/ +def endAddr := roleBase X termBase stride + 4*DemandRAM.absoluteCount X + +/-- Score-pass operands for the motif rows, selector bits, two consecutive score counters and +the layout-choice cell at offset two from the score origin. -/ +def scoreTables (selectorBits : Word w) : TermScores.Tables w := + ⟨termBase,stride,Fin.ofNat _ (origin X termBase stride),selectorBits,Fin.ofNat _ (origin X termBase stride+2)⟩ + +/-- Machine-word address of the start of placement column `t`, spaced by the number of old +positions. -/ +def placementWord (t : Fin 4) : Word w := Fin.ofNat _ (placementBase X termBase stride+t.val*positions X) + +/-- Build the fourteen shrink-worker operands from the existing geometry and input pointers, +the selected layout word and the four placement-column addresses. -/ +def shrinkWords (p₀ : Fin 14 → Word w) (layout : Word w) : Fin 14 → Word w := + ![p₀ 0,p₀ 1,p₀ 2,p₀ 3,p₀ 4,layout,p₀ 6,p₀ 7,p₀ 8,p₀ 9, + placementWord X termBase stride 0,placementWord X termBase stride 1, + placementWord X termBase stride 2,placementWord X termBase stride 3] + +/-- The dynamic operand is read from the cell written by the strict score comparison. -/ +def selectedWords (p₀ : Fin 14 → Word w) (m : Memory w) : Fin 14 → Word w := + shrinkWords X termBase stride p₀ (m (origin X termBase stride+2)) + +/-- Assemble the eleven demand-worker operands from shrink geometry, the old outgoing incidence +array, the selected placement columns and the role-record destination. -/ +def demandWords (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) : Fin 11 → Word w := + ![p₀ 2,p₀ 0,p₀ 1,p₀ 3,0,T.actualOut,placementWord X termBase stride 1, + placementWord X termBase stride 0,placementWord X termBase stride 2, + placementWord X termBase stride 3,Fin.ofNat _ (roleBase X termBase stride)] + +/-- The exclusive end of the score, placement and role arena lies strictly below the +machine-word modulus. -/ +abbrev Fits := endAddr X termBase stride < 2^w + +private theorem order : origin X termBase stride + 3 = placementBase X termBase stride ∧ + placementBase X termBase stride + 4*positions X = roleBase X termBase stride ∧ + roleBase X termBase stride ≤ endAddr X termBase stride := ⟨rfl,rfl,Nat.le_add_right ..⟩ + +theorem score_layout (selectorBits : Word w) (hstride : 10 ≤ stride.val) (fit : Fits X termBase stride) : + TermScores.Layout (scoreTables X termBase stride selectorBits) (motifs X) (List.ofFn SelectedScore.axes) := by + let L := scoreTables X termBase stride selectorBits + obtain ⟨h₁,h₂,h₃⟩ := order X termBase stride + change endAddr X termBase stride < 2^w at fit + have hs : L.scoreBase.val = origin X termBase stride := Nat.mod_eq_of_lt (by omega) + have hl : L.levelCell.val = origin X termBase stride+2 := Nat.mod_eq_of_lt (by omega) + apply TermScores.Layout.ofIntervals L + · exact (by decide : 1 < 10).trans_le hstride + · intro axis h + obtain ⟨j,rfl⟩ := List.mem_ofFn.mp h + have hcoord : (SelectedScore.axes (w := w) j).coordinate.val ≤ j.val := Nat.mod_le .. + have := j.isLt + change 2 + (SelectedScore.axes j).coordinate.val < stride.val + omega + · change origin X termBase stride ≤ 2^w; omega + · omega + · exact Or.inl hs.ge + · exact Or.inr (by omega) + +theorem score_frame (selectorBits : Word w) (fit : Fits X termBase stride) {m out : Memory w} + (frame : ∀ j, j ≠ (scoreTables X termBase stride selectorBits).levelCell.val → + (∀ l, j ≠ (TermScores.counter (scoreTables X termBase stride selectorBits) l).val) → out j=m j) : + ∀ j, j < origin X termBase stride ∨ placementBase X termBase stride ≤ j → out j=m j := by + let L := scoreTables X termBase stride selectorBits + obtain ⟨h₁,h₂,h₃⟩ := order X termBase stride + change endAddr X termBase stride < 2^w at fit + have hs : L.scoreBase.val = origin X termBase stride := Nat.mod_eq_of_lt (by omega) + have hl : L.levelCell.val = origin X termBase stride+2 := Nat.mod_eq_of_lt (by omega) + intro j hj + apply frame j (by change j ≠ L.levelCell.val; omega) + intro l + have hb := Bool.toNat_le l + change j ≠ (TermScores.counter L l).val + rw [TermScores.counter,Fin.val_add,TermScores.word,Fin.val_ofNat,Nat.add_mod_mod,hs,Nat.mod_eq_of_lt (by omega)] + omega + +theorem shrink_params (p₀ : Fin 14 → Word w) {b₀ b : Bool} + (hp : ShrinkRAM.Params p₀ a (Shrink.colors a) (Shrink.J a) g b₀) + (m : Memory w) (hc : m (origin X termBase stride+2) = (b.toNat : Word w)) : + ShrinkRAM.Params (selectedWords X termBase stride p₀ m) a (Shrink.colors a) (Shrink.J a) g b := + ⟨hp.lane,hp.tag,hp.degree,hp.mask,hp.last,by cases b <;> exact hc,hp.low_fit,hp.color_fit,hp.two_fit⟩ + +theorem demand_params (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) {b₀ : Bool} + (hp : ShrinkRAM.Params p₀ a (Shrink.colors a) (Shrink.J a) g b₀) : + BundleRAM.Params (demandWords X termBase stride p₀ T) a (Shrink.colors a) (Shrink.J a) g 0 := + ⟨hp.degree,hp.lane,hp.tag,hp.mask,rfl⟩ + +theorem inputs (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) (layout : Word w) : + DemandRAM.Inputs (demandWords X termBase stride p₀ T) (shrinkWords X termBase stride p₀ layout) T := + ⟨rfl,rfl,rfl,rfl,rfl⟩ + +theorem column_value (fit : Fits X termBase stride) (t : Fin 4) : + (placementWord X termBase stride t).val = placementBase X termBase stride+t.val*positions X := by + have h := Nat.mul_le_mul_right (positions X) t.isLt.le + obtain ⟨_,h₂,h₃⟩ := order X termBase stride + change endAddr X termBase stride < 2^w at fit + exact Nat.mod_eq_of_lt (by omega) + +theorem output_column (p₀ : Fin 14 → Word w) (layout : Word w) (fit : Fits X termBase stride) (t : Fin 4) : + ((shrinkWords X termBase stride p₀ layout) (t.natAdd 10)).val = + placementBase X termBase stride+t.val*positions X := by + have h : shrinkWords X termBase stride p₀ layout (t.natAdd 10) = placementWord X termBase stride t := by + fin_cases t <;> rfl + rw [h,column_value X termBase stride fit] + +/-- The old color/offset entries are indexed by base vertices, while the +mate/displacement entries are indexed by directed base slots. -/ +private theorem decoded_offsets (p : Fin 14 → Word w) {l : Bool} + (hp : ShrinkRAM.Params p a (Shrink.colors a) (Shrink.J a) g l) + (i : Word w) (hi : i.val < positions X) : + (ShrinkRAM.decode p i).base.val < Fintype.card X.Base ∧ + (ShrinkRAM.baseArc p (ShrinkRAM.decode p i)).val < Fintype.card X.Base * 2^a := by + let x := (Shrink.oldIndex (a := a) (g := g) X.baseIndex).symm ⟨i.val,hi⟩ + have hx : i.val = Shrink.oldNumber X.baseIndex x := by rw [← Shrink.oldIndex_val]; simp [x] + have dec := ShrinkRAM.decode_exact hp i + rw [hx,Shrink.decode_oldNumber] at dec + have hb : (ShrinkRAM.decode p i).base.val < Fintype.card X.Base := by + rw [dec] + exact (Nat.mod_le ..).trans_lt (X.baseIndex x.1.1).isLt + have hs : (ShrinkRAM.decode p i).slot.val < 2^a := by + rw [dec] + exact (Nat.mod_le ..).trans_lt (bitWordFinEquiv a x.2.2).isLt + refine ⟨hb,?_⟩ + have h := Nat.mul_le_mul_right (2^a) hb + rw [Nat.succ_mul] at h + rw [ShrinkRAM.baseArc,Fin.val_add,Fin.val_mul,hp.degree] + exact (Nat.mod_le ..).trans_lt (by have := Nat.mod_le ((ShrinkRAM.decode p i).base.val * 2^a) (2^w); omega) + +/-- The old color, offset, mate, displacement and outgoing incidence arrays all end at or +before the score origin, separating them from the new output columns. -/ +structure OldInputs (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) : Prop where + color : (p₀ 6).val + Fintype.card X.Base ≤ origin X termBase stride + offset : (p₀ 7).val + Fintype.card X.Base ≤ origin X termBase stride + mate : (p₀ 8).val + Fintype.card X.Base*2^a ≤ origin X termBase stride + displacement : (p₀ 9).val + Fintype.card X.Base*2^a ≤ origin X termBase stride + actualOut : T.actualOut.val + DemandRAM.oldCount X ≤ origin X termBase stride + +theorem shrink_regions (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) (layout : Word w) {l : Bool} + (hp : ShrinkRAM.Params (shrinkWords X termBase stride p₀ layout) a (Shrink.colors a) (Shrink.J a) g l) + (old : OldInputs X termBase stride p₀ T) (fit : Fits X termBase stride) : + ShrinkRAM.Regions (shrinkWords X termBase stride p₀ layout) (positions X) := by + let p := shrinkWords X termBase stride p₀ layout + obtain ⟨h₁,h₂,h₃⟩ := order X termBase stride + change endAddr X termBase stride < 2^w at fit + apply ShrinkRAM.Regions.packed p (by omega) (output_column X termBase stride p₀ layout fit) + intro c i hi + left + obtain ⟨hb,ha⟩ := decoded_offsets X p hp i hi + have h (q o : Word w) (hn : ℕ) (hq : q.val+hn ≤ origin X termBase stride) (ho : o.val.imp_right (And.imp_right Prod.mk.inj) + rw [ins.thick] + exact h + have bit : mem (p 6+code src).val = ((decide (X.packingData.thick src)).toNat : Word w) := + Fin.ext (th.trans (Nat.mod_eq_of_lt (th ▸ (mem (p 6+code src).val).isLt)).symm) + refine ⟨hs ▸ small src, ht ▸ small dst, ?_⟩ + unfold DemandRAM.endpoints + rw [hs,ht] + change (code src + mem (p 6+code src).val*(code dst-code src)).val < _ ∧ + (code dst-mem (p 6+code src).val*(code dst-code src)).val < _ + rw [bit] + by_cases h : X.packingData.thick src + · simpa only [h,decide_true,Bool.toNat_true,Nat.cast_one,one_mul,add_sub_cancel,sub_sub_cancel] using + And.intro (small dst) (small src) + · simpa only [h,decide_false,Bool.toNat_false,Nat.cast_zero,zero_mul,add_zero,sub_zero] using + And.intro (small src) (small dst) + +theorem demand_outside (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) (layoutWord : Word w) + (mem : Memory w) (layout : Bool) (degree : (p₀ 2).val=2^a) (inc : T.ActualColumns X mem) + (place : ShrinkRAM.PlacementColumns X.slots X.baseIndex (shrinkWords X termBase stride p₀ layoutWord) layout mem) + (old : OldInputs X termBase stride p₀ T) (fit : Fits X termBase stride) + (i : Word w) (c : Fin 6) (hi : i.val Or.inl (rb.symm ▸ demand_outside X termBase stride p₀ T layoutWord mem layout hp.degree inc place old fit i c hi)) + simpa only [rb,endAddr] using r + +end CompressorRecords.SelectedArena + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedFinish.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedFinish.lean new file mode 100644 index 0000000000..9c065a6923 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedFinish.lean @@ -0,0 +1,156 @@ +import OAI.Computability.VPVNP.CompressorRecordsSelectedStage +import OAI.Computability.VPVNP.CompressorRecordsSelectedPreimages + +/-! # Retaining the selected term and its complete preimage directory + +The new arrays are allocated after the old-arc role table. Clearing the +counts and appending children therefore preserves the chosen term, layout, +placement and role records at their original addresses. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.SelectedFinish + +open Compression BurstRAM ShrinkMotif SelectedArena +open PairSimulation.LocalHistory PairSimulation.TraversalRows +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) +variable (term stride selectors : Word w) (p₀ : Fin 14 → Word w) (s : SelectedScore.Selection B X) +variable (mem : Memory w) (p : SelectedStage.Passes w) + +/-- The Boolean shrink layout selected for all motifs by comparing their aggregate supply +energies for the given term choices. -/ +abbrev chosen := X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s +/-- The shrink-worker operand vector using the chosen-layout word actually stored by the +completed score passes. -/ +abbrev shr := selectedWords X term stride p₀ (p.afterScores mem) + +/-- All physical artifacts of the selected shrinking branch, after the two +new native passes in their chronological memory. -/ +structure Built (q : Passes w) : Prop where + raw : Collected X term stride (shr X term stride p₀ mem p) (chosen B X s) (p.final mem) q + chosenCell : q.final (p.final mem) (origin X term stride+2) = ((chosen B X s).toNat : Word w) + placement : ShrinkRAM.PlacementColumns X.slots X.baseIndex (shr X term stride p₀ mem p) + (chosen B X s) (q.final (p.final mem)) + roles : DemandRAM.RoleColumns X (chosen B X s) (roleBase X term stride) (q.final (p.final mem)) + terms : SelectedScore.Stored B X s (SelectedScore.headAt X (scoreTables X term stride selectors)) + (q.final (p.final mem)) + frame : ∀ j, j < origin X term stride ∨ stop X term stride ≤ j → q.final (p.final mem) j = mem j + +private theorem preserve_terms (room : stop X term stride ≤ 2^w) (wide : 10 ≤ stride.val) + (h : SelectedScore.Stored B X s (SelectedScore.headAt X (scoreTables X term stride selectors)) mem) + (post : Memory w) (fr : ∀ j, j < origin X term stride → post j = mem j) : + SelectedScore.Stored B X s (SelectedScore.headAt X (scoreTables X term stride selectors)) post := by + let L := scoreTables X term stride selectors + intro i + have hi := Nat.mul_le_mul_right stride.val i.isLt + rw [Nat.succ_mul] at hi + have hfit : origin X term stride ≤ 2^w := by + dsimp only [stop,rowStart,countStart,endAddr,roleBase,placementBase] at room + omega + change i.val*stride.val+stride.val ≤ motifs X*stride.val at hi + have hbase : (SelectedScore.headAt X L i).val = term.val+i.val*stride.val := by + apply TermScores.rowBase_val + change term.val+i.val*stride.val < 2^w + unfold origin at hfit; omega + have small (j : ℕ) (hj : j<10) : (SelectedScore.headAt X L i).val+j < origin X term stride := by + unfold origin; rw [hbase]; omega + obtain ⟨d,r,fields⟩ := h i + refine ⟨?_,?_,?_⟩ + · have hz := small 0 (by decide) + rw [Nat.add_zero] at hz + rwa [fr _ hz] + · rwa [fr _ (small 1 (by decide))] + · intro j + have hf : 2+j.val < 10 := by have hj : j.val < 8 := j.isLt; omega + have hs := small _ hf + rw [← Nat.add_assoc] at hs + rw [fr _ hs] + exact fields j + +/-- Execute the preimage build from the actual final memory of the score, +placement, and role passes, including nonzero prior workspace contents. -/ +theorem build (stored : SelectedStage.Stored B X term stride p₀ s mem p) + (terms : SelectedScore.Stored B X s (SelectedScore.headAt X (scoreTables X term stride selectors)) mem) + (wide : 10 ≤ stride.val) (room : stop X term stride ≤ 2^w) : + ∃ q, Built B X term stride selectors p₀ s mem p q := by + let bit := (p.afterScores mem) (origin X term stride+2) + obtain ⟨q,raw⟩ := collect X term stride p₀ bit (chosen B X s) (p.final mem) room stored.placement + have stopEq : stop X term stride = endAddr X term stride + ShrinkPreimages.newCount X + ShrinkPreimages.oldCount X := rfl + have pos : 0 < ShrinkPreimages.oldCount X := Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos _) + have fit : Fits X term stride := by change endAddr X term stride < _; omega + have before (j : ℕ) (hj : j < endAddr X term stride) : q.final (p.final mem) j = p.final mem j := + raw.frame j (Or.inl hj) + have all (j : ℕ) (hj : j < origin X term stride ∨ stop X term stride ≤ j) : q.final (p.final mem) j = mem j := by + rcases hj with lo|hi + · have endGt : origin X term stride < endAddr X term stride := by unfold endAddr roleBase placementBase; omega + exact (before j (lo.trans endGt)).trans (stored.frame j (Or.inl lo)) + · exact (raw.frame j (Or.inr hi)).trans (stored.frame j (Or.inr (by omega))) + refine ⟨q,⟨raw,?_,?_,?_,preserve_terms B X term stride selectors s mem room wide terms _ (fun j hj => all j (.inl hj)),all⟩⟩ + · exact (before _ (by unfold endAddr roleBase placementBase; omega)).trans stored.chosen + · constructor + intro x + let i := ShrinkRAM.word w (Shrink.oldNumber X.baseIndex x) + have hsmall : i.val < positions X := (Nat.mod_le ..).trans_lt + ((Shrink.oldIndex_val X.baseIndex x) ▸ (Shrink.oldIndex X.baseIndex x).isLt) + have keep (t : Fin 4) : q.final (p.final mem) (ShrinkRAM.outAddr (shr X term stride p₀ mem p) t i) = + p.final mem (ShrinkRAM.outAddr (shr X term stride p₀ mem p) t i) := by + apply before + have ht := Nat.mul_le_mul_right (positions X) t.isLt + rw [Nat.succ_mul] at ht + change (((shrinkWords X term stride p₀ bit) (t.natAdd 10)).val + i.val) % (2^w) < _ + apply (Nat.mod_le ..).trans_lt + rw [output_column X term stride p₀ bit fit] + unfold endAddr roleBase; omega + change ((q.final (p.final mem) (ShrinkRAM.outAddr _ 0 i)).val, (q.final (p.final mem) (ShrinkRAM.outAddr _ 1 i)).val, + (q.final (p.final mem) (ShrinkRAM.outAddr _ 2 i)).val, (q.final (p.final mem) (ShrinkRAM.outAddr _ 3 i)).val) = _ + rw [keep 0,keep 1,keep 2,keep 3] + exact stored.placement.atSite x + · constructor + · intro e + rw [before] + · exact stored.roles.cd e + · have hi : (DemandRAM.absoluteIndex X e).val < DemandRAM.absoluteCount X := (DemandRAM.absoluteIndex X e).isLt + unfold endAddr; omega + · intro e r + rw [before] + · exact stored.roles.packed e r + · have hi : (DemandRAM.absoluteIndex X e.val).val < DemandRAM.absoluteCount X := (DemandRAM.absoluteIndex X e.val).isLt + have hr : SlotOwners.roleOffset r < 3 := by cases r <;> decide + unfold endAddr; omega + +section DFS + +open NetworkKernel MotifBlocks MotifGrid MotifConversion SurvivingSlots + +variable {R : Type*} [CommRing R] {δ : ℝ} {b : ℕ} +variable (κ : (parameterData B.shrink).Entry → R) (hκ : (parameterData B.shrink).IsSolution κ) +variable (ready : Ready (2^a) (Shrink.colors a) (2^b) δ) + +/-- The final chronological memory supplies the DFS row data for the actual +selected pass term and the site orders of its actual source and next states. -/ +def Built.selectedDirectory {q : Passes w} (r : Built B X term stride selectors p₀ s mem p q) + (room : stop X term stride ≤ 2^w) : + PairSimulation.TraversalRows.Directory (ShrinkPreimages.selectedTerm X B.shrink κ hκ ready s) + (siteOrder X) (siteOrder (X.shrinkNext B.shrink ready s)) (q.final (p.final mem)) (stop X term stride) := by + let bit := (p.afterScores mem) (origin X term stride+2) + have ar := areas X term stride p₀ bit room + apply ShrinkPreimages.selectedDirectory X B.shrink κ hκ ready s ar _ r.raw.preimages + rw [← ShrinkPreimages.oldCount_eq X] + exact Nat.add_le_add_right (Nat.mod_le ..) _ + +end DFS +end CompressorRecords.SelectedFinish + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedPreimages.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedPreimages.lean new file mode 100644 index 0000000000..eb76729c06 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedPreimages.lean @@ -0,0 +1,118 @@ +import OAI.Computability.VPVNP.CompressorRecordsSelectedArenaDemand +import OAI.Computability.VPVNP.CompressorRecordsShrinkPreimages + +/-! # Two-pass native preimage directory following the selected role rows -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.SelectedFinish + +open Compression BurstRAM PrimedStackRAM SelectedArena +open scoped Fin.CommRing Classical + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) (term stride : Word w) + +/-- The first address after the selected role records, reserved for the new sites' preimage +counts. -/ +def countStart := endAddr X term stride +/-- The address immediately after the count column where the directory stores the old site +identifiers. -/ +def rowStart := countStart X term stride + ShrinkPreimages.newCount X +/-- The exclusive upper bound of the preimage directory, after space for every old site +identifier. -/ +def stop := rowStart X term stride + ShrinkPreimages.oldCount X +/-- Encode the base address of the selected preimage count column as a machine word. -/ +def counts : Word w := Fin.ofNat _ (countStart X term stride) +/-- Encode the base address of the selected preimage rows as a machine word. -/ +def rows : Word w := Fin.ofNat _ (rowStart X term stride) + +private theorem room_vals (room : stop X term stride ≤ 2^w) : + Fits X term stride ∧ (counts X term stride).val=countStart X term stride ∧ + (rows X term stride).val=rowStart X term stride := by + have pos : 0 < ShrinkPreimages.oldCount X := Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos _) + change countStart X term stride+ShrinkPreimages.newCount X+ShrinkPreimages.oldCount X ≤ 2^w at room + exact ⟨show countStart X term stride < 2^w by omega,Nat.mod_eq_of_lt (by omega), + Nat.mod_eq_of_lt (show countStart X term stride+ShrinkPreimages.newCount X < 2^w by omega)⟩ + +theorem areas (p₀ : Fin 14 → Word w) (bit : Word w) (room : stop X term stride ≤ 2^w) : + ShrinkPreimages.Areas X (shrinkWords X term stride p₀ bit) (counts X term stride) (rows X term stride) := by + have fit := (room_vals X term stride room).1 + have col := output_column X term stride p₀ bit fit 0 + change ((shrinkWords X term stride p₀ bit) 10).val = placementBase X term stride+0*positions X at col + apply ShrinkPreimages.Areas.packed (endAddr X term stride) _ room + change ((shrinkWords X term stride p₀ bit) 10).val + positions X ≤ placementBase X term stride+4*positions X+_ + omega + +/-- The chronological RAM reports for clearing the new sites' counts and collecting their +old-site preimages. -/ +structure Passes (w : ℕ) where + /-- Reports of the pass that zeros one preimage count per new site. -/ + clear : List (Report w) + /-- Reports of the pass that appends each old site's identifier to its selected owner's + preimage row. -/ + collect : List (Report w) + +/-- The memory handed to the collection pass after the counts have been cleared. -/ +def Passes.middle (p : Passes w) (m : Memory w) := after m (eventLog p.clear) +/-- The memory after the clearing and collection passes have both run. -/ +def Passes.final (p : Passes w) (m : Memory w) := after (p.middle m) (eventLog p.collect) + +theorem Passes.after_append (p : Passes w) (m : Memory w) : + after m (eventLog (p.clear++p.collect)) = p.final m := by + simp only [Passes.final,Passes.middle,eventLog,List.flatMap_append,after,List.foldl_append] + +/-- The public operands for collecting preimages, including the placement data and the +addresses of the counts and rows. -/ +abbrev params (shr : Fin 14 → Word w) := ShrinkPreimages.params X shr (counts X term stride) (rows X term stride) + +/-- Evidence that the two preimage scans ran, produced the selected layout's directory, +preserved memory outside it, and incurred their stated cost. -/ +structure Collected (shr : Fin 14 → Word w) (layout : Bool) (m : Memory w) (p : Passes w) : Prop where + clear : let C := (template SliceRAM.clearOps 0).instantiate w (fun _ => counts X term stride) + runSegment C.program 8 (some 0) m (List.replicate (ShrinkPreimages.newCount X) []) = some p.clear + collect : let C := (template collectPreimage 3).instantiate w (params X term stride shr) + runSegment C.program 23 (some 0) (p.middle m) (List.replicate (ShrinkPreimages.oldCount X) []) = some p.collect + preimages : PreimagesAt (params X term stride shr) (ShrinkPreimages.place X layout) (p.final m) (ShrinkPreimages.oldCount X) + directory : ShrinkPreimages.Directory X layout (counts X term stride) (rows X term stride) (p.final m) + frame : ∀ j, j < countStart X term stride ∨ stop X term stride ≤ j → p.final m j = m j + clearEnd : endState (some 0) p.clear = some (Fin.ofNat _ (ShrinkPreimages.newCount X)) + collectEnd : endState (some 0) p.collect = some (Fin.ofNat _ (ShrinkPreimages.oldCount X)) + clearCount : p.clear.length = ShrinkPreimages.newCount X + collectCount : p.collect.length = ShrinkPreimages.oldCount X + cost : RAMBuckets.cost Report.probes (p.clear++p.collect) = 2*ShrinkPreimages.newCount X+5*ShrinkPreimages.oldCount X + +/-- Both loops start from the live memory left by the selected placement and +role scans. The count clear makes arbitrary old scratch contents harmless. -/ +theorem collect (p₀ : Fin 14 → Word w) (bit : Word w) (layout : Bool) (m : Memory w) + (room : stop X term stride ≤ 2^w) + (place : ShrinkRAM.PlacementColumns X.slots X.baseIndex (shrinkWords X term stride p₀ bit) layout m) : + ∃ p, Collected X term stride (shrinkWords X term stride p₀ bit) layout m p := by + let shr := shrinkWords X term stride p₀ bit + have hA := areas X term stride p₀ bit room + obtain ⟨cs,rs,hc,hr,hpre,dir,frame,hce,hre,hcn,hrn,cost⟩ := ShrinkPreimages.build X hA layout m place + refine ⟨⟨cs,rs⟩,⟨hc,hr,hpre,dir,?_,hce,hre,hcn,hrn,cost⟩⟩ + intro j hj + apply frame j + obtain ⟨_,hc',hr'⟩ := room_vals X term stride room + obtain ⟨_,hN,hC⟩ := hA.dimensions + let q := params X term stride shr + change (j < (counts X term stride).val ∨ (counts X term stride).val+(q 2).val ≤ j) ∧ + (j < (rows X term stride).val ∨ (rows X term stride).val+(q 2).val*(q 4).val ≤ j) + change (q 2).val = ShrinkPreimages.newCount X at hN + change (q 4).val = ShrinkPreimages.capacity a at hC + rw [hc',hr',hN,hC,← ShrinkPreimages.oldCount_eq X] + change j fin_cases t <;> decide + +theorem supplyCoordinate (l : Bool) (t : Fin 4) : supplyOrder.entries (coordinate l t) = (l,t) := by + change (finTwoEquiv.prodCongr (Equiv.refl _)) (finProdFinEquiv.symm (finProdFinEquiv (finTwoEquiv.symm l,t))) = _ + simp + +/-- The established term readback predicate, over the actual filtered old arc list. -/ +def Stored (s : Selection B X) (base : Fin (motifOrder X).length → Word w) (mem : Memory w) : Prop := + ∀ i, let m := (motifOrder X).entries i + TermRecordScan.Fields B.shrink supplyOrder.entries demandMass_pos + (X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth m) (s m).val (base i) mem + +/-- Read a selected coordinate's payload width and add the selector bits contributed by each +repetition in its motif row. -/ +def widthAt (base : Fin (motifOrder X).length → Word w) (mem : Memory w) + (i : Fin (motifOrder X).length) (l : Bool) (t : Fin 4) : ℕ := + (mem ((base i).val+2+(coordinate l t).val)).val + (mem ((base i).val+1)).val * B.shrink.selectorBits + +theorem widthAt_eq (s : Selection B X) (base : Fin (motifOrder X).length → Word w) (mem : Memory w) + (h : Stored B X s base mem) (i : Fin (motifOrder X).length) (l : Bool) (t : Fin 4) : + widthAt B X base mem i l t = + X.packingData.termWidths B.shrink X.shrinkNumber X.packingWidth s ((motifOrder X).entries i) l t := by + obtain ⟨_,hu,hv⟩ := h i + rw [widthAt, hu, hv (coordinate l t)] + rw [supplyCoordinate] + rfl + +/-- The weighted sum of squared selected widths over all motifs and four supply coordinates on +one layout side. -/ +def score (base : Fin (motifOrder X).length → Word w) (mem : Memory w) (l : Bool) : ℕ := + ∑ t : Fin 4, ∑ i : Fin (motifOrder X).length, MotifAdmission.weight relativeMass t * + widthAt B X base mem i l t ^ 2 + +theorem score_eq (s : Selection B X) (base : Fin (motifOrder X).length → Word w) (mem : Memory w) + (h : Stored B X s base mem) (l : Bool) : + score B X base mem l = layoutScore relativeMass + (X.packingData.termWidths B.shrink X.shrinkNumber X.packingWidth s) l := by + unfold score layoutScore MotifAdmission.energy + rw [Finset.sum_comm] + apply Fintype.sum_equiv (motifOrder X).entries + intro i + simp only [widthAt_eq B X s base mem h] + +/-- The bit written on a strict improvement is the actual term-dependent shrinking layout. -/ +theorem chosenLayout_eq (s : Selection B X) (base : Fin (motifOrder X).length → Word w) (mem : Memory w) + (h : Stored B X s base mem) : + decide (score B X base mem true < score B X base mem false) = + X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s := by + rw [score_eq B X s base mem h, score_eq B X s base mem h] + apply selectLayout_eq relativeMass relativeMass_pos + unfold equalArcMass + exact div_pos one_pos (mul_pos (Nat.cast_pos.mpr (Fintype.card_pos (α := Position X.Base (BitWord a) (BitWord (packingTagBits (2^a))) (BitWord g) (2*2^a+1)))) + (Nat.cast_pos.mpr (Nat.two_pow_pos a))) + +end CompressorRecords.SelectedScore + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedScoreRun.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedScoreRun.lean new file mode 100644 index 0000000000..04cbdac4ad --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedScoreRun.lean @@ -0,0 +1,104 @@ +import OAI.Computability.VPVNP.CompressorRecordsSelectedScore +import OAI.Computability.VPVNP.CompressorRecordTermScores + +/-! +# Native selection of the actual shrinking layout + +The two accumulators and the level's chosen-layout cell lie in the allocated +workspace. Each of eight coordinate passes visits the selected term rows in +motif order and reads the payload and repetition words directly. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SelectedScore + +open Compression BurstRAM PairSimulation.LocalHistory ShrinkMotif TermScores +open scoped Fin.CommRing Classical + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) + +/-- The coordinate number, layout side, and integer weight used by one of the eight +score-accumulation passes. -/ +def axes (j : Fin 8) : Axis w := + let e := supplyOrder.entries j + ⟨TermScores.word j.val, e.1, TermScores.word (MotifAdmission.weight relativeMass e.2)⟩ + +theorem axes_side (j : Fin 2 × Fin 4) : + (axes (w := w) (finProdFinEquiv j)).side = finTwoEquiv j.1 := by + change ((finTwoEquiv.prodCongr (Equiv.refl _)) (finProdFinEquiv.symm (finProdFinEquiv j))).1 = _ + rw [Equiv.symm_apply_apply]; rfl + +/-- Address of the term record for a motif at the given position in the physical score scan. -/ +def headAt (L : Tables w) (i : Fin (motifOrder X).length) := rowBase L (TermScores.word i.val) + +theorem total_score (L : Tables w) (m : Memory w) + (hstride : 10 ≤ L.termStride.val) + (hterm : L.termBase.val + (motifOrder X).length * L.termStride.val ≤ 2^w) + (hc : 8 ≤ 2^w) (hw : ∀ t, MotifAdmission.weight relativeMass t < 2^w) + (hs : L.selectorBits.val = B.shrink.selectorBits) (l : Bool) : + total L m (motifOrder X).length (List.ofFn axes) l = score B X (headAt X L) m l := by + rw [total_fin_axes L m _ axes axes_side] + unfold score + apply Finset.sum_congr rfl + intro t _ + apply Finset.sum_congr rfl + intro i _ + let j := coordinate l t + have hcoord : (axes (w := w) j).coordinate.val = j.val := Nat.mod_eq_of_lt (j.isLt.trans_le hc) + have weight : (axes (w := w) j).weight.val = MotifAdmission.weight relativeMass t := by + change (TermScores.word (w := w) (MotifAdmission.weight relativeMass (supplyOrder.entries j).2)).val = _ + rw [show supplyOrder.entries j = (l,t) from supplyCoordinate l t] + exact Nat.mod_eq_of_lt (hw t) + have room : L.termBase.val+i.val*L.termStride.val+2+j.val < 2^w := by + have h := Nat.mul_le_mul_right L.termStride.val i.isLt + rw [Nat.succ_mul] at h + have := j.isLt + omega + have hr := repetitions_val L (i := i.val) (by omega) + have hv := payload_val L (axes (w := w) j) (i := i.val) (hcoord ▸ room) + have hb := rowBase_val L (i := i.val) (by omega) + change (axes j).weight.val * supplyWidth L (axes j) m i.val ^ 2 = _ + rw [weight,supplyWidth,hr,hv,hcoord,hs] + change _ = _ * ((m ((rowBase L (TermScores.word i.val)).val+2+j.val)).val + + (m ((rowBase L (TermScores.word i.val)).val+1)).val * B.shrink.selectorBits)^2 + rw [hb] + +/-- Run all eight native scans on the true selected term records. Read the chosen +layout in the resulting memory, with exact call/probe charges and the frame. -/ +theorem run_selected (L : Tables w) (m : Memory w) (s : Selection B X) + (stored : Stored B X s (headAt X L) m) + (hstride : 10 ≤ L.termStride.val) + (hterm : L.termBase.val + (motifOrder X).length * L.termStride.val ≤ 2^w) + (hc : 8 ≤ 2^w) (hw : ∀ t, MotifAdmission.weight relativeMass t < 2^w) + (hs : L.selectorBits.val = B.shrink.selectorBits) + (layout : TermScores.Layout L (motifOrder X).length (List.ofFn axes)) + (fit : ∀ l, layoutScore relativeMass (X.packingData.termWidths B.shrink X.shrinkNumber X.packingWidth s) l < 2^w) : + let n := (motifOrder X).length + let chosen := X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s + ∃ rs, TermScores.run L n (List.ofFn axes) m = some rs ∧ + after m (eventLog rs) L.levelCell.val = (chosen.toNat : Word w) ∧ + endState (some 0) rs = some (chosen.toNat : Word w) ∧ + (∀ j, j ≠ L.levelCell.val → (∀ l, j ≠ (counter L l).val) → after m (eventLog rs) j = m j) ∧ + rs.length = 8*n+2 ∧ RAMBuckets.probeCount Report.probes rs = 32*n+5 := by + let N := (motifOrder X).length + let htot (l : Bool) := total_score B X L m hstride hterm hc hw hs l + have valid (l : Bool) : total L m N (List.ofFn axes) l < 2^w := by + rw [htot l, score_eq B X s _ _ stored] + exact fit l + obtain ⟨rs,hr,_,hcell,hframe,hstate,hcalls,hprobes⟩ := run_eight L N axes m layout valid + have bit : (if total L m N (List.ofFn axes) true < total L m N (List.ofFn axes) false then + (1 : Word w) else 0) = + ((X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s).toNat : Word w) := by + rw [htot true,htot false, ← chosenLayout_eq B X s _ _ stored] + by_cases hlt : score B X (headAt X L) m true < score B X (headAt X L) m false <;> simp [hlt] + exact ⟨rs,hr,hcell.trans bit,hstate.trans (congrArg some bit),hframe,hcalls,hprobes⟩ + +end CompressorRecords.SelectedScore + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedStage.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedStage.lean new file mode 100644 index 0000000000..7cae2b8a61 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsSelectedStage.lean @@ -0,0 +1,216 @@ +import OAI.Computability.VPVNP.CompressorRecordsSelectedArenaDemand +import OAI.Computability.VPVNP.CompressorRecordsSelectedScoreRun + +/-! +# Chronological layout, position and demand-record passes + +After the selected motif records have been written, compare their two layout +scores. Use the resulting memory word as the placement scan's operand, then use +the newly written positions and the original incidence table to materialize the +absolute A/B/D/CD directory. The three groups of calls occupy consecutive, +disjoint workspace intervals. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SelectedStage + +open Compression BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ShrinkMotif +open SelectedArena +open scoped Fin.CommRing Classical + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) +variable (term stride selectors : Word w) (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) + +private theorem address_lt (base : Word w) {endAt n j : ℕ} (h : base.val+n ≤ endAt) (hj : j (same _ (addr _ hO e)).trans (inc.actualOut e), + fun e => (same _ (addr _ hI e)).trans (inc.actualIn e), + fun e => (same _ (addr _ hW e)).trans (inc.width e)⟩ + +/-- Report groups in actual execution order. -/ +structure Passes (w : ℕ) where + /-- The reports that accumulate the two layout scores and compare them to select a layout. -/ + scores : List (Report w) + /-- The reports of placing old sites using the layout selected by the preceding score + comparison. -/ + positions : List (Report w) + /-- The reports that construct absolute A, B, D, and CD demand records from the selected + placement and old incidence. -/ + roles : List (Report w) + +/-- The memory containing the completed score accumulators and layout selection. -/ +def Passes.afterScores (p : Passes w) (m : Memory w) := after m (eventLog p.scores) +/-- The memory handed to the role scan after writing the selected old-site placements. -/ +def Passes.afterPositions (p : Passes w) (m : Memory w) := after (p.afterScores m) (eventLog p.positions) +/-- The memory after scoring, site placement, and absolute role construction in chronological +order. -/ +def Passes.final (p : Passes w) (m : Memory w) := after (p.afterPositions m) (eventLog p.roles) +/-- Concatenate the score, position, and role reports in their execution order. -/ +def Passes.all (p : Passes w) := (p.scores++p.positions)++p.roles + +theorem Passes.all_after (p : Passes w) (m : Memory w) : after m (eventLog p.all) = p.final m := by + simp only [Passes.all,Passes.final,Passes.afterPositions,Passes.afterScores,eventLog,List.flatMap_append, + after,List.foldl_append] + +/-- The score writes, old-position scan, and final old-arc scan all run in this same memory. -/ +structure Execution (mem : Memory w) (p : Passes w) : Prop where + scores : TermScores.run (scoreTables X term stride selectors) (motifs X) + (List.ofFn SelectedScore.axes) mem = some p.scores + positions : let pub := selectedWords X term stride p₀ (p.afterScores mem) + let M := (template ShrinkRAM.visit 0).instantiate w pub + runSegment M.program 65 (some 0) (p.afterScores mem) (List.replicate (SelectedArena.positions X) []) = some p.positions + roles : let M := (template DemandRAM.visit 0).instantiate w (demandWords X term stride p₀ T) + runSegment M.program 65 (some 0) (p.afterPositions mem) (List.replicate (DemandRAM.oldCount X) []) = some p.roles + incidenceBeforeRoles : T.ActualColumns X (p.afterPositions mem) + +/-- The workspace cells still available after constructing the old-arc record table. -/ +structure Stored (s : SelectedScore.Selection B X) (mem : Memory w) (p : Passes w) : Prop where + chosen : (p.final mem) (origin X term stride+2) = + ((X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s).toNat : Word w) + placement : ShrinkRAM.PlacementColumns X.slots X.baseIndex + (selectedWords X term stride p₀ (p.afterScores mem)) + (X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s) (p.final mem) + placementBeforeRoles : ShrinkRAM.PlacementColumns X.slots X.baseIndex + (selectedWords X term stride p₀ (p.afterScores mem)) + (X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s) (p.afterPositions mem) + roles : DemandRAM.RoleColumns X (X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s) + (roleBase X term stride) (p.final mem) + frame : ∀ j, j scFrame j (.inl hj)) dir + have reg := shrink_regions X term stride p₀ T bit hp' old fit + have ho : DemandRAM.oldCount X ≤ 2^w := by + rw [DemandRAM.count_eq X] + change roleBase X term stride + 4*DemandRAM.absoluteCount X < 2^w at hend + omega + have hslot : Fintype.card X.Base*(2^(Shrink.J a)*2^g)*2^a ≤ 2^w := by + apply le_trans _ ho + apply Nat.mul_le_mul_right + rw [← pow_add] + apply Nat.mul_le_mul_left + apply Nat.pow_le_pow_right (by decide) + unfold packingLaneBits Shrink.J + omega + obtain ⟨pr,hprun,hpscan,hplace⟩ := ShrinkRAM.placement_run X.slots X.baseIndex p b m₁ hp' d' reg hslot + let m₂ := after m₁ (eventLog pr) + have posFrame := shrink_frame X term stride p₀ bit fit hpscan + have inc' := carry_actual X T old.actualOut hI hW + (m' := m₂) (fun j hj => (posFrame j (.inl (by omega))).trans (scFrame j (.inl hj))) inc + obtain ⟨rr,hrrun,hrole,roFrame,_,_,rc⟩ := + SelectedArena.run_roles X term stride p₀ T bit m₂ b hp inc' hplace old fit + let passes : Passes w := ⟨sr,pr,rr⟩ + refine ⟨passes,⟨hsrun,hprun,hrrun,inc'⟩,⟨?_,?_,hplace,hrole,?_⟩,sc,sp,hpscan.cost,rc⟩ + · exact (roFrame _ (.inl (by omega))).trans ((posFrame _ (.inl h₀)).trans cell) + · constructor + intro x + let i := ShrinkRAM.word w (Shrink.oldNumber X.baseIndex x) + have iv : i.val < positions X := by + have le : i.val ≤ Shrink.oldNumber X.baseIndex x := Nat.mod_le .. + rw [← Shrink.oldIndex_val] at le + exact le.trans_lt (Shrink.oldIndex X.baseIndex x).isLt + have f (t : Fin 4) : passes.final m (ShrinkRAM.outAddr p t i) = m₂ (ShrinkRAM.outAddr p t i) := by + apply roFrame _ ∘ Or.inl + have hc := output_column X term stride p₀ bit fit t + have ht := Nat.mul_le_mul_right (positions X) t.isLt + rw [Nat.succ_mul] at ht + change ((p (t.natAdd 10)).val+i.val) % (2^w) < roleBase X term stride + change (p (t.natAdd 10)).val = _ at hc + unfold roleBase + rw [hc] + exact (Nat.mod_le ..).trans_lt (by omega) + change ((passes.final m (ShrinkRAM.outAddr p 0 i)).val,(passes.final m (ShrinkRAM.outAddr p 1 i)).val, + (passes.final m (ShrinkRAM.outAddr p 2 i)).val,(passes.final m (ShrinkRAM.outAddr p 3 i)).val) = _ + rw [f 0,f 1,f 2,f 3]; exact hplace.atSite x + · intro j hj + rcases hj with h | h + · exact (roFrame j (.inl (by omega))).trans ((posFrame j (.inl (by omega))).trans (scFrame j (.inl h))) + · exact (roFrame j (.inr h)).trans ((posFrame j (.inr (by omega))).trans (scFrame j (.inr (by omega)))) + +end CompressorRecords.SelectedStage + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrink.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrink.lean new file mode 100644 index 0000000000..e15c541abd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrink.lean @@ -0,0 +1,318 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshOldWidths +import OAI.Computability.VPVNP.BitSlotXor +import OAI.Computability.VPVNP.CompressorRecordPlacement +import OAI.Computability.VPVNP.ShrinkStateInput + +/-! +# Numeric addresses in the shrinking placement pass + +An old position is scanned in base, color-mask, slot-label, tag, residual-lane order. +The four directory reads are the base color, base offset, base slot mate, and its +displacement. The low tag and lane fields are kept together when the offset and the +base displacement are applied. This computes both possible layout owners even when +the two endpoints are thin. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Shrink + +open Compression + +/-- Concatenate a most-significant field and a low binary field. -/ +def join (g x y : ℕ) := x * 2 ^ g + y + +private theorem join_div (g x : ℕ) {y : ℕ} (hy : y < 2 ^ g) : join g x y / 2 ^ g = x := by + rw [join, Nat.mul_comm x, Nat.mul_add_div (Nat.two_pow_pos _), Nat.div_eq_of_lt hy, Nat.add_zero] + +private theorem join_mod (g x : ℕ) {y : ℕ} (hy : y < 2 ^ g) : join g x y % 2 ^ g = y := + Nat.mul_add_mod_of_lt hy + +private theorem join_lt {g j x y : ℕ} (hx : x < 2^j) (hy : y < 2^g) : + join g x y < 2 ^ (j+g) := by + rw [join, pow_add] + calc + x * 2^g + y < x * 2^g + 2^g := by omega + _ = (x+1)*2^g := by ring + _ ≤ 2^j*2^g := Nat.mul_le_mul_right _ hx + +theorem join_xor (g x t : ℕ) {y l : ℕ} (hy : y < 2^g) (hl : l < 2^g) : + join g x y ^^^ join g t l = join g (x ^^^ t) (y ^^^ l) := by + rw [← Nat.mod_add_div (join g x y ^^^ join g t l) (2^g)] + rw [Nat.xor_mod_two_pow, Nat.xor_div_two_pow, join_mod g x hy, join_mod g t hl, + join_div g x hy, join_div g t hl, join] + ac_rfl + +/-- The color bit selected by the indexed greedy coloring, in big-endian lane order. -/ +theorem bitWord_test {c : ℕ} (u : BitWord c) (j : Fin c) : + (bitWordFinEquiv c u).val.testBit (c-1-j.val) = decide (u j = 1) := by + induction c with + | zero => exact j.elim0 + | succ n ih => + rw [bitWordFinEquiv_val, Nat.add_comm, Nat.testBit_two_pow_mul_add _ (bitWordFinEquiv n (Fin.tail u)).isLt] + induction j using Fin.cases with + | zero => + simp only [Fin.val_zero, Nat.sub_zero, Nat.add_sub_cancel, lt_self_iff_false, ite_false, Nat.sub_self] + generalize u 0 = b + decide +revert + | succ j => + have h : n - (j.val+1) < n := by have := j.isLt; omega + rw [Fin.val_succ, Nat.add_sub_cancel, ite_eq_left h, show n-(j.val+1)=n-1-j.val by omega, ih] + rfl + +/-- The four natural-number fields obtained by decoding an old site for the shrinking placement +scan. -/ +structure Fields where + /-- The index of the old base vertex whose greedy color and offset are consulted. -/ + base : ℕ + /-- The old site's color mask, tested at its base vertex's assigned color to determine + thickness. -/ + mask : ℕ + /-- The old site's slot label, used to look up the mate and displacement at its base port. -/ + slot : ℕ + /-- The combined tag and residual-lane bits, kept together when applying the greedy offset + and the arc displacement. -/ + low : ℕ + +/-- The concatenated tag and residual lane occupy the least significant bits. -/ +def decode (a c lowBits i : ℕ) : Fields := + let v := i / 2^lowBits + let b := v / 2^a + ⟨b / 2^c, b % 2^c, v % 2^a, i % 2^lowBits⟩ + +theorem decode_join (a c l b u h low : ℕ) (hu : u < 2^c) (hh : h < 2^a) (hl : low < 2^l) : + decode a c l (join l (join a (join c b u) h) low) = ⟨b,u,h,low⟩ := by + simp [decode, join_div _ _ hu, join_div _ _ hh, join_div _ _ hl, + join_mod _ _ hu, join_mod _ _ hh, join_mod _ _ hl] + +/-- The packed site, bundle endpoints, assigned port, thickness, and layout-dependent owner +calculated for one old position. -/ +structure Row (α : Type) where + /-- The packed index obtained by retaining the old position's base, tag, and residual lane. -/ + packed : α + /-- The bundle's source site A, obtained by applying the base vertex's greedy offset to the + low lane bits. -/ + source : α + /-- The bundle's target site B, obtained from the base mate and the displaced source lane. -/ + target : α + /-- The bundle's outgoing port, combining its source-site index with the old slot label. -/ + assigned : α + /-- Whether the bit at the old base vertex's greedy color is set in this position's mask. -/ + thick : Bool + /-- The packed owner of the old position, using the packed site for a thick position and the + chosen bundle endpoint for a thin one. -/ + owner : α + deriving DecidableEq + +/-- Four source columns and a layout bit determine the records for this position. -/ +def row (a c j g : ℕ) (layout : Bool) (color offset mate displacement : ℕ → ℕ) + (i : ℕ) : Row ℕ := + let f := decode a c (j+g) i + let e := f.base * 2^a + f.slot + let thick := f.mask.testBit (c-1-color f.base) + let laneA := f.low ^^^ (offset f.base * 2^g) + let A := join (j+g) f.base laneA + let B := join (j+g) (mate e / 2^a) (laneA ^^^ (displacement e % 2^(j+g))) + let packed := join (j+g) f.base f.low + ⟨packed,A,B,A*2^a + f.slot,thick,if thick then packed else if layout then B else A⟩ + +variable {V : Type} {n a g : ℕ} +/-- Number of packing-tag bits for a graph whose degree is two to the given exponent. -/ +abbrev J (a : ℕ) := packingTagBits (2^a) +/-- The number of greedy colors for the old graph, twice its degree plus one. -/ +abbrev colors (a : ℕ) := 2 * 2^a + 1 +/-- A site after shrinking, consisting of a base vertex, packing tag, and residual lane. -/ +abbrev Packed (V : Type) (a g : ℕ) := Site V (BitWord (J a)) (BitWord g) +/-- A position before shrinking, with its base site, tag, residual lane, color mask, and slot +label. -/ +abbrev Old (V : Type) (a g : ℕ) := Position V (BitWord a) (BitWord (J a)) (BitWord g) (colors a) + +/-- Concatenate the binary packing tag above the residual-lane bits to form the low part of a +site number. -/ +def lowNumber (v : BitWord (J a) × BitWord g) : ℕ := + join g (bitWordFinEquiv (J a) v.1).val (bitWordFinEquiv g v.2).val + +/-- Number a packed site by concatenating the ordered base vertex with the tag-and-lane number. -/ +def packedNumber (order : V ≃ Fin n) (v : Packed V a g) : ℕ := + join (J a + g) (order v.1).val (lowNumber v.2) + +/-- Number an old position in base, mask, slot-label, tag, and residual-lane order. -/ +def oldNumber (order : V ≃ Fin n) (x : Old V a g) : ℕ := + join (J a + g) (join a (join (colors a) (order x.1.1).val + (bitWordFinEquiv (colors a) x.2.1).val) (bitWordFinEquiv a x.2.2).val) (lowNumber x.1.2) + +theorem decode_oldNumber (order : V ≃ Fin n) (x : Old V a g) : + decode a (colors a) (J a+g) (oldNumber order x) = + ⟨(order x.1.1).val, (bitWordFinEquiv (colors a) x.2.1).val, + (bitWordFinEquiv a x.2.2).val, lowNumber x.1.2⟩ := + decode_join _ _ _ _ _ _ _ (Fin.isLt _) (Fin.isLt _) (join_lt (Fin.isLt _) (Fin.isLt _)) + +private theorem lowNumber_add (u v : BitWord (J a) × BitWord g) : + lowNumber (u+v) = lowNumber u ^^^ lowNumber v := by + unfold lowNumber + rw [join_xor _ _ _ (Fin.isLt _) (Fin.isLt _)] + simp only [Prod.fst_add, Prod.snd_add, bitWordFinEquiv_add_val] + +private theorem lowNumber_offset (u : BitWord (J a) × BitWord g) (s : BitWord (J a)) : + lowNumber (u.1+s,u.2) = lowNumber u ^^^ ((bitWordFinEquiv (J a) s).val * 2^g) := by + have hz : (bitWordFinEquiv g (0 : BitWord g)).val = 0 := by + simpa using bitWordFinEquiv_add_val (0 : BitWord g) 0 + have h := lowNumber_add u (s,0) + simpa [lowNumber, join, hz] using h + +/-- Directory invariant at the start of a placement scan. Base slots retain both their +outgoing and incoming numbers; displacement is stored in the full old lane order. -/ +structure Directory (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) + (order : V ≃ Fin n) (color offset mate displacement : ℕ → ℕ) : Prop where + color_at : ∀ v, color (order v).val = ((orderedDyadicPacking G order).color v).val + offset_at : ∀ v, offset (order v).val = + (bitWordFinEquiv (J a) ((orderedDyadicPacking G order).offset v)).val + mate_at : ∀ v h, mate (join a (order v).val h.val) = + join a (order (G.base.target (v,h)).1).val (G.base.target (v,h)).2.val + shift_at : ∀ v h, displacement (join a (order v).val h.val) = + (bitWordFinEquiv (packingLaneBits a g) (G.displacement (v,h))).val + +theorem packingFields_number (x : BitWord (packingLaneBits a g)) : + (bitWordFinEquiv _ x).val = join (J a+g) + (join a (bitWordFinEquiv (colors a) (packingFields a g x).1).val + (bitWordFinEquiv a (packingFields a g x).2.1).val) (lowNumber (packingFields a g x).2.2) := by + let y := (splitBitWord (colors a) (a+(J a+g)) x).2 + let z := (splitBitWord a (J a+g) y).2 + rw [splitBitWord_number (colors a) (a+(J a+g)) x, + show (splitBitWord (colors a) (a+(J a+g)) x).2 = y from rfl, splitBitWord_number a (J a+g) y, + show (splitBitWord a (J a+g) y).2 = z from rfl, splitBitWord_number (J a) g z] + change _ = ((bitWordFinEquiv (colors a) ((splitBitWord _ _ x).1)).val * 2^a + + (bitWordFinEquiv a ((splitBitWord _ _ y).1)).val) * 2^(J a+g) + + ((bitWordFinEquiv (J a) ((splitBitWord _ _ z).1)).val * 2^g + + (bitWordFinEquiv g ((splitBitWord _ _ z).2)).val) + rw [pow_add 2 a] + ring + +/-- The full old site scan follows the order of the original compression state. -/ +theorem oldNumber_original (order : V ≃ Fin n) (x : Old V a g) : + oldNumber order x = (order x.1.1).val * 2^(packingLaneBits a g) + + (bitWordFinEquiv _ ((packingInputSites V a g x).2)).val := by + let l := (packingFields a g).symm (x.2.1,x.2.2,x.1.2) + change _ = _ + (bitWordFinEquiv _ l).val + rw [packingFields_number, show packingFields a g l = (x.2.1,x.2.2,x.1.2) from + (packingFields a g).apply_symm_apply _] + simp only [oldNumber, join, packingLaneBits, pow_add] + ring + +/-- Correctness for every old site, including the color and tie conventions of Appendix C. -/ +theorem row_exact (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) + (order : V ≃ Fin n) {color offset mate displacement : ℕ → ℕ} + (d : Directory G order color offset mate displacement) (layout : Bool) (x : Old V a g) : + let P := orderedDyadicPacking G order + let e := P.assignedBundle x + row a (colors a) (J a) g layout color offset mate displacement (oldNumber order x) = + ⟨packedNumber order x.1, packedNumber order e.1, packedNumber order (P.siteGraph.target e).1, + join a (packedNumber order e.1) e.2.val, decide (P.thick x), packedNumber order (P.placement layout x)⟩ := by + let P := orderedDyadicPacking G order + let h := bitWordFinEquiv a x.2.2 + let v := x.1.1 + let e := P.assignedBundle x + have htag : lowNumber e.1.2 = lowNumber x.1.2 ^^^ (offset (order v).val * 2^g) := by + rw [d.offset_at] + exact lowNumber_offset x.1.2 (P.offset v) + have hs := packingFields_number (G.displacement (v,h)) + have hsmod : displacement (join a (order v).val h.val) % 2^(J a+g) = + lowNumber (P.siteShift (v,h)) := by + have hlow : lowNumber ((packingFields a g) (G.displacement (v,h))).2.2 < 2^(J a+g) := + join_lt (Fin.isLt _) (Fin.isLt _) + rw [d.shift_at, hs, join_mod _ _ hlow] + rfl + have hb : mate (join a (order v).val h.val) / 2^a = (order (G.base.target (v,h)).1).val := by + rw [d.mate_at, join_div _ _ (Fin.isLt _)] + have ht : (bitWordFinEquiv (colors a) x.2.1).val.testBit (colors a-1-color (order v).val) = + decide (P.thick x) := by rw [d.color_at]; exact bitWord_test _ _ + have hA : packedNumber order e.1 = join (J a+g) (order v).val + (lowNumber x.1.2 ^^^ (offset (order v).val * 2^g)) := by rw [← htag]; rfl + have hB : packedNumber order (P.siteGraph.target e).1 = + join (J a+g) (order (G.base.target (v,h)).1).val (lowNumber e.1.2 ^^^ lowNumber (P.siteShift (v,h))) := by + rw [← lowNumber_add] + rfl + let sa := join (J a+g) (order v).val (lowNumber x.1.2 ^^^ (offset (order v).val * 2^g)) + let sb := join (J a+g) (mate (join a (order v).val h.val) / 2^a) + ((lowNumber x.1.2 ^^^ (offset (order v).val * 2^g)) ^^^ + (displacement (join a (order v).val h.val) % 2^(J a+g))) + have eqB : sb = packedNumber order (P.siteGraph.target e).1 := by + dsimp only [sb]; rw [hb, hsmod, ← htag, ← hB] + unfold row + rw [decode_oldNumber] + change Row.mk (packedNumber order x.1) sa sb (join a sa h.val) _ + (if _ then packedNumber order x.1 else if layout then sb else sa) = + Row.mk _ (packedNumber order e.1) (packedNumber order (P.siteGraph.target e).1) + (join a (packedNumber order e.1) h.val) (decide (P.thick x)) (packedNumber order (P.placement layout x)) + rw [ht, eqB, show sa = packedNumber order e.1 from hA.symm] + by_cases hx : P.thick x <;> cases layout <;> simp [PackingData.placement, hx, e] + + +/-- Old sites are scanned in the original state numbering. -/ +def oldIndex (order : V ≃ Fin n) : Old V a g ≃ Fin (n * 2^(packingLaneBits a g)) := + (packingInputSites V a g).trans ((order.prodCongr (bitWordFinEquiv _)).trans finProdFinEquiv) + +/-- The packed vertex combines the promoted tag and remaining lane. -/ +def packedIndex (order : V ≃ Fin n) : Packed V a g ≃ Fin (n * (2^(J a) * 2^g)) := + (order.prodCongr (((bitWordFinEquiv (J a)).prodCongr (bitWordFinEquiv g)).trans + finProdFinEquiv)).trans finProdFinEquiv + +theorem oldIndex_val (order : V ≃ Fin n) (x : Old V a g) : + (oldIndex order x).val = oldNumber order x := by + rw [oldNumber_original] + change _ + _ * _ = _ * _ + _ + ac_rfl + +theorem packedIndex_val (order : V ≃ Fin n) (x : Packed V a g) : + (packedIndex order x).val = packedNumber order x := by + change (bitWordFinEquiv g x.2.2).val + 2^g * (bitWordFinEquiv (J a) x.2.1).val + + (2^(J a)*2^g) * (order x.1).val = _ * 2^(J a+g) + (_ * _ + _) + rw [pow_add] + ring + +/-- On the numerical old-site prefix, the computed owner is exactly the placement +whose fibers are scanned by the native preimage-list builder. -/ +theorem owner_encoded (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) + (order : V ≃ Fin n) {color offset mate displacement : ℕ → ℕ} + (d : Directory G order color offset mate displacement) (layout : Bool) + {w : ℕ} (ho : n * 2^(packingLaneBits a g) ≤ 2^w) (hn : n * (2^(J a) * 2^g) ≤ 2^w) + (i : Fin (n * 2^(packingLaneBits a g))) : + (row a (colors a) (J a) g layout color offset mate displacement i.val).owner = + (encodedPlacement (oldIndex order) (packedIndex order) + ((orderedDyadicPacking G order).placement layout) (Fin.ofNat (2^w) i.val)).val := by + rw [encodedPlacement_eq _ _ _ ho hn i, packedIndex_val] + have he : i.val = oldNumber order ((oldIndex order).symm i) := by + rw [← oldIndex_val, Equiv.apply_symm_apply] + rw [he, row_exact G order d] + +/-- Read the two endpoint rows to determine the thin C role and opposite D owner. +The source is used as C when both endpoints are thin. -/ +def demandRoles (src dst : Row ℕ) : ℕ × ℕ × ℕ × ℕ := + let C := if src.thick then dst else src + let D := if src.thick then src else dst + (C.assigned,C.source,C.target,D.owner) + +theorem demandRoles_exact (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) + (order : V ≃ Fin n) {color offset mate displacement : ℕ → ℕ} + (d : Directory G order color offset mate displacement) (layout : Bool) + (m : (orderedDyadicPacking G order).Motif) : + let P := orderedDyadicPacking G order + let readRow := fun x : Old V a g => row a (colors a) (J a) g layout color offset mate + displacement (oldNumber order x) + demandRoles (readRow (sourcePosition m.val)) (readRow (sourcePosition (P.actual m.val))) = + (join a (packedNumber order (P.roleA m)) (P.bundle m).2.val, + packedNumber order (P.roleA m), packedNumber order (P.roleB m), + packedNumber order (P.roleD layout m)) := by + dsimp only + rw [row_exact G order d, row_exact G order d] + by_cases ht : (orderedDyadicPacking G order).thick (sourcePosition m.val) <;> + simp [demandRoles, PackingData.roleA, PackingData.roleB, PackingData.roleD, PackingData.bundle, + PackingData.C, PackingData.D, ht] + +end CompressorRecords.Shrink + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkBranch.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkBranch.lean new file mode 100644 index 0000000000..053448ae8b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkBranch.lean @@ -0,0 +1,162 @@ +import OAI.Computability.VPVNP.CompressorRecordsChosenGeometry +import OAI.Computability.VPVNP.CompressorShrinkBundleAbsolute +import OAI.Computability.VPVNP.CompressorShrinkBundleFrame +import OAI.Computability.VPVNP.CompressorRecordsShrinkSelectedInputs + +/-! +# The ordered shrinking branch through the selected geometry + +Starting from an old represented wire graph and unused workspace, generate the +greedy geometry, sort and split the demand bundles, and transpose their old arc IDs. +The deterministic prefix is independent of the forthcoming term stream. At the +following worker the legal tapes are in bijection with the original shrinking +choices. On each such choice, use its output words to build the selected role and +preimage directories while retaining the dense absolute-ID table. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkBranch + +open Compression BurstRAM ShrinkMotif +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) +variable (start : ℕ) (stride selectors : Word w) (cap : ℕ) + +local notation "Z" => ShrinkInput.plan X start +local notation "dense" => ShrinkInput.demandHead (w := w) X start +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "oldPub" => ShrinkInput.placementBank X T start +local notation "absHead" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w + +/-- Numerical bounds of the deterministic input scans and the admitted-term worker. -/ +structure PrefixFits : Prop where + before : ∀ c : Fin 6, (T.column c).val+DemandRAM.oldCount X ≤ start + wide : 10 ≤ stride.val + termRoom : ShrinkInput.termEnd X start stride.val < 2^w + widthRoom : (Z).Q*X.maxWireWidth < 2^w + termWords : ShrinkTermSelection.fitConstant B.shrink+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w + gatherClock : ShrinkDemandGather.cost < cap + termClock : TermWorker.budget B.shrink 2 8 w X.maxWireWidth ≤ cap + +/-- Actual chronological reports before the first nondeterministic shrinking call. -/ +structure Prefix (m : Memory w) where + /-- The deterministic shrinking-input run that produces the sorted AB and CD width data. -/ + input : ShrinkInput.Run X T start m + /-- Reports of writing the absolute old arc identifiers into the bundle directory before term + selection. -/ + absolute : List (Report w) + /-- Reports of gathering the demand data into dense motif rows for the term chooser. -/ + gather : List (Report w) + absoluteRun : ShrinkBundlePlan.AbsoluteRun input absolute + gatherRun : ShrinkDemandGather.Gathered (ShrinkTermSelection.bundles X) (ShrinkTermSelection.ranks a) + (ShrinkInput.pairBank X T start) cap (after input.post (eventLog absolute)) gather + +namespace Prefix + +variable {X T start cap} {m : Memory w} + +/-- The memory at entry to the term chooser, after input construction, absolute arc indexing, +and demand gathering. -/ +def beforeTerm (p : Prefix X T start cap m) := after (after p.input.post (eventLog p.absolute)) (eventLog p.gather) +/-- All reports before the first term choice, in the order of input preparation, absolute arc +indexing, and demand gathering. -/ +def reports (p : Prefix X T start cap m) := (p.input.reports++p.absolute)++p.gather + +theorem replay (p : Prefix X T start cap m) : after m (eventLog p.reports) = p.beforeTerm := by + rw [reports,eventLog,List.flatMap_append,List.flatMap_append,after,List.foldl_append,List.foldl_append] + change after (after (after m (eventLog p.input.reports)) (eventLog p.absolute)) (eventLog p.gather) = _ + rw [p.input.post_reports]; rfl + +end Prefix + +/-- Fixed chronological term and chosen-geometry runs for a specified shrinking choice. -/ +structure Selected (m : Memory w) (p : Prefix X T start cap m) (s : SelectedScore.Selection B X) where + /-- Reports of the term-selection calls for the specified motif choices. -/ + terms : List (Report w) + /-- The native construction of the layout, role records, and child directory determined by + those choices. -/ + geometry : ChosenGeometry.Construction w + termRun : ShrinkTermSelection.Written B.shrink X dense term stride.val cap s p.beforeTerm terms + postTerm : ChosenGeometry.Run B X term stride selectors oldPub T s p.beforeTerm terms geometry + absoluteDirectory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber absHead + (geometry.final (after p.beforeTerm (eventLog terms))) + lowerFrame : ∀ j, j ShrinkInput.plan X start +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "dense" => ShrinkInput.demandHead (w := w) X start +local notation "bank" => ShrinkInput.placementBank X T start +local notation "ids" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w +local notation "keepEnd" => SelectedFinish.stop X (ShrinkInput.termHead (w := w) X start) stride +local notation "role" => SelectedArena.roleBase X (ShrinkInput.termHead (w := w) X start) stride + +private theorem absolute_room (room : ShrinkInput.termEnd X start stride.val < 2^w) : + (ids).val + ShrinkOutput.motifCount X ≤ keepEnd := by + have h₀ : (ids).val ≤ (Z).gathered+(Z).B*(Z).Q := Nat.mod_le .. + have hr : (Z).gathered + (Z).B*(Z).Q + (Z).B*(Z).Q = (Z).ranks := by + change _ = (Z).gathered+(2*(Z).B)*(Z).Q + ring + have hc : ShrinkOutput.motifCount X = (Z).B*(Z).Q := rfl + have h₁ : (Z).ranks ≤ ShrinkInput.stop X start := by + change (Z).ranks ≤ (Z).ranks+(Z).A + _ + _ + omega + have h₂ : ShrinkInput.stop X start ≤ (term).val := by + unfold ShrinkInput.termEnd at room + change _ ≤ (_+_ : ℕ) % 2^w + rw [Nat.mod_eq_of_lt (by omega)] + omega + have h₃ : (term).val ≤ keepEnd := by + unfold SelectedFinish.stop SelectedFinish.rowStart SelectedFinish.countStart SelectedArena.endAddr + SelectedArena.roleBase SelectedArena.placementBase SelectedArena.origin + omega + rw [hc] + omega + +/-- The stored outcomes of every native part of a full shrinking pass. -/ +structure Complete (m : Memory w) (p : Prefix X T start cap m) (s : SelectedScore.Selection B X) where + /-- The chosen term and geometry runs extending this deterministic shrinking prefix. -/ + selected : Selected B X T start stride selectors cap m p s + /-- The native passes building the next state's widths and slot directory from the selected + records. -/ + output : ShrinkOutput.Passes w + outputRun : ShrinkOutput.Complete B X ready s term stride ids cap selected.beforeOutput output + +namespace Complete + +variable {B X ready T start stride selectors cap} {m : Memory w} +variable {p : Prefix X T start cap m} {s : SelectedScore.Selection B X} +variable (r : Complete B X ready T start stride selectors cap m p s) + +/-- The complete branch trace in prefix, selected-term and geometry, then output order. -/ +def reports := (p.reports ++ r.selected.reports) ++ r.output.reports + +/-- The physical RAM memory after the entire branch is the post-memory of the slot construction. -/ +theorem replay : after m (eventLog r.reports) = r.output.final := by + rw [reports,eventLog,List.flatMap_append,List.flatMap_append,after,List.foldl_append,List.foldl_append] + change after (after (after m (eventLog p.reports)) (eventLog r.selected.reports)) + (eventLog r.output.reports) = _ + rw [p.replay,r.selected.replay] + exact r.outputRun.replay + +end Complete + +set_option maxHeartbeats 1200000 in +/-- Compile the actual wire-state transition for all admitted choices, in the same order +in which the fused term worker reads their canonical tapes. -/ +theorem build_complete (m : Memory w) (old : T.Represents X m) + (hp : PrefixFits B X T start stride cap) (selectorsFit : selectors.val = B.shrink.selectorBits) + (weightsFit : ∀ t, MotifAdmission.weight relativeMass t < 2^w) + (geometryFit : keepEnd ≤ 2^w) + (outputFit : ShrinkOutput.FitsWords (b := b) X B.shrink term stride.val role keepEnd) + (outputClock : ShrinkSliceSweep.SurvivingNative.ops.length < cap) : + ∃ p : Prefix X T start cap m, + (∀ bs : Fin (ShrinkTermInputs.motifCount X) → List Bool, + (runSegment (ShrinkTermSelection.termProgram B.shrink dense term stride.val) cap (some 0) + p.beforeTerm (List.ofFn bs)).isSome ↔ + ∃! s : X.ShrinkSelection B.shrink, bs = ShrinkTermSelection.tapes B.shrink X s w) ∧ + ∀ s : SelectedScore.Selection B X, + (∀ l, layoutScore relativeMass (X.packingData.termWidths B.shrink X.shrinkNumber X.packingWidth s) l < 2^w) → + Nonempty (Complete B X ready T start stride selectors cap m p s) := by + obtain ⟨p,legal,make⟩ := build B X T start stride selectors cap m old hp selectorsFit weightsFit geometryFit + refine ⟨p,legal,?_⟩ + intro s hs + obtain ⟨r⟩ := make s hs + let before := after p.beforeTerm (eventLog r.terms) + obtain ⟨out,hout⟩ := ShrinkOutput.build_selected B X ready s term stride ids selectors bank before + r.geometry.placed r.geometry.children r.postTerm.geometry hp.wide outputFit + (absolute_room X start stride hp.termRoom) r.absoluteDirectory cap outputClock + exact ⟨⟨r,out,hout⟩⟩ + +end CompressorRecords.ShrinkBranch + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkFrame.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkFrame.lean new file mode 100644 index 0000000000..b0b135f97d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkFrame.lean @@ -0,0 +1,77 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleInputs + +/-! +# Retaining the old incidence and placement directories across shrink passes + +Both directories precede the temporary width and ordering arrays. A frame +theorem below the new arena therefore retains their typed readbacks even +when the following pass starts with arbitrary contents in its own region. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM Compression + +variable {w a l : ℕ} + +namespace IncidenceDirectory + +/-- The number of actual port slots, counting every base vertex, lane, and slot in the state. -/ +abbrev slotCount (X : State a l) := Fintype.card X.Base * 2^l * 2^a + +theorem basePort_lt (X : State a l) (e : X.Base × Fin (2^a)) : (basePort (w := w) X e).val < slotCount X := by + rw [basePort_number, Fin.val_ofNat] + exact ((Nat.mod_le ..).trans_lt (baseOrder X e).isLt).trans_le + (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos l))) + +theorem actualPort_lt (X : State a l) (e : (X.Base × BitWord l) × Fin (2^a)) : + (actualPort (w := w) X e).val < slotCount X := by + rw [actualPort_number,Fin.val_ofNat]; exact (Nat.mod_le ..).trans_lt (actualOrder X e).isLt + +theorem Represents.retain {T : IncidenceDirectory w} {X : State a l} {m m' : Memory w} + (old : T.Represents X m) {limit : ℕ} (before : ∀ c, (T.column c).val+slotCount X ≤ limit) + (frame : ∀ addr < limit, m' addr = m addr) : T.Represents X m' := by + have atBase (c : Fin 6) (e : X.Base × Fin (2^a)) : + m' (T.column c + basePort X e).val = m (T.column c + basePort X e).val := by + apply frame; rw [Fin.val_add]; exact ((Nat.mod_le ..).trans_lt + (Nat.add_lt_add_left (basePort_lt X e) _)).trans_le (before c) + have atActual (c : Fin 6) (e : (X.Base × BitWord l) × Fin (2^a)) : + m' (T.column c + actualPort X e).val = m (T.column c + actualPort X e).val := by + apply frame; rw [Fin.val_add]; exact ((Nat.mod_le ..).trans_lt + (Nat.add_lt_add_left (actualPort_lt X e) _)).trans_le (before c) + exact ⟨fun e ↦ (atBase 0 e).trans (old.baseOut e), fun e ↦ (atBase 1 e).trans (old.baseIn e), + fun e ↦ (atBase 2 e).trans (old.shift e),fun e ↦ (atActual 3 e).trans (old.actualOut e), + fun e ↦ (atActual 4 e).trans (old.actualIn e),fun e ↦ (atActual 5 e).trans (old.width e)⟩ + +end IncidenceDirectory + +namespace ShrinkRAM + +variable {V : Type} {g n : ℕ} {G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))} +variable {order : V ≃ Fin n} {p : Fin 14 → Word w} {layout : Bool} {m m' : Memory w} + +theorem PlacementColumns.retain (old : PlacementColumns G order p layout m) {limit : ℕ} + (before : ∀ t : Fin 4, (p (t.natAdd 10)).val+PositionCount n a g ≤ limit) + (frame : ∀ addr < limit, m' addr = m addr) : PlacementColumns G order p layout m' := by + constructor + intro x P i + have hsite : i.val < PositionCount n a g := by + change (Shrink.oldNumber order x) % (2^w) < _ + rw [← Shrink.oldIndex_val]; exact (Nat.mod_le ..).trans_lt (Fin.isLt _) + have keep (t : Fin 4) : m' (outAddr p t i) = m (outAddr p t i) := by + apply frame + rw [outAddr,Fin.val_add] + exact ((Nat.mod_le ..).trans_lt (Nat.add_lt_add_left hsite _)).trans_le (before t) + rw [keep 0,keep 1,keep 2,keep 3]; exact old.atSite x + +end ShrinkRAM + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGraph.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGraph.lean new file mode 100644 index 0000000000..305e6c738c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGraph.lean @@ -0,0 +1,75 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkScan +import OAI.Computability.VPVNP.CompressorRecordsShrinkWords + +/-! +# Placement columns on the typed shrinking graph + +The four output columns of the native old-position scan encode the owner, the +thickness bit, the assigned outgoing bundle and the bundle's target. The +indexed old positions include the tag, mask, slot label and residual lane. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkRAM + +open BurstRAM Compression PrimedStackRAM + +variable {V : Type} {w a g n : ℕ} +variable (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) (order : V ≃ Fin n) + +/-- The number of old positions scanned for placement, counting every packing lane of each base +vertex. -/ +abbrev PositionCount (n a g : ℕ) := n*2^(packingLaneBits a g) + +/-- The fixed four columns as consumed by subsequent arc and preimage passes. -/ +structure PlacementColumns (p : Fin 14 → Word w) (layout : Bool) (m : Memory w) : Prop where + atSite : ∀ x : Shrink.Old V a g, + let P := orderedDyadicPacking G order + let i := word w (Shrink.oldNumber order x) + ((m (outAddr p 0 i)).val, (m (outAddr p 1 i)).val, + (m (outAddr p 2 i)).val, (m (outAddr p 3 i)).val) = + (Shrink.packedNumber order (P.placement layout x), (decide (P.thick x)).toNat, + Shrink.join a (Shrink.packedNumber order (P.assignedBundle x).1) (P.assignedBundle x).2.val, + Shrink.packedNumber order (P.siteGraph.target (P.assignedBundle x)).1) + +theorem ScanResult.placementColumns (p : Fin 14 → Word w) (layout : Bool) (m : Memory w) + (hp : Params p a (Shrink.colors a) (Shrink.J a) g layout) + (d : Shrink.Directory G order (column p m 6) (column p m 7) (column p m 8) (column p m 9)) + (hOld : PositionCount n a g ≤ 2^w) + (hSlots : n*(2^(Shrink.J a)*2^g)*2^a ≤ 2^w) {rs : List (Report w)} + (h : ScanResult p (PositionCount n a g) 0 (PositionCount n a g) m rs) : + PlacementColumns G order p layout (after m (eventLog rs)) := by + constructor + intro x P i + have hx : Shrink.oldNumber order x < PositionCount n a g := by + rw [← Shrink.oldIndex_val]; exact Fin.isLt _ + have hi : i.val < 0 + PositionCount n a g := by + change (Shrink.oldNumber order x) % (2^w) < _ + rw [Nat.mod_eq_of_lt (hx.trans_le hOld), Nat.zero_add] + exact hx + rw [h.readback 0 i (Nat.zero_le _) hi, h.readback 1 i (Nat.zero_le _) hi, + h.readback 2 i (Nat.zero_le _) hi, h.readback 3 i (Nat.zero_le _) hi] + exact outputs_exact G order p m layout hp d hOld hSlots x + +/-- The shrinking scan on the entire old graph fills the typed placement arrays. -/ +theorem placement_run (p : Fin 14 → Word w) (layout : Bool) (m : Memory w) + (hp : Params p a (Shrink.colors a) (Shrink.J a) g layout) + (d : Shrink.Directory G order (column p m 6) (column p m 7) (column p m 8) (column p m 9)) + (regions : Regions p (PositionCount n a g)) + (hSlots : n*(2^(Shrink.J a)*2^g)*2^a ≤ 2^w) : + let N := PositionCount n a g + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 65 (some (word w 0)) m (List.replicate N []) = some rs ∧ + ScanResult p N 0 N m rs ∧ PlacementColumns G order p layout (after m (eventLog rs)) := by + intro N M + obtain ⟨rs,he,h⟩ := scan_run p N 0 N m regions (by omega) + exact ⟨rs,he,h,h.placementColumns G order p layout m hp d regions.fits hSlots⟩ + +end CompressorRecords.ShrinkRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGreedy.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGreedy.lean new file mode 100644 index 0000000000..235f5514b4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGreedy.lean @@ -0,0 +1,316 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedyPhases +import OAI.Computability.VPVNP.CompressorRecordsShrinkTagColumn + +/-! +# Computing the shrinking placement directory from the old incidence table + +The tag extraction visits the old outgoing slots and initializes the zero +operand. A color scan and an offset scan then fill their disjoint fresh +directories. The full old displacement word remains available to the +placement worker, while the offset worker sees only the projected tag. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyArena + +open BurstRAM Compression Greedy +open scoped Fin.CommRing + +variable {w a g : ℕ} + +/-- A compressor state whose lane width supplies the packing fields required by shrinking at +the given degree and residual width. -/ +abbrev ShrinkingState (a g : ℕ) := State a (packingLaneBits a g) + +/-- Extract the packing-tag component of an outgoing base port's lane displacement for the +offset assignment. -/ +def projectedTag (X : ShrinkingState a g) (e : X.Base × Fin (2 ^ a)) : BitWord (Shrink.J a) := + (packingFields a g (X.slots.displacement e)).2.2.1 + +/-- The tag-projection worker's public operands, including the old incidence data and +destinations for projected tags and zero. -/ +def projectionWords (T : IncidenceDirectory w) (origin n a g : ℕ) : Fin 5 → Word w := + ShrinkTagColumn.params T a g (CursorRAM.encode w (shiftBase origin n a)) (CursorRAM.encode w (zeroCell origin n a)) + +/-- The memory after scanning all old base ports to write projected displacement tags and +initialize the shared zero operand. -/ +def projectedMemory (X : ShrinkingState a g) (T : IncidenceDirectory w) (origin : ℕ) (m : Memory w) : Memory w := + let n := Fintype.card X.Base + after m (eventLog (ShrinkTagColumn.reports (projectionWords T origin n a g) (n * 2 ^ a) m)) + +/-- The greedy color pass's port tables, using the fresh color column, shared zero, and +original displacements. -/ +def colorTables (T : IncidenceDirectory w) (origin n a : ℕ) : PortTables w := + tables T a (CursorRAM.encode w (colorBase origin)) (CursorRAM.encode w (zeroCell origin n a)) T.shift + +/-- The offset pass's port tables, using the fresh offset column and projected tag +displacements. -/ +def tagTables (T : IncidenceDirectory w) (origin n a : ℕ) : PortTables w := + tables T a (CursorRAM.encode w (offsetBase origin n a)) (CursorRAM.encode w (zeroCell origin n a)) + (CursorRAM.encode w (shiftBase origin n a)) + +/-- The report traces of all six native visits, in their memory execution order. -/ +structure Run (X : ShrinkingState a g) (T : IncidenceDirectory w) (origin : ℕ) (m : Memory w) where + room : greedyStop origin (Fintype.card X.Base) a < 2 ^ w + old : OldBelow X T origin + input : T.Represents X m + tagFit : Shrink.J a ≤ w + projection : ShrinkTagColumn.Result (projectionWords T origin (Fintype.card X.Base) a g) + (Fintype.card X.Base * 2 ^ a) m + /-- The executed greedy color assignment in the color walk's workspace. -/ + color : Assignment (colorLayout w origin (Fintype.card X.Base) a room) + (colorTables T origin (Fintype.card X.Base) a) X.slots.base X.baseIndex (colorOperandRows (2 ^ a)) + 1 (2 * 2 ^ a) (projectedMemory X T origin m) (fun v : Fin (Shrink.colors a) => CursorRAM.encode w v.val) + ((orderedDyadicPacking X.slots X.baseIndex).color) + /-- The executed tag-offset assignment using the projected displacement table after coloring. -/ + offsets : Assignment (tagLayout w origin (Fintype.card X.Base) a room) + (tagTables T origin (Fintype.card X.Base) a) X.slots.base X.baseIndex (tagOperandRows (2 ^ a)) + 4 (WalkLayout.tagCount (2 ^ a)) color.post (tagWord tagFit) ((orderedDyadicPacking X.slots X.baseIndex).offset) + +private theorem destCell (origin n a w i : ℕ) (room : greedyStop origin n a < 2 ^ w) (hi : i < n * 2 ^ a) : + ShrinkTagColumn.cell (CursorRAM.encode w (shiftBase origin n a)) i = shiftBase origin n a + i := by + have hstop : shiftBase origin n a + n * 2 ^ a + 1 < 2 ^ w := room + change ((Fin.ofNat (2 ^ w) (shiftBase origin n a)) + (i : Word w)).val = _ + rw [Fin.val_add, Fin.val_natCast, Fin.val_ofNat, Nat.mod_eq_of_lt (by omega : i < 2 ^ w), + Nat.mod_eq_of_lt (by omega : shiftBase origin n a < 2 ^ w), Nat.mod_eq_of_lt (by omega)] + +private theorem projection_frame (X : ShrinkingState a g) (T : IncidenceDirectory w) (origin : ℕ) (m : Memory w) + (room : greedyStop origin (Fintype.card X.Base) a < 2 ^ w) + (r : ShrinkTagColumn.Result (projectionWords T origin (Fintype.card X.Base) a g) (Fintype.card X.Base * 2 ^ a) m) + (z : ℕ) (hz : z < shiftBase origin (Fintype.card X.Base) a) : + projectedMemory X T origin m z = m z := by + let n := Fintype.card X.Base + change greedyStop origin n a < 2 ^ w at room + have hs : zeroCell origin n a < 2 ^ w := Nat.lt_of_succ_lt room + change z < shiftBase origin n a at hz + apply r.preserve z + · change z ≠ (zeroCell origin n a) % (2 ^ w) + rw [Nat.mod_eq_of_lt hs]; change z ≠ shiftBase origin n a + n * 2 ^ a + omega + · intro i hi + rw [show (projectionWords T origin n a g) 1 = CursorRAM.encode w (shiftBase origin n a) by rfl, + destCell origin n a w i room hi] + omega + +private theorem shifted_port (X : ShrinkingState a g) (origin : ℕ) + (room : greedyStop origin (Fintype.card X.Base) a < 2 ^ w) (e : X.Base × Fin (2 ^ a)) : + (CursorRAM.encode w (shiftBase origin (Fintype.card X.Base) a) + IncidenceDirectory.basePort X e).val = + shiftBase origin (Fintype.card X.Base) a + (IncidenceDirectory.baseOrder X e).val := by + rw [IncidenceDirectory.basePort_number] + exact destCell origin _ a w _ room (IncidenceDirectory.baseOrder X e).isLt + +private theorem region (X : ShrinkingState a g) (T : IncidenceDirectory w) (origin : ℕ) + (old : OldBelow X T origin) (room : greedyStop origin (Fintype.card X.Base) a < 2 ^ w) : + ShrinkTagColumn.Regions (projectionWords T origin (Fintype.card X.Base) a g) (Fintype.card X.Base * 2 ^ a) := by + let n := Fintype.card X.Base + have hb := bounds origin n a + change origin + n ≤ _ ∧ _ at hb + have fit := old.baseFits + change greedyStop origin n a < 2 ^ w at room + have hs : zeroCell origin n a < 2 ^ w := Nat.lt_of_succ_lt room + change n * 2 ^ a ≤ origin at fit + refine ⟨fit.trans (by omega), ?_, ?_⟩ + · intro i j hi hj + change i < n * 2 ^ a at hi + change j < n * 2 ^ a at hj + change (T.shift + (i : Word w)).val ≠ ShrinkTagColumn.cell (CursorRAM.encode w (shiftBase origin n a)) j + have he : (T.shift + (i : Word w)).val < origin := old.cell 2 _ ((Nat.mod_le i _).trans_lt + (hi.trans_le (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _))))) + rw [destCell origin n a w j room hj]; omega + · intro i hi + change i < n * 2 ^ a at hi + change ShrinkTagColumn.cell (CursorRAM.encode w (shiftBase origin n a)) i ≠ zeroCell origin n a % (2 ^ w) + rw [destCell origin n a w i room hi, Nat.mod_eq_of_lt hs] + change shiftBase origin n a + i ≠ shiftBase origin n a + n * 2 ^ a + omega + +namespace Run + +variable {X : ShrinkingState a g} {T : IncidenceDirectory w} {origin : ℕ} {m : Memory w} +variable (r : Run X T origin m) + +/-- The final memory of the greedy shrinking run, after the offset assignment completes. -/ +def post : Memory w := r.offsets.post + +theorem below (z : ℕ) (hz : z < origin) : r.post z = m z := by + let n := Fintype.card X.Base + have hb := bounds origin n a + change origin + n ≤ _ ∧ _ at hb + exact (r.offsets.frame z (.inl (by change z < offsetBase origin n a; omega))).trans + ((r.color.frame z (.inl hz)).trans (projection_frame X T origin m r.room r.projection z (by change z < shiftBase origin n a; omega))) + +theorem incidence : T.Represents X r.post := r.old.preserve r.input r.below + +private theorem address_label {n width : ℕ} (L : WalkLayout w n width) (i : Fin n) : + CursorRAM.encode w L.origin + CursorRAM.encode w i.val = L.label i := Fin.ext (Nat.add_mod ..).symm + +theorem color_at (x : X.Base) : + r.post (CursorRAM.encode w (colorBase origin) + CursorRAM.encode w (X.baseIndex x).val).val = + CursorRAM.encode w ((orderedDyadicPacking X.slots X.baseIndex).color x).val := by + let n := Fintype.card X.Base + let L := colorLayout w origin n a r.room + rw [show colorBase origin = L.origin by rfl, address_label] + apply (r.offsets.frame _ (.inl ?_)).trans (r.color.atLabel x) + have hx : (X.baseIndex x).val < n := (X.baseIndex x).isLt + change (L.label (X.baseIndex x)).val < offsetBase origin n a + rw [WalkLayout.label_val] + have hb := (bounds origin n a).1 + change colorBase origin + (X.baseIndex x).val < offsetBase origin n a + omega + +theorem offset_at (x : X.Base) : + r.post (CursorRAM.encode w (offsetBase origin (Fintype.card X.Base) a) + CursorRAM.encode w (X.baseIndex x).val).val = + tagWord r.tagFit ((orderedDyadicPacking X.slots X.baseIndex).offset x) := by + let L := tagLayout w origin (Fintype.card X.Base) a r.room + rw [show offsetBase origin (Fintype.card X.Base) a = L.origin by rfl, address_label] + exact r.offsets.atLabel x + +end Run + +/-- Read a natural-number label from an indexed word of a greedy assignment column. -/ +def column (m : Memory w) (base : Word w) (i : ℕ) : ℕ := (m (base + CursorRAM.encode w i).val).val + +theorem Run.directory {X : ShrinkingState a g} {T : IncidenceDirectory w} {origin : ℕ} {m : Memory w} + (r : Run X T origin m) : Shrink.Directory X.slots X.baseIndex + (column r.post (CursorRAM.encode w (colorBase origin))) + (column r.post (CursorRAM.encode w (offsetBase origin (Fintype.card X.Base) a))) + (column r.post T.baseOut) (column r.post T.shift) := by + let n := Fintype.card X.Base + have hc := colorFits origin n a w Fintype.card_pos r.room + have hb := bounds origin n a + change origin + n ≤ _ ∧ _ at hb + have hroom : greedyStop origin n a < 2 ^ w := r.room + have hf := r.old.laneFits (by omega : origin < 2 ^ w) + constructor + · intro x + rw [column, r.color_at] + apply Nat.mod_eq_of_lt + exact ((orderedDyadicPacking X.slots X.baseIndex).color x).isLt.trans_le (Nat.succ_le_of_lt hc) + · intro x + rw [column, r.offset_at, tagWord_val] + · intro x i + change (r.post (T.baseOut + IncidenceDirectory.basePort X (x,i)).val).val = _ + rw [r.incidence.baseOut, IncidenceDirectory.basePort_number, Shrink.join, ← IncidenceDirectory.baseOrder_val] + exact Nat.mod_eq_of_lt ((IncidenceDirectory.baseOrder X _).isLt.trans_le (r.old.baseFits.trans (by omega))) + · intro x i + change (r.post (T.shift + IncidenceDirectory.basePort X (x,i)).val).val = _ + rw [r.incidence.shift] + exact Nat.mod_eq_of_lt ((bitWordFinEquiv _ _).isLt.trans_le (Nat.pow_le_pow_right (by decide) hf)) + + +/-- Build the native color and offset setup in arbitrary scratch memory. The +input comprises exactly the old represented incidence table and the fresh range. -/ +theorem build (X : ShrinkingState a g) (T : IncidenceDirectory w) (origin : ℕ) (m : Memory w) + (rep : T.Represents X m) (old : OldBelow X T origin) + (room : greedyStop origin (Fintype.card X.Base) a < 2 ^ w) : Nonempty (Run X T origin m) := by + let n := Fintype.card X.Base + let L := colorLayout w origin n a room + let K := tagLayout w origin n a room + let C := colorTables T origin n a + let U := tagTables T origin n a + let dst := CursorRAM.encode w (shiftBase origin n a) + let zero := CursorRAM.encode w (zeroCell origin n a) + let projected := projectedMemory X T origin m + have hb := bounds origin n a + change origin + n ≤ _ ∧ _ at hb + change greedyStop origin n a < 2 ^ w at room + have hr : origin < 2 ^ w := by omega + have colorFit := colorFits origin n a w Fintype.card_pos room + have degreeFit : 2 ^ a < 2 ^ w := by omega + have baseFit := old.baseFits.trans hr.le + have laneFit := old.laneFits hr + have hw := (ShrinkTagColumn.radices_fit laneFit).2.2 + obtain ⟨projRun, projectedSlots⟩ := ShrinkTagColumn.extract_directory X T dst zero m rep laneFit (region X T origin old room) + have preBelow : ∀ z < origin, projected z = m z := + fun z hz => projection_frame X T origin m room projRun z (by change z < shiftBase origin n a; omega) + have preRep := old.preserve rep preBelow + have hsC : L.limit < 2 ^ w := by change offsetBase origin n a < 2 ^ w; omega + obtain ⟨colors⟩ := assignment_exists L C X.slots.base X.baseIndex (colorOperandRows (2 ^ a)) 1 (2 * 2 ^ a) projected + (fun v : Fin (Shrink.colors a) => CursorRAM.encode w v.val) ((orderedDyadicPacking X.slots X.baseIndex).color) rfl + (tables_rep preRep _ _ _ degreeFit baseFit) hsC (old.graphOutside L le_rfl _ _ _) + (fun i => rowWords_color_length _ _ _ _) (WalkLayout.color_read_prepared L C X.slots.base X.baseIndex projected rfl colorFit) + have colorBelow : ∀ z < origin, colors.post z = m z := + fun z hz => (colors.frame z (.inl hz)).trans (preBelow z hz) + have hsK : K.limit < 2 ^ w := by change shiftBase origin n a < 2 ^ w; omega + have zval : zero.val = zeroCell origin n a := Nat.mod_eq_of_lt (Nat.lt_of_succ_lt room) + have zfar : K.limit ≤ zero.val := by rw [zval]; change shiftBase origin n a ≤ shiftBase origin n a + _; omega + have sfar (e : X.Base × Fin (2 ^ a)) : K.limit ≤ (dst + IncidenceDirectory.basePort X e).val := by + rw [shifted_port X origin room e]; change shiftBase origin n a ≤ shiftBase origin n a + _; omega + have kl : L.limit ≤ K.limit := by change offsetBase origin n a ≤ shiftBase origin n a; omega + have data : WalkLayout.OffsetData K U X.baseIndex hw (projectedTag X) colors.post := by + constructor + · exact (colors.frame zero.val (.inr (kl.trans zfar))).trans projRun.zero + · exact Or.inr zfar + · intro e + exact (colors.frame _ (.inr (kl.trans (sfar e)))).trans (projectedSlots e) + · exact fun e => Or.inr (sfar e) + have hcard := packingTagBits_sufficient (2 ^ a) + obtain ⟨offsets⟩ := assignment_exists K U X.slots.base X.baseIndex (tagOperandRows (2 ^ a)) 4 + (WalkLayout.tagCount (2 ^ a)) colors.post (tagWord hw) ((orderedDyadicPacking X.slots X.baseIndex).offset) + rfl (tables_rep (old.preserve rep colorBelow) _ _ _ degreeFit baseFit) hsK + (old.graphOutside K (by change origin ≤ offsetBase origin n a; omega) _ _ _) + (fun i => by rw [rowWords_tag_length, tagTests_length, Nat.mul_comm]) + (WalkLayout.tag_read_prepared K U X.slots.base X.baseIndex colors.post rfl (projectedTag X) hw hcard data) + exact ⟨⟨room, old, rep, hw, projRun, colors, offsets⟩⟩ + + +namespace Run + +variable {X : ShrinkingState a g} {T : IncidenceDirectory w} {origin : ℕ} {m : Memory w} (r : Run X T origin m) + +/-- Chronological reports of the two tag-extraction visits, the color setup and +reader, and the tag setup and reader. -/ +def reports : List (Report w) := + ShrinkTagColumn.reports (projectionWords T origin (Fintype.card X.Base) a g) + (Fintype.card X.Base * 2 ^ a) m ++ r.color.prep ++ r.color.reads ++ r.offsets.prep ++ r.offsets.reads + +theorem post_reports : after m (eventLog r.reports) = r.post := by + simp only [reports, eventLog, List.flatMap_append, after, List.foldl_append] + rfl + +theorem reports_length : r.reports.length = Fintype.card X.Base * (2 ^ a + 4) + 1 := by + simp only [reports, List.length_append, r.projection.calls, r.color.prepLength, r.color.readLength, + r.offsets.prepLength, r.offsets.readLength] + ring + +private theorem readCost {N width degree : ℕ} {L : WalkLayout w N width} {V A : Type*} {U : PortTables w} + {G : SlotGraph V degree} {order : V ≃ Fin N} {rows : OperandRows degree} {arity tests : ℕ} + {src : Memory w} {encode : A → Word w} {f : V → A} (P : Assignment L U G order rows arity tests src encode f) : + RAMBuckets.cost Report.probes P.reads = N * (4 + 2 * arity * tests * tests) := by + have h (rs : List (Report w)) (hw : ∀ r ∈ rs, r.probes = 3 + 2 * arity * tests * tests) : + RAMBuckets.cost Report.probes rs = rs.length * (4 + 2 * arity * tests * tests) := by + induction rs with + | nil => simp [RAMBuckets.cost] + | cons r rs ih => + rw [RAMBuckets.cost, hw r List.mem_cons_self, ih (fun s hs => hw s (List.mem_cons_of_mem _ hs))] + simp only [List.length_cons, Nat.succ_mul] + omega + rw [h _ (fun z hz => (P.readWork z hz).2), P.readLength] + +/-- Total native calls plus probes depend linearly on the number of base +vertices for each of the fixed degrees used by the compressor. -/ +theorem reports_cost : + let d := 2 ^ a + let t := WalkLayout.tagCount d + RAMBuckets.cost Report.probes r.reports = + 2 + Fintype.card X.Base * (16 + 7*d + 8*d^2 + 5*t + 8*t^2) := by + simp only [reports, RAMBuckets.cost_append, r.projection.cost, r.color.prepCost, readCost, + r.offsets.prepCost, colorOperandRows, tagOperandRows, List.length_map, incidences_length, + tagTests_length, WalkLayout.tagCount] + ring + +end Run + +theorem greedyStop_eq (origin n a : ℕ) : + greedyStop origin n a = origin + n * (6 + 3 * 2 ^ a + 4 * WalkLayout.tagCount (2 ^ a)) + 1 := by + unfold greedyStop zeroCell shiftBase offsetBase + ring + +end CompressorRecords.GreedyArena + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGreedyLayout.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGreedyLayout.lean new file mode 100644 index 0000000000..780c084ebd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGreedyLayout.lean @@ -0,0 +1,138 @@ +import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout +import OAI.Computability.VPVNP.CompressorRecordsShrink +import OAI.Computability.VPVNP.CompressorRecordGreedyPass + +/-! +# Fresh storage for the shrinking step's color and tag assignments + +Both directed mate arrays and the original lane displacement stay in the +input incidence directory. New storage contains the two complete assignment +directories, one projected tag per outgoing base port, and a shared zero. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyArena + +open BurstRAM Compression Greedy + +/-- The origin of the greedy color assignment's fresh storage. -/ +def colorBase (origin : ℕ) := origin +/-- The first address after the color walk's labels and work rows, where the tag-offset walk +begins. -/ +def offsetBase (origin n a : ℕ) := origin + n + n * (2 + 2 * 2 ^ a) +/-- The first address after both greedy walk regions, reserved for the projected displacements +of old base ports. -/ +def shiftBase (origin n a : ℕ) := offsetBase origin n a + n + n * (2 + 4 * WalkLayout.tagCount (2 ^ a)) +/-- The shared zero operand stored immediately after the projected displacement column. -/ +def zeroCell (origin n a : ℕ) := shiftBase origin n a + n * 2 ^ a +/-- The exclusive upper bound of the greedy assignment workspace, one word past its zero +operand. -/ +def greedyStop (origin n a : ℕ) := zeroCell origin n a + 1 + +theorem bounds (origin n a : ℕ) : + colorBase origin + n ≤ offsetBase origin n a ∧ offsetBase origin n a + n ≤ shiftBase origin n a ∧ + shiftBase origin n a + n * 2 ^ a < greedyStop origin n a := by + simp only [colorBase, greedyStop, zeroCell, shiftBase, offsetBase] + omega + +/-- The bounded layout of the greedy color walk, with room for the two directed incidences at +each slot. -/ +def colorLayout (w origin n a : ℕ) (room : greedyStop origin n a < 2 ^ w) : WalkLayout w n (2 * 2 ^ a) := + ⟨colorBase origin, by change offsetBase origin n a ≤ 2 ^ w; have := bounds origin n a; omega⟩ + +/-- The bounded layout of the greedy offset walk, using its four tag-count groups per work row. -/ +def tagLayout (w origin n a : ℕ) (room : greedyStop origin n a < 2 ^ w) : + WalkLayout w n (4 * WalkLayout.tagCount (2 ^ a)) := + ⟨offsetBase origin n a, by change shiftBase origin n a ≤ 2 ^ w; have := bounds origin n a; omega⟩ + +@[simp] theorem color_limit (w origin n a : ℕ) (h : greedyStop origin n a < 2 ^ w) : + (colorLayout w origin n a h).limit = offsetBase origin n a := rfl + +@[simp] theorem tag_limit (w origin n a : ℕ) (h : greedyStop origin n a < 2 ^ w) : + (tagLayout w origin n a h).limit = shiftBase origin n a := rfl + +variable {w a l : ℕ} + +/-- The six old columns are below the beginning of the new scratch range. -/ +def OldBelow (X : State a l) (T : IncidenceDirectory w) (origin : ℕ) : Prop := + ∀ c : Fin 6, (T.column c).val + Fintype.card X.Base * 2 ^ l * 2 ^ a ≤ origin + +private theorem basePort_lt (X : State a l) (e : X.Base × Fin (2 ^ a)) : + (IncidenceDirectory.basePort (w := w) X e).val < Fintype.card X.Base * 2 ^ l * 2 ^ a := by + rw [IncidenceDirectory.basePort_number] + have h := (IncidenceDirectory.baseOrder X e).isLt + exact (Nat.mod_le _ _).trans_lt (h.trans_le (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos l)))) + +private theorem actualPort_lt (X : State a l) (e : (X.Base × BitWord l) × Fin (2 ^ a)) : + (IncidenceDirectory.actualPort (w := w) X e).val < Fintype.card X.Base * 2 ^ l * 2 ^ a := by + rw [IncidenceDirectory.actualPort_number] + exact (Nat.mod_le _ _).trans_lt (IncidenceDirectory.actualOrder X e).isLt + +theorem OldBelow.cell {X : State a l} {T : IncidenceDirectory w} {origin : ℕ} + (h : OldBelow X T origin) (c : Fin 6) (j : Word w) + (hj : j.val < Fintype.card X.Base * 2 ^ l * 2 ^ a) : (T.column c + j).val < origin := by + rw [Fin.val_add] + exact (Nat.mod_le _ _).trans_lt (Nat.add_lt_add_left hj _ |>.trans_le (h c)) + +theorem OldBelow.preserve {X : State a l} {T : IncidenceDirectory w} {origin : ℕ} + {m post : Memory w} (h : OldBelow X T origin) (rep : T.Represents X m) + (frame : ∀ z < origin, post z = m z) : T.Represents X post := by + constructor + · intro e; exact (frame _ (h.cell 0 _ (basePort_lt X e))).trans (rep.baseOut e) + · intro e; exact (frame _ (h.cell 1 _ (basePort_lt X e))).trans (rep.baseIn e) + · intro e; exact (frame _ (h.cell 2 _ (basePort_lt X e))).trans (rep.shift e) + · intro e; exact (frame _ (h.cell 3 _ (actualPort_lt X e))).trans (rep.actualOut e) + · intro e; exact (frame _ (h.cell 4 _ (actualPort_lt X e))).trans (rep.actualIn e) + · intro e; exact (frame _ (h.cell 5 _ (actualPort_lt X e))).trans (rep.width e) + +theorem OldBelow.fit {X : State a l} {T : IncidenceDirectory w} {origin : ℕ} (old : OldBelow X T origin) : + Fintype.card X.Base * 2 ^ l * 2 ^ a ≤ origin := by have := old 0; omega + +/-- Assemble the walker's port tables from the old incidence directory and the specified label, +zero, and displacement columns. -/ +def tables (T : IncidenceDirectory w) (a : ℕ) (labels zero disps : Word w) : PortTables w := + { T.greedyTables a labels zero with displacements := disps } + +theorem tables_rep {X : State a l} {T : IncidenceDirectory w} {m : Memory w} (rep : T.Represents X m) + (labels zero disps : Word w) (degree : 2 ^ a < 2 ^ w) (baseFits : Fintype.card X.Base * 2 ^ a ≤ 2 ^ w) : + (tables T a labels zero disps).Represents X.slots.base X.baseIndex m := by + have h := rep.greedy labels zero degree baseFits + exact ⟨h.degree,h.fits,h.vertices,h.outgoing,h.incoming⟩ + +theorem OldBelow.graphOutside {X : State a l} {T : IncidenceDirectory w} {origin width : ℕ} + (h : OldBelow X T origin) (L : WalkLayout w (Fintype.card X.Base) width) (hle : origin ≤ L.origin) + (labels zero disps : Word w) : GraphOutside (d := 2 ^ a) L (tables T a labels zero disps) X.baseIndex := by + intro e b hb + change b ∈ [T.baseOut,T.baseIn] at hb + rcases List.mem_cons.mp hb with rfl | hb + · exact Or.inl ((h.cell 0 _ (basePort_lt X e)).trans_le hle) + · obtain rfl := List.mem_singleton.mp hb + exact Or.inl ((h.cell 1 _ (basePort_lt X e)).trans_le hle) + + +theorem OldBelow.baseFits {X : State a l} {T : IncidenceDirectory w} {origin : ℕ} + (old : OldBelow X T origin) : Fintype.card X.Base * 2 ^ a ≤ origin := + (Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos l))).trans old.fit + +theorem OldBelow.laneFits {X : State a l} {T : IncidenceDirectory w} {origin : ℕ} + (old : OldBelow X T origin) (room : origin < 2 ^ w) : l ≤ w := by + have npos : 0 < Fintype.card X.Base := Fintype.card_pos + have h : 2 ^ l ≤ origin := + (Nat.le_mul_of_pos_left _ npos).trans ((Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)).trans old.fit) + exact Nat.le_of_not_gt fun bad => (Nat.pow_lt_pow_right (by decide : 1 < 2) bad).not_ge (h.trans room.le) + +theorem colorFits (origin n a w : ℕ) (npos : 0 < n) (room : greedyStop origin n a < 2 ^ w) : + 2 * 2 ^ a < 2 ^ w := by + have h : 2 + 2 * 2 ^ a ≤ n * (2 + 2 * 2 ^ a) := Nat.le_mul_of_pos_left _ npos + have := bounds origin n a + unfold offsetBase at * + omega + +end CompressorRecords.GreedyArena + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGreedyPhases.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGreedyPhases.lean new file mode 100644 index 0000000000..b753d425ae --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkGreedyPhases.lean @@ -0,0 +1,82 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedyLayout +import OAI.Computability.VPVNP.CompressorGreedyRelocated + +/-! # External state transfer between the shrinking assignment passes -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.GreedyArena + +open BurstRAM Compression Greedy + +variable {w N width d : ℕ} {V A : Type*} + +/-- A pair of actual reset-on-entry burst scans with the public parameters used +by the planner. The reader begins in exactly the memory left by preparation. -/ +structure Assignment (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows : OperandRows d) (arity n : ℕ) (m : Memory w) + (encode : A → Word w) (label : V → A) where + /-- Reports of preparing one operand row per old base vertex for a greedy assignment. -/ + prep : List (Report w) + /-- Reports of the visits that read the prepared rows and write each vertex's assigned label. -/ + reads : List (Report w) + prepRun : runSegment ((Relocated.preparePass rows).table.instantiate w + (Relocated.publicWords d L T)).program (1 + (Relocated.prepareCode rows).length) (some 0) m + (List.replicate N []) = some prep + prepEnd : endState (some 0) prep = some (Fin.ofNat _ N) + prepMemory : after m (eventLog prep) = + L.initialMemory (fun i => rowWords T G order (order.symm i) rows) m + prepCost : RAMBuckets.cost Report.probes prep = N * (4 + rows.length + width) + prepLength : prep.length = N + prepWork : ∀ r ∈ prep, r.events.length ≤ 22 + 8 * rows.length + 6 * width ∧ + r.probes = 3 + rows.length + width + readRun : runSegment (visitMachine w arity n).program (1 + (visitCode arity n).length) + (some (L.base 0)) (after m (eventLog prep)) (List.replicate N []) = some reads + readEnd : endState (some (L.base 0)) reads = some (L.base N) + readMemory : L.Represents (after m (eventLog prep)) (after (after m (eventLog prep)) (eventLog reads)) + encode order label + readLength : reads.length = N + readWork : ∀ r ∈ reads, r.events.length = 12 + ((4 * arity + 4) * n + 4) * n ∧ + countProbes r.events = 3 + 2 * arity * n * n + +namespace Assignment + +variable {L : WalkLayout w N width} {T : PortTables w} {G : SlotGraph V d} {order : V ≃ Fin N} + {rows : OperandRows d} {arity n : ℕ} {m : Memory w} {encode : A → Word w} {label : V → A} + (P : Assignment L T G order rows arity n m encode label) + +/-- The memory containing the completed greedy assignment after row preparation and visits. -/ +def post : Memory w := after (after m (eventLog P.prep)) (eventLog P.reads) + +theorem atLabel (v : V) : P.post (L.label (order v)).val = encode (label v) := P.readMemory.labels v + +theorem frame (z : ℕ) (away : z < L.origin ∨ L.limit ≤ z) : P.post z = m z := by + have h := P.readMemory.frame z (away.imp_right (fun h => by unfold WalkLayout.limit at h; omega)) + change P.post z = _ at h + rw [h, P.prepMemory] + rcases away with hz | hz + · simp [WalkLayout.initialMemory, hz] + · exact L.initialMemory_after _ _ hz + +end Assignment + +theorem assignment_exists (L : WalkLayout w N width) (T : PortTables w) (G : SlotGraph V d) + (order : V ≃ Fin N) (rows : OperandRows d) (arity n : ℕ) (m : Memory w) + (encode : A → Word w) (label : V → A) (labels : T.labels = Fin.ofNat _ L.origin) + (rep : T.Represents G order m) (space : L.limit < 2 ^ w) (outside : GraphOutside (d := d) L T order) + (size : ∀ i : Fin N, (rowWords T G order (order.symm i) rows).length = width) + (reader : L.Pass (L.initialMemory (fun i => rowWords T G order (order.symm i) rows) m) + arity n encode order label) : Nonempty (Assignment L T G order rows arity n m encode label) := by + obtain ⟨prep, hp, hend, hm, hl, hc, hw⟩ := + Relocated.prepare_directory L T G order rows m labels rep space outside size + rw [← hm] at reader + obtain ⟨reads, hr, hrend, hmem, hlen, hwork⟩ := reader + exact ⟨⟨prep, reads, hp, hend, hm, hc, hl, hw, hr, hrend, hmem, hlen, hwork⟩⟩ + +end CompressorRecords.GreedyArena + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkHistory.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkHistory.lean new file mode 100644 index 0000000000..0cd371d0e4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkHistory.lean @@ -0,0 +1,154 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkPreimages +import OAI.Computability.VPVNP.ShrinkFieldBounds + +/-! +# Ordered resident hidden fields and maps of a shrinking history node + +Each dense motif/type or motif/party ordinal is appended exactly once to its +packed owner. Reading the resulting row recovers the same restricted order +as the mathematical parser, including occurrences sharing a motif or owner. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkHistoryRows + +open Compression Compression.PackingData BurstRAM PrimedStackRAM PairSimulation.LocalHistory PairSimulation.TraversalRows +open scoped Classical Fin.CommRing + +variable {I J : Type} [Fintype I] [DecidableEq J] {w : ℕ} + +/-- Restrict an existing enumeration to entries whose placement equals the given owner, +retaining their original order. -/ +abbrev residents (old : Order I) (place : I → J) (v : J) := old.restrict (fun u => v = place u) + +/-- The four or six low-order role digits remain part of the stored identifier. -/ +structure Directory (old : Order I) (next : Order J) (place : I → J) (p : Fin 6 → Word w) + (mem : Memory w) : Prop where + count (v : J) : (mem ((p 3).val+(next.entries.symm v).val)).val = (residents old place v).length + idAt (v : J) (j : Fin (residents old place v).length) : + mem ((p 5).val+(next.entries.symm v).val*(p 4).val+j.val) = siteWord w old ((residents old place v).entries j).val + +open private countAt_val rowAt_val from OAI.Computability.VPVNP.CompressorRecordPreimageScan + +theorem directory_of_rows (old : Order I) (next : Order J) (place : I → J) + (p : Fin 6 → Word w) (areas : RowRegions p) (ho : (p 0).val = old.length) (hn : (p 2).val = next.length) + (mem : Memory w) (h : PreimagesAt p (encodedPlacement old.entries.symm next.entries.symm place) mem old.length) : + Directory old next place p mem := by + have oldFits := ho ▸ (p 0).isLt.le + have newFits := hn ▸ (p 2).isLt.le + have hv (v : J) : (siteWord w next v).val = (next.entries.symm v).val := + Nat.mod_eq_of_lt ((next.entries.symm v).isLt.trans_le newFits) + have valid (v : J) : siteWord w next v < p 2 := by + change (siteWord w next v).val < (p 2).val + rw [hv,hn] + exact (next.entries.symm v).isLt + let physical := encodedPlacement (w := w) old.entries.symm next.entries.symm place + have eq (v : J) := preimagePrefix_eq_orderedIds old next place physical + (encodedPlacement_represents old next place oldFits newFits) oldFits newFits v + have row (v : J) := h.rows (siteWord w next v) (valid v) + constructor + · intro v + have h := (row v).1 + rw [countAt_val areas (valid v),hv,eq] at h + simpa only [orderedIds,List.length_ofFn] using h + · intro v j + have h := (row v).2 + rw [eq] at h + have a := h ⟨j.val,by simpa only [orderedIds,List.length_ofFn] using j.isLt⟩ + rw [rowAt_val areas (valid v),hv] at a + simpa only [orderedIds,List.getElem_ofFn] using a + +/-- Clear the chosen site's counters and append each dense occurrence through +the native four-probe collector. The row capacity follows from the typed +fiber cardinality, independently of the chosen layout and the bit assignments. -/ +theorem build (old : Order I) (next : Order J) (place : I → J) (p : Fin 6 → Word w) + (areas : RowRegions p) (ho : (p 0).val = old.length) (hn : (p 2).val = next.length) + (hcap : ∀ v : J, Fintype.card {u : I // place u = v} ≤ (p 4).val) (mem : Memory w) + (owner : ∀ i : Word w, i < p 0 → ownerAt p mem i = encodedPlacement old.entries.symm next.entries.symm place i) : + ∃ cs rs, let mid := after mem (eventLog cs) + let out := after mid (eventLog rs) + runSegment ((template SliceRAM.clearOps 0).instantiate w (fun _ => p 3)).program 8 + (some 0) mem (List.replicate next.length []) = some cs ∧ + runSegment ((template collectPreimage 3).instantiate w p).program 23 + (some 0) mid (List.replicate old.length []) = some rs ∧ + Directory old next place p out ∧ cs.length=next.length ∧ rs.length=old.length ∧ + (∀ r ∈ cs, r.probes=1 ∧ r.events.length+1=8) ∧ (∀ r ∈ rs, r.probes=4 ∧ r.events.length+1=23) ∧ + (∀ j, OutsidePreimageWrites p j → out j = mem j) := by + have hOld := ho ▸ (p 0).isLt + have hNew := hn ▸ (p 2).isLt + have upper := hn ▸ areas.countsBeforeRows + obtain ⟨cs,clear,zero,frame,_,clen,cwork⟩ := + SliceRAM.clearPass_run (p 3) next.length (upper.trans (p 5).isLt.le) hNew mem + let mid := after mem (eventLog cs) + let phys := encodedPlacement (w := w) old.entries.symm next.entries.symm place + have live (i : Word w) (hi : i < p 0) : ownerAt p mid i = phys i := by + change mid (p 1+i).val = phys i + have small : (p 1+i).val < (p 3).val := (Nat.mod_le ..).trans_lt + ((Nat.add_lt_add_left hi _).trans_le areas.ownersBeforeCounts) + rw [show mid (p 1+i).val = mem (p 1+i).val from frame _ (.inl small)] + exact owner i hi + have legal (i : Word w) (hi : i < p 0) : phys i < p 2 := by + let j : Fin old.length := ⟨i.val,ho ▸ hi⟩ + have e : Fin.ofNat (2^w) j.val = i := Fin.ext (Nat.mod_eq_of_lt i.isLt) + change (encodedPlacement _ _ _ i).val < (p 2).val + rw [← e,encodedPlacement_eq old.entries.symm next.entries.symm place hOld.le hNew.le j,hn] + exact (next.entries.symm _).isLt + have cap (v : Word w) (hv : v < p 2) : (preimagePrefix phys v (p 0).val).length ≤ (p 4).val := by + let j : Fin next.length := ⟨v.val,hn ▸ hv⟩ + let site := next.entries j + have eq : Fin.ofNat (2^w) (next.entries.symm site).val = v := by + rw [show next.entries.symm site = j from Equiv.symm_apply_apply _ _] + exact Fin.ext (Nat.mod_eq_of_lt v.isLt) + rw [ho,← eq,encodedPlacement_rowLength old.entries.symm next.entries.symm place hOld.le hNew.le site] + exact hcap site + have start : PreimagesAt p phys mid 0 := by + refine ⟨live,fun v hv => ?_⟩ + have addr := countAt_val areas hv + have zz : mid (countAt p v).val = 0 := by + apply zero + · omega + · have hh : v.val < (p 2).val := hv + omega + simp [rowRepresents,preimagePrefix,zz] + obtain ⟨rs,scan,rows,rlen,rwork⟩ := collectPreimages_run areas legal cap start old.length (by simp [ho]) + obtain ⟨_,rframe⟩ := collectPreimages_cursor_frame (k := 0) areas scan + refine ⟨cs,rs,clear,scan,directory_of_rows old next place p areas ho hn _ (by simpa using rows),clen,rlen,cwork,?_,?_⟩ + · intro r hr + exact ⟨(rwork r hr).2,by rw [(rwork r hr).1]⟩ + · intro j hj + have hf := frame j (by simpa only [← hn] using hj.1) + exact (rframe j hj).trans hf + +variable {a g : ℕ} (X : State a (packingLaneBits a g)) + +/-- Enumerate the four hidden field types of each motif in the shrinking motif order. -/ +abbrev hiddenOrder := (shrinkMotifOrder X).prod (Order.fin 4) +/-- Enumerate the six map parties of each motif in the shrinking motif order. -/ +abbrev mapOrder := (shrinkMotifOrder X).prod (Order.fin 6) + +/-- The enumeration of packed owners used to index the shrinking history's resident rows. -/ +def packedOrder : Order ((X.Base × BitWord (Shrink.J a)) × BitWord g) := + ⟨ShrinkPreimages.newCount X,(Shrink.packedIndex X.baseIndex).symm.trans packedSiteEquiv⟩ + +theorem hidden_count (layout : Bool) (site : (X.Base × BitWord (Shrink.J a)) × BitWord g) : + Fintype.card {e : X.packingData.Motif × Fin 4 // X.packingData.shrinkInternalOwner layout e = site} = + 4*(2^a*pieceCount (2^a) (Shrink.colors a)) := + X.packingData.card_shrinkInternalOwner (by have := Nat.two_pow_pos a; change 2 ≤ 2 * 2^a + 1; omega) layout site + +theorem map_count (layout : Bool) (site : (X.Base × BitWord (Shrink.J a)) × BitWord g) : + Fintype.card {e : X.packingData.Motif × Fin 6 // X.packingData.shrinkPartySite layout e.1 e.2 = site} = + 6*(2^a*pieceCount (2^a) (Shrink.colors a)) := + X.packingData.card_shrinkPartySite (by have := Nat.two_pow_pos a; change 2 ≤ 2 * 2^a + 1; omega) layout site + +end CompressorRecords.ShrinkHistoryRows + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkHistoryTrace.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkHistoryTrace.lean new file mode 100644 index 0000000000..c94ceab2ec --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkHistoryTrace.lean @@ -0,0 +1,262 @@ +import OAI.Computability.VPVNP.CompressorRecordsSelectedFinish +import OAI.Computability.VPVNP.CompressorRecordsOrdinalFootprint +import OAI.Computability.VPVNP.RAMChoicePrefix + +/-! +# Linking the selected shrinking placement and role scans + +A completed row returns the next ordinal. Its four writes lie in the +placement or role array. The online dispatcher's tag, ordinal, directory +length and installed frame therefore stay ready throughout the scan. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkHistoryTrace + +open BurstRAM Schedule OrdinalRun PrimedStackRAM +open scoped Fin.CommRing + +variable {w n : ℕ} {Q : Type*} {d : ℕ} + +/-- Link a deterministic ordinal scan after checking the single-call +return and the four physical writes for every live ordinal. -/ +private theorem ordinal_valid (C : Catalog d) (worker : Fin d) (ports : Ports w) + (pub : Fin (C worker).params → Word w) (P : BurstRAM.Program w Q) (fuel : ℕ) + (nativeEvents : Memory w → Word w → List (Event w)) + (one : ∀ m i, execute P fuel (P.start i) m [] = some ⟨nativeEvents m i,some (i+1)⟩) + (stable : ∀ j < n, ∀ m, Preserved (C worker).params ports m (after m (nativeEvents m (j : Word w)))) + (fit : n < 2^w) (m : Memory w) (reports : List (Report w)) + (ready : Ready C worker ports pub (n : Word w) m) + (run : runSegment P fuel (some 0) m (List.replicate n []) = some reports) : + ValidTrace C worker ports pub (n : Word w) 0 m reports ∧ + Preserved (C worker).params ports m (after m (eventLog reports)) := by + let cursor (i : ℕ) : Word w := i + have active (j : ℕ) (hj : j True) + active le_rfl advance 0 _ m reports (by simp) trivial ready run + exact ⟨trace,keep⟩ + +open private store_other from OAI.Computability.VPVNP.CompressorRecordsShrinkScan +open private store_outside from OAI.Computability.VPVNP.CompressorRecordsDemandScan + +theorem placement_valid (C : Catalog d) (worker : Fin d) (ports : Ports w) + (pub : Fin (C worker).params → Word w) (p : Fin 14 → Word w) + (fit : n < 2^w) (m : Memory w) (reports : List (Report w)) (ready : Ready C worker ports pub (n : Word w) m) + (apart : ∀ (j : ℕ), j < n → ∀ (t : Fin 4) x, ControlCell (C worker).params ports x → x ≠ ShrinkRAM.outAddr p t (j : Word w)) + (run : runSegment ((template ShrinkRAM.visit 0).instantiate w p).program 65 (some 0) m (List.replicate n []) = some reports) : + ValidTrace C worker ports pub (n : Word w) 0 m reports ∧ + Preserved (C worker).params ports m (after m (eventLog reports)) := by + apply ordinal_valid C worker ports pub _ 65 (ShrinkRAM.events p) (ShrinkRAM.visit_native p) _ fit m reports ready run + intro j hj mem x hx + rw [ShrinkRAM.visit_after] + exact store_other p mem _ _ x fun t => apart j hj t x hx + +theorem roles_valid (C : Catalog d) (worker : Fin d) (ports : Ports w) + (pub : Fin (C worker).params → Word w) (p : Fin 11 → Word w) + (fit : n < 2^w) (m : Memory w) (reports : List (Report w)) (ready : Ready C worker ports pub (n : Word w) m) + (apart : ∀ (j : ℕ), j < n → ∀ (t : Fin 4) x, ControlCell (C worker).params ports x → x ≠ DemandRAM.fieldAddr p (j : Word w) t) + (run : runSegment ((template DemandRAM.visit 0).instantiate w p).program 65 (some 0) m (List.replicate n []) = some reports) : + ValidTrace C worker ports pub (n : Word w) 0 m reports ∧ + Preserved (C worker).params ports m (after m (eventLog reports)) := by + apply ordinal_valid C worker ports pub _ 65 (DemandRAM.events p) (DemandRAM.visit_native p) _ fit m reports ready run + intro j hj mem x hx + rw [DemandRAM.visit_after] + exact store_outside p mem _ x fun t => apart j hj t x hx + +/-- A native clear before appending either child rows or local-map rows. -/ +theorem clear_valid (C : Catalog d) (worker : Fin d) (ports : Ports w) + (pub : Fin (C worker).params → Word w) (base : Word w) (fit : n < 2^w) (room : base.val+n ≤ 2^w) + (m : Memory w) (rs : List (Report w)) (ready : Ready C worker ports pub (n : Word w) m) + (apart : ∀ x, ControlCell (C worker).params ports x → x < base.val ∨ base.val+n ≤ x) + (run : runSegment ((template SliceRAM.clearOps 0).instantiate w (fun _ => base)).program 8 + (some 0) m (List.replicate n []) = some rs) : + ValidTrace C worker ports pub (n : Word w) 0 m rs ∧ + Preserved (C worker).params ports m (after m (eventLog rs)) := by + apply ordinal_valid C worker ports pub _ 8 (fun _ i => (SliceRAM.clearReport base i).events) + (fun mem i => SliceRAM.clearVisit_native base i mem) _ fit m rs ready run + intro j hj mem x hx + have he : (base+(j : Word w)).val = base.val+j := by + rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (hj.trans fit),Nat.mod_eq_of_lt (by omega)] + have neq : x ≠ (base+(j : Word w)).val := by have := apart x hx; omega + change writeMemory mem _ 0 x = mem x + exact ite_eq_right neq + +open private collectUpdate_frame from OAI.Computability.VPVNP.CompressorSlotFrames + +/-- The guarded preimage worker checks the owner and the row counter before +appending. Every successful call preserves all the indicated controller cells. -/ +theorem append_valid (C : Catalog d) (worker : Fin d) (ports : Ports w) + (pub : Fin (C worker).params → Word w) (p : Fin 6 → Word w) (areas : RowRegions p) + (m : Memory w) (rs : List (Report w)) (ready : Ready C worker ports pub (p 0) m) + (apart : ∀ x, ControlCell (C worker).params ports x → OutsidePreimageWrites p x) + (run : runSegment ((template collectPreimage 3).instantiate w p).program 23 (some 0) m + (List.replicate (p 0).val []) = some rs) : + ValidTrace C worker ports pub (p 0) 0 m rs ∧ + Preserved (C worker).params ports m (after m (eventLog rs)) := by + let M := (template collectPreimage 3).instantiate w p + let cursor (j : ℕ) : Word w := j + have live (j : ℕ) (hj : j < (p 0).val) : cursor j < p 0 := by + change j%(2^w) < (p 0).val + rwa [Nat.mod_eq_of_lt (hj.trans (p 0).isLt)] + let I := fun j mem => ∃ tail, runSegment M.program 23 (some (cursor j)) mem + (List.replicate ((p 0).val-j) []) = some tail + have advance (j : ℕ) (hj : j < (p 0).val) (mem : Memory w) (inv : I j mem) (bits : List Bool) (rep : Report w) + (h : execute M.program 23 (M.program.start (cursor j)) mem bits = some rep) : + rep.result = some (cursor (j+1)) ∧ I (j+1) (after mem rep.events) ∧ Preserved (C worker).params ports mem (after mem rep.events) := by + let i := cursor j + obtain ⟨tail,ht⟩ := inv + rw [show (p 0).val-j=(p 0).val-(j+1)+1 by omega,List.replicate_succ,runSegment] at ht + cases head : execute M.program 23 (M.program.start i) mem [] with + | none => rw [head] at ht; contradiction + | some r => + have eqn : r = rep := (execute_prefix_unique (suffix := bits) head h).2 + subst r + rw [head] at ht + obtain ⟨rest,next,_⟩ := Option.map_eq_some_iff.mp ht + by_cases ok : i < p 0 ∧ ownerAt p mem i < p 2 ∧ mem (countAt p (ownerAt p mem i)).val < p 4 + · have one := collectPreimage_native p mem i ok.1 ok.2.1 ok.2.2 + have eq := Option.some.inj (head.symm.trans one) + subst rep + have succ : i+1=cursor (j+1) := by simp [i,cursor] + refine ⟨congrArg some succ,⟨rest,?_⟩,?_⟩ + · exact succ ▸ next + · intro x hx + change after mem (collectEvents p mem i) x = mem x + rw [after_collectEvents] + exact collectUpdate_frame areas mem i ok.2.1 ok.2.2 x (apart x hx) + · change execute M.program (1+collectPreimage.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ mem [] = _ at head + rw [execute_template,run_eq_trace,collectPreimage_invalid p i _ mem ok] at head + contradiction + have last : p 0 ≤ cursor (p 0).val := by change _ ≤ (p 0).val % (2^w); rw [Nat.mod_eq_of_lt (p 0).isLt] + have start : I 0 m := ⟨rs,by simpa only [Nat.sub_zero,Nat.cast_zero,cursor] using run⟩ + obtain ⟨trace,_,keep⟩ := OrdinalRun.validTrace C worker ports M.program 23 pub (p 0) cursor (p 0).val + I live last advance 0 _ m rs (by simp) start ready run + exact ⟨trace,keep⟩ + +open Compression SelectedArena + +/-- Exact numerical ranges of the two output tables on the selected +branch, including the permutation from old ports to absolute arc IDs. -/ +theorem selected_ranges {a g : ℕ} (X : State a (packingLaneBits a g)) (term stride : Word w) + (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) (m : Memory w) {b : Bool} + (hp : ShrinkRAM.Params p₀ a (Shrink.colors a) (Shrink.J a) g b) (fit : Fits X term stride) : + (∀ (j : ℕ), j < positions X → ∀ t : Fin 4, + let a := ShrinkRAM.outAddr (selectedWords X term stride p₀ m) t (j : Word w) + placementBase X term stride ≤ a ∧ a < roleBase X term stride) ∧ + (∀ (j : ℕ), j < DemandRAM.oldCount X → ∀ t : Fin 4, + let a := DemandRAM.fieldAddr (demandWords X term stride p₀ T) (j : Word w) t + roleBase X term stride ≤ a ∧ a < endAddr X term stride) := by + have room : roleBase X term stride + 4*DemandRAM.absoluteCount X < 2^w := fit + have hn : placementBase X term stride + 4*positions X = roleBase X term stride := rfl + constructor + · intro j hj t + let bit := m (origin X term stride+2) + have hcols := output_column X term stride p₀ bit fit t + have ht := Nat.mul_le_mul_right (positions X) t.isLt + rw [Nat.succ_mul] at ht + have sj : ((j : Word w)).val = j := Nat.mod_eq_of_lt (by omega) + dsimp only [selectedWords,ShrinkRAM.outAddr,Fin.val_add] + rw [hcols,sj,Nat.mod_eq_of_lt (by omega)] + omega + · intro j hj t + let E := BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex + let edge := E.symm ⟨j,hj⟩ + have base := role_base_val X term stride p₀ T fit + have sizes := DemandRAM.count_eq X + have sj : ((j : Word w)).val = (E edge).val := by + rw [show E edge = ⟨j,hj⟩ from Equiv.apply_symm_apply E _] + exact Nat.mod_eq_of_lt (by omega) + rw [DemandRAM.fieldAddr_exact X (demand_params X term stride p₀ T hp) (by rw [base]; exact room.le) edge sj t,base] + have he : (DemandRAM.absoluteIndex X edge).val < DemandRAM.absoluteCount X := (DemandRAM.absoluteIndex X edge).isLt + have ht := t.isLt + change _ ∧ _ < roleBase X term stride + 4*DemandRAM.absoluteCount X + omega + +/-- The two report groups of the actual selected score/placement/role +execution pass the guarded scheduler at their chronological input memories. -/ +theorem selected_valid {a g : ℕ} (X : State a (packingLaneBits a g)) (term stride selectors : Word w) + (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) (m : Memory w) (p : SelectedStage.Passes w) + (exec : SelectedStage.Execution X term stride selectors p₀ T m p) {b : Bool} + (hp : ShrinkRAM.Params p₀ a (Shrink.colors a) (Shrink.J a) g b) (fit : Fits X term stride) + (C : Catalog d) (positionsID rolesID : Fin d) (ports : Ports w) + (pp : Fin (C positionsID).params → Word w) (rp : Fin (C rolesID).params → Word w) + (pr : Ready C positionsID ports pp (positions X : Word w) (p.afterScores m)) + (rr : Ready C rolesID ports rp (DemandRAM.oldCount X : Word w) (p.afterPositions m)) + (psep : ∀ x, ControlCell (C positionsID).params ports x → x < placementBase X term stride ∨ roleBase X term stride ≤ x) + (rsep : ∀ x, ControlCell (C rolesID).params ports x → x < roleBase X term stride ∨ endAddr X term stride ≤ x) : + ValidTrace C positionsID ports pp (positions X : Word w) 0 (p.afterScores m) p.positions ∧ + ValidTrace C rolesID ports rp (DemandRAM.oldCount X : Word w) 0 (p.afterPositions m) p.roles := by + have room : placementBase X term stride+4*positions X+4*DemandRAM.absoluteCount X < 2^w := fit + have cnt := DemandRAM.count_eq X + obtain ⟨rng,rng'⟩ := selected_ranges X term stride p₀ T (p.afterScores m) hp fit + refine ⟨(placement_valid C positionsID ports pp _ (by omega) _ _ pr ?_ exec.positions).1, + (roles_valid C rolesID ports rp _ (by omega) _ _ rr ?_ exec.roles).1⟩ + · intro j hj t x hx + have ha := rng j hj t + have ho := psep x hx + omega + · intro j hj t x hx + have ha := rng' j hj t + have ho := rsep x hx + omega + +/-- The collector and counter clear at the two addresses following the +selected placement/role arena pass the online guards in the same memory. -/ +theorem selected_finish_valid {a g : ℕ} (X : State a (packingLaneBits a g)) (term stride : Word w) + (p₀ : Fin 14 → Word w) (layoutWord : Word w) (side : Bool) (m : Memory w) (pass : SelectedFinish.Passes w) + (room : SelectedFinish.stop X term stride ≤ 2^w) + (exec : SelectedFinish.Collected X term stride (shrinkWords X term stride p₀ layoutWord) side m pass) + (C : Catalog d) (clearID appendID : Fin d) (ports : Ports w) (cp : Fin (C clearID).params → Word w) + (ap : Fin (C appendID).params → Word w) + (cr : Ready C clearID ports cp (ShrinkPreimages.newCount X : Word w) m) + (ar : Ready C appendID ports ap (ShrinkPreimages.oldCount X : Word w) (pass.middle m)) + (cs : ∀ x, ControlCell (C clearID).params ports x → + x < SelectedFinish.countStart X term stride ∨ SelectedFinish.rowStart X term stride ≤ x) + (as : ∀ x, ControlCell (C appendID).params ports x → + x < SelectedFinish.countStart X term stride ∨ SelectedFinish.stop X term stride ≤ x) : + ValidTrace C clearID ports cp (ShrinkPreimages.newCount X : Word w) 0 m pass.clear ∧ + ValidTrace C appendID ports ap (ShrinkPreimages.oldCount X : Word w) 0 (pass.middle m) pass.collect := by + let p := SelectedFinish.params X term stride (shrinkWords X term stride p₀ layoutWord) + have areas := SelectedFinish.areas X term stride p₀ layoutWord room + obtain ⟨ho,hn,hcap⟩ := areas.dimensions + change (p 0).val=ShrinkPreimages.oldCount X at ho + change (p 2).val=ShrinkPreimages.newCount X at hn + change (p 4).val=ShrinkPreimages.capacity a at hcap + have endEq := ShrinkPreimages.oldCount_eq X + have pos : 0 < ShrinkPreimages.oldCount X := Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos _) + have capRoom : SelectedFinish.countStart X term stride+ShrinkPreimages.newCount X+ShrinkPreimages.oldCount X ≤ 2^w := room + have cval : (SelectedFinish.counts X term stride).val = SelectedFinish.countStart X term stride := Nat.mod_eq_of_lt (by omega) + have rval : (SelectedFinish.rows X term stride).val = SelectedFinish.rowStart X term stride := + Nat.mod_eq_of_lt (by unfold SelectedFinish.rowStart; omega) + have hw : p 0 = (ShrinkPreimages.oldCount X : Word w) := by + apply Fin.ext + rw [Fin.val_natCast,Nat.mod_eq_of_lt areas.sizes.1] + exact ho + refine ⟨(clear_valid C clearID ports cp (SelectedFinish.counts X term stride) areas.sizes.2.1 + (by rw [cval]; omega) m pass.clear cr (by simpa only [cval,SelectedFinish.rowStart] using cs) exec.clear).1,?_⟩ + rw [← hw] + apply (append_valid C appendID ports ap p areas.regions (pass.middle m) pass.collect (hw ▸ ar) _ (ho.symm ▸ exec.collect)).1 + intro x hx + change (x < (SelectedFinish.counts X term stride).val ∨ (SelectedFinish.counts X term stride).val+(p 2).val ≤ x) ∧ + (x < (SelectedFinish.rows X term stride).val ∨ (SelectedFinish.rows X term stride).val+(p 2).val*(p 4).val ≤ x) + rw [cval,rval,hn,hcap,←endEq] + have h := as x hx + dsimp only [SelectedFinish.stop,SelectedFinish.rowStart] at h ⊢ + omega + +end CompressorRecords.ShrinkHistoryTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkInput.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkInput.lean new file mode 100644 index 0000000000..bc2caf7cd2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkInput.lean @@ -0,0 +1,337 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy +import OAI.Computability.VPVNP.CompressorRecordsShrinkPlacement +import OAI.Computability.VPVNP.CompressorRecordsShrinkRankArena +import OAI.Computability.VPVNP.CompressorRecordsShrinkWidthArena + +/-! +# Physical input to term selection at a shrinking level + +Starting from the old incidence directory, run the two greedy assignments, a +preliminary layout, arc classification and ranking, width sorting, and both +prefix constructions. The preliminary layout places thin sites at their bundle +source. The thick-wire and CD assignments computed before term selection +depend only on the two thickness flags, the old slot, and the assigned bundle. + +The report lists in the execution begin with the memory produced by their +predecessors. All counters needed by the list pass are explicitly cleared. +The original directory, the greedy colors and offsets, and the preliminary +placement records remain readable alongside the sorted AB and CD inputs. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkInput + +open BurstRAM Compression PrimedStackRAM BundleKeys ShrinkRankSpace + +variable {w a g : ℕ} (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) (start : ℕ) +local notation "N" => Fintype.card X.Base +local notation "S" => N*2^(packingLaneBits a g) +local notation "A" => S*2^a + +/-- The start of the preliminary old-site placement columns, immediately after the greedy +workspace. -/ +def placementBase := GreedyArena.greedyStop start N a +/-- The start of the bundle classification and ranking arena, immediately after the preliminary +placement columns. -/ +def rankBase := ShrinkPlacement.stop X (placementBase X start) +/-- The layout of bucket, key, count, identifier, gathered-key, and rank storage for the old +ports. -/ +abbrev plan := ShrinkRankArena.shape X (rankBase X start) +/-- The start of the sorted width and prefix tables following the bundle ranking arena. -/ +def widthBase := (plan X start).stop +/-- The exclusive end of the deterministic shrinking-input arena, including width rectangles +and bundle totals. -/ +def stop := widthBase X start+6*((plan X start).B*(plan X start).Q)+2*(plan X start).B + +/-- The preliminary placement worker's operands, using the greedy color and offset columns and +the layout that assigns thin sites to their bundle source. -/ +def placementBank := ShrinkPlacement.bank X T + (ShrinkRAM.word w (GreedyArena.colorBase start)) + (ShrinkRAM.word w (GreedyArena.offsetBase start N a)) (placementBase X start) false + +local notation "Z" => plan X start +local notation "sh" => placementBank X T start +local notation "classBank" => Shape.classifyBank (plan X start) T (placementBank X T start) +local notation "q" => Shape.collectBank (plan X start) w +local notation "dest" => ShrinkRAM.word w (Shape.ranks (plan X start)) +local notation "wb" => widthBase X start + +/-- Chronological execution of the deterministic, pre-selection part of a +shrinking level. Each component exposes its actual instruction tables. -/ +structure Run (m : Memory w) where + /-- The color and offset assignments supplying the preliminary placement pass. -/ + greedy : GreedyArena.Run X T start m + /-- Reports of placing all old sites under the preliminary layout. -/ + sites : List (Report w) + positions : runSegment ((template ShrinkRAM.visit 0).instantiate w sh).program 65 (some (ShrinkRAM.word w 0)) + greedy.post (List.replicate S []) = some sites + siteWork : ShrinkRAM.ScanResult sh S 0 S greedy.post sites + preliminary : ShrinkRAM.PlacementColumns X.slots X.baseIndex sh false (after greedy.post (eventLog sites)) + siteFrame : ∀ addr < placementBase X start, after greedy.post (eventLog sites) addr = greedy.post addr + /-- Reports of clearing the thick-wire and CD row counts before appending any old ports. -/ + clear : List (Report w) + /-- Reports of computing the bucket and sorting key for every old outgoing port. -/ + classify : List (Report w) + /-- Reports of appending each old port identifier to its classified bundle row. -/ + append : List (Report w) + /-- Reports of reading each row's identifiers to gather the corresponding old-port sorting + keys. -/ + gather : List (Report w) + /-- Reports of calculating each old port's rank in its classified row from the gathered keys. -/ + rank : List (Report w) + ranking : ShrinkRankArena.Run X T sh (rankBase X start) (after greedy.post (eventLog sites)) + clear classify append gather rank + /-- Reports of scattering old arc widths into their bundle rows at the computed ranks. -/ + scatter : List (Report w) + /-- Reports of computing starts and totals of sorted thick-wire payloads in each bundle. -/ + thickPrefixes : List (Report w) + /-- Reports of computing starts and totals of sorted CD motif payloads in each bundle. -/ + cdPrefixes : List (Report w) + /-- Reports of splitting each thick payload total into AB piece widths and prefix offsets. -/ + abPieces : List (Report w) + widths : ShrinkWidthArena.Run X T q dest wb + (ShrinkRankArena.finalMemory (after greedy.post (eventLog sites)) clear classify append gather rank) + scatter thickPrefixes cdPrefixes abPieces + +theorem range_bounds : + start ≤ placementBase X start ∧ placementBase X start ≤ rankBase X start ∧ + rankBase X start ≤ wb ∧ wb ≤ stop X start := by + have hg := GreedyArena.bounds start N a + change GreedyArena.colorBase start+N ≤ _ ∧ _ at hg + have hpre : start ≤ placementBase X start := by + change start ≤ GreedyArena.greedyStop start N a + unfold GreedyArena.colorBase at hg + omega + have hrs : rankBase X start ≤ wb := by + dsimp [widthBase,Shape.stop,Shape.ranks,Shape.gathered,Shape.ids,Shape.counts,plan,ShrinkRankArena.shape] + omega + exact ⟨hpre,Nat.le_add_right ..,hrs,by unfold stop; omega⟩ + +theorem pre_starts (room : stop X start < 2^w) (t : Fin 4) : + (sh (t.natAdd 10)).val + S ≤ rankBase X start := by + obtain ⟨_,_,hr,hw⟩ := range_bounds X start + have fit := hr.trans_lt (hw.trans_lt room) + rw [show (sh (t.natAdd 10)).val = placementBase X start+t.val*S from + ShrinkPlacement.starts X T _ _ _ false fit t] + change _ ≤ placementBase X start+4*S + have hh := Nat.mul_le_mul_right S t.isLt + rw [Nat.succ_mul] at hh; omega + +namespace Run + +variable {X T start} {m : Memory w} (r : Run X T start m) + +/-- The memory after preliminary site placement and all bucket, append, key-gathering, and +ranking passes. -/ +def rankPost := ShrinkRankArena.finalMemory (after r.greedy.post (eventLog r.sites)) + r.clear r.classify r.append r.gather r.rank + +/-- The final shrinking-input memory containing the ranked widths, prefix tables, and split AB +piece data. -/ +def post := ShrinkWidthArena.finalMemory r.rankPost r.scatter r.thickPrefixes r.cdPrefixes r.abPieces + +theorem afterRank (addr : ℕ) (h : addr < widthBase X start) : r.post addr = r.rankPost addr := + r.widths.frame addr h + +theorem afterSites (addr : ℕ) (h : addr < rankBase X start) : + r.post addr = after r.greedy.post (eventLog r.sites) addr := + (r.afterRank addr (h.trans_le (range_bounds X start).2.2.1)).trans (r.ranking.below addr h) + +theorem afterGreedy (addr : ℕ) (h : addr < placementBase X start) : r.post addr = r.greedy.post addr := + (r.afterSites addr (h.trans_le (range_bounds X start).2.1)).trans (r.siteFrame addr h) + +theorem below (addr : ℕ) (h : addr < start) : r.post addr = m addr := + (r.afterGreedy addr (h.trans_le (range_bounds X start).1)).trans (r.greedy.below addr h) + +theorem incidence : T.Represents X r.post := r.greedy.input.retain r.greedy.old r.below + +theorem placement (room : stop X start < 2^w) : + ShrinkRAM.PlacementColumns X.slots X.baseIndex sh false r.post := + r.preliminary.retain (pre_starts X T start room) r.afterSites + +include r in +/-- The extents of the old color, offset, mate and shift columns in the +preliminary and selected-layout scans. -/ +theorem inputBounds : + (sh 6).val+N ≤ placementBase X start ∧ (sh 7).val+N ≤ placementBase X start ∧ + (sh 8).val+N*2^a ≤ placementBase X start ∧ (sh 9).val+N*2^a ≤ placementBase X start := by + have hb := GreedyArena.bounds start N a + have h₆ : (sh 6).val+N ≤ placementBase X start := by + have hc : GreedyArena.colorBase start < 2^w := by have := r.greedy.room; omega + change GreedyArena.colorBase start % (2^w)+N ≤ GreedyArena.greedyStop start N a + rw [Nat.mod_eq_of_lt hc]; omega + have h₇ : (sh 7).val+N ≤ placementBase X start := by + have hc : GreedyArena.offsetBase start N a < 2^w := by have := r.greedy.room; omega + change GreedyArena.offsetBase start N a % (2^w)+N ≤ GreedyArena.greedyStop start N a + rw [Nat.mod_eq_of_lt hc]; omega + have hs := Nat.mul_le_mul_right (2^a) (Nat.le_mul_of_pos_right N (Nat.two_pow_pos (packingLaneBits a g))) + refine ⟨h₆,h₇,(Nat.add_le_add_left hs _).trans ((r.greedy.old 0).trans (range_bounds X start).1), + (Nat.add_le_add_left hs _).trans ((r.greedy.old 2).trans (range_bounds X start).1)⟩ + +theorem incidence_after {out : Memory w} (frame : ∀ addr < stop X start, out addr = r.post addr) : + T.Represents X out := by + obtain ⟨h₁,h₂,h₃,h₄⟩ := range_bounds X start + exact r.incidence.retain (fun c ↦ (r.greedy.old c).trans (h₁.trans (h₂.trans (h₃.trans h₄)))) frame + +theorem placement_after {out : Memory w} (room : stop X start < 2^w) + (frame : ∀ addr < stop X start, out addr = r.post addr) : + ShrinkRAM.PlacementColumns X.slots X.baseIndex sh false out := by + obtain ⟨_,_,h₃,h₄⟩ := range_bounds X start + exact (r.placement room).retain (fun t ↦ (pre_starts X T start room t).trans (h₃.trans h₄)) frame + +/-- Both assignments can be read in any later memory preserving the shrinking input. -/ +theorem directory_before {out : Memory w} (frame : ∀ addr < placementBase X start, out addr = r.post addr) : + Shrink.Directory X.slots X.baseIndex + (ShrinkRAM.column sh out 6) (ShrinkRAM.column sh out 7) + (ShrinkRAM.column sh out 8) (ShrinkRAM.column sh out 9) := by + obtain ⟨h₆,h₇,h₈,h₉⟩ := r.inputBounds + have after (z : ℕ) (h : z < placementBase X start) : out z = r.greedy.post z := + (frame z h).trans (r.afterGreedy z h) + have keep (c : Fin 14) (j k : ℕ) (hc : (sh c).val+k ≤ placementBase X start) (hj : j Shrink.packedIndex (a := a) (g := g) X.baseIndex +local notation "sh" => levelShape (b := b) X +local notation "T" => splitBank (b := b) X F sel term stride role retained +local notation "h" => slotHeads (b := b) X term.val stride role retained +local notation "cutoff" => widthBase X term.val stride role retained +local notation "last" => stop (b := b) X term.val stride role retained +local notation "side" => selectedLayout X F sel +local notation "termInput" => Terms X.packingData X.shrinkNumber sitesOrd T F X.packingWidth sel +local notation "sizeAt" => selected X.packingData X.shrinkNumber sitesOrd T F X.packingWidth sel +local notation "splits" => SlotWidthScan.SplitRows X.packingData (Shape.subdivisions sh) X.baseIndex + (bitWordFinEquiv (Shrink.J a)) (bitWordFinEquiv g) (branchWidth X F sel) cutoff + +/-- The total probe count for constructing the output slot directory, including genuine and +dummy slots and the base and actual arc scans. -/ +def slotProbes (s : Shape) := + (24+2*sites s+2*(owners s+fields s)) + + (6*genuineCount s+3*dummyCount s+5*fields s+3*(owners s*s.newDegree)+8*baseArcs s+12*actualCount s) + +/-- Word bounds on static arithmetic and the current maximum wire width, +independent of the selected branch. -/ +structure FitsWords : Prop where + room : last < 2^w + selector : F.selectorBits < 2^w + supply : fieldFactor F * (X.maxWireWidth+1) < 2^w + lanes : (sh).lanes < 2^w + tags : (sh).tags < 2^w + profile : (∑ t, (sh).subdivisions t) < 2^w + degree : (sh).newDegree < 2^w + +private theorem roles_frame (mem out : Memory w) (roles : DemandRAM.RoleColumns X side role mem) + (eqn : ∀ x < cutoff, out x = mem x) : DemandRAM.RoleColumns X side role out := by + have bound (arc) (j : ℕ) (hj : j < 4) : role + 4*(DemandRAM.absoluteIndex X arc).val+j < cutoff := by + have hi := (DemandRAM.absoluteIndex X arc).isLt + have stopRole := role_room X term stride role retained + change (DemandRAM.absoluteIndex X arc).val < absoluteCount X at hi + omega + constructor + · intro arc; rw [eqn _ (bound arc 3 (by decide))]; exact roles.cd arc + · intro arc r; rw [eqn _ (bound arc.val (roleOffset r) (by cases r <;> decide))]; exact roles.packed arc r + +/-- Every selected physical supply width is bounded by the same quantity +fixed before the verifier chooses the terms. -/ +theorem supply_fit (hw : FitsWords (b := b) X F term stride role retained) (i : Allocation.Id (motifCount X)) : + sizeAt i < 2^w := by + let m := (ShrinkMotifOrder.stateNumber X).symm i.1 + have bound := X.packingData.shrinkTerm_bounds (State.two_le_packingColors _) (Nat.two_pow_pos _) + X.shrinkNumber X.packingWidth (fun _ => X.width_le_maxWireWidth _) F m (sel m) + exact (bound.2 (side,i.2)).2.trans_lt hw.supply + +/-- The complete slot build and the readbacks of the final shared memory. -/ +structure Constructed (mem out : Memory w) (r : Build.Construction w) + (slotStart : ℕ := (h).role) : Prop where + inputRoles : DemandRAM.RoleColumns X side role out + slots : r.Native sh (heads sh role slotStart) cutoff side out + cursors : r.Cursors sh + incidence : (directory sh (heads sh role slotStart) w).Represents (X.shrinkNext F ready sel) (r.final out) + roles : DemandRAM.RoleColumns X side role (r.final out) + widths : splits (r.final out) + intervals : ∀ i, Image ((T).row i) (sizeAt i) (r.final out) + frame : ∀ x, x < cutoff ∨ finish sh (heads sh role slotStart) ≤ x → r.final out x = mem x + probes : RAMBuckets.cost Report.probes r.all = slotProbes sh + +set_option maxHeartbeats 1600000 in +/-- The surviving sweep's absolute width rows are the input of the native +slot passes. Their interval records and the earlier directories survive. -/ +theorem finish_after_sweep_at (slotStart : ℕ) (gap : (h).role ≤ slotStart) + (endFit : finish sh (heads sh role slotStart) < 2^w) (wide : 10 ≤ stride) (hw : FitsWords (b := b) X F term stride role retained) + (mem out : Memory w) (roles : DemandRAM.RoleColumns X side role mem) + (images : ∀ i, Image ((T).row i) (sizeAt i) out) + (values : ∀ (m : X.packingData.Motif) (t : Fin 4) (j : Fin ((T).subdiv t)), + (out ((T).widthBase+((oldArcIndex X.packingData X.baseIndex (bitWordFinEquiv (Shrink.J a)) + (bitWordFinEquiv g) m.val).val*4+t.val)*(T).stride+j.val)).val = + splitWidth (X.packingData.termWidths F X.shrinkNumber X.packingWidth sel m (T).layout t) ((T).subdiv t) j) + (oldFrame : ∀ x, x < cutoff ∨ (T).last ≤ x → out x = mem x) : + ∃ r, Constructed X F ready sel term stride role retained mem out r slotStart := by + let fit := fits X F sel term stride role retained ready wide hw.room + have sr := Build.splitRows_of_values X (sh).subdivisions cutoff out (branchWidth X F sel) (fun m t j => by + have hl : (T).layout = side := rfl + have hv := values m t j + rw [hl] at hv + rw [← Nat.add_assoc] + exact hv) + have kept := roles_frame X F sel term stride role retained mem out roles (fun x hx => oldFrame x (.inl hx)) + have roleRoom : role+4*absoluteCount X ≤ (h).role := + (role_room X term stride role retained).trans (width_le_slots X term stride role retained) + have splitRoom : cutoff+(oldBaseArcCount (sh).bases (sh).tags (sh).oldDegree (sh).colors*(sh).lanes)*4* + (∑ t,(sh).subdivisions t) ≤ (h).role := Nat.le_add_right .. + obtain ⟨r,native,cursors,inc,ro,sp,slotFrame,slotCost⟩ := + Build.build X F ready sel (heads sh role slotStart) cutoff out kept sr (roleRoom.trans gap) (splitRoom.trans gap) + le_rfl le_rfl le_rfl endFit + hw.lanes hw.tags hw.profile hw.degree + refine ⟨r,⟨kept,native,cursors,inc,ro,sp,?_,?_,slotCost⟩⟩ + · intro i + apply (images i).keep + intro x hx + exact slotFrame x (.inl (lt_of_not_ge fun he => hx ((T).rowOutside fit i x (.inr (gap.trans he))))) + · intro x hx + have hle := width_le_slots (b := b) X term stride role retained + have he : (h).role ≤ finish sh (heads sh role slotStart) := gap.trans (by + dsimp [finish, widthHead, inHead, outHead, inverseBaseHead, stopAddress, shiftsHead, targetsHead, inverseHead, rowsHead, heads] + omega) + exact (slotFrame x (hx.imp (fun p => p.trans_le (hle.trans gap)) id)).trans + (oldFrame x (hx.imp id (fun p => he.trans p))) + +/-- The consecutive allocation uses the first free address after the width +and interval rectangle as the start of the ordered-slot bank. -/ +theorem finish_after_sweep (wide : 10 ≤ stride) (hw : FitsWords (b := b) X F term stride role retained) + (mem out : Memory w) (roles : DemandRAM.RoleColumns X side role mem) + (images : ∀ i, Image ((T).row i) (sizeAt i) out) + (values : ∀ (m : X.packingData.Motif) (t : Fin 4) (j : Fin ((T).subdiv t)), + (out ((T).widthBase+((oldArcIndex X.packingData X.baseIndex (bitWordFinEquiv (Shrink.J a)) + (bitWordFinEquiv g) m.val).val*4+t.val)*(T).stride+j.val)).val = + splitWidth (X.packingData.termWidths F X.shrinkNumber X.packingWidth sel m (T).layout t) ((T).subdiv t) j) + (oldFrame : ∀ x, x < cutoff ∨ (T).last ≤ x → out x = mem x) : + ∃ r, Constructed X F ready sel term stride role retained mem out r := + finish_after_sweep_at X F ready sel term stride role retained (h).role le_rfl hw.room + wide hw mem out roles images values oldFrame + +end CompressorRecords.ShrinkOutput + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkPlacement.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkPlacement.lean new file mode 100644 index 0000000000..c57626cff1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkPlacement.lean @@ -0,0 +1,136 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkRankSpace + +/-! +# Four consecutive placement columns for a shrinking pass + +The two short greedy columns are indexed by old base vertex. The mate and +shift columns are indexed by old base port. The output rectangles are +indexed by all old sites. These separate extents allow the four rectangles +to begin immediately after the old directories. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkPlacement + +open BurstRAM Compression PrimedStackRAM ShrinkRAM + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) +local notation "N" => Fintype.card X.Base +local notation "S" => N*2^(packingLaneBits a g) +local notation "D" => (2:ℕ)^a +local notation "C" => Shrink.colors a +local notation "J" => Shrink.J a + +/-- The fourteen public placement operands, including radices, layout choice, old incidence and +greedy data, and four output column bases. -/ +def bank (color offset : Word w) (base : ℕ) (layout : Bool) : Fin 14 → Word w := + ![word w (2^g), word w (2^J), word w D, word w (2^C), word w (C-1), + if layout then 1 else 0, color, offset, T.baseOut,T.shift, + word w (base+0*S),word w (base+1*S),word w (base+2*S),word w (base+3*S)] + +/-- The first address after the four placement columns, each of which has one entry per old +site. -/ +def stop (base : ℕ) := base+4*S + +variable (color offset : Word w) (base : ℕ) (layout : Bool) +local notation "p" => bank X T color offset base layout + +theorem params (room : stop X base < 2^w) : Params p a C J g layout := by + have hsite : S < 2^w := by change base+4*S < _ at room; omega + have hp : 2^(packingLaneBits a g) < 2^w := (Nat.le_mul_of_pos_left _ (Fintype.card_pos : 0 < N)).trans_lt hsite + have fit (j : ℕ) (hj : j ≤ packingLaneBits a g) : 2^j < 2^w := + (Nat.pow_le_pow_right Nat.zero_lt_two hj).trans_lt hp + have hg := fit g (by simp only [packingLaneBits]; omega) + have hj := fit J (by simp only [packingLaneBits,Shrink.J]; omega) + have hd := fit a (by simp only [packingLaneBits]; omega) + have hc := fit C (by simp only [packingLaneBits,Shrink.colors]; omega) + have hlow := fit (J+g) (by simp only [packingLaneBits,Shrink.J]; omega) + have hc' := (Nat.pow_lt_pow_iff_right Nat.one_lt_two).mp hc + have he : C-1 < 2^w := (Nat.sub_le ..).trans_lt (hc'.trans Nat.lt_two_pow_self) + have h2 : 2 < 2^w := (Nat.pow_le_pow_right Nat.zero_lt_two (show 1 ≤ C by unfold Shrink.colors; omega)).trans_lt hc + exact ⟨Nat.mod_eq_of_lt hg,Nat.mod_eq_of_lt hj,Nat.mod_eq_of_lt hd,Nat.mod_eq_of_lt hc,Nat.mod_eq_of_lt he, + rfl,hlow,by omega,h2⟩ + +theorem starts (room : stop X base < 2^w) (i : Fin 4) : + (p (i.natAdd 10)).val = base+i.val*S := by + have h : base+i.val*S < 2^w := by + have hi := Nat.mul_le_mul_right S i.isLt.le + change base+4*S < _ at room; omega + fin_cases i <;> exact Nat.mod_eq_of_lt h + +private theorem divWord (x y : Word w) : (div x y).val = x.val / y.val := + Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt) + +private theorem modWord (x y : Word w) : (mod x y).val = x.val % y.val := + Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt) + +private theorem offsets (hp : Params p a C J g layout) (i : Word w) (hi : i.val < S) : + (decode p i).base.val < N ∧ (baseArc p (decode p i)).val < N*D := by + have hchunk : (p 1*p 0).val = 2^(J+g) := by rw [Fin.val_mul,hp.tag,hp.lane,← pow_add,Nat.mod_eq_of_lt hp.low_fit] + have hb : (decode p i).base.val < N := by + change (div (div (div i (p 1*p 0)) (p 2)) (p 3)).val < _ + rw [divWord,divWord,divWord,hchunk,hp.degree,hp.mask] + apply (Nat.div_lt_iff_lt_mul (Nat.two_pow_pos _)).mpr + apply (Nat.div_lt_iff_lt_mul (Nat.two_pow_pos _)).mpr + apply (Nat.div_lt_iff_lt_mul (Nat.two_pow_pos _)).mpr + simpa only [packingLaneBits,Shrink.J,Shrink.colors,pow_add,Nat.mul_assoc] using hi + have hs : (decode p i).slot.val < D := by + change (mod (div i (p 1*p 0)) (p 2)).val < _ + rw [modWord,hp.degree]; exact Nat.mod_lt _ (Nat.two_pow_pos _) + refine ⟨hb,?_⟩ + have hh := Nat.mul_le_mul_right D hb + rw [Nat.succ_mul] at hh + rw [baseArc,Fin.val_add,Fin.val_mul,hp.degree,Nat.mod_add_mod] + exact (Nat.mod_le ..).trans_lt (by omega) + +theorem regions (room : stop X base < 2^w) (colorBefore : color.val+N ≤ base) (offBefore : offset.val+N ≤ base) + (old : ∀ t : Fin 6, (T.column t).val+S*D ≤ base) : Regions p S := by + have hp := params X T color offset base layout room + apply Regions.packed p room.le (starts X T color offset base layout room) + intro c i hi + obtain ⟨hb, ha⟩ := offsets X T color offset base layout hp i hi + have hsmall : N*D ≤ S*D := Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _)) + have access (addr k : Word w) (h : addr.val+k.val < base) : (addr+k).val < base := + (Nat.mod_le ..).trans_lt h + left + fin_cases c + · exact access color _ ((Nat.add_lt_add_left hb _).trans_le colorBefore) + · exact access offset _ ((Nat.add_lt_add_left hb _).trans_le offBefore) + · exact access T.baseOut _ ((Nat.add_lt_add_left (ha.trans_le hsmall) _).trans_le (old 0)) + · exact access T.shift _ ((Nat.add_lt_add_left (ha.trans_le hsmall) _).trans_le (old 2)) + +theorem actual_run (m : Memory w) (dir : Shrink.Directory X.slots X.baseIndex + (column p m 6) (column p m 7) (column p m 8) (column p m 9)) + (room : stop X base < 2^w) (colorBefore : color.val+N ≤ base) (offBefore : offset.val+N ≤ base) + (old : ∀ t : Fin 6, (T.column t).val+S*D ≤ base) : + ∃ rs, runSegment ((template ShrinkRAM.visit 0).instantiate w p).program 65 (some (word w 0)) m + (List.replicate S []) = some rs ∧ ScanResult p S 0 S m rs ∧ + PlacementColumns X.slots X.baseIndex p layout (after m (eventLog rs)) ∧ + ∀ z < base, after m (eventLog rs) z = m z := by + have reg := regions X T color offset base layout room colorBefore offBefore old + have hx : N*(2^J*2^g)*D ≤ S := by + simp only [packingLaneBits,pow_add,Shrink.J] + have h := Nat.le_mul_of_pos_left (N*2^(packingTagBits (2^a))*2^g*2^a) (Nat.two_pow_pos (2*2^a+1)) + rw [Nat.mul_assoc N (2^(packingTagBits (2^a))) (2^g)] at h + convert h using 1; ring + obtain ⟨rs,he,scan,rows⟩ := placement_run X.slots X.baseIndex p layout m + (params X T color offset base layout room) dir reg (hx.trans reg.fits) + refine ⟨rs,he,scan,rows,?_⟩ + intro z hz + apply scan.preserve + intro t i _ hi + have hi' : i.val v = X.packingData.placement layout u) + +/-- Physical row counts and ordinal data words, in the restricted old-site order used +by the local history parser. -/ +structure Directory (layout : Bool) (counts rows : Word w) (m : Memory w) : Prop where + count : ∀ v : Shrink.Packed X.Base a g, + (m (counts.val + (Shrink.packedIndex X.baseIndex v).val)).val = capacity a + child : ∀ (v : Shrink.Packed X.Base a g) (j : Fin (children X layout v).length), + (m (rows.val + (Shrink.packedIndex X.baseIndex v).val * capacity a + j.val)).val = + (Shrink.oldIndex X.baseIndex ((children X layout v).entries j).val).val + +open private countAt_val rowAt_val from OAI.Computability.VPVNP.CompressorRecordPreimageScan + +theorem directory_of_collected (areas : Areas X shrink counts rows) (layout : Bool) (m : Memory w) + (collected : PreimagesAt (params X shrink counts rows) (place X layout) m (oldCount X)) : + Directory X layout counts rows m := by + let p := params X shrink counts rows + let o := oldOrder X + let e := newOrder X + obtain ⟨hA, hB, hC⟩ := areas.dimensions + have ownerVal (v) : (siteWord w e v).val = (Shrink.packedIndex X.baseIndex v).val := + Nat.mod_eq_of_lt ((Shrink.packedIndex X.baseIndex v).isLt.trans areas.sizes.2.1) + have valid (v) : siteWord w e v < p 2 := by + change (siteWord w e v).val < (p 2).val + rw [ownerVal, hB]; exact (Shrink.packedIndex X.baseIndex v).isLt + have realize : RepresentsPlacement o e (X.packingData.placement layout) (place X layout (w := w)) := + encodedPlacement_represents o e _ areas.sizes.1.le areas.sizes.2.1.le + constructor + · intro v + have h := (collected.rows (siteWord w e v) (valid v)).1 + rw [countAt_val areas.regions (valid v), ownerVal] at h + refine h.trans ?_ + rw [show siteWord w e v = Fin.ofNat (2^w) (Shrink.packedIndex X.baseIndex v).val from rfl] + rw [place, encodedPlacement_rowLength _ _ _ areas.sizes.1.le areas.sizes.2.1.le, + X.packingData.card_placement (by omega)] + · intro v j + have h := collected.rows (siteWord w e v) (valid v) + have ids := preimagePrefix_eq_orderedIds o e (X.packingData.placement layout) (place X layout) + realize areas.sizes.1.le areas.sizes.2.1.le v + change rowRepresents m (countAt p (siteWord w e v)) (rowAt p (siteWord w e v)) + (preimagePrefix (place X layout) (siteWord w e v) o.length) at h + rw [ids] at h + have k := h.2 ⟨j.val, by simpa only [orderedIds, List.length_ofFn] using j.isLt⟩ + rw [rowAt_val areas.regions (valid v), ownerVal, hC] at k + simp only [orderedIds, List.getElem_ofFn] at k + exact (congrArg Fin.val k).trans (Nat.mod_eq_of_lt + ((Shrink.oldIndex X.baseIndex ((children X layout v).entries j).val).isLt.trans areas.sizes.1)) + +private theorem clear_cost (cs : List (Report w)) (h : ∀ r ∈ cs, r.probes = 1) : + RAMBuckets.cost Report.probes cs = 2*cs.length := by + induction cs with + | nil => rfl + | cons r cs ih => + rw [RAMBuckets.cost, h r (List.mem_cons_self ..), ih (fun q hq => h q (List.mem_cons_of_mem _ hq)), + List.length_cons, Nat.mul_succ] + omega + +/-- The count clear and the append pass execute from arbitrary initial scratch contents. +One clear costs two calls-plus-probes per packed position. Appending costs five per +old position. Every address outside the count and row arrays retains its initial word. -/ +theorem build (areas : Areas X shrink counts rows) (layout : Bool) (mem : Memory w) + (column : ShrinkRAM.PlacementColumns X.slots X.baseIndex shrink layout mem) : + let p := params X shrink counts rows + let zero := (template SliceRAM.clearOps 0).instantiate w (fun _ => counts) + let collect := (template collectPreimage 3).instantiate w p + ∃ cs rs, let m₁ := after mem (eventLog cs) + let m₂ := after m₁ (eventLog rs) + runSegment zero.program 8 (some 0) mem (List.replicate (newCount X) []) = some cs ∧ + runSegment collect.program 23 (some 0) m₁ (List.replicate (oldCount X) []) = some rs ∧ + PreimagesAt p (place X layout) m₂ (oldCount X) ∧ Directory X layout counts rows m₂ ∧ + (∀ j, OutsidePreimageWrites p j → m₂ j = mem j) ∧ + endState (some 0) cs = some (Fin.ofNat _ (newCount X)) ∧ + endState (some 0) rs = some (Fin.ofNat _ (oldCount X)) ∧ + cs.length = newCount X ∧ rs.length = oldCount X ∧ + RAMBuckets.cost Report.probes (cs++rs) = 2*newCount X + 5*oldCount X := by + intro p zero collect + obtain ⟨hA, hB, hC⟩ := areas.dimensions + obtain ⟨cs, hc, z, frame, cend, clen, ccost⟩ := + SliceRAM.clearPass_run counts (newCount X) (areas.countEnd.trans rows.isLt.le) areas.sizes.2.1 mem + let m₁ := after mem (eventLog cs) + have own (i : Word w) (hi : i < p 0) : ownerAt p m₁ i = place X layout i := by + have hi' : i.val < oldCount X := hA ▸ hi + have ha : (shrink 10+i).val = (shrink 10).val+i.val := by + rw [Fin.val_add, Nat.mod_eq_of_lt (by have := areas.ownerEnd; have := counts.isLt; omega)] + change m₁ (shrink 10+i).val = _ + rw [show m₁ (shrink 10+i).val = mem (shrink 10+i).val from frame _ (.inl (by rw [ha]; have := areas.ownerEnd; omega))] + exact owner_at areas column i hi' + have cz (v : Word w) (hv : v < p 2) : m₁ (countAt p v).val = 0 := by + rw [countAt_val areas.regions hv] + have hv' : v.val < newCount X := hB ▸ hv + exact z _ (Nat.le_add_right _ _) (Nat.add_lt_add_left hv' _) + obtain ⟨rs, hr, done, _, cost, _, _⟩ := PhaseCosts.placementPreimages X.packingData layout + (by omega) (Shrink.oldIndex X.baseIndex) (Shrink.packedIndex X.baseIndex) + p areas.regions hA hB hC m₁ own cz + obtain ⟨rend, rf⟩ := collectPreimages_cursor_frame (k := 0) areas.regions hr + refine ⟨cs, rs, hc, hr, done, directory_of_collected X areas layout _ done, ?_, cend, by simpa using rend, + clen, ?_, ?_⟩ + · intro j hj + have hb : (p 2).val = newCount X := hB + have hx : j < counts.val ∨ counts.val+(p 2).val ≤ j := hj.1 + exact (rf j hj).trans (frame j (hb ▸ hx)) + · simpa using PhaseCosts.run_length hr + · rw [RAMBuckets.cost_append, clear_cost cs (fun r h => (ccost r h).1), clen, cost, oldCount_eq] + ring + +section Selected + +open NetworkKernel MotifBlocks MotifGrid MotifConversion ShrinkMotif SurvivingSlots + +variable {k R : Type*} [_root_.Field k] [CommRing R] {δ factor : ℝ} {b : ℕ} +variable (B : FixedBlock k demandSource demandTarget supply + (realWidths demandMass) (realWidths supplyMass) (31/16) factor) +variable (κ : (parameterData B).Entry → R) (hκ : (parameterData B).IsSolution κ) +variable (ready : Ready (2^a) (Shrink.colors a) (2^b) δ) (s : X.ShrinkSelection B) + +local notation "Y" => X.shrinkNext B ready s +/-- The term chosen by the shrink selection in the state's compression step. Its placement +determines the children used by the traversal directory. -/ +noncomputable abbrev selectedTerm := (X.shrinkStatePass B κ hκ ready).step.term s +local notation "selected" => selectedTerm X B κ hκ ready s +local notation "side" => X.packingData.shrinkTermLayout B X.shrinkNumber X.packingWidth s + +private theorem next_length : (siteOrder Y).length = newCount X := by + change Fintype.card (X.Base × BitWord (Shrink.J a)) * 2^g = + Fintype.card X.Base * (2^(Shrink.J a)*2^g) + rw [Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv (Shrink.J a)), Fintype.card_fin, Nat.mul_assoc] + +private theorem next_number (v : Shrink.Packed X.Base a g) : + ((siteOrder Y).entries.symm (packedSiteEquiv v)).val = (Shrink.packedIndex X.baseIndex v).val := by + change (bitWordFinEquiv g v.2.2).val + 2^g * + ((bitWordFinEquiv (Shrink.J a) v.2.1).val + 2^(Shrink.J a) * (X.baseIndex v.1).val) = _ + rw [Shrink.packedIndex_val] + simp only [Shrink.packedNumber, Shrink.lowNumber, Shrink.join, pow_add] + ring + +/-- The physical owner map agrees on every word with the placement of the selected +shrinking term in the actual input and output state orders. -/ +theorem selected_placement : + encodedPlacement (w := w) (siteOrder X).entries.symm (siteOrder Y).entries.symm (selected).place = + place X side := by + funext i + change (if h : i.val < oldCount X then _ else 0) = (if h : i.val < oldCount X then _ else 0) + split + · rename_i h + let j : Fin (oldCount X) := ⟨i.val,h⟩ + let x := (Shrink.oldIndex X.baseIndex).symm j + change Fin.ofNat (2^w) ((siteOrder Y).entries.symm ((selected).place ((siteOrder X).entries j))).val = + Fin.ofNat (2^w) ((Shrink.packedIndex X.baseIndex) (X.packingData.placement side x)).val + have oldSite : (siteOrder X).entries j = packingInputSites X.Base a g x := by + apply (siteOrder X).entries.symm.injective + erw [Equiv.symm_apply_apply] + change j = (Shrink.oldIndex X.baseIndex) x + exact (Equiv.apply_symm_apply _ _).symm + rw [oldSite] + change Fin.ofNat (2^w) ((siteOrder Y).entries.symm + (packedSiteEquiv (X.packingData.placement side + ((packingInputSites X.Base a g).symm (packingInputSites X.Base a g x))))).val = _ + rw [Equiv.symm_apply_apply, next_number] + · rfl + +/-- The concrete raw directory can be passed directly to the DFS layer compiler for +this selected term. Both site orders are those used by the branch's kernel readers. -/ +noncomputable def selectedDirectory (areas : Areas X shrink counts rows) (m : Memory w) + (collected : PreimagesAt (params X shrink counts rows) (place X side) m (oldCount X)) + (limit : ℕ) (before : rows.val + newCount X * capacity a ≤ limit) : + PairSimulation.TraversalRows.Directory selected (siteOrder X) (siteOrder Y) m limit := by + let p := params X shrink counts rows + obtain ⟨hA,hB,hC⟩ := areas.dimensions + have hB' : (p 2).val = newCount X := hB + have hC' : (p 4).val = capacity a := hC + refine ⟨p, hA, hB.trans (next_length X B ready s).symm, areas.regions, ?_, ?_, ?_⟩ + · change rows.val+(p 2).val*(p 4).val ≤ limit + rwa [hB', hC'] + · erw [selected_placement (w := w) X B κ hκ ready s] + exact collected + · intro v hv + erw [selected_placement (w := w) X B κ hκ ready s] + let idx : Fin (newCount X) := ⟨v.val, hB' ▸ hv⟩ + let owner := (Shrink.packedIndex X.baseIndex).symm idx + have he : Fin.ofNat (2^w) ((Shrink.packedIndex X.baseIndex) owner).val = v := by + rw [show Shrink.packedIndex X.baseIndex owner = idx from Equiv.apply_symm_apply _ _] + exact Fin.ext (Nat.mod_eq_of_lt v.isLt) + change (preimagePrefix (encodedPlacement (Shrink.oldIndex X.baseIndex) (Shrink.packedIndex X.baseIndex) + (X.packingData.placement side)) v (oldCount X)).length ≤ (p 4).val + rw [← he, encodedPlacement_rowLength _ _ _ areas.sizes.1.le areas.sizes.2.1.le, + X.packingData.card_placement (by omega), hC'] + +end Selected + +end CompressorRecords.ShrinkPreimages + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkRAM.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkRAM.lean new file mode 100644 index 0000000000..9b0abee68b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkRAM.lean @@ -0,0 +1,166 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrink +import OAI.Computability.VPVNP.PrimedStackRAMCode + +/-! +# Native computation of shrinking placement rows + +Scan old positions in their original order. Four reads recover the greedy color and +offset and the selected outgoing base slot's mate and shift. The resulting four +columns give the layout owner, the thickness bit, the assigned bundle's outgoing +index, and its target site. The bundle's source site is the quotient of its index by +the degree. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkRAM + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM + +variable {w : ℕ} + +/-- Public words are the residual and tag radices, degree, color-mask radix, last +color, layout bit, four input columns and four output columns. -/ +def visit : List (Op 24 14) := + [.stateWord 0, .publicWord 1 0, .publicWord 2 1, .publicWord 3 2, .publicWord 4 3, + .publicWord 5 4, .publicWord 6 5, .constant 22 1, .constant 23 2, + .binary .mul 7 2 1, .binary .mod 8 0 7, .binary .div 9 0 7, + .binary .mod 10 9 3, .binary .div 9 9 3, .binary .mod 11 9 4, .binary .div 12 9 4, + .publicWord 13 6, .binary .add 13 13 12, .read 14 13, + .publicWord 13 7, .binary .add 13 13 12, .read 15 13, + .binary .mul 9 12 3, .binary .add 9 9 10, + .publicWord 13 8, .binary .add 13 13 9, .read 16 13, + .publicWord 13 9, .binary .add 13 13 9, .read 17 13, + .binary .sub 14 5 14, .binary .shiftRight 19 11 14, .binary .mod 19 19 23, + .binary .mul 15 15 1, .binary .bitXor 15 8 15, + .binary .mod 17 17 7, .binary .bitXor 17 15 17, .binary .div 16 16 3, + .binary .mul 16 16 7, .binary .add 16 16 17, + .binary .mul 18 12 7, .binary .add 15 18 15, .binary .add 18 18 8, + .binary .mul 20 15 3, .binary .add 20 20 10, + .binary .sub 21 16 15, .binary .mul 21 6 21, .binary .add 21 15 21, + .binary .sub 18 18 21, .binary .mul 18 19 18, .binary .add 21 21 18, + .publicWord 13 10, .binary .add 13 13 0, .write 13 21, + .publicWord 13 11, .binary .add 13 13 0, .write 13 19, + .publicWord 13 12, .binary .add 13 13 0, .write 13 20, + .publicWord 13 13, .binary .add 13 13 0, .write 13 16, .binary .add 0 0 22] + +/-- Unsigned word quotient used to remove low fields when decoding a shrinking position. -/ +def div (x y : Word w) := BinaryOp.div.eval x y +/-- Unsigned word remainder used to isolate a low field or a single color bit. -/ +def mod (x y : Word w) := BinaryOp.mod.eval x y +/-- Bitwise exclusive OR of two words, used to apply tag offsets and lane displacements. -/ +def xor (x y : Word w) := BinaryOp.bitXor.eval x y + +/-- Arithmetic selection in the word ring, used with zero-or-one selectors. -/ +def select (bit zeroValue oneValue : Word w) := zeroValue + bit * (oneValue - zeroValue) + +@[simp] theorem select_zero (x y : Word w) : select 0 x y = x := by simp [select] +@[simp] theorem select_one (x y : Word w) : select 1 x y = y := by simp [select] + +/-- The four machine words obtained by unpacking an old-position cursor in the shrinking scan. -/ +structure Fields (w : ℕ) where + /-- Base vertex index used to look up the greedy color and tag offset. -/ + base : Word w + /-- Color mask of the old position. Its bit for the base vertex's color determines thickness. -/ + mask : Word w + /-- Slot label selecting the outgoing base port whose mate and displacement are read. -/ + slot : Word w + /-- The tag and residual lane packed together, with the residual lane in the least + significant bits. -/ + low : Word w + +/-- Split the old-position cursor into base vertex, color mask, slot label, and combined tag +and residual lane using the public radices. -/ +def decode (p : Fin 14 → Word w) (i : Word w) : Fields w := + let chunk := p 1 * p 0 + let v := div i chunk + let b := div v (p 2) + ⟨div b (p 3), mod b (p 3), mod v (p 2), mod i chunk⟩ + +/-- Linear index of the outgoing base port, computed as the base vertex index times the degree +plus the slot label. -/ +def baseArc (p : Fin 14 → Word w) (f : Fields w) := f.base * p 2 + f.slot + +/-- Read the color and tag offset at the base vertex, then the mate and displacement at its +selected outgoing port. -/ +def readColumns (p : Fin 14 → Word w) (m : Memory w) (f : Fields w) : + Word w × Word w × Word w × Word w := + (m (p 6+f.base).val, m (p 7+f.base).val, m (p 8+baseArc p f).val, m (p 9+baseArc p f).val) + +/-- The four entries of a shrinking placement row, parameterized by the type used to represent +their values. -/ +structure Outputs (α : Type) where + /-- Packed site to which the chosen layout assigns the old position. -/ + owner : α + /-- Thickness flag obtained from the old position's color mask at the base vertex's greedy + color. -/ + thick : α + /-- Outgoing port index of the assigned bundle, encoding its source site and slot. -/ + assigned : α + /-- Packed target site of the assigned bundle. -/ + target : α + +/-- Compute the placement row from the four input columns. A thick position keeps its packed +site, while the layout bit selects the source or target for a thin position. -/ +def outputs (p : Fin 14 → Word w) (m : Memory w) (i : Word w) : Outputs (Word w) := + let f := decode p i + let cols := readColumns p m f + let chunk := p 1 * p 0 + let thick := mod (BinaryOp.shiftRight.eval f.mask (p 4-cols.1)) 2 + let laneA := xor f.low (cols.2.1 * p 0) + let A := f.base * chunk + laneA + let B := div cols.2.2.1 (p 2) * chunk + xor laneA (mod cols.2.2.2 chunk) + let packed := f.base * chunk + f.low + ⟨select thick (select (p 5) A B) packed,thick,A*p 2+f.slot,B⟩ + +/-- The 64-event trace of one shrinking visit, including four directory reads and four output +writes at the old-position cursor. -/ +def events (p : Fin 14 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + let f := decode p i + let c := readColumns p m f + let out := outputs p m i + List.replicate 18 .tick ++ [.read (p 6+f.base) c.1, .tick,.tick, + .read (p 7+f.base) c.2.1,.tick,.tick,.tick,.tick,.read (p 8+baseArc p f) c.2.2.1, + .tick,.tick,.read (p 9+baseArc p f) c.2.2.2] ++ List.replicate 23 .tick ++ + [.write (p 10+i) out.owner,.tick,.tick,.write (p 11+i) out.thick,.tick,.tick, + .write (p 12+i) out.assigned,.tick,.tick,.write (p 13+i) out.target,.tick] + +theorem visit_work (p : Fin 14 → Word w) (m : Memory w) (i : Word w) : + (events p m i).length = 64 ∧ countProbes (events p m i) = 8 := ⟨rfl,rfl⟩ + +/-- Write the owner, thickness, assigned port, and target to their respective output columns at +the old-position cursor. -/ +def store (p : Fin 14 → Word w) (m : Memory w) (i : Word w) (out : Outputs (Word w)) : Memory w := + writeMemory (writeMemory (writeMemory (writeMemory m (p 10+i) out.owner) + (p 11+i) out.thick) (p 12+i) out.assigned) (p 13+i) out.target + +theorem visit_after (p : Fin 14 → Word w) (m : Memory w) (i : Word w) : + after m (events p m i) = store p m i (outputs p m i) := rfl + +set_option maxHeartbeats 1400000 in +set_option maxRecDepth 8192 in +private theorem visit_trace (p : Fin 14 → Word w) (m : Memory w) (i : Word w) (rs : Regs w 24) : + ∃ rs', trace p i visit rs m = some (events p m i, rs', store p m i (outputs p m i)) ∧ + rs' 0 = i+1 := by + simp (config := {decide := true}) [visit, trace, Op.effect, Function.update, BinaryOp.eval, + events, outputs, readColumns, decode, baseArc, select, div, mod, xor, store] + repeat' apply And.intro + all_goals rfl + +/-- One deterministic burst builds all four output columns and advances the old-site cursor. -/ +theorem visit_native (p : Fin 14 → Word w) (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program 65 (M.program.start i) m [] = some ⟨events p m i, some (i+1)⟩ := by + obtain ⟨rs, ht, hr⟩ := visit_trace p m i (fun _ => 0) + let M := (template visit 0).instantiate w p + change execute M.program (1 + visit.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ m [] = _ + rw [execute_template, run_eq_trace, ht] + simp [hr] + +end CompressorRecords.ShrinkRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkRankArena.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkRankArena.lean new file mode 100644 index 0000000000..2f3bf8b69d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkRankArena.lean @@ -0,0 +1,196 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkRankSpace +import OAI.Computability.VPVNP.CompressorSlicePreparation + +/-! +# Running the packed rank and list arena from arbitrary memory + +The preliminary placement rows and old incidence precede the fresh rank +arena. Clear its count column, then run classification, append, uniform key +gather and ranking. Every preceding memory cell remains available to later +shrinking passes, including a second placement scan in the chosen layout. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkRankArena + +open BurstRAM PrimedStackRAM Compression Compression.PackingData BundleKeys BundleGather +open ShrinkRankSpace + +variable {w a g : ℕ} (X : State a (packingLaneBits a g)) +local notation "N" => Fintype.card X.Base +local notation "S" => N*2^(packingLaneBits a g) +local notation "A" => S*2^a +local notation "O" => oldArcOrder (a := a) (g := g) X.baseIndex +local notation "P" => X.packingData +local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex + +/-- Set the rank arena's dimensions from the state's base vertex count, degree exponent, and +residual lane width, with allocation beginning at the supplied origin. -/ +abbrev shape (origin : ℕ) : Shape := ⟨N,a,g,origin⟩ + +variable (T : IncidenceDirectory w) (shr : Fin 14 → Word w) (origin : ℕ) +local notation "Z" => shape X origin +local notation "p" => Shape.classifyBank (shape X origin) T shr +local notation "q" => Shape.collectBank (shape X origin) w +local notation "keys" => Fin.ofNat (2^w) (Shape.gathered (shape X origin)) +local notation "dest" => Fin.ofNat (2^w) (Shape.ranks (shape X origin)) + +private theorem site_lt (m : Memory w) (inc : T.ActualColumns X m) + (v : (Z).Values T shr) (fit : A≤2^w) (i : Word w) (hi : i.val rfl + | cons r rs ih => + rw [RAMBuckets.cost,hw r (by simp),ih (fun z hz ↦ hw z (by simp [hz])),List.length_cons,Nat.mul_succ] + omega + +/-- Initialize the bounded count lists, run all four ranking stages, and retain +the earlier arrays below the arena. -/ +theorem build (m : Memory w) (old : T.Represents X m) (layout : Bool) + (pre : ShrinkRAM.PlacementColumns X.slots X.baseIndex shr layout m) + (before : ∀ c, (T.column c).val+A ≤ origin) + (preBefore : ∀ t : Fin 4, (shr (t.natAdd 10)).val+S ≤ origin) (room : (Z).stop<2^w) : + ∃ z cs ls gs rs, Run X T shr origin m z cs ls gs rs := by + have v := (Z).values T shr Fintype.card_pos room + have fit := (Z).scalarFits Fintype.card_pos room + have wz : T.width.val+A ≤ origin := before 5 + obtain ⟨qreg,kreg,rreg⟩ := (Z).regions T shr Fintype.card_pos wz room + have oid : (Z).owner = origin := rfl + have kid : (Z).key = origin+A := rfl + have cid : (Z).counts = origin+2*A := rfl + have iid : (Z).ids = (Z).counts+2*(Z).B := rfl + have gid : (Z).gathered = (Z).ids+2*(Z).B*(Z).Q := rfl + have rid : (Z).ranks = (Z).gathered+2*(Z).B*(Z).Q := rfl + have eid : (Z).stop = (Z).ranks+A := rfl + have za : (Z).A = A := rfl + have hcids : (Z).counts ≤ (Z).ids := Nat.le_add_right .. + have hig : (Z).ids ≤ (Z).gathered := Nat.le_add_right .. + have hgr : (Z).gathered ≤ (Z).ranks := Nat.le_add_right .. + have hrc : (Z).ranks ≤ (Z).stop := Nat.le_add_right .. + have org : origin ≤ (Z).counts := Nat.le_add_right .. + have hfit : (q 3).val+2*(Z).B ≤ 2^w := by rw [v.counts]; omega + obtain ⟨z,hzero,hvals,hout,_,hlen,hwork⟩ := SliceRAM.clearPass_run (q 3) (2*(Z).B) hfit fit.2.1 m + let m₀ := after m (eventLog z) + have zeroFrame (addr : ℕ) (h : addr < origin) : m₀ addr = m addr := + hout _ (.inl (by rw [v.counts,cid]; omega)) + have hOld := old.retain before zeroFrame + have hPre := pre.retain preBefore zeroFrame + have reg := classifyRegions X T shr origin m₀ hOld.actual before preBefore room + have hz (u : Word w) (hu : u rfl + +private theorem events_same {p : Fin 14 → Word w} {m snapshot : Memory w} (i : Word w) + (agree : ∀ c : Fin 4, m (readAddr p c i) = snapshot (readAddr p c i)) : + events p m i = events p snapshot i := by + let f := decode p i + have hcols : readColumns p m f = readColumns p snapshot f := + Prod.ext (agree 0) (Prod.ext (agree 1) (Prod.ext (agree 2) (agree 3))) + dsimp only [f] at hcols + simp only [events, outputs, hcols] + +/-- The report sequence in increasing old-position order. Every lookup is +expressed directly in the initial external memory. -/ +def scanReports (p : Fin 14 → Word w) (snapshot : Memory w) (k : ℕ) : ℕ → List (Report w) + | 0 => [] + | n+1 => ⟨events p snapshot (Fin.ofNat _ k), some (Fin.ofNat _ (k+1))⟩ :: + scanReports p snapshot (k+1) n + +private theorem after_snapshot (p : Fin 14 → Word w) (snapshot m : Memory w) (i : Word w) : + after m (events p snapshot i) = store p m i (outputs p snapshot i) := rfl + +private theorem after_succ (p : Fin 14 → Word w) (snapshot m : Memory w) (k n : ℕ) : + after m (eventLog (scanReports p snapshot k (n+1))) = + after (store p m (Fin.ofNat _ k) (outputs p snapshot (Fin.ofNat _ k))) + (eventLog (scanReports p snapshot (k+1) n)) := by + simp only [scanReports, eventLog, List.flatMap_cons, after, List.foldl_append] + rfl + +private theorem scan_native_aux {p : Fin 14 → Word w} {N : ℕ} (reg : Regions p N) + (snapshot : Memory w) (k n : ℕ) (m : Memory w) (bound : k+n ≤ N) + (agree : ∀ c i, i.val < N → m (readAddr p c i) = snapshot (readAddr p c i)) : + let M := (template visit 0).instantiate w p + runSegment M.program 65 (some (Fin.ofNat _ k)) m (List.replicate n []) = + some (scanReports p snapshot k n) := by + induction n generalizing k m with + | zero => rfl + | succ n ih => + let i := Fin.ofNat (2^w) k + have hv : i.val = k := Nat.mod_eq_of_lt (by have := reg.fits; omega) + have hi : i.val < N := by omega + have hn : i+1 = Fin.ofNat (2^w) (k+1) := by + apply Fin.ext + simp [i, Fin.val_add, Nat.mod_add_mod, Nat.add_mod_mod] + have he := events_same i (fun c ↦ agree c i hi) + have hnext := ih (k+1) (store p m i (outputs p snapshot i)) (by omega) + (fun c j hj ↦ (store_other _ _ _ _ _ (fun t ↦ reg.inputs c t j i hj hi)).trans (agree c j hj)) + dsimp only + rw [List.replicate_succ, runSegment, visit_native p m i, he, hn] + simp only [after_snapshot, hnext, Option.map_some, scanReports, i] + +/-- The complete native segment, with no change to the four input columns. -/ +theorem scan_native (p : Fin 14 → Word w) (N k n : ℕ) (m : Memory w) (reg : Regions p N) + (bound : k+n ≤ N) : + let M := (template visit 0).instantiate w p + runSegment M.program 65 (some (Fin.ofNat _ k)) m (List.replicate n []) = + some (scanReports p m k n) := + scan_native_aux reg m k n m bound (fun _ _ _ ↦ rfl) + +private theorem scan_preserve {p : Fin 14 → Word w} {N : ℕ} (reg : Regions p N) + (snapshot m : Memory w) (k n addr : ℕ) (bound : k+n ≤ N) + (outside : ∀ (t : Fin 4) (i : Word w), k ≤ i.val → i.val < k+n → addr ≠ outAddr p t i) : + after m (eventLog (scanReports p snapshot k n)) addr = m addr := by + induction n generalizing k m with + | zero => rfl + | succ n ih => + let i := Fin.ofNat (2^w) k + have hv : i.val = k := Nat.mod_eq_of_lt (by have := reg.fits; omega) + rw [after_succ, ih _ (k+1) (by omega) (fun t j hj hlt ↦ outside t j (by omega) (by omega))] + exact store_other _ _ _ _ _ (fun t ↦ outside t i (by omega) (by omega)) + +private theorem scan_field {p : Fin 14 → Word w} {N : ℕ} (reg : Regions p N) + (snapshot m : Memory w) (k n : ℕ) (bound : k+n ≤ N) + (t : Fin 4) (i : Word w) (hi : k ≤ i.val) (hi' : i.val < k+n) : + after m (eventLog (scanReports p snapshot k n)) (outAddr p t i) = (outputs p snapshot i).field t := by + induction n generalizing k m with + | zero => omega + | succ n ih => + rw [after_succ] + rcases eq_or_lt_of_le hi with he | he + · have hv : Fin.ofNat (2^w) k = i := Fin.ext (by simp [he]) + rw [hv] + rw [scan_preserve reg snapshot _ _ _ _ (by omega)] + · exact store_field reg _ i (by omega) _ t + · intro u j hj hlt h + have hij := ((reg.unique t u i j (by omega) (by omega)).mp h).2 + subst j + omega + · exact ih _ _ (by omega) (by omega) (by omega) + +/-- The returned registers, external work and complete memory contents of a +shrinking scan, including the untouched portion of each output column. -/ +structure ScanResult (p : Fin 14 → Word w) (N k n : ℕ) (m : Memory w) (rs : List (Report w)) : Prop where + endCursor : endState (some (Fin.ofNat _ k)) rs = some (Fin.ofNat _ (k+n)) + calls : rs.length = n + work : ∀ r ∈ rs, r.events.length = 64 ∧ countProbes r.events = 8 + cost : RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = 9*n + readback : ∀ (t : Fin 4) (i : Word w), k ≤ i.val → i.val < k+n → + after m (eventLog rs) (outAddr p t i) = (outputs p m i).field t + preserve : ∀ addr, (∀ (t : Fin 4) (i : Word w), k ≤ i.val → i.val < k+n → addr ≠ outAddr p t i) → + after m (eventLog rs) addr = m addr + inputs : ∀ (c : Fin 4) (i : Word w), i.val < N → + after m (eventLog rs) (readAddr p c i) = m (readAddr p c i) + +private theorem scan_accounting (p : Fin 14 → Word w) (m : Memory w) (k n : ℕ) : + let rs := scanReports p m k n + endState (some (Fin.ofNat _ k)) rs = some (Fin.ofNat _ (k+n)) ∧ rs.length = n ∧ + (∀ r ∈ rs, r.events.length = 64 ∧ countProbes r.events = 8) ∧ + RAMBuckets.cost (fun r : Report w ↦ countProbes r.events) rs = 9*n := by + induction n generalizing k with + | zero => exact ⟨rfl, rfl, by simp [scanReports], rfl⟩ + | succ n ih => + obtain ⟨hend,hlen,hwork,hcost⟩ := ih (k+1) + refine ⟨?_, ?_, ?_, ?_⟩ + · rw [scanReports, endState, hend] + congr 2 + omega + · simp only [scanReports, List.length_cons, hlen] + · intro r hr + rcases List.mem_cons.mp hr with rfl | h + · exact visit_work p m _ + · exact hwork r h + · rw [scanReports, RAMBuckets.cost, (visit_work p m _).2, hcost, Nat.mul_succ] + omega + +/-- Execute the whole interval from its initial memory. Every one of the +four output columns agrees with the graph placement computed from the four +original input values. -/ +theorem scan_run (p : Fin 14 → Word w) (N k n : ℕ) (m : Memory w) (regions : Regions p N) + (bound : k+n ≤ N) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 65 (some (Fin.ofNat _ k)) m (List.replicate n []) = some rs ∧ + ScanResult p N k n m rs := by + obtain ⟨he,hl,hw,hc⟩ := scan_accounting p m k n + refine ⟨scanReports p m k n, scan_native p N k n m regions bound, he, hl, hw, hc, + scan_field regions m m k n bound, fun addr ↦ scan_preserve regions m m k n addr bound, ?_⟩ + intro c i hi + apply scan_preserve regions m m k n _ bound + exact fun t j _ hlt ↦ regions.inputs c t i j hi (hlt.trans_le bound) + +end CompressorRecords.ShrinkRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkSelectedInputs.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkSelectedInputs.lean new file mode 100644 index 0000000000..3e172b6cd7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkSelectedInputs.lean @@ -0,0 +1,60 @@ +import OAI.Computability.VPVNP.CompressorShrinkInputTerms +import OAI.Computability.VPVNP.CompressorRecordsSelectedArena + +/-! +# Old directories available when a shrinking layout has been selected + +The term bank starts after the deterministic input arena. Therefore both +greedy columns and the actual incidence arrays fit below the selected +layout's fresh score, position and role tables. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkInput.Run + +open BurstRAM Compression + +variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ} +variable {m : Memory w} (r : Run X T start m) + +private theorem origin_bounds : start ≤ placementBase X start ∧ placementBase X start ≤ stop X start := by + obtain ⟨h₀,h₁,h₂,h₃⟩ := range_bounds X start + exact ⟨h₀,h₁.trans (h₂.trans h₃)⟩ + +include r + +theorem selectedInputs (termBase stride : Word w) (later : stop X start ≤ termBase.val) : + SelectedArena.OldInputs X termBase stride (placementBank X T start) T := by + obtain ⟨hc,ho,hm,hs⟩ := r.inputBounds + obtain ⟨h₀,h₁⟩ := origin_bounds (X := X) (start := start) + have h : placementBase X start ≤ SelectedArena.origin X termBase stride := + h₁.trans (later.trans (Nat.le_add_right ..)) + exact ⟨hc.trans h, ho.trans h, hm.trans h, hs.trans h, (r.greedy.old 3).trans (h₀.trans h)⟩ + +theorem selectedActualInputs (termBase stride : Word w) (later : stop X start ≤ termBase.val) : + T.actualIn.val+DemandRAM.oldCount X ≤ SelectedArena.origin X termBase stride ∧ + T.width.val+DemandRAM.oldCount X ≤ SelectedArena.origin X termBase stride := by + obtain ⟨h₀,h₁⟩ := origin_bounds (X := X) (start := start) + have h := h₀.trans (h₁.trans (later.trans (Nat.le_add_right termBase.val (SelectedArena.motifs X*stride.val)))) + exact ⟨(r.greedy.old 4).trans h,(r.greedy.old 5).trans h⟩ + +/-- Specialization to the native term bank after the compact AB/CD pairs. -/ +theorem termInputs (stride : Word w) (room : termEnd X start stride.val < 2^w) : + SelectedArena.OldInputs X (termHead X start) stride (placementBank X T start) T ∧ + T.actualIn.val+DemandRAM.oldCount X ≤ SelectedArena.origin X (termHead X start) stride ∧ + T.width.val+DemandRAM.oldCount X ≤ SelectedArena.origin X (termHead X start) stride := by + let M := ShrinkTermSelection.bundles X * ShrinkTermSelection.ranks a + change stop X start+2*M+M*stride.val < _ at room + have h : stop X start ≤ (termHead (w := w) X start).val := by + change stop X start ≤ (stop X start+2*M) % (2^w) + rw [Nat.mod_eq_of_lt (by omega)]; omega + exact ⟨r.selectedInputs _ stride h,r.selectedActualInputs _ stride h⟩ + +end CompressorRecords.ShrinkInput.Run + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkTagColumn.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkTagColumn.lean new file mode 100644 index 0000000000..36c5a8ed5c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkTagColumn.lean @@ -0,0 +1,365 @@ +import OAI.Computability.VPVNP.CompressorRecordIncidenceLayout +import OAI.Computability.VPVNP.CompressorRecordsOrdinalFootprint +import OAI.Computability.VPVNP.RAMChoicePrefix +import OAI.Computability.VPVNP.CompressorRecordsShrink + +/-! +# Extracting the shrinking tag increments from the displacement column + +Before the greedy tag scan, each base port contributes the tag component of its +old displacement. The worker skips the residual lane bits by division, takes +the low tag bits, and writes a separate column in base-port order. A final call +initializes the zero operand used for absent increments. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkTagColumn + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression +open scoped Fin.CommRing + +variable {w a g : ℕ} + +/-- Both workers use the same frame throughout the two phases. -/ +def publicWords (src dst zero divisor modulus : Word w) : Fin 5 → Word w := + ![src, dst, zero, divisor, modulus] + +/-- Build the workers' shared parameters from the incidence displacement column, tag +destination, zero cell, residual-lane radix and tag radix. -/ +def params (T : IncidenceDirectory w) (a g : ℕ) (dst zero : Word w) : Fin 5 → Word w := + publicWords T.shift dst zero (CursorRAM.encode w (2^g)) (CursorRAM.encode w (2^(Shrink.J a))) + +/-- Read one base port's displacement, divide out its residual lane, write the remaining low +tag bits, and advance the port cursor. -/ +def extractOps : List (Op 4 5) := + [.stateWord 0, .publicWord 1 0, .binary .add 1 1 0, .read 2 1, + .publicWord 3 3, .binary .div 2 2 3, .publicWord 3 4, .binary .mod 2 2 3, + .publicWord 1 1, .binary .add 1 1 0, .write 1 2, .constant 3 1, .binary .add 0 0 3] + +/-- Write zero to the operand cell used for absent tag increments and set the return cursor to +one. -/ +def zeroOps : List (Op 4 5) := + [.publicWord 1 2, .constant 2 0, .write 1 2, .constant 0 1] + +/-- The scheduled worker that extracts one tag increment from the displacement column per call. -/ +abbrev extractPass : Schedule.Pass := ⟨_, _, _, template extractOps 0⟩ +/-- The scheduled worker that initializes the absent-increment operand after the tag extraction +scan. -/ +abbrev zeroPass : Schedule.Pass := ⟨_, _, _, template zeroOps 0⟩ + +/-- Natural address of an indexed column entry, obtained by adding its index to the base in +word arithmetic. -/ +def cell (base : Word w) (i : ℕ) : ℕ := (base + (i : Word w)).val + +/-- Recover the displacement's tag component by dividing by the residual radix and reducing +modulo the tag radix. -/ +def extract (p : Fin 5 → Word w) (x : Word w) : Word w := + BinaryOp.mod.eval (BinaryOp.div.eval x (p 3)) (p 4) + +/-- Report for one port visit, recording the displacement read, tag increment write, and next +cursor. -/ +def row (p : Fin 5 → Word w) (i : Word w) (m : Memory w) : Report w := + let x := m (p 0+i).val + ⟨[.tick, .tick, .tick, .read (p 0+i) x, .tick, .tick, .tick, .tick, .tick, .tick, + .write (p 1+i) (extract p x), .tick, .tick], some (i+1)⟩ + +/-- Report of the final zero-initialization call, with one external write and return cursor +one. -/ +def zeroRow (p : Fin 5 → Word w) : Report w := + ⟨[.tick, .tick, .write (p 2) 0, .tick], some 1⟩ + +theorem row_after (p : Fin 5 → Word w) (i : Word w) (m : Memory w) : + after m (row p i m).events = writeMemory m (p 1+i) (extract p (m (p 0+i).val)) := rfl + +theorem zero_after (p : Fin 5 → Word w) (m : Memory w) : + after m (zeroRow p).events = writeMemory m (p 2) 0 := rfl + +theorem row_native (p : Fin 5 → Word w) (i : Word w) (m : Memory w) : + let P := (extractPass.table.instantiate w p).program + execute P 14 (P.start i) m [] = some (row p i m) := by + let M := (template extractOps 0).instantiate w p + change execute M.program (1+extractOps.length) ⟨M.entry, i, fun _ ↦ 0, fun _ ↦ 0⟩ m [] = _ + rw [execute_template] + simp (config := {decide := true}) [extractOps, run, Op.run, Op.effect, Function.update, BinaryOp.eval, + row, extract, Report.prepend] + +theorem zero_native (p : Fin 5 → Word w) (i : Word w) (m : Memory w) : + let P := (zeroPass.table.instantiate w p).program + execute P 5 (P.start i) m [] = some (zeroRow p) := by + let M := (template zeroOps 0).instantiate w p + change execute M.program (1+zeroOps.length) ⟨M.entry, i, fun _ ↦ 0, fun _ ↦ 0⟩ m [] = _ + rw [execute_template] + simp (config := {decide := true}) [zeroOps, run, Op.run, Op.effect, Function.update, zeroRow, + Report.prepend] + +/-- Reports from the actual, successively updated external memory. -/ +def scan (p : Fin 5 → Word w) : ℕ → ℕ → Memory w → List (Report w) + | _, 0, _ => [] + | i, n+1, m => + let r := row p (i : Word w) m + r :: scan p (i+1) n (after m r.events) + +/-- The reports for all base ports in order starting at zero, followed by the report that +initializes the zero operand. -/ +def reports (p : Fin 5 → Word w) (B : ℕ) (m : Memory w) := scan p 0 B m ++ [zeroRow p] + +theorem scan_native (p : Fin 5 → Word w) (i n : ℕ) (m : Memory w) : + let P := (extractPass.table.instantiate w p).program + runSegment P 14 (some (i : Word w)) m (List.replicate n []) = some (scan p i n m) := by + induction n generalizing i m with + | zero => rfl + | succ n ih => + dsimp only + rw [List.replicate_succ, runSegment, row_native] + change (runSegment _ _ (some ((i : Word w)+1)) _ _).map _ = _ + rw [← Nat.cast_add_one, ih] + rfl + +theorem scan_work (p : Fin 5 → Word w) (i n : ℕ) (m : Memory w) : + let rs := scan p i n m + rs.length = n ∧ RAMBuckets.cost Report.probes rs = 3*n ∧ + ∀ r ∈ rs, r.events.length = 13 ∧ r.probes = 2 ∧ choiceBits r.events = [] := by + induction n generalizing i m with + | zero => exact ⟨rfl, rfl, by simp [scan]⟩ + | succ n ih => + let r := row p (i : Word w) m + obtain ⟨hl,hc,hw⟩ := ih (i+1) (after m r.events) + refine ⟨congrArg Nat.succ hl, ?_, ?_⟩ + · change 1+2+RAMBuckets.cost _ _ = _ + rw [hc]; omega + · intro z hz + rcases List.mem_cons.mp hz with rfl | ht + · exact ⟨rfl,rfl,rfl⟩ + · exact hw _ ht + +private theorem scan_after (p : Fin 5 → Word w) (i n : ℕ) (m : Memory w) : + after m (eventLog (scan p i (n+1) m)) = + after (after m (row p (i : Word w) m).events) + (eventLog (scan p (i+1) n (after m (row p (i : Word w) m).events))) := + List.foldl_append + +theorem scan_outside (p : Fin 5 → Word w) (i n : ℕ) (m : Memory w) (v : ℕ) + (away : ∀ j, i ≤ j → j < i+n → v ≠ cell (p 1) j) : + after m (eventLog (scan p i n m)) v = m v := by + induction n generalizing i m with + | zero => rfl + | succ n ih => + rw [scan_after, ih _ _ (fun j lo hi ↦ away j (by omega) (by omega)), row_after] + exact ite_eq_right (away i le_rfl (by omega)) + +/-- The shift columns do not overlap. The final zero cell is distinct from +all populated output rows. -/ +structure Regions (p : Fin 5 → Word w) (B : ℕ) : Prop where + fits : B ≤ 2^w + source : ∀ i j : ℕ, i < B → j < B → cell (p 0) i ≠ cell (p 1) j + zero : ∀ i : ℕ, i < B → cell (p 1) i ≠ (p 2).val + +private theorem cell_inj (base : Word w) {i j : ℕ} (hi : i < 2^w) (hj : j < 2^w) + (e : cell base i = cell base j) : i = j := by + have h : (i : Word w) = (j : Word w) := + add_left_cancel (Fin.ext e : base+(i : Word w) = base+(j : Word w)) + have hv : i % (2^w) = j % (2^w) := congrArg Fin.val h + simpa only [Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt hj] using hv + +theorem scan_read {p : Fin 5 → Word w} {B : ℕ} (reg : Regions p B) + (i n : ℕ) (m : Memory w) (bound : i+n ≤ B) (j : ℕ) (lo : i ≤ j) (hi : j < i+n) : + after m (eventLog (scan p i n m)) (cell (p 1) j) = extract p (m (cell (p 0) j)) := by + induction n generalizing i m with + | zero => omega + | succ n ih => + rw [scan_after] + rcases eq_or_lt_of_le lo with rfl | h + · rw [scan_outside _ _ _ _ _ (fun k hk hlt eqn ↦ by + have he := cell_inj (p 1) (by have := reg.fits; omega) (by have := reg.fits; omega) eqn + omega), row_after] + exact ite_eq_left rfl + · rw [ih _ _ (by omega) (by omega) (by omega), row_after] + exact congrArg (extract p) (ite_eq_right (reg.source j i (by omega) (by omega))) + +private theorem after_reports (p : Fin 5 → Word w) (B : ℕ) (m : Memory w) : + after m (eventLog (reports p B m)) = writeMemory (after m (eventLog (scan p 0 B m))) (p 2) 0 := by + simp only [reports, eventLog, List.flatMap_append, after, List.foldl_append] + rfl + +/-- Complete native execution, memory contents, and external charge of the two phases. -/ +structure Result (p : Fin 5 → Word w) (B : ℕ) (m : Memory w) : Prop where + extractRun : let P := (extractPass.table.instantiate w p).program + runSegment P 14 (some 0) m (List.replicate B []) = some (scan p 0 B m) + zeroRun : let P := (zeroPass.table.instantiate w p).program + runSegment P 5 (some 0) (after m (eventLog (scan p 0 B m))) [[]] = some [zeroRow p] + readback : ∀ i, i < B → after m (eventLog (reports p B m)) (cell (p 1) i) = extract p (m (cell (p 0) i)) + zero : after m (eventLog (reports p B m)) (p 2).val = 0 + preserve : ∀ v, v ≠ (p 2).val → (∀ i, i < B → v ≠ cell (p 1) i) → after m (eventLog (reports p B m)) v = m v + calls : (reports p B m).length = B+1 + cost : RAMBuckets.cost Report.probes (reports p B m) = 3*B+2 + work : ∀ r ∈ reports p B m, r.events.length ≤ 13 ∧ r.probes ≤ 2 ∧ choiceBits r.events = [] + +theorem scan_result (p : Fin 5 → Word w) (B : ℕ) (m : Memory w) (reg : Regions p B) : Result p B m := by + obtain ⟨hl,hc,hw⟩ := scan_work p 0 B m + constructor + · simpa using scan_native p 0 B m + · dsimp only + rw [runSegment, zero_native] + rfl + · intro i hi + rw [after_reports, writeMemory, ite_eq_right (reg.zero i hi)] + exact scan_read reg 0 B m (by omega) i (by omega) (by omega) + · rw [after_reports, writeMemory, ite_eq_left rfl] + · intro v hv h + rw [after_reports, writeMemory, ite_eq_right hv] + exact scan_outside p 0 B m v (fun j _ hlt ↦ h j (by omega)) + · simp [reports, hl] + · rw [reports, RAMBuckets.cost_append, hc] + rfl + · intro r hr + rcases List.mem_append.mp hr with hr | hr + · obtain ⟨he,hp,hb⟩ := hw r hr + exact ⟨he.le,hp.le,hb⟩ + · rcases List.mem_singleton.mp hr with rfl + exact ⟨show 4 ≤ 13 by decide,show 1 ≤ 2 by decide,rfl⟩ + +/-- The tag is the binary field directly above the residual lane. -/ +theorem packedTagNumber {a g : ℕ} (x : BitWord (packingLaneBits a g)) : + (bitWordFinEquiv _ x).val / 2^g % 2^(Shrink.J a) = + (bitWordFinEquiv _ (packingFields a g x).2.2.1).val := by + rw [Shrink.packingFields_number] + let high := Shrink.join a (bitWordFinEquiv _ (packingFields a g x).1).val + (bitWordFinEquiv _ (packingFields a g x).2.1).val + let tag := bitWordFinEquiv _ (packingFields a g x).2.2.1 + let lane := bitWordFinEquiv _ (packingFields a g x).2.2.2 + change (high * 2^(Shrink.J a + g) + (tag.val * 2^g + lane.val)) / 2^g % 2^(Shrink.J a) = tag.val + rw [show high * 2^(Shrink.J a + g) + (tag.val * 2^g + lane.val) = + 2^g * (high * 2^(Shrink.J a) + tag.val) + lane.val by rw [pow_add]; ring, + Nat.mul_add_div (Nat.two_pow_pos _), Nat.div_eq_of_lt lane.isLt, Nat.add_zero] + exact Nat.mul_add_mod_of_lt tag.isLt + +theorem radices_fit {a g w : ℕ} (h : packingLaneBits a g ≤ w) : + 2^g < 2^w ∧ 2^(Shrink.J a) < 2^w ∧ Shrink.J a ≤ w := by + change (2 * 2^a + 1) + (a + (Shrink.J a + g)) ≤ w at h + exact ⟨Nat.pow_lt_pow_right Nat.one_lt_two (by omega), Nat.pow_lt_pow_right Nat.one_lt_two (by omega), + by omega⟩ + +private theorem extract_val (p : Fin 5 → Word w) (x : Word w) : + (extract p x).val = x.val / (p 3).val % (p 4).val := by + have h := (Nat.div_le_self x.val (p 3).val).trans_lt x.isLt + simp only [extract, BinaryOp.eval, Fin.val_ofNat, Nat.mod_eq_of_lt h, + Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt h)] + +/-- The emitted increments are exactly the tag fields used by the ordered +shrinking construction, with an initialized external zero operand. -/ +theorem extract_directory (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) + (dst zero : Word w) (m : Memory w) (rep : T.Represents X m) + (fullFit : packingLaneBits a g ≤ w) + (reg : Regions (params T a g dst zero) (Fintype.card X.Base * 2^a)) : + let p := params T a g dst zero + let B := Fintype.card X.Base * 2^a + Result p B m ∧ ∀ e : X.Base × Fin (2^a), + after m (eventLog (reports p B m)) (dst+IncidenceDirectory.basePort X e).val = + tagWord (radices_fit fullFit).2.2 ((packingFields a g) (X.slots.displacement e)).2.2.1 := by + let p := params T a g dst zero + have hr := scan_result p _ m reg + refine ⟨hr, ?_⟩ + intro e + let i := IncidenceDirectory.baseOrder X e + have hs : cell (p 0) i.val = (T.shift+IncidenceDirectory.basePort X e).val := by + rw [IncidenceDirectory.basePort_number]; rfl + have hd : cell (p 1) i.val = (dst+IncidenceDirectory.basePort X e).val := by + rw [IncidenceDirectory.basePort_number]; rfl + rw [← hd, hr.readback _ i.isLt, hs, rep.shift] + apply Fin.ext + rw [extract_val, tagWord_val] + obtain ⟨hg,hj,_⟩ := radices_fit fullFit + have hx := (bitWordFinEquiv _ (X.slots.displacement e)).isLt.trans_le + (Nat.pow_le_pow_right (by decide : 0 < 2) fullFit) + change (_ % 2^w) / (2^g % 2^w) % (2^(Shrink.J a) % 2^w) = _ + rw [Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hg, Nat.mod_eq_of_lt hj] + exact packedTagNumber _ + +section Dispatcher + +open OrdinalRun Schedule SourceTransport + +/-- The actual word addresses used by an indexed column, including wrapping heads. -/ +def InColumn (base : Word w) (B x : ℕ) : Prop := ∃ i < B, x = cell base i + +private theorem row_footprints (p : Fin 5 → Word w) (m : Memory w) {i B : ℕ} (hi : i < B) : + Reads (InColumn (p 0) B) (row p (i : Word w) m).events ∧ + Writes (InColumn (p 1) B) (row p (i : Word w) m).events := by + constructor <;> intro a v h + · obtain ⟨rfl,_⟩ := (by simpa [row] using h : a = p 0+(i : Word w) ∧ v = _) + exact ⟨i,hi,rfl⟩ + · obtain ⟨rfl,_⟩ := (by simpa [row] using h : a = p 1+(i : Word w) ∧ v = _) + exact ⟨i,hi,rfl⟩ + +/-- The shift scan reads only old base displacements and writes only extracted tags. -/ +theorem scan_footprints (p : Fin 5 → Word w) (B : ℕ) (m : Memory w) : + Reads (InColumn (p 0) B) (eventLog (scan p 0 B m)) ∧ + Writes (InColumn (p 1) B) (eventLog (scan p 0 B m)) := by + let P := (extractPass.table.instantiate w p).program + let cursor (i : ℕ) : Word w := i + apply OrdinalRun.footprint P 14 cursor B (fun _ _ => True) _ _ _ 0 _ m _ (by simp) trivial + (scan_native p 0 B m) + intro j hj m _ bits r h + have eqn := (execute_prefix_unique (row_native p (cursor j) m) + (show execute P 14 (P.start (cursor j)) m ([] ++ bits) = some r from h)).2 + subst r + obtain ⟨rd,wr⟩ := row_footprints p m hj + exact ⟨by simp [cursor,row],trivial,rd,wr⟩ + +/-- The zero initializer has no read dependency and writes just its own cell. -/ +theorem zero_footprints (p : Fin 5 → Word w) : + Reads (fun _ => False) (eventLog [zeroRow p]) ∧ + Writes (fun x => x = (p 2).val) (eventLog [zeroRow p]) := by + constructor <;> intro a v h + · simp [eventLog, zeroRow] at h + · obtain ⟨rfl,_⟩ := (by simpa [eventLog,zeroRow] using h : a = p 2 ∧ v = 0) + rfl + +variable {d : ℕ} (C : Catalog d) (worker : Fin d) (ports : Ports w) + +/-- The installed frame stays ready through all rows and the final cursor closes the worker. -/ +theorem scan_valid (pub : Fin (C worker).params → Word w) (p : Fin 5 → Word w) (B : ℕ) (m : Memory w) + (fit : B < 2^w) (ready : Ready C worker ports pub (B : Word w) m) + (apart : ∀ x, ControlCell (C worker).params ports x → ¬ InColumn (p 1) B x) : + ValidTrace C worker ports pub (B : Word w) 0 m (scan p 0 B m) ∧ + Preserved (C worker).params ports m (after m (eventLog (scan p 0 B m))) := by + let P := (extractPass.table.instantiate w p).program + let cursor (i : ℕ) : Word w := i + have active (i : ℕ) (hi : i < B) : cursor i < cursor B := by + change i%(2^w) < B%(2^w) + rwa [Nat.mod_eq_of_lt (hi.trans fit), Nat.mod_eq_of_lt fit] + have advance (j : ℕ) (hj : j < B) (mem : Memory w) (_ : True) (bits : List Bool) (r : Report w) + (h : execute P 14 (P.start (cursor j)) mem bits = some r) : + r.result = some (cursor (j+1)) ∧ True ∧ Preserved (C worker).params ports mem (after mem r.events) := by + have eqn := (execute_prefix_unique (row_native p (cursor j) mem) + (show execute P 14 (P.start (cursor j)) mem ([] ++ bits) = some r from h)).2 + subst r + exact ⟨by simp [cursor,row], trivial, + fun x hx ↦ after_outside mem (row_footprints p mem hj).2 (apart x hx)⟩ + obtain ⟨trace,_,keep⟩ := OrdinalRun.validTrace C worker ports P 14 pub (cursor B) cursor B + (fun _ _ => True) active le_rfl advance 0 _ m _ (by simp) trivial ready (scan_native p 0 B m) + exact ⟨trace,keep⟩ + +/-- Guard and frame correctness of the single zero write after the shift scan. -/ +theorem zero_valid (pub : Fin (C worker).params → Word w) (p : Fin 5 → Word w) (m : Memory w) + (fit : 1 < 2^w) (ready : Ready C worker ports pub 1 m) + (apart : ∀ x, ControlCell (C worker).params ports x → x ≠ (p 2).val) : + ValidTrace C worker ports pub 1 0 m [zeroRow p] ∧ + Preserved (C worker).params ports m (after m (eventLog [zeroRow p])) := by + have keep : Preserved (C worker).params ports m (after m (zeroRow p).events) := + fun x hx ↦ by rw [zero_after]; exact ite_eq_right (apart x hx) + have lt : (0 : Word w) < 1 := by + change 0 < 1%(2^w) + rw [Nat.mod_eq_of_lt fit]; decide + exact ⟨⟨ready,lt,1,rfl,ready_of_preserved C worker ports ready keep,le_rfl⟩,keep⟩ + +end Dispatcher + +end CompressorRecords.ShrinkTagColumn + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkWidthArena.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkWidthArena.lean new file mode 100644 index 0000000000..c7d4d582d1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkWidthArena.lean @@ -0,0 +1,201 @@ +import OAI.Computability.VPVNP.CompressionHistory +import OAI.Computability.VPVNP.CompressorBundleRankedInput +import OAI.Computability.VPVNP.CompressorRecordsDemandWidths + +/-! +# Widths and field starts in the shrinking arena + +Scatter the widths of the ranked old ports, scan the two sorted row families, +and split the thick totals into balanced AB pieces. All four workers run in +sequence on a fresh arena after the rank and incidence directories. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkWidthArena + +open BurstRAM PrimedStackRAM Compression Compression.PackingData BundleKeys +open scoped Classical + +variable {w a g : ℕ} (X : State a (packingLaneBits a g)) +local notation "N" => Fintype.card X.Base +local notation "A" => N * 2^(packingLaneBits a g) * 2^a +local notation "D" => (2:ℕ)^a +local notation "C" => Shrink.colors a +local notation "n" => N*(2^(Shrink.J a)*2^g) +local notation "B" => numBundles N a g +local notation "Q" => pieceCount D C +local notation "P" => X.packingData +local notation "arcs" => oldArcOrder (a := a) (g := g) X.baseIndex +local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex + +variable (T : IncidenceDirectory w) (q : Fin 6 → Word w) (dest : Word w) (start : ℕ) + +/-- Public words for scattering old port widths into sorted bundle rows, giving the owner, +rank, and old-width columns, row stride, and output base. -/ +def scatterBank : Fin 5 → Word w := + BundleWidthScatter.scatterPublic q dest T.width (Fin.ofNat _ start) + +/-- First address of the field-start rectangles, immediately after the two families of sorted +width rows. -/ +def prefixBase := start + 2*(B*(q 4).val) +/-- First address of the AB piece-width rectangle, following both start rectangles and both +columns of bundle totals. -/ +def abBase := prefixBase X q start + 2*(B*(q 4).val) + 2*B +/-- First free address after the dense AB piece-width and field-start rectangles. -/ +def stop := abBase X q start + 2*(B*Q) + +/-- Parameters for scanning sorted widths into field starts and bundle totals. The motif flag +selects the CD rows when true and the thick-wire rows when false. -/ +def prefixBank (motif : Bool) : Fin 5 → Word w := + BundlePrefixGraph.prefixPublic (scatterBank T q dest start) B D C (prefixBase X q start) motif + +/-- Parameters for splitting each thick-wire bundle total into balanced AB pieces and storing +their widths and starting offsets. -/ +def abBank : Fin 5 → Word w := + DemandWidths.packedPublic (prefixBank X T q dest start false 4) B Q (abBase X q start) + +local notation "s" => scatterBank T q dest start +local notation "t" => prefixBank X T q dest start false +local notation "u" => prefixBank X T q dest start true +local notation "p" => abBank X T q dest start + +/-- The owner, rank and old width columns can be anywhere before the fresh arena. -/ +theorem scatterLayout (stride : Q ≤ (q 4).val) (ownerBefore : (q 1).val+A ≤ start) + (rankBefore : dest.val+A ≤ start) (widthBefore : T.width.val+A ≤ start) + (room : stop X q start < 2^w) : BundleWidthScatter.Layout s A n D C := by + change start + 2*(B*(q 4).val) + 2*(B*(q 4).val) + 2*B + 2*(B*Q) < 2^w at room + have base : (s 4).val = start := Nat.mod_eq_of_lt (by omega) + have before (i : Fin 3) : (s (i.castAdd 2)).val+A ≤ start := by + fin_cases i + · exact ownerBefore + · exact rankBefore + · exact widthBefore + refine ⟨stride, ?_, fun i ↦ (before i).trans (by omega), ?_, fun i ↦ .inl ((before i).trans base.ge)⟩ + · change B+B ≤ _; omega + · change (s 4).val + (B+B)*(q 4).val ≤ _ + rw [base,Nat.add_mul]; omega + +/-- Memory after scattering the widths and applying first the thick-wire and then the motif +prefix-scan reports. -/ +def prefixedMemory (m : Memory w) (ws ts us : List (Report w)) : Memory w := + after (after (after m (eventLog ws)) (eventLog ts)) (eventLog us) + +/-- Memory after the AB piece reports have written widths and starts on top of the completed +scatter and prefix scans. -/ +def finalMemory (m : Memory w) (ws ts us rs : List (Report w)) : Memory w := + after (prefixedMemory m ws ts us) (eventLog rs) + +/-- Four native executions, readbacks at their joint endpoint, and their cost. -/ +structure Run (m : Memory w) (ws ts us rs : List (Report w)) : Prop where + scatter : runSegment ((template BundleWidthScatter.visit 0).instantiate w s).program 19 (some 0) m + (List.replicate A []) = some ws + prefixes : BundlePrefixGraph.Completed P sites X.packingWidth X.shrinkOrder X.shrinkNumber t u + (after m (eventLog ws)) ts us + ab : runSegment ((template ABWidths.visit 0).instantiate w p).program 30 (some (Fin.ofNat _ 0)) + (prefixedMemory m ws ts us) (List.replicate (B*Q) []) = some rs + stored : DemandWidths.Stored P sites X.packingWidth X.shrinkOrder X.shrinkNumber t u p (finalMemory m ws ts us rs) + frame : ∀ addr < start, finalMemory m ws ts us rs addr = m addr + cost : RAMBuckets.cost Report.probes ws + RAMBuckets.cost Report.probes ts + + RAMBuckets.cost Report.probes us + RAMBuckets.cost Report.probes rs = 10*A + 4*(B*Q) + +private theorem scatter_frame {m : Memory w} {ws : List (Report w)} + (layout : BundleWidthScatter.Layout s A n D C) + (ranked : BundleWidthScatter.RankedInput P X.shrinkNumber X.shrinkOrder arcs sites s m X.packingWidth) + (run : runSegment ((template BundleWidthScatter.visit 0).instantiate w s).program 19 (some 0) m + (List.replicate A []) = some ws) {addr : ℕ} (ha : addr < (s 4).val) : + after m (eventLog ws) addr = m addr := by + have regions := BundleWidthScatter.regions_of_layout P X.shrinkNumber X.shrinkOrder arcs sites layout ranked + obtain ⟨ls,hr,_,filled,_⟩ := BundleWidthScatter.run s m A regions + obtain rfl := Option.some.inj (hr.symm.trans run) + apply filled.frame + intro j hj + let e := (arcs).symm ⟨j,hj⟩ + have he : (arcs e).val = j := congrArg Fin.val ((arcs).apply_symm_apply _) + have h := BundleWidthScatter.output_eq P X.shrinkNumber X.shrinkOrder arcs sites layout ranked e + unfold BundleWidthScatter.arcWord at h + rw [he] at h + exact Nat.ne_of_lt (h ▸ ha.trans_le (Nat.le_add_right ..)) + +private theorem prefix_frame {bank : Fin 5 → Word w} {count : ℕ} {m : Memory w} {ls : List (Report w)} + (run : BundlePrefixRAM.FullRun bank count m ls) {addr : ℕ} (h₁ : addr < (bank 3).val) + (h₂ : addr < (bank 4).val) : after m (eventLog ls) addr = m addr := + run.frame addr (fun _ _ _ _ ↦ by omega) (fun _ _ ↦ by omega) + +private theorem ab_frame {bank : Fin 5 → Word w} {count : ℕ} {m : Memory w} {rs : List (Report w)} + (layout : ABWidths.Layout bank count) (dense : (bank 1).val = (bank 0).val) + (run : runSegment ((template ABWidths.visit 0).instantiate w bank).program 30 (some (Fin.ofNat _ 0)) m + (List.replicate (count*(bank 0).val) []) = some rs) + {addr : ℕ} (ha : ∀ i : Fin 2, addr < (bank (i.natAdd 3)).val) : after m (eventLog rs) addr = m addr := by + obtain ⟨ls,hr,filled,_⟩ := ABWidths.run bank count m layout.regions + obtain rfl := Option.some.inj (hr.symm.trans run) + apply filled.frame + intro i j hj + have hjw := hj.trans_le layout.regions.fits + have row : (ABWidths.row bank (Fin.ofNat _ j)).val = j/(bank 0).val := by + change (j % (2^w)/(bank 0).val) % (2^w) = _ + rw [Nat.mod_eq_of_lt hjw,Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt hjw)] + have rank : (ABWidths.rank bank (Fin.ofNat _ j)).val = j%(bank 0).val := by + change (j % (2^w)%(bank 0).val) % (2^w) = _ + rw [Nat.mod_eq_of_lt hjw,Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt hjw)] + have offset : j/(bank 0).val * (bank 0).val + j%(bank 0).val = j := by + rw [Nat.mul_comm, Nat.add_comm, Nat.mod_add_div] + have fit := layout.outFit i + rw [dense] at fit + change addr ≠ (ABWidths.address bank i (Fin.ofNat _ j)).val + rw [ABWidths.address, Fin.val_add, Fin.val_add, Fin.val_mul, row, rank, dense, + Nat.mod_add_mod, Nat.add_mod_mod, offset, Nat.mod_eq_of_lt (by omega)] + exact Nat.ne_of_lt ((ha i).trans_le (Nat.le_add_right ..)) + +/-- Starting with the native rank directory, materialize all widths and starts. +The original directories and every other address below the allocation survive. -/ +theorem build (m : Memory w) (stride : Q ≤ (q 4).val) (ownerBefore : (q 1).val+A ≤ start) + (rankBefore : dest.val+A ≤ start) (widthBefore : T.width.val+A ≤ start) + (room : stop X q start < 2^w) (widthFit : Q*X.maxWireWidth < 2^w) + (ranked : BundleWidthScatter.RankedInput P X.shrinkNumber X.shrinkOrder arcs sites s m X.packingWidth) : + ∃ ws ts us rs, Run X T q dest start m ws ts us rs := by + let block := B*(q 4).val + have hroom : start+2*block+2*block+2*B+2*(B*Q) < 2^w := room + have hc : 2 ≤ C := by have := Nat.two_pow_pos a; unfold Shrink.colors; omega + have layout := scatterLayout X T q dest start stride ownerBefore rankBefore widthBefore room + have sorted : (s 4).val = start := Nat.mod_eq_of_lt (by omega) + have endWidths : (s 4).val + 2*((n*D)*(s 3).val) ≤ prefixBase X q start := by + rw [sorted]; exact le_rfl + obtain ⟨rows,abLayout,cap,tot,apart⟩ := DemandWidths.allocation s (prefixBase X q start) + hc (Nat.two_pow_pos a) layout endWidths room + obtain ⟨ws,ts,us,rs,hs,hp,hab,stored,cost⟩ := DemandWidths.from_ranked_input P sites X.packingWidth + X.shrinkOrder X.shrinkNumber arcs hc s t u p rows m ranked X.maxWireWidth + (fun _ ↦ X.width_le_maxWireWidth _) widthFit abLayout cap tot apart + refine ⟨ws,ts,us,rs,hs,hp,hab,stored,?_,cost⟩ + intro addr ha + have baseT : (t 3).val = start+2*block := + Nat.mod_eq_of_lt (show start+2*block < 2^w by omega) + have totalT : (t 4).val = start+2*block+2*block := + Nat.mod_eq_of_lt (show start+2*block+2*block < 2^w by omega) + have baseU : (u 3).val = start+2*block+block := + Nat.mod_eq_of_lt (show start+2*block+block < 2^w by omega) + have totalU : (u 4).val = start+2*block+2*block+B := + Nat.mod_eq_of_lt (show start+2*block+2*block+B < 2^w by omega) + have baseP : (p 3).val = start+2*block+2*block+2*B := + Nat.mod_eq_of_lt (show start+2*block+2*block+2*B < 2^w by omega) + have endP : (p 4).val = start+2*block+2*block+2*B+B*Q := + Nat.mod_eq_of_lt (show start+2*block+2*block+2*B+B*Q < 2^w by omega) + have hab' : runSegment ((template ABWidths.visit 0).instantiate w p).program 30 (some (Fin.ofNat _ 0)) + (prefixedMemory m ws ts us) (List.replicate (B*(p 0).val) []) = some rs := by + change (p 0).val = Q at cap + rw [cap]; exact hab + have final := ab_frame abLayout rfl hab' (addr := addr) (by + intro i; fin_cases i + · change addr < (p 3).val; omega + · change addr < (p 4).val; omega) + exact final.trans ((prefix_frame hp.motif (by omega) (by omega)).trans + ((prefix_frame hp.thick (by omega) (by omega)).trans + (scatter_frame X T q dest start layout ranked hs (ha.trans_le sorted.ge)))) + +end CompressorRecords.ShrinkWidthArena + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkWords.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkWords.lean new file mode 100644 index 0000000000..9d4ff1ff0a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsShrinkWords.lean @@ -0,0 +1,233 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkRAM + +/-! +# Word correctness of the shrinking owner computation + +The native directory arithmetic is carried out modulo the machine word size. Only +the low-field XOR and the color-bit test need a nonwrapping intermediate. Addresses +of the four inputs are taken in the actual external memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkRAM + +open BurstRAM BurstRAM.PrivateRAM Compression + +variable {w : ℕ} + +/-- Encode a natural number as a machine word by reducing it modulo `2^w`. -/ +abbrev word (w n : ℕ) : Word w := Fin.ofNat (2^w) n + +private theorem word_val {n : ℕ} (h : n < 2^w) : (word w n).val = n := Nat.mod_eq_of_lt h + +private theorem word_of_val (z : Word w) : word w z.val = z := Fin.ext (word_val z.isLt) + +private theorem word_add (x y : ℕ) : word w x + word w y = word w (x+y) := by + apply Fin.ext; exact (Nat.add_mod ..).symm + +private theorem word_mul (x y : ℕ) : word w x * word w y = word w (x*y) := by + apply Fin.ext; exact (Nat.mul_mod ..).symm + +private theorem word_sub_val (x y : Word w) (h : y.val ≤ x.val) : (x-y).val = x.val-y.val := by + rw [Fin.val_sub, show 2^w-y.val+x.val = x.val-y.val+2^w by have := y.isLt; omega, + Nat.add_mod_right, Nat.mod_eq_of_lt (by have := x.isLt; omega)] + +@[simp] private theorem div_val (x y : Word w) : (div x y).val = x.val/y.val := + Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt x.isLt) + +@[simp] private theorem mod_val (x y : Word w) : (mod x y).val = x.val%y.val := + Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt x.isLt) + +private theorem bit_value (z k : ℕ) : z / 2^k % 2 = (z.testBit k).toNat := by + rw [Nat.testBit_eq_decide_div_mod_eq] + rcases Nat.mod_two_eq_zero_or_one (z / 2^k) with h | h <;> simp [h] + +private theorem shiftBit_val (z last col : Word w) (hc : col.val ≤ last.val) + (hw : last.val < w) (hw2 : 2 < 2^w) : + (mod (BinaryOp.shiftRight.eval z (last-col)) 2).val = + (z.val.testBit (last.val-col.val)).toNat := by + have hk := word_sub_val last col hc + have fit : (last-col).val < w := by omega + have h2 : (2 : Word w).val = 2 := Nat.mod_eq_of_lt hw2 + have hz : z.val >>> (last.val-col.val) < 2^w := by + rw [Nat.shiftRight_eq_div_pow]; exact (Nat.div_le_self ..).trans_lt z.isLt + rw [mod_val, BinaryOp.eval, ite_eq_left fit, hk, Fin.val_ofNat, Nat.mod_eq_of_lt hz, h2, + Nat.shiftRight_eq_div_pow, bit_value] + +/-- Conditions on the shrinking worker's public radices, last color, and layout selector that +justify decoding the low field and testing the color bit in a machine word. -/ +structure Params (p : Fin 14 → Word w) (a c j g : ℕ) (layout : Bool) : Prop where + lane : (p 0).val = 2^g + tag : (p 1).val = 2^j + degree : (p 2).val = 2^a + mask : (p 3).val = 2^c + last : (p 4).val = c-1 + choose : p 5 = if layout then 1 else 0 + low_fit : 2^(j+g) < 2^w + color_fit : c-1 < w + two_fit : 2 < 2^w + +/-- Read the natural value in a column at the given index, adding the index to its public base +address in word arithmetic. -/ +def column (p : Fin 14 → Word w) (m : Memory w) (c : Fin 14) (index : ℕ) : ℕ := + (m (p c + word w index).val).val + +private theorem chunk_val {p : Fin 14 → Word w} {a c j g : ℕ} {layout : Bool} + (h : Params p a c j g layout) : (p 1*p 0).val = 2^(j+g) := by + rw [Fin.val_mul, h.tag, h.lane, ← pow_add, Nat.mod_eq_of_lt h.low_fit] + +/-- Decode the fixed-width old position into its base, mask, slot and low lane. -/ +theorem decode_exact {p : Fin 14 → Word w} {a c j g : ℕ} {layout : Bool} + (h : Params p a c j g layout) (i : Word w) : + let f := Shrink.decode a c (j+g) i.val + decode p i = ⟨word w f.base,word w f.mask,word w f.slot,word w f.low⟩ := by + unfold decode Shrink.decode + simp only [div, mod, BinaryOp.eval, Fin.val_ofNat, h.degree, h.mask, chunk_val h] + have h₁ := (Nat.div_le_self i.val (2^(j+g))).trans_lt i.isLt + have h₂ := (Nat.div_le_self (i.val / 2^(j+g)) (2^a)).trans_lt h₁ + rw [Nat.mod_eq_of_lt h₁, Nat.mod_eq_of_lt h₂] + +private theorem select_bit (z : Word w) (b : Bool) (hz : z.val = b.toNat) (x y : Word w) : + select z x y = if b then y else x := by + cases b with + | false => have e : z = 0 := Fin.ext hz; simp [e] + | true => + have e : z = 1 := by + apply Fin.ext + have h : 1 < 2^w := by have := z.isLt; simp at hz; omega + exact hz.trans (Nat.mod_eq_of_lt h).symm + simp [e] + +set_option maxHeartbeats 850000 in +/-- Numeric correctness for one native position. Output addresses remain words, so +only values used inside bit-field operations require a fit bound. -/ +theorem outputs_row {p : Fin 14 → Word w} {a c j g : ℕ} {layout : Bool} + (hp : Params p a c j g layout) (m : Memory w) (i : Word w) + (hc : column p m 6 (Shrink.decode a c (j+g) i.val).base ≤ c-1) + (hj : column p m 7 (Shrink.decode a c (j+g) i.val).base < 2^j) : + let r := Shrink.row a c j g layout (column p m 6) (column p m 7) (column p m 8) (column p m 9) i.val + outputs p m i = ⟨word w r.owner, word w r.thick.toNat, word w r.assigned, word w r.target⟩ := by + let f := Shrink.decode a c (j+g) i.val + let e := f.base*2^a+f.slot + let co := m (p 6 + word w f.base).val + let off := m (p 7 + word w f.base).val + let mate := m (p 8 + word w e).val + let shift := m (p 9 + word w e).val + let t := f.mask.testBit (c-1-co.val) + let lo := f.low ^^^ (off.val*2^g) + let chunk := p 1*p 0 + let A := Shrink.join (j+g) f.base lo + let B := Shrink.join (j+g) (mate.val / 2^a) (lo ^^^ (shift.val % 2^(j+g))) + let pack := Shrink.join (j+g) f.base f.low + have hdeg : p 2 = word w (2^a) := by rw [← hp.degree, word_of_val] + have hchunk : chunk = word w (2^(j+g)) := by rw [← chunk_val hp, word_of_val] + have hr : p 0 = word w (2^g) := by rw [← hp.lane, word_of_val] + have he : baseArc p ⟨word w f.base,word w f.mask,word w f.slot,word w f.low⟩ = word w e := by + simp only [baseArc,hdeg,word_mul,word_add,e] + have hm : f.mask < 2^w := by + dsimp [f,Shrink.decode] + exact (Nat.mod_lt _ (Nat.two_pow_pos _)).trans (hp.mask ▸ (p 3).isLt) + have hl : f.low < 2^w := by + exact (Nat.mod_lt _ (Nat.two_pow_pos _)).trans hp.low_fit + have hoff : off.val * 2^g < 2^w := by + exact (Nat.mul_lt_mul_of_pos_right hj (Nat.two_pow_pos _)).trans (by simpa [pow_add] using hp.low_fit) + have hbit : (mod (BinaryOp.shiftRight.eval (word w f.mask) (p 4-co)) 2).val = t.toNat := by + rw [shiftBit_val _ _ _ (hp.last ▸ hc) (hp.last ▸ hp.color_fit) hp.two_fit, word_val hm, hp.last] + have hlow : xor (word w f.low) (off*p 0) = word w lo := by + rw [← word_of_val off, hr, word_mul] + change word w ((word w f.low).val ^^^ (word w (off.val*2^g)).val) = _ + rw [word_val hl, word_val hoff] + have hlowfit : lo < 2^w := Nat.xor_lt_two_pow hl hoff + have hB : div mate (p 2) * chunk + xor (word w lo) (mod shift chunk) = word w B := by + have hdiv : div mate (p 2) = word w (mate.val/2^a) := by simp [div, BinaryOp.eval,hp.degree,word] + have hx : xor (word w lo) (mod shift chunk) = word w (lo ^^^ (shift.val % 2^(j+g))) := by + change word w ((word w lo).val ^^^ (mod shift chunk).val) = _ + rw [word_val hlowfit, mod_val, show chunk.val = _ from chunk_val hp] + rw [hdiv, hx, hchunk, word_mul, word_add]; rfl + have hA : word w f.base * chunk + word w lo = word w A := by rw [hchunk, word_mul, word_add]; rfl + have hpack : word w f.base * chunk + word w f.low = word w pack := by rw [hchunk, word_mul, word_add]; rfl + let fw : Fields w := ⟨word w f.base,word w f.mask,word w f.slot,word w f.low⟩ + have hdc : decode p i = fw := decode_exact hp i + have hcs : readColumns p m fw = (co,off,mate,shift) := by + dsimp only [readColumns,fw] + rw [he] + unfold outputs + rw [hdc] + dsimp only + rw [hcs] + change Outputs.mk (select _ (select _ (word w f.base*chunk+xor (word w f.low) (off*p 0)) + (div mate (p 2)*chunk+xor (xor (word w f.low) (off*p 0)) (mod shift chunk))) + (word w f.base*chunk+word w f.low)) _ _ _ = _ + dsimp only [fw] + rw [hlow, hA, hB, hpack, select_bit _ t hbit, hp.choose] + rw [show word w A * p 2 + word w f.slot = word w (A*2^a+f.slot) by rw [hdeg, word_mul, word_add]] + have ht : mod (BinaryOp.shiftRight.eval (word w f.mask) (p 4-co)) 2 = word w t.toNat := by + rw [← hbit, word_of_val] + rw [ht] + change Outputs.mk (if t then word w pack else select (if layout then 1 else 0) (word w A) (word w B)) + (word w t.toNat) (word w (A*2^a+f.slot)) (word w B) = + Outputs.mk (word w (if t then pack else if layout then B else A)) + (word w t.toNat) (word w (A*2^a+f.slot)) (word w B) + cases layout <;> cases t <;> simp + +/-- Word values written by the opcode table on a genuine old position, in the +numbering used by the next level's site and incidence directories. -/ +theorem outputs_exact {V : Type} {a g n : ℕ} (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) + (order : V ≃ Fin n) (p : Fin 14 → Word w) (m : Memory w) (layout : Bool) + (hp : Params p a (Shrink.colors a) (Shrink.J a) g layout) + (d : Shrink.Directory G order (column p m 6) (column p m 7) (column p m 8) (column p m 9)) + (hOld : n * 2^(packingLaneBits a g) ≤ 2^w) + (hSlots : n * (2^(Shrink.J a) * 2^g) * 2^a ≤ 2^w) (x : Shrink.Old V a g) : + let P := orderedDyadicPacking G order + let i := word w (Shrink.oldNumber order x) + let out := outputs p m i + (out.owner.val, out.thick.val, out.assigned.val, out.target.val) = + (Shrink.packedNumber order (P.placement layout x), (decide (P.thick x)).toNat, + Shrink.join a (Shrink.packedNumber order (P.assignedBundle x).1) (P.assignedBundle x).2.val, + Shrink.packedNumber order (P.siteGraph.target (P.assignedBundle x)).1) := by + let P := orderedDyadicPacking G order + let i := word w (Shrink.oldNumber order x) + have hi : i.val = Shrink.oldNumber order x := by + apply word_val + rw [← Shrink.oldIndex_val] + exact (Fin.isLt _).trans_le hOld + have hd := Shrink.decode_oldNumber order x + have hco : column p m 6 (Shrink.decode a (Shrink.colors a) (Shrink.J a+g) i.val).base ≤ Shrink.colors a-1 := by + rw [hi, hd, d.color_at] + exact Nat.le_sub_one_of_lt (P.color x.1.1).isLt + have hj : column p m 7 (Shrink.decode a (Shrink.colors a) (Shrink.J a+g) i.val).base < 2^(Shrink.J a) := by + rw [hi,hd,d.offset_at]; exact Fin.isLt _ + have he := outputs_row hp m i hco hj + dsimp only at he ⊢ + rw [hi, Shrink.row_exact G order d] at he + change ((outputs p m i).owner.val, (outputs p m i).thick.val, (outputs p m i).assigned.val, + (outputs p m i).target.val) = _ + rw [he] + have hsite (v : Shrink.Packed V a g) : + Shrink.packedNumber order v < n * (2^(Shrink.J a) * 2^g) := by + rw [← Shrink.packedIndex_val]; exact Fin.isLt _ + have hsiteWord (v : Shrink.Packed V a g) : Shrink.packedNumber order v < 2^w := + (hsite v).trans_le ((Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)).trans hSlots) + have hefit : Shrink.join a (Shrink.packedNumber order (P.assignedBundle x).1) (P.assignedBundle x).2.val < 2^w := by + unfold Shrink.join + calc + _ < Shrink.packedNumber order (P.assignedBundle x).1 * 2^a + 2^a := by + exact Nat.add_lt_add_left (Fin.isLt _) _ + _ = (Shrink.packedNumber order (P.assignedBundle x).1+1)*2^a := by ring + _ ≤ _ := (Nat.mul_le_mul_right _ (hsite (P.assignedBundle x).1)).trans hSlots + have boundBit (b : Bool) : b.toNat < 2 := by cases b <;> decide + have htfit := (boundBit (decide (P.thick x))).trans hp.two_fit + change ((word w (Shrink.packedNumber order (P.placement layout x))).val, + (word w (decide (P.thick x)).toNat).val, + (word w (Shrink.join a (Shrink.packedNumber order (P.assignedBundle x).1) (P.assignedBundle x).2.val)).val, + (word w (Shrink.packedNumber order (P.siteGraph.target (P.assignedBundle x)).1)).val) = _ + rw [word_val (hsiteWord _), word_val htfit, word_val hefit, word_val (hsiteWord _)] + +end CompressorRecords.ShrinkRAM + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsTermLayout.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsTermLayout.lean new file mode 100644 index 0000000000..0a53c2cbf4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsTermLayout.lean @@ -0,0 +1,87 @@ +import OAI.Computability.VPVNP.CompressorShrinkTermPhases +import OAI.Computability.VPVNP.CompressorRecordsSelectedScoreRun + +/-! +# Choosing the common layout after the native term scan + +The width cells read by the score passes are the cells written by the fused term +worker on the very same admitted motif choices. A legal term stream therefore +determines one global layout, and the scratch for its score does not overwrite +any earlier term words. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +set_option maxHeartbeats 1800000 + +namespace CompressorRecords.SelectedScore + +open Compression BurstRAM PairSimulation.LocalHistory ShrinkMotif TermScores +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) + +private theorem motifNumber (i : Fin (Fintype.card X.packingData.Motif)) : + (ShrinkMotifOrder.stateNumber X ((ShrinkMotifOrder.entries X) i)).val = i.val := by + change ((ShrinkMotifOrder.entries X).symm ((ShrinkMotifOrder.entries X) i)).val = i.val + exact congrArg (fun j : Fin (Fintype.card X.packingData.Motif) => j.val) + ((ShrinkMotifOrder.entries X).symm_apply_apply i) + +/-- All eight exact inputs to the score scan are physically present immediately after +the actual fused term execution. -/ +theorem stored_of_term_run (L : Tables w) (dense : Word w) (cap : ℕ) (s : Selection B X) + (before : Memory w) (reports : List (Report w)) + (term : ShrinkTermSelection.Written B.shrink X dense L.termBase L.termStride.val cap s before reports) : + Stored B X s (headAt X L) (after before (eventLog reports)) := by + intro i + let m := (motifOrder X).entries i + have he := term.fields m + have hb : ShrinkTermSelection.rowBase X L.termBase L.termStride.val m = headAt X L i := by + dsimp only [ShrinkTermSelection.rowBase,headAt,TermScores.rowBase,m] + rw [show (ShrinkMotifOrder.stateNumber X ((motifOrder X).entries i)).val = i.val from motifNumber X i] + change ((L.termBase.val + i.val * L.termStride.val : ℕ) : Word w) = L.termBase + (i.val : Word w)*L.termStride + have ht : (L.termBase.val : Word w) = L.termBase := Fin.ext (Nat.mod_eq_of_lt L.termBase.isLt) + have hs : (L.termStride.val : Word w) = L.termStride := Fin.ext (Nat.mod_eq_of_lt L.termStride.isLt) + simp [ht,hs] + rw [hb] at he + exact he + +/-- From the supplied physical demand pairs, every admitted sequence gives an actual +term scan followed by the deterministic eight-axis layout computation. -/ +theorem choose_layout (L : Tables w) (dense : Word w) (mem : Memory w) (cap : ℕ) + (hstride : 10 ≤ L.termStride.val) + (separate : dense.val + (motifOrder X).length*2 ≤ L.termBase.val) + (termFit : L.termBase.val + (motifOrder X).length * L.termStride.val < 2^w) + (pairs : ShrinkTermInputs.statePairs X dense mem) + (hw : ShrinkTermSelection.fitConstant B.shrink + 4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (hcap : TermWorker.budget B.shrink 2 8 w X.maxWireWidth ≤ cap) + (hc : 8 ≤ 2^w) (hweights : ∀ t, MotifAdmission.weight relativeMass t < 2^w) + (hselectors : L.selectorBits.val = B.shrink.selectorBits) + (scratch : TermScores.Layout L (motifOrder X).length (List.ofFn axes)) + (s : Selection B X) + (hscore : ∀ l, layoutScore relativeMass (X.packingData.termWidths B.shrink X.shrinkNumber X.packingWidth s) l < 2^w) : + let n := (motifOrder X).length + let chosen := X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s + ∃ terms scores, ShrinkTermSelection.Written B.shrink X dense L.termBase L.termStride.val cap s mem terms ∧ + TermScores.run L n (List.ofFn axes) (after mem (eventLog terms)) = some scores ∧ + after mem (eventLog (terms++scores)) L.levelCell.val = (chosen.toNat : Word w) ∧ + (∀ j, j ≠ L.levelCell.val → (∀ l, j ≠ (counter L l).val) → + after mem (eventLog (terms++scores)) j = after mem (eventLog terms) j) ∧ + scores.length = 8*n+2 ∧ RAMBuckets.probeCount Report.probes scores = 32*n+5 := by + obtain ⟨terms,ht⟩ := (ShrinkTermSelection.native B.shrink X dense L.termBase L.termStride.val + hstride separate termFit mem pairs hw cap hcap).2 s + let m := after mem (eventLog terms) + obtain ⟨scores,hr,chosen,_,frame,count,probes⟩ := run_selected B X L m s + (stored_of_term_run B X L dense cap s mem terms ht) hstride termFit.le hc hweights hselectors scratch hscore + have hm : after mem (eventLog (terms++scores)) = after m (eventLog scores) := by + simp only [eventLog, List.flatMap_append, after, List.foldl_append,m] + exact ⟨terms,scores,ht,hr,hm ▸ chosen,hm ▸ frame,count,probes⟩ + +end CompressorRecords.SelectedScore + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRecordsWorkspace.lean b/lean/OAI/Computability/VPVNP/CompressorRecordsWorkspace.lean new file mode 100644 index 0000000000..08a765d2a6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRecordsWorkspace.lean @@ -0,0 +1,346 @@ +import OAI.Computability.VPVNP.CompressorRecordsController +import OAI.Computability.VPVNP.CompressorRecordsSchedule + +/-! +# The pair workspace as the compressor scheduler's native parameter bank + +Public word two of the eleven-word pair ABI points to the workspace. +Its first six words supply the scheduler's parameters. The following three +words hold its tag, ordinal and row count. The active frame occupies the +next maximum-arity-plus-one words. One reserved word separates the frame +from the directory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.Workspace + +open BurstRAM BurstRAM.PrivateRAM +open scoped Fin.CommRing + +variable {w d : ℕ} + +/-- Locate the scheduler's active frame, directory, ordinal, row count, and tag relative to the +pair workspace base, allowing room for the maximum worker arity. -/ +def ports (g : ℕ) (base : Word w) : Schedule.Ports w := + ⟨base+9, base+((11+g : ℕ) : Word w), base+7, base+8, base+6⟩ + +/-- The six public scheduler pointers stored in the workspace header. The internal scheduler +tag and its stage linker share one tag cell. -/ +def bank (g : ℕ) (base : Word w) : Fin 6 → Word w := + LiveStageLink.publicData (ports g base).data (ports g base).tag + +/-- The header's two tag parameters refer to the same external cell. -/ +def Installed (g : ℕ) (base : Word w) (m : Memory w) : Prop := + (Frame.data base m : Fin 6 → Word w) = bank g base + +variable (C : Schedule.Catalog d) + +private abbrev inner := Schedule.template C (Controller.table (Schedule.arity C)) + +/-- The only public operand accessed by the enclosing frame loader is word two. -/ +def table := LiveStageLink.widen (Frame.compile (inner C)) (Function.Embedding.refl _) + (fun _ : Fin 1 ↦ (2 : Fin 11)) + +/-- Prefix a scheduler report with the events that load its six parameter words from the +workspace header. -/ +def report (base : Word w) (m : Memory w) (rep : Report w) : Report w := + LiveStageLink.prependLog (Frame.loadEvents base m 0 6) rep + +theorem execute_dispatch (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bits : List Bool) (cap : ℕ) (h : Installed (Schedule.arity C) (pub 2) m) : + let W := ((table C).instantiate w pub).program + let S := (Schedule.machine C (Controller.table (Schedule.arity C)) (ports (Schedule.arity C) (pub 2))).program + execute W cap (W.start s) m bits = + (execute S (cap-24) (S.start s) m bits).map (report (pub 2) m) := by + dsimp only [table] + rw [LiveStageLink.execute_widen_start] + change execute (Frame.machine (inner C) (pub 2)).program cap + ((Frame.machine (inner C) (pub 2)).program.start s) m bits = _ + rw [Frame.execute_cap, show (Frame.data (pub 2) m : Fin 6 → Word w) = _ from h] + rfl + +theorem report_effect (base : Word w) (m : Memory w) (rep : Report w) : + (report base m rep).events.length = 24+rep.events.length ∧ + (report base m rep).probes = 6+rep.probes ∧ + choiceBits (report base m rep).events = choiceBits rep.events ∧ + after m (report base m rep).events = after m rep.events ∧ + (report base m rep).result = rep.result := Frame.frame_cost base m 0 6 rep + +/-- A successful scheduler report with its exact branch stream lifts at a cost of +six external reads and eighteen private ticks. -/ +theorem execute_dispatch_of (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bits : List Bool) (fuel : ℕ) (h : Installed (Schedule.arity C) (pub 2) m) (rep : Report w) + (run : let S := (Schedule.machine C (Controller.table (Schedule.arity C)) + (ports (Schedule.arity C) (pub 2))).program + execute S fuel (S.start s) m bits = some rep) : + let W := ((table C).instantiate w pub).program + execute W (fuel+24) (W.start s) m bits = some (report (pub 2) m rep) := by + dsimp only at run ⊢ + rw [execute_dispatch C pub s m bits _ h, Nat.add_sub_cancel, run] + rfl + +/-- Offsets from the workspace base stored in the header. The last two cells +are control words initialized to zero. Row count at offset eight comes from +the level-directory constructor. -/ +private def offset (g : ℕ) : Fin 8 → ℕ := ![9,11+g,7,8,6,6,0,0] + +/-- Value installed in one of the first eight workspace cells. The first six hold scheduler +pointers, followed by the initial zero tag and ordinal. -/ +def headerWord (g : ℕ) (base : Word w) (i : Fin 8) : Word w := + (if i.val < 6 then base else 0) + ((offset g i : ℕ) : Word w) + +theorem headerWord_bank (g : ℕ) (base : Word w) (j : Fin 6) : + headerWord g base (j.castLE (by decide)) = bank g base j := by + fin_cases j <;> simp [headerWord, offset, bank, ports, LiveStageLink.publicData, Schedule.Ports.data] + +private def width (g : ℕ) := Nat.clog 2 (g+12) +private theorem literal_fit (g i : ℕ) (h : i < g+12) : i < 2^width g := + h.trans_le (Nat.le_pow_clog (by decide : 1 < 2) _) + +private def cell (j : Fin 8) (phase : Fin 5) : Fin 42 := (finProdFinEquiv (j,phase)).natAdd 2 +private def next (j : ℕ) : Fin 42 := if h : j < 8 then cell ⟨j,h⟩ 0 else 1 + +private def cellCode (g : ℕ) (j : Fin 8) : Fin 5 → Instr (width g) 42 4 11 + | 0 => .constant 1 (Fin.ofNat _ j.val) (cell j 1) + | 1 => .binary .add 1 0 1 (cell j 2) + | 2 => .constant 2 (Fin.ofNat _ (offset g j)) (cell j 3) + | 3 => .binary .add 2 (if j.val < 6 then 0 else 3) 2 (cell j 4) + | 4 => .writeExternal 1 2 (next (j.val+1)) + +/-- One native call installs the six pointers and resets the scheduler's tag +and ordinal. Its accepting exit allows the outer linker to enter the next stage. -/ +def initTable (g : ℕ) : Template 42 4 11 where + literalWidth := width g + entry := 0 + code := Fin.addCases (m := 2) (n := 40) (fun i ↦ if i.val = 0 then .publicWord 0 2 (next 0) else .accept) + (fun k ↦ let p := finProdFinEquiv.symm k; cellCode g p.1 p.2) + +/-- Instantiate the header initializer at the chosen word width using the pair ABI's public +words and maximum worker arity. -/ +abbrev initMachine (g : ℕ) (pub : Fin 11 → Word w) := (initTable g).instantiate w pub + +private theorem code_cell (g : ℕ) (pub : Fin 11 → Word w) (j : Fin 8) (i : Fin 5) : + (initMachine g pub).code (cell j i) = (cellCode g j i).resize w := by + simp [initMachine, initTable, cell, Template.instantiate] + +private theorem code_end (g : ℕ) (pub : Fin 11 → Word w) : + (initMachine g pub).code 1 = .accept := rfl + +private def events (g : ℕ) (base : Word w) (i : ℕ) : ℕ → List (Event w) + | 0 => [] + | n+1 => + let j : Fin 8 := Fin.ofNat _ i + [.tick,.tick,.tick,.tick,.write (base+(i : Word w)) (headerWord g base j)] ++ events g base (i+1) n + +/-- Accepting initialization report recording eight header writes to install the scheduler +pointers and reset its tag and ordinal. -/ +def initReport (g : ℕ) (base : Word w) : Report w := + ⟨.tick :: events g base 0 8, none⟩ + +private theorem write_one (g : ℕ) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (rs : Fin 4 → Word w) (z : rs 3 = 0) (j : Fin 8) (bs : List Bool) (f : ℕ) : + let a := rs 0 + (j.val : Word w) + let v := headerWord g (rs 0) j + execute (initMachine g pub).program (f+5) ⟨next j.val,s,rs,fun _ ↦ 0⟩ m bs = + (execute (initMachine g pub).program f ⟨next (j.val+1),s, + Function.update (Function.update rs 1 a) 2 v,fun _ ↦ 0⟩ (writeMemory m a v) bs).map + (LiveStageLink.prependLog [.tick,.tick,.tick,.tick,.write a v]) := by + have hj := literal_fit g j.val (by have := j.isLt; omega) + have ho := literal_fit g (offset g j) (by fin_cases j <;> simp [offset]; omega) + rw [show next j.val = cell j 0 by simp [next,j.isLt]] + by_cases h : j.val < 6 <;> + simp (config := {decide := true}) [execute, Machine.program, code_cell, cellCode, Instr.resize, + Instr.run, Config.put, BinaryOp.eval, Nat.mod_eq_of_lt hj, Nat.mod_eq_of_lt ho, h, z, + Function.update_idem, Function.comp_def, Report.prepend, headerWord] <;> rfl + +private theorem init_tail (g : ℕ) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (rs : Fin 4 → Word w) (z : rs 3 = 0) (bs : List Bool) (f i n : ℕ) (hlen : i+n = 8) : + execute (initMachine g pub).program (f+1+5*n) ⟨next i,s,rs,fun _ ↦ 0⟩ m bs = + if bs = [] then some ⟨events g (rs 0) i n,none⟩ else none := by + induction n generalizing i rs m with + | zero => + simp only [Nat.add_zero] at hlen + subst i + simp [next, events, execute, Machine.program, code_end, Instr.run] + | succ n ih => + let j : Fin 8 := ⟨i,by omega⟩ + have hj : Fin.ofNat 8 i = j := Fin.ext (Nat.mod_eq_of_lt j.isLt) + rw [show f+1+5*(n+1) = (f+1+5*n)+5 by omega, write_one g pub s m rs z j bs, + ih _ _ (by simpa (config := {decide := true})) (i+1) (by omega)] + by_cases h : bs = [] <;> simp (config := {decide := true}) [h, events, LiveStageLink.prependLog, j] + exact congrArg (headerWord g (rs 0)) hj.symm + +/-- The initializer executes exactly one deterministic accepting history at every +sufficient instruction cap. -/ +theorem execute_init (g : ℕ) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bs : List Bool) (cap : ℕ) (budget : 42 ≤ cap) : + execute (initMachine g pub).program cap ((initMachine g pub).program.start s) m bs = + if bs = [] then some (initReport g (pub 2)) else none := by + obtain ⟨f,rfl⟩ : ∃ f, cap = (f+1+5*8)+1 := ⟨cap-42,by omega⟩ + rw [execute] + have hs : (initMachine g pub).program.step ((initMachine g pub).program.start s) = + .localStep ⟨next 0,s,Function.update (fun _ ↦ 0) 0 (pub 2),fun _ ↦ 0⟩ := rfl + simp only [hs] + let rs : Fin 4 → Word w := Function.update (fun _ ↦ 0) 0 (pub 2) + have hz : rs 3 = 0 := by simp (config := {decide := true}) [rs] + rw [init_tail g pub s m rs hz bs f 0 8 (by decide)] + by_cases h : bs = [] <;> simp [h, initReport, Report.prepend, rs] + +theorem initReport_cost (g : ℕ) (base : Word w) : + (initReport g base).events.length = 41 ∧ (initReport g base).probes = 8 ∧ + choiceBits (initReport g base).events = [] := ⟨rfl,rfl,rfl⟩ + +private theorem events_outside (g : ℕ) (base : Word w) (m : Memory w) (a i n : ℕ) + (h : ∀ t, i ≤ t → t < i+n → a ≠ (base+(t : Word w)).val) : + after m (events g base i n) a = m a := by + induction n generalizing i m with + | zero => rfl + | succ n ih => + change after (writeMemory m (base+(i : Word w)) _) (events g base (i+1) n) a = m a + rw [ih _ (i+1) (fun t h₁ h₂ ↦ h t (by omega) (by omega))] + simp [writeMemory, h i le_rfl (by omega)] + +theorem init_outside (g : ℕ) (base : Word w) (m : Memory w) (a : ℕ) + (h : ∀ i : Fin 8, a ≠ (base+(i.val : Word w)).val) : + after m (initReport g base).events a = m a := + events_outside g base m a 0 8 fun t _ ht ↦ h ⟨t, by omega⟩ + +private theorem address_ne (base : Word w) {i j : ℕ} + (hi : i < 2^w) (hj : j < 2^w) (hne : i ≠ j) : + (base+(i : Word w)).val ≠ (base+(j : Word w)).val := by + intro e + have hx : (i : Word w) = (j : Word w) := add_left_cancel (Fin.ext e) + have hv := congrArg Fin.val hx + simp only [Fin.val_natCast, Nat.mod_eq_of_lt hi, Nat.mod_eq_of_lt hj] at hv + exact hne hv + +private theorem events_at (g : ℕ) (base : Word w) (m : Memory w) (k : Fin 8) (i n : ℕ) + (lo : i ≤ k.val) (hi : k.val < i+n) (last : i+n = 8) (fit : 8 ≤ 2^w) : + after m (events g base i n) (base+(k.val : Word w)).val = headerWord g base k := by + induction n generalizing m i with + | zero => omega + | succ n ih => + change after (writeMemory m (base+(i : Word w)) _) (events g base (i+1) n) _ = _ + by_cases e : k.val = i + · subst i + rw [events_outside] + · simp [writeMemory] + · intro t h₁ h₂ + exact address_ne base (k.isLt.trans_le fit) (by omega) (by omega) + · exact ih _ (i+1) (by omega) (by omega) (by omega) + +/-- The eight contiguous installed words, including the two mutable control cells. -/ +theorem init_cell (g : ℕ) (base : Word w) (m : Memory w) (i : Fin 8) (fit : 8 ≤ 2^w) : + after m (initReport g base).events (base+(i.val : Word w)).val = headerWord g base i := + events_at g base m i 0 8 (by omega) i.isLt rfl fit + +/-- The scheduler sees the computed pointer bank on its very first call. -/ +theorem init_installed (g : ℕ) (base : Word w) (m : Memory w) (fit : 8 ≤ 2^w) : + Installed g base (after m (initReport g base).events) := by + funext i + exact (init_cell g base m (i.castLE (by decide)) fit).trans (headerWord_bank g base i) + +theorem init_controls (g : ℕ) (base : Word w) (m : Memory w) (fit : 8 ≤ 2^w) : + after m (initReport g base).events (ports g base).tag.val = 0 ∧ + after m (initReport g base).events (ports g base).ordinal.val = 0 := by + constructor + · simpa [ports, headerWord, offset] using init_cell g base m 6 fit + · simpa [ports, headerWord, offset] using init_cell g base m 7 fit + +theorem init_rowCount (g : ℕ) (base : Word w) (m : Memory w) (fit : 8 < 2^w) : + after m (initReport g base).events (ports g base).rows.val = m (ports g base).rows.val := by + apply init_outside + intro i + exact address_ne base (i := 8) fit (i.isLt.trans fit) (by have := i.isLt; omega) + +/-- Reuse of the header on later calls only requires that the six pointer cells +retain their values. The internal tag and ordinal may change on every row. -/ +theorem Installed.preserve {g : ℕ} {base : Word w} {m m' : Memory w} (h : Installed g base m) + (keep : ∀ i : Fin 6, m' (base+(i.val : Word w)).val = m (base+(i.val : Word w)).val) : + Installed g base m' := (funext keep : (Frame.data base m' : Fin 6 → Word w) = Frame.data base m).trans h + +/-- Consecutive native initialization and dispatch, using the memory left by the +initializer. The input row count and all precomputed directory entries may already +be present when initialization starts. -/ +theorem execute_initialized (pub : Fin 11 → Word w) (initState state : Word w) + (m : Memory w) (fit : 8 ≤ 2^w) (bits : List Bool) (cap : ℕ) : + let g := Schedule.arity C + let base := pub 2 + let setup := (initMachine g pub).program + let m' := after m (initReport g base).events + let W := ((table C).instantiate w pub).program + let S := (Schedule.machine C (Controller.table g) (ports g base)).program + execute setup 42 (setup.start initState) m [] = some (initReport g base) ∧ + execute W cap (W.start state) m' bits = + (execute S (cap-24) (S.start state) m' bits).map (report base m') := by + constructor + · exact execute_init (Schedule.arity C) pub initState m [] 42 le_rfl + · exact execute_dispatch C pub state _ bits cap (init_installed _ _ _ fit) + +/-- After installing the workspace, the online scheduler begins at the calendar +stage whose tag follows the `d` data-worker tags. -/ +def calendarStart (d : ℕ) : Template 6 3 11 where + literalWidth := Nat.clog 2 (d+8) + entry := 0 + code pc := match pc.val with + | 0 => .publicWord 0 2 1 + | 1 => .constant 1 (Fin.ofNat _ 6) 2 + | 2 => .binary .add 1 0 1 3 + | 3 => .constant 2 (Fin.ofNat _ (d+1)) 4 + | 4 => .writeExternal 1 2 5 + | _ => .accept + +/-- Accepting report for starting the calendar stage, with four private ticks and a write of +tag `d+1` at workspace offset six. -/ +def calendarReport (d : ℕ) (base : Word w) : Report w := + ⟨[.tick,.tick,.tick,.tick,.write (base+6) ((d+1 : ℕ) : Word w)],none⟩ + +theorem execute_calendarStart (d : ℕ) (pub : Fin 11 → Word w) (s : Word w) (m : Memory w) + (bits : List Bool) (cap : ℕ) (budget : 6 ≤ cap) : + let M := (calendarStart d).instantiate w pub + execute M.program cap (M.program.start s) m bits = + if bits = [] then some (calendarReport d (pub 2)) else none := by + obtain ⟨f,rfl⟩ : ∃ f, cap = f+6 := ⟨cap-6,by omega⟩ + let M := (calendarStart d).instantiate w pub + have fit := Nat.le_pow_clog (by decide : 1 < 2) (d+8) + have const₆ : M.code 1 = .constant 1 6 2 := by + change Instr.constant _ (Fin.ofNat (2^w) (6 % 2^Nat.clog 2 (d+8))) _ = _ + rw [Nat.mod_eq_of_lt (by omega)] + rfl + have constTag : M.code 3 = .constant 2 ((d+1 : ℕ) : Word w) 4 := by + change Instr.constant _ (Fin.ofNat (2^w) ((d+1) % 2^Nat.clog 2 (d+8))) _ = _ + rw [Nat.mod_eq_of_lt (by omega)] + rfl + have p0 : M.code 0 = .publicWord 0 2 1 := rfl + have p2 : M.code 2 = .binary .add 1 0 1 3 := rfl + have p4 : M.code 4 = .writeExternal 1 2 5 := rfl + have p5 : M.code 5 = .accept := rfl + change execute M.program (f+6) ⟨0,s,fun _ ↦ 0,fun _ ↦ 0⟩ m bits = _ + by_cases h : bits = [] <;> + simp (config := {decide := true}) [execute, Machine.program, p0, p2, p4, p5, + const₆, constTag, Instr.run, Config.put, BinaryOp.eval, h, calendarReport, Report.prepend, M] + rfl + +theorem calendar_effect (d g : ℕ) (base : Word w) (m : Memory w) : + after m (calendarReport d base).events = + writeMemory m (ports g base).tag ((d+1 : ℕ) : Word w) ∧ + (calendarReport d base).probes = 1 ∧ choiceBits (calendarReport d base).events = [] := ⟨rfl,rfl,rfl⟩ + +theorem calendar_installed (d g : ℕ) (base : Word w) (m : Memory w) + (h : Installed g base m) (fit : 6 < 2^w) : + Installed g base (after m (calendarReport d base).events) := by + apply h.preserve + intro i + rw [(calendar_effect d g base m).1] + have hi := i.isLt + change writeMemory m (base+(6 : Word w)) _ (base+(i.val : Word w)).val = _ + exact ite_eq_right (address_ne base (i := i.val) (j := 6) (by omega) fit (by omega)) + +end CompressorRecords.Workspace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshArgumentPlan.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshArgumentPlan.lean new file mode 100644 index 0000000000..8a2cff5409 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshArgumentPlan.lean @@ -0,0 +1,130 @@ +import OAI.Computability.VPVNP.CompressorRefreshOperandInputs +import OAI.Computability.VPVNP.CompressorRefreshLevelRecipe +import OAI.Computability.VPVNP.CompressorRecordRefreshResult + +/-! +# Constructing the refresh argument bank from level and traversal addresses + +The two node numbers, their common site ordinal, the private arena and the old inverse +column are traversal inputs. The segment and term heads and the next incidence columns +are evaluated from the same packed level plan used by the native refresh builder. Its +interval frame preserves the old incidence columns through the complete execution. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.OperandInputs + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh NewSlots PhaseRecipe SpectralGeometry +open PairSimulation.NodeArguments RefreshMapOperands + +/-- Expressions supplied by the traversal to locate the old and new node arguments at a shared +site ordinal. -/ +structure Traversal where + /-- Expression for the base address of the private node argument arena. -/ + arena : Expr + /-- Expression for the number of arena words reserved per node. -/ + stride : Expr + /-- Expression for the child node number indexing the old half of the refresh argument. -/ + child : Expr + /-- Expression for the parent node number indexing the refreshed half of the argument. -/ + parent : Expr + /-- Expression for the ordinal shared by the old site and its promoted site. -/ + site : Expr + /-- Expression for the base of the old actual incoming incidence column. -/ + oldIn : Expr + +/-- Builds the child and parent operand records from the traversal addresses and the scratch, +incidence, demand and term columns of the refresh level. -/ +def fromLevel (s : LevelRecipe.Shape) (L : LevelRecipe.Input) (J : Traversal) : Input := + let q := LevelRecipe.scratch s L + ⟨⟨J.arena,J.stride,J.child,J.site,J.oldIn,L.oldWidth⟩, + ⟨J.arena,J.stride,J.parent,J.site,LevelRecipe.column s L 4,LevelRecipe.column s L 5⟩, + L.lanes,q 5,q 6,q 1,q 7,LevelRecipe.demandStart s L,LevelRecipe.termStart s L⟩ + +variable {w g : ℕ} (s : LevelRecipe.Shape) (L : LevelRecipe.Input) (J : Traversal) (C : LevelRecipe.Context w) + (X : State s.a (s.a+g)) (p : (X.Base × BitWord g) × Fin (2^s.a)) + (P : SlotGraph (Fin (2^s.a)) s.dH) (hD : 1 < 2^s.a) (hd : s.dH+1 ≤ 2^s.a₀) + (internal : X.Base × BitWord g → Fin (2^s.a) × Fin s.dH → ℕ) + (A : Arena) (child parent start : ℕ) (T : IncidenceDirectory w) + +local notation "O" => sites (D := 2^s.a) X.baseIndex (bitWordFinEquiv g) +local notation "plan" => Allocation.plan X s.a₀ s.dH s.ties s.stride start +local notation "Y" => newState X P hD hd internal + +private theorem newSite_number : ArgumentAddress.siteOrdinal Y (promotedSites p) = (O p).val := by + rw [sites_val] + change (p.2.val + 2^s.a*(X.baseIndex p.1.1).val) * 2^g + (bitWordFinEquiv g p.1.2).val = _ + ring + +/-- The packed allocation supplies every numerical operand of the endpoint setup. -/ +theorem describes_fromLevel (level : LevelRecipe.Describes L C X start T) + (base : C.eval J.arena = word A.start) (stride : C.eval J.stride = word A.stride) + (oldNode : C.eval J.child = word child) (newNode : C.eval J.parent = word parent) + (site : (C.eval J.site).val = (O p).val) (oldIn : C.eval J.oldIn = T.actualIn) (lanes : 2^g < 2^w) : + Describes (fromLevel s L J) C.pub C.state C.memory X p P hD hd internal A child parent T ((plan).output w) + ((plan).scratch w) (word (plan).demand) (word (plan).term) := by + have heads := LevelRecipe.addresses L C X start T level + have hs : C.eval J.site = word (O p).val := Fin.ext (site.trans (Nat.mod_eq_of_lt (site ▸ (C.eval J.site).isLt)).symm) + have oldSite : ArgumentAddress.siteOrdinal X (oldSite X p) = (O p).val := ArgumentSite.oldSite_number X p + have newSite := newSite_number s X p P hD hd internal + exact ⟨⟨base,stride,oldNode,oldSite ▸ hs,oldIn,level.oldWidth_eq⟩, + ⟨base,stride,newNode,newSite ▸ hs,heads.column_eq 4,heads.column_eq 5⟩, + site,(congrArg Fin.val level.lanes_eq).trans (Nat.mod_eq_of_lt lanes), + heads.scratch_eq 5,heads.scratch_eq 6,heads.scratch_eq 1,heads.scratch_eq 7,heads.demand_eq,heads.term_eq⟩ + +/-- Every old incidence read survives the packed refresh. This applies both to the +private operand setup and to future descriptor traversals reaching this older level. -/ +theorem old_directory {a g w : ℕ} (X : State a (a+g)) (T : IncidenceDirectory w) (m m' : Memory w) + (rep : T.Represents X m) (start : ℕ) + (before : ∀ c : Fin 6, (T.column c).val + Fintype.card X.Base * 2^a * 2^g * 2^a ≤ start) + (unchanged : ∀ addr < start, m' addr = m addr) : T.Represents X m' := by + let capacity := Fintype.card X.Base * 2^a * 2^g * 2^a + have atColumn (c : Fin 6) (j : W w) (hj : j.val < capacity) : + m' (T.column c+j).val = m (T.column c+j).val := + unchanged _ (((Nat.mod_le ..).trans_lt (Nat.add_lt_add_left hj _)).trans_le (before c)) + have baseRoom : Fintype.card X.Base * 2^a ≤ capacity := by + apply (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g)).trans (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)) + have base (c : Fin 6) (e) := atColumn c (IncidenceDirectory.basePort X e) (by + rw [IncidenceDirectory.basePort_number] + exact (Nat.mod_le ..).trans_lt ((IncidenceDirectory.baseOrder X e).isLt.trans_le baseRoom)) + have total : Fintype.card X.Base*2^(a+g)*2^a = capacity := by dsimp [capacity]; rw [pow_add]; ring + have actual (c : Fin 6) (e) := atColumn c (IncidenceDirectory.actualPort X e) (by + rw [IncidenceDirectory.actualPort_number] + exact (Nat.mod_le ..).trans_lt (total ▸ (IncidenceDirectory.actualOrder X e).isLt)) + exact ⟨fun e => (base 0 e).trans (rep.baseOut e),fun e => (base 1 e).trans (rep.baseIn e), + fun e => (base 2 e).trans (rep.shift e),fun e => (actual 3 e).trans (rep.actualOut e), + fun e => (actual 4 e).trans (rep.actualIn e),fun e => (actual 5 e).trans (rep.width e)⟩ + +/-- Both incidence inputs and all stored fields for the native map and diagonal setups +are available together after the selected refresh level. -/ +theorem run_argument_data {k : Type*} [_root_.Field k] {K K' : ℝ} {a a₀ g dH bits t cap : ℕ} + (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) + (choice : DyadicRefreshChoice X E hdH conn F) (ties : Fin t ≃ Tie (2^a)) + (T : IncidenceDirectory bits) (start stride : ℕ) + {L : Allocation.PrepareLayout X T a₀ dH t stride start} {m : Memory bits} {rs : List (Report bits)} + (execution : Build.Run X E hdH conn F hD hd choice ties T start stride cap L m rs) + (old : T.Represents X m) + (before : ∀ c : Fin 6, (T.column c).val + Fintype.card X.Base*2^a*2^g*2^a ≤ start) + (wide : 2+2^a*dH ≤ stride) (room : (Allocation.plan X a₀ dH t stride start).stop < 2^bits) + (termBits : termConstant E hdH conn F ties + 4*Nat.clog 2 (X.maxWireWidth+1) ≤ bits) + (nextWidth : (dyadicRefreshNext X E hdH conn F hD hd choice).maxWireWidth < 2^bits) + (capFit : TermWorker.budget F t (2^a*dH) bits X.maxWireWidth ≤ cap) : + let final := after m (eventLog rs) + T.Represents X final ∧ + ((Allocation.plan X a₀ dH t stride start).output bits).Represents + (dyadicRefreshNext X E hdH conn F hD hd choice) final ∧ + Build.Stored X E hdH conn F choice ties start stride L.regions.fits final := by + obtain ⟨rep,stored,frame,_⟩ := Build.Run.result X E hdH conn F hD hd choice ties T start stride execution old + before wide room termBits nextWidth capFit + exact ⟨old_directory X T m _ old start before (fun a ha => frame a (Or.inl ha)),rep,stored⟩ + +end CompressorRecords.PortRefresh.OperandInputs + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshArgumentReads.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshArgumentReads.lean new file mode 100644 index 0000000000..d9df2770e2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshArgumentReads.lean @@ -0,0 +1,97 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshArgumentAddress +import OAI.Computability.VPVNP.CompressorFormulaFootprint + +/-! +# External reads of numbered half-wire addresses + +A field address is a sum of widths. For incoming slots the incidence directory +maps the destination slot to its original outgoing slot before the width is read. +Both passes stay inside their respective finite columns, for static and runtime slots. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.ArgumentAddress + +open BurstRAM Compression PairSimulation.NodeArguments PhaseRecipe +open scoped Fin.CommRing +open private eval_port from OAI.Computability.VPVNP.CompressorRecordRefreshArgumentAddress + +variable {a g w : ℕ} {pub : Fin 5 → Word w} {state : Word w} {m : Memory w} + {I : Input} {X : State a g} {u : X.network.Site} {T : IncidenceDirectory w} {A : Arena} + {node limit : ℕ} +local notation "ok" => Expr.ReadsFrom (· < limit) pub state m +local notation "ev" => Expr.eval pub state m +local notation "N" => Fintype.card X.Base * 2 ^ g * 2 ^ a + +/-- Requires every load used to evaluate the arena base, stride, node, site, incoming column +and width column to lie below the given limit. -/ +structure Readable (I : Input) (limit : ℕ) (pub : Fin 5 → Word w) (state : Word w) + (m : Memory w) : Prop where + arena : Expr.ReadsFrom (· < limit) pub state m I.arenaBase + stride : Expr.ReadsFrom (· < limit) pub state m I.stride + node : Expr.ReadsFrom (· < limit) pub state m I.node + site : Expr.ReadsFrom (· < limit) pub state m I.siteOrd + actualIn : Expr.ReadsFrom (· < limit) pub state m I.actualIn + width : Expr.ReadsFrom (· < limit) pub state m I.width + +private theorem port_below (col : Word w) (e : (X.Base × BitWord g) × Fin (2 ^ a)) + (room : col.val + N ≤ limit) : + (col + IncidenceDirectory.actualPort X e).val < limit := by + rw [IncidenceDirectory.actualPort_number] + exact (Nat.mod_le ..).trans_lt ((Nat.add_lt_add_left ((Nat.mod_le ..).trans_lt + (IncidenceDirectory.actualOrder X e).isLt) _).trans_le room) + +private theorem sum_reads {J : Type*} (xs : List J) (f : J → Expr) + (read : ∀ j, ok (f j)) : ok (sum (xs.map f)) := by + induction xs with + | nil => trivial + | cons i is ih => exact ⟨read i, ih⟩ + +variable (base : Readable I limit pub state m) (h : Represents pub state m I X u T A node) + (cols : T.ActualColumns X m) + (inRoom : T.actualIn.val + Fintype.card X.Base * 2 ^ g * 2 ^ a ≤ limit) + (widthRoom : T.width.val + Fintype.card X.Base * 2 ^ g * 2 ^ a ≤ limit) + +include base h cols inRoom widthRoom in +private theorem half_reads (incoming : Bool) (i : Fin (2 ^ a)) : ok (I.half incoming i) := by + have slot : ok (I.port i) := ⟨⟨base.site, trivial⟩, trivial⟩ + have idx := eval_port h i + cases incoming with + | false => + refine ⟨⟨base.width, slot⟩, ?_⟩ + change (ev I.width + ev (I.port i)).val < limit + rw [h.width, idx]; exact port_below _ _ widthRoom + | true => + refine ⟨⟨base.width, ⟨⟨base.actualIn, slot⟩, ?_⟩⟩, ?_⟩ + · change (ev I.actualIn + ev (I.port i)).val < limit + rw [h.actualIn, idx]; exact port_below _ _ inRoom + · change (ev I.width + m (ev I.actualIn + ev (I.port i)).val).val < limit + rw [h.width, h.actualIn, idx, cols.actualIn]; exact port_below _ _ widthRoom + +include base h cols inRoom widthRoom in +private theorem outgoing_reads (incoming : Bool) : ok (outgoing (2 ^ a) I incoming) := by + cases incoming with + | false => trivial + | true => exact sum_reads _ _ (half_reads base h cols inRoom widthRoom false) + +include base h cols inRoom widthRoom in +theorem field_reads_below (incoming : Bool) (j : Expr) + (index : ok j) : ok (field (2 ^ a) I incoming j) := by + have earlier (i : Fin (2 ^ a)) : ok (before j i) := ⟨trivial, trivial, ⟨index, trivial⟩, trivial⟩ + exact ⟨⟨base.arena, base.node, base.stride⟩, outgoing_reads base h cols inRoom widthRoom incoming, + sum_reads _ _ (fun i => ⟨earlier i, half_reads base h cols inRoom widthRoom incoming i⟩)⟩ + +include base h cols inRoom widthRoom in +theorem fieldStatic_reads_below (incoming : Bool) + (j : Fin (2 ^ a)) : ok (fieldStatic I incoming j) := + ⟨⟨base.arena, base.node, base.stride⟩, outgoing_reads base h cols inRoom widthRoom incoming, + sum_reads _ _ (half_reads base h cols inRoom widthRoom incoming)⟩ + +end CompressorRecords.PortRefresh.ArgumentAddress + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshBeforeGroup.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshBeforeGroup.lean new file mode 100644 index 0000000000..66f827fb55 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshBeforeGroup.lean @@ -0,0 +1,203 @@ +import OAI.Computability.VPVNP.CompressorRefreshHeaderGroup +import OAI.Computability.VPVNP.CompressorRefreshPrepareGroup +import OAI.Computability.VPVNP.CompressorPublishedHeadWindows +import OAI.Computability.VPVNP.CompressorDefaultSelection +import OAI.Computability.VPVNP.CompressorDeterministicGroup + +/-! +# From a current graph boundary to the native refresh selector + +The three header publishers and the full demand preparation are one quiet +interval. The header reports are independent of the mathematical term. +At its final memory the physical selector sees the original block demands. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +set_option quotPrecheck false + +namespace CompressorRecords.RefreshBefore + +open BurstRAM BlockPlanner Schedule DescriptorSpace Compression +open BlockHeaderRun SourceOnline SourceTransport PairSimulation.LocalHistory +open PortRefresh PortRefresh.LevelRecipe +open scoped Fin.CommRing +open private publisherCounts from OAI.Computability.VPVNP.CompressorScheduledGreedyRates + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) +variable {w g : ℕ} (base : Word w) (positions blocks t : ℕ) (X : State S.portExponent + (S.portExponent + g)) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "fl" => Script.levelsPerBlock scr * t +local notation "cur" => fl + S.steps +local notation "nxt" => fl + (S.steps + 1) +local notation "start" => arrayBase L cur +local notation "T" => packedIncidence L w cur (X.positions * 2 ^ S.portExponent) +local notation "role" => Scalars.Pass.refresh S.portExponent (S.degreeExponent 0) S.expanderExponent +local notation "origin" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "c₀" => defaultSelection origin +local notation "v" => RefreshPlacement.selectedLevel B f hf X c₀ [] +local notation "hwin" => RefreshHeaders.window B +local notation "pwin" => RefreshPrepare.window B +local notation "offset" => (scr).initial.length + t * (scr).block.length + (hwin).before.length +local notation "log" => (fun xs : List (Packet scr w) ↦ xs.flatMap SourceWalk.Packet.reports) +local notation "P" => PortRefresh.Allocation.plan X (S.degreeExponent 0) + (RefreshBlockPlan.shape B).dH + (RefreshBlockPlan.shape B).ties (RefreshBlockPlan.shape B).stride start + +private theorem reports_charge (V : SelectedLevel B f hf) (K : Layout) (m : Memory w) (a b : ℕ) : + RAMBuckets.cost Report.probes (reports V K a b m) = ScheduledRates.headerRate K.shape + (Scalars.ofOrigin V.origin) := by + have x := publisherCounts (inputRow V) (scalarPorts (header w K a)) (header w K a) m + have y := publisherCounts (outputRow V) (scalarPorts (header w K b)) (header w K a) + (inputMemory V K a m) + have z := publisherCounts (DescriptorHeads.publisher K.shape) + (headPorts (header w K b) (header w K 0)) 0 (outputMemory V K a b m) + change (1 + _) + ((1 + _) + ((1 + _) + 0)) = _ + simp only [scalarReport,headReport] + rw [x.2.1,y.2.1,z.2.1] + exact (by simp only [ScheduledRates.headerRate,inputRow,outputRow,Nat.add_assoc,Nat.add_zero]) + +theorem header_charge (m : Memory w) (a b : ℕ) : + RAMBuckets.cost Report.probes (reports v L a b m) = ScheduledRates.headerRate + (BlockProgram.geometry B) role := + reports_charge B f hf v L m a b + +theorem header_choice_independent (c : Compression.Refresh.DyadicRefreshChoice X S.graph + (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) (m : Memory w) + (a b : ℕ) : + reports (RefreshPlacement.selectedLevel B f hf X c sel) L a b m = reports v L a b m := rfl + +/-- Certifies the consecutive header and preparation packet groups before the refresh core, +including their reports, preserved incidence and traversal headers, quiet choices and exact +probe charge. -/ +structure Before (cap : ℕ) (m : Memory w) (hs ds : List (Packet scr w)) : Prop where + group : SourceOnline.Group scr L base cap offset (directoryRows L) m (hs ++ ds) + phases : (hs ++ ds).map (fun q ↦ q.stage.phase) = (hwin).indices ++ (pwin).indices + headerReports : log hs = reports v L cur nxt m + oldLive : cur < (L).levels + newLive : nxt < (L).levels + headerRun : Substep v L ⟨cur,oldLive⟩ ⟨nxt,newLive⟩ (by change 6 ≤ 54; decide) m + counts : LevelFields.Published L cur v (Scalars.ofOrigin (v).origin).expanderDegree (post m hs) + inputHeader : RefreshCore.Header (Fintype.card X.Base) g (levelStart L cur) start T (post m hs) + represented : (T).Represents X (post m hs) + atOldHeads : TraversalHeaders.HeadBank L cur (v).oldSlots (post m hs) + atNewHeads : TraversalHeaders.HeadBank L nxt (v).outputSlots (post m hs) + headerPitch : post m hs ((pt).directory - 1).val = (levelWords L : Word w) + headerRows : post m hs (pt).rows.val = (directoryRows L : Word w) + data : RefreshPrepare.Prepared B base positions blocks t X (post m hs) (log ds) + header : RefreshCore.Header (Fintype.card X.Base) g (levelStart L cur) start T (post m (hs ++ ds)) + oldHeads : TraversalHeaders.HeadBank L cur (v).oldSlots (post m (hs ++ ds)) + newHeads : TraversalHeaders.HeadBank L nxt (v).outputSlots (post m (hs ++ ds)) + pitch : post m (hs ++ ds) ((pt).directory - 1).val = (levelWords L : Word w) + rows : post m (hs ++ ds) (pt).rows.val = (directoryRows L : Word w) + quiet : ∀ p ∈ hs ++ ds, p.stage.choices = List.replicate p.stage.choices.length [] + charge : RAMBuckets.cost Report.probes (log (hs ++ ds)) = + ScheduledRates.headerRate (BlockProgram.geometry B) role + (6 * (P).sites + 12 * + (P).segments + 3 * (P).blocks * (RefreshBlockPlan.shape B).ties) + +private theorem next_window : + (hwin).before.length + 3 = (pwin).before.length := by + change (BlockGroups.refresh B 0).before.length + 3 = (BlockGroups.refresh B 1).before.length + rw [BlockGroups.refresh_offset,BlockGroups.refresh_offset] + rfl + +set_option maxHeartbeats 900000 in +-- The two packet groups share dependent representations of the old and successor headers. +theorem run (termCap cap : ℕ) (m : Memory w) (n : ℕ) (ht : t < blocks) (size : X.positions ≤ + positions) + (fit : endAddress L < 2 ^ w) (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory - 1).val = (levelWords L : Word w)) + (headerClock : scanCap scr (ScheduledRates.headerCap (BlockProgram.geometry B) role) ≤ cap) + (termClock : scanCap scr (max 64 termCap) ≤ cap) (current : CurrentGraph.Current L cur X n m) + (sites : X.positions < 2 ^ w) (degree : slotDegree S < 2 ^ w) + (width : 2 ^ S.portExponent * X.maxWireWidth < 2 ^ w) (pos : 0 < termCap) : + ∃ hs ds, Before B f hf base positions blocks t X cap m hs ds := by + obtain ⟨oi,ni,hs,old,new,hgroup,hlabels,hl,quiet,hsub,rep,oldBank,newBank⟩ := + RefreshHeaders.install B f hf base positions blocks t X c₀ [] m n cap ht size fit rows pitch + headerClock + current sites degree + let mid := post m hs + have hm : mid = finalMemory v L oi ni m := by + change after m (eventLog (hs.flatMap SourceWalk.Packet.reports)) = _ + rw [hl,reports_after] + have Hfit := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + have low := Window.lowCells (A := scr) L base rfl rfl Hfit + have oLe := levelStart_mono L (Nat.zero_le oi.val) + have nLe := levelStart_mono L (Nat.zero_le ni.val) + have lowEq (a : ℕ) (ha : a < levelStart L 0) : mid a = m a := by + rw [hm] + exact hsub.outside a (.inl (ha.trans_le oLe)) (.inl (ha.trans_le nLe)) (.inl (by omega)) + have mr := (lowEq _ low.1).trans rows + have mp := (lowEq _ low.2).trans pitch + have curr : LevelFields.Published L cur v (Scalars.ofOrigin (v).origin).expanderDegree mid := by + rw [← old,hm]; exact hsub.input + rw [old] at rep oldBank + rw [new] at newBank + have hr := PublishedHeads.level_room B base positions blocks t S.steps ht le_rfl fit + have head : RefreshCore.Header (Fintype.card X.Base) g (levelStart L cur) start T mid := + RefreshCore.Header.ofPublished curr oldBank rfl (by change 0 < 6; decide) (by omega) + obtain ⟨ds,dgroup,dlabels,prep⟩ := RefreshPrepare.install B base positions blocks t X termCap + cap mid + ht size fit mr mp termClock head rep width pos + have hlen : hs.length = 3 := by + have card : (hwin).indices.length = 3 := by + rw [Window.indices,List.length_ofFn] + exact BlockHeaderPlan.substep_length .. + exact (List.length_map _).symm.trans ((congrArg List.length hlabels).trans card) + have offsetEq : offset + hs.length = (scr).initial.length + t * (scr).block.length + + (pwin).before.length := by + rw [hlen,Nat.add_assoc,next_window] + have both := hgroup.append (offsetEq.symm ▸ dgroup) + have dataMem : post m (hs ++ ds) = after mid (eventLog (log ds)) := post_append .. + have span : levelStart L cur + 66 ≤ start := by + change _ ≤ levelStart L cur + 66 + 6 * slotCapacity L; omega + have endOf := (BlockLevelFit.refresh B base.val positions blocks oi rfl X size fit).1.next + rw [old] at endOf + change (PortRefresh.Allocation.plan X (S.degreeExponent 0) (RefreshBlockPlan.shape B).dH + (RefreshBlockPlan.shape B).ties (RefreshBlockPlan.shape B).stride (start + 0 * tableWords + L)).stop ≤ + levelStart L (cur + 1) at endOf + simp only [Nat.zero_mul,Nat.add_zero,show cur + 1 = nxt by omega] at endOf + have keep (a : ℕ) (away : a < start ∨ levelStart L nxt ≤ a) : post m (hs ++ ds) a = mid a := by + rw [dataMem] + exact after_outside mid prep.writes (by + intro hit + change start ≤ a ∧ a < (P).stop at hit + omega) + have lower := levelStart_mono L (Nat.zero_le (cur)) + have hhead := head.keep (fun i hi ↦ keep _ (.inl (by omega))) + have ho := oldBank.keep (m' := post m (hs ++ ds)) (fun i hi ↦ keep _ (.inl + (by change i < 66 at hi; omega))) + have hn := newBank.keep (m' := post m (hs ++ ds)) (fun i _ ↦ keep _ (.inr (Nat.le_add_right ..))) + have paths : (hs ++ ds).flatMap (fun p ↦ p.stage.choices) = List.replicate (3 + + (log ds).length) [] := by + rw [PublishedHeads.chronological_tapes m _ both.chronological,List.flatMap_append,hl, + branchPaths, + List.map_append,← branchPaths,← branchPaths,quiet,prep.quiet,List.replicate_add] + rfl + have ol : cur < (L).levels := old ▸ oi.isLt + have nl : nxt < (L).levels := new ▸ ni.isLt + have so : oi = (⟨cur,ol⟩ : Fin (L).levels) := Fin.ext old + have sn : ni = (⟨nxt,nl⟩ : Fin (L).levels) := Fin.ext new + refine ⟨hs,ds,both,by rw [List.map_append,hlabels,dlabels],old ▸ new ▸ hl,ol,nl,so ▸ sn ▸ hsub, + curr,head,rep,oldBank,newBank,mp,mr,prep,hhead,ho,hn, + (keep _ (.inl (by omega))).trans mp,(keep _ (.inl (by omega))).trans mr, + ScheduledTrace.packet_quiet_of_flat paths,?_⟩ + change RAMBuckets.cost Report.probes ((hs ++ ds).flatMap SourceWalk.Packet.reports) = _ + rw [List.flatMap_append,hl,RAMBuckets.cost_append,header_charge,prep.charge] + +end CompressorRecords.RefreshBefore + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshBeforeMatch.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshBeforeMatch.lean new file mode 100644 index 0000000000..edb1ebcff6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshBeforeMatch.lean @@ -0,0 +1,129 @@ +import OAI.Computability.VPVNP.CompressorRefreshBeforeGroup +import OAI.Computability.VPVNP.CompressorRecordRefreshDeterminism + +/-! +# Aligning the deterministic prefix with every selected refresh + +The pre - selection reports depend only on the current graph. Thus the +canonical prefix reaches the identical data memory used by every +selected branch, at the selector's actual ordinal in the repeated block. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +set_option quotPrecheck false + +namespace CompressorRecords.RefreshBefore + +open BurstRAM BlockPlanner Schedule DescriptorSpace Compression +open BlockHeaderRun SourceOnline SourceTransport PairSimulation.LocalHistory +open PortRefresh PortRefresh.LevelRecipe PortRefresh.NewSlots +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable {B : S.Templates} {f : B.Entry → R} {hf : B.IsSolution f} +variable {w g : ℕ} {base : Word w} {positions blocks t : ℕ} {X : State S.portExponent + (S.portExponent + g)} +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "fl" => Script.levelsPerBlock scr * t +local notation "cur" => fl + S.steps +local notation "nxt" => fl + (S.steps + 1) +local notation "start" => arrayBase L cur +local notation "T" => packedIncidence L w cur (X.positions * 2 ^ S.portExponent) +local notation "s₀" => RefreshBlockPlan.shape B +local notation "P" => PortRefresh.Allocation.plan X (S.degreeExponent 0) (s₀).dH (s₀).ties + (s₀).stride start +local notation "ties" => RefreshBlockPlan.order B +local notation "origin" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "v" => RefreshPlacement.selectedLevel B f hf X (defaultSelection origin) [] +local notation "hwin" => RefreshHeaders.window B +local notation "pwin" => RefreshPrepare.window B +local notation "offset" => (scr).initial.length + t * (scr).block.length + (hwin).before.length +local notation "log" => (fun xs : List (Packet scr w) ↦ xs.flatMap SourceWalk.Packet.reports) + +variable {cap : ℕ} {m : Memory w} {hs ds : List (Packet (BlockProgram.script B) w)} +variable (b : Before B f hf base positions blocks t X cap m hs ds) + +theorem Before.start_offset : + (hwin).before.length = ((List.finRange S.steps).flatMap (BlockProgram.shrink B)).length := by + change (BlockGroups.refresh B 0).before.length = _ + rw [BlockGroups.refresh_offset] + simp + +include b in +theorem Before.length : (hs ++ ds).length = 6 + (s₀).ties := by + have hh : (hwin).indices.length = 3 := by + rw [Window.indices,List.length_ofFn] + exact BlockHeaderPlan.substep_length .. + have dd : (pwin).indices.length = 3 + (s₀).ties := by + rw [Window.indices,List.length_ofFn,List.length_map] + simp only [RefreshPrepare.stages,List.length_map,List.length_append,List.length_cons, + List.length_nil,List.length_finRange] + calc + (hs ++ ds).length = ((hwin).indices ++ (pwin).indices).length := + (List.length_map _).symm.trans (congrArg List.length b.phases) + _ = 3 + (3 + (s₀).ties) := (List.length_append ..).trans (congrArg₂ Nat.add hh dd) + _ = 6 + (s₀).ties := by omega + +include b in +theorem Before.selector_offset : + offset + (hs ++ ds).length = + (scr).initial.length + t * (scr).block.length + (BlockIndex.blockRefresh B).index.val := by + rw [b.length,Before.start_offset,BlockIndex.block_refresh_offset] + omega + +include b in +theorem Before.headers_eq (c : Compression.Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) : + post m hs = finalMemory (RefreshPlacement.selectedLevel B f hf X c sel) L cur nxt m := by + calc + post m hs = after m (eventLog (reports v L cur nxt m)) := + congrArg (fun rs : List (Report w) ↦ after m (eventLog rs)) b.headerReports + _ = finalMemory v L cur nxt m := reports_after .. + _ = _ := rfl + +include b in +theorem Before.matches (c : Compression.Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) {rs : List + (Report w)} + {out : Memory w} {fit : (P).segments ≤ 2 ^ w} + (other : PrepareRun X T ((P).scratch w) (word (P).demand) ties (word (2 ^ g)) fit + (finalMemory (RefreshPlacement.selectedLevel B f hf X c sel) L cur nxt m) out rs) : + log ds = rs ∧ post m (hs ++ ds) = out := by + rw [← b.headers_eq c sel] at other + rw [post_append] + exact PrepareRun.deterministic b.data.run other + +include b in +/-- The header fields depend on the input dimensions, which are shared by all terms. -/ +theorem Before.counts_for + (c : Compression.Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) : + let u := RefreshPlacement.selectedLevel B f hf X c sel + LevelFields.Published L cur u (Scalars.ofOrigin u.origin).expanderDegree (post m hs) := + ⟨b.counts.room,b.counts.vertices,b.counts.degree,b.counts.lanes,b.counts.residual, + b.counts.nextDegree,b.counts.expander⟩ + +/-- The same three native publishers certify every selected successor's header. -/ +theorem Before.header_for + (c : Compression.Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) : + let u := RefreshPlacement.selectedLevel B f hf X c sel + Substep u L ⟨cur,b.oldLive⟩ ⟨nxt,b.newLive⟩ (by change 6 ≤ 54; decide) m := by + intro u + have published := b.counts_for c sel + rw [b.headers_eq c sel] at published + exact ⟨b.headerRun.relabel,b.headerRun.advance,b.headerRun.heads,published, + b.headerRun.output,b.headerRun.firstCounts,b.headerRun.outside⟩ + +end CompressorRecords.RefreshBefore + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshBeforeSelector.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshBeforeSelector.lean new file mode 100644 index 0000000000..53ba2978af --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshBeforeSelector.lean @@ -0,0 +1,101 @@ +import OAI.Computability.VPVNP.CompressorRefreshVerifiedStages +import OAI.Computability.VPVNP.CompressorRecordRefreshResult + +/-! +# Choice-independent native refresh preparation + +Before the motif selector runs, the gather, bundle and offset workers and all +ordered demand workers already determine their report sequences. Their only +numerical width requirement is that the sum of the old port widths fits a word. +The post-memory contains the exact demand at every block of the current graph. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.PortRefresh.Scheduled +open BurstRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry +open LevelRecipe NewSlots Allocation SourceTransport +open private lift_bounds from OAI.Computability.VPVNP.CompressorRefreshVerifiedStages +open private prepare_memory from OAI.Computability.VPVNP.CompressorRecordRefreshBuild + +variable {w a a₀ g dH t : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') (hd : dH+1 ≤ 2^a₀) + (ties : Fin t ≃ Tie (2^a)) (old : IncidenceDirectory w) (start stride : ℕ) +local notation "P" => plan X a₀ dH t stride start +local notation "Q" => Plan.scratch P w +local notation "S₀" => shape (t := t) E hdH conn F stride +local notation "J" => Stage S₀ +local notation "D" => word (bits := w) (Plan.demand P) +local notation "Lₙ" => word (bits := w) (2^g) +local notation "term" => TermWorker.motifPass F ties (2^a*dH) +local notation "termData" => TermWorker.motifData F ties finProdFinEquiv.symm w +local notation "checks" => StageBounds (t := t) X E hdH conn F start stride + +/-- The fixed deterministic worker, initialized from the current public bank, before any choice tape. -/ +def PreSource (cap : ℕ) (j : J) (m : Memory w) (rs : List (Report w)) : Prop := + let data := fun z ↦ j.nativeBank hd E ties X start old termData (Fin.cast (j.worker_params hd term) z) + let M := ((j.worker hd term).table.instantiate w data).program + runSegment M (fuel hd cap j) (some (word j.first)) m (List.replicate (j.limit X start-j.first) []) = some rs + +local notation "src" => PreSource X E hdH conn F hd ties old start stride + +private theorem pre_demands (low cap : ℕ) (lo : low ≤ start) (room : (P).stop < 2^w) + {js : List (Fin t)} {m : Memory w} {rs : List (Report w)} + (h : DemandScan.Runs (DemandScan.words (r := 2^g) ties Q D) (P).blocks js m rs) : + SourceWalk (fun j mem logs ↦ src cap j mem logs ∧ checks low j mem logs) (js.map Stage.demand) m rs := by + induction h with + | nil => exact .done _ + | cons i run _ ih => + have s := TermDataFrame.demand_trace X a₀ dH stride start ties room i _ _ run + exact .next ⟨run,lift_bounds s (fun _ h ↦ lo.trans h.1) (fun _ h ↦ h)⟩ ih + +/-- Prepare the actual numerical selector input without a selected term. Each raw +worker comes with its physical bank, ordinal guard, reads above `low`, and writes +only within this level. The report list and demand post-memory are the same ones +used by `Build.Run` and its reverse enumeration. -/ +theorem prepare_verified (low cap : ℕ) (L : PrepareLayout X old a₀ dH t stride start) + (m : Memory w) (rep : old.Represents X m) (above : ∀ j, low ≤ (old.column j).val) + (before : ∀ j, (old.column j).val+(P).segments ≤ start) (room : (P).stop < 2^w) + (totalFit : 2^a*X.maxWireWidth < 2^w) : + ∃ pre : List (Report w), let post := after m (eventLog pre) + SourceWalk (fun j mem logs ↦ src cap j mem logs ∧ checks low j mem logs) + ([.gather,.bundles,.offsets] ++ (List.finRange t).map Stage.demand) m pre ∧ + PrepareRun X old Q D ties Lₙ L.regions.fits m post pre ∧ SegmentFields X Q L.regions.fits post ∧ + (∀ s, DemandPreparation.demandAt ties (DemandScan.rowBase X t D s) post = + blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) s) ∧ + (∀ x, outsideLevel Q (P).segments x → (x < (D).val ∨ (D).val+(P).blocks*t ≤ x) → post x = m x) ∧ + RAMBuckets.cost Report.probes pre = 6*(P).sites+12*(P).segments+3*(P).blocks*t := by + have widths b := (Build.bundle_total_le_max X b).trans_lt totalFit + obtain ⟨pre,post,pr,sg,dem,frame,cost⟩ := prepare_demands X old Q D ties m rep Lₙ L.degree L.lanes + L.regions L.directory L.gather L.baseApart widths L.demandRoom L.demandApart + have hp := prepare_memory X ties old pr + subst post + refine ⟨pre,?_,pr,sg,dem,frame,cost⟩ + obtain ⟨rg,rd,re,ds,ext,runs,_,rfl⟩ := pr + have h := FrontFrame.external_scans X old a₀ dH t stride start before room widths m rep rg rd re L.regions.fits ext + have lo := (above 0).trans ((Nat.le_add_right ..).trans (before 0)) + have oldRead (x) (cell : FrontFrame.OldCell old (P).segments x) : low ≤ x := by + obtain ⟨j,hj,_⟩ := cell + exact (above j).trans hj + have arenaRead (x) (cell : TermDataFrame.InArena P x) := lo.trans cell.1 + have ⟨hg,hb,he,_⟩ := ext + have first : SourceWalk (fun j mem logs ↦ src cap j mem logs ∧ checks low j mem logs) [.gather,.bundles,.offsets] + m (rg++rd++re) := by + rw [List.append_assoc] + exact .next ⟨hg,lift_bounds h.1 oldRead (fun _ h ↦ h)⟩ (.next ⟨hb,lift_bounds h.2.1 oldRead (fun _ h ↦ h)⟩ + (.singleton ⟨he,lift_bounds h.2.2 arenaRead (fun _ h ↦ h)⟩)) + have demandWalk := pre_demands X E hdH conn F hd ties old start stride low cap lo room runs + exact first.append (by simpa only [SourceWalk.after_append] using demandWalk) + +end CompressorRecords.PortRefresh.Scheduled + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshBlockPlan.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshBlockPlan.lean new file mode 100644 index 0000000000..669c17c906 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshBlockPlan.lean @@ -0,0 +1,91 @@ +import OAI.Computability.VPVNP.CompressorBlockHeaderPlan +import OAI.Computability.VPVNP.CompressorRefreshLevelRecipe + +/-! +# The degree-refresh phase list of a fixed compressor block + +All phases share the same runtime input and allocation formulas. The +finite graph fixes each ROM pair and each local expander slot in the +program text. Six final scans copy the verified output columns to the +published incidence heads for the next level. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshBlockPlan + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh +open PhaseRecipe BlockPlanner DescriptorSpace LevelFields +open PortRefresh LevelRecipe + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Computes the refresh dimensions from the block schedule and template, including the tie +count, term-record stride and selector width. -/ +def shape : LevelRecipe.Shape := + ⟨S.portExponent,S.degreeExponent 0,2^S.expanderExponent,Fintype.card (Tie (2^S.portExponent)), + 2+(2^S.portExponent)*(2^S.expanderExponent),B.refresh.selectorBits⟩ + +/-- Numbers the ties between refresh ports in the order used by the block's motif worker. -/ +def order : Fin (shape B).ties ≃ Tie (shape B).ports := (Fintype.equivFin _).symm + +/-- Reads the arena start, vertex and residual-lane counts, and old incidence heads from the +specified descriptor level. -/ +def input (F : DescriptorSpace.Shape) (step : ℕ) (arena : Fin F.tables) : LevelRecipe.Input := + ⟨table F step arena,vertices step,residualLanes step,incidence F step 0,incidence F step + 2,incidence F step 5⟩ + +/-- The motif worker pass for this template, using the block's tie ordering and one payload +entry per directed expander incidence. -/ +abbrev term := TermWorker.motifPass B.refresh (order B) ((shape B).ports*(shape B).dH) + +/-- Compiles a refresh stage to its worker visit with the corresponding cursor interval and +operand expressions. -/ +def stage (I : LevelRecipe.Input) (j : LevelRecipe.Stage (shape B)) : Visit := + ⟨j.worker S.degree_bounds.2 (term B), j.initial, j.stop I, + j.workerBank I S.degree_bounds.2 S.graph (order B) (term B) + (TermWorker.motifExprs B.refresh (order B) finProdFinEquiv.symm)⟩ + +/-- Computes the copy length for a refreshed incidence column, counting base slots for columns +zero through two and actual slots for columns three through five. -/ +def columnCount (I : LevelRecipe.Input) (c : Fin 6) : Expr := + if c.val < 3 then (I.vertices.mul (.lit (shape B).ports)).mul (.lit (shape B).degree) + else capacity (shape B) I + +/-- Copies one incidence column from the refresh allocation to its assigned column at the next +descriptor level. -/ +def copyColumn (F : DescriptorSpace.Shape) (step : ℕ) (I : LevelRecipe.Input) (c : Fin 6) : Visit := + BlockPlanner.copy (columnCount B I c) (column (shape B) I c) (incidence F (step+1) c) + +/-- The native refresh worker visits in execution order followed by the six incidence-column +copies. -/ +def visits (F : DescriptorSpace.Shape) (step : ℕ) (arena : Fin F.tables) : List Visit := + let I := input F step arena + (LevelRecipe.order (shape B)).map (stage B I) ++ List.ofFn (copyColumn B F step I) + +theorem visits_length (F : DescriptorSpace.Shape) (step : ℕ) (arena : Fin F.tables) : + (visits B F step arena).length = 12+(shape B).ties+(shape B).ports*(shape B).dH+(shape + B).degree := by + simp [visits,LevelRecipe.order]; omega + +theorem stage_worker (I : LevelRecipe.Input) (j : LevelRecipe.Stage (shape B)) : + (stage B I j).worker = j.worker S.degree_bounds.2 (term B) := rfl + +/-- The native worker bank is exactly the bank for which the refresh recipe +proves pointwise agreement with the semantic stage's operands. -/ +theorem stage_params (I : LevelRecipe.Input) (j : LevelRecipe.Stage (shape B)) : + (stage B I j).params = + j.workerBank I S.degree_bounds.2 S.graph (order B) (term B) + (TermWorker.motifExprs B.refresh (order B) finProdFinEquiv.symm) := rfl + +end CompressorRecords.RefreshBlockPlan + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshCopyGeometry.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshCopyGeometry.lean new file mode 100644 index 0000000000..f914f87fe6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshCopyGeometry.lean @@ -0,0 +1,151 @@ +import OAI.Computability.VPVNP.CompressorShrinkSlotFootprint + +/-! +# Packed copy geometry for a selected degree refresh + +The scratch columns and canonical successor columns use the full number of +output slots as their common stride. Only the populated prefix of each +column participates in the copy. The first three prefixes end after the +base ports, and the last three include all residual lanes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.CopyGeometry + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry +open DescriptorSpace CopyIncidence + +/-- The output allocation and the canonical successor have the same +column stride, and the scratch output fits before the successor arrays. -/ +structure Packed {b l : ℕ} (Y : State b l) (P : Allocation.Plan) (L : Layout) + (level : Fin L.levels) (w : ℕ) : Prop where + slots : Y.positions * 2^b = P.capacity + capacity : Y.positions * 2^b ≤ slotCapacity L + apart : P.stop ≤ incidenceStart L level + fit : endAddress L < 2^w + lower : levelStart L 0 ≤ P.next + +namespace Packed + +variable {b l w : ℕ} {Y : State b l} {P : Allocation.Plan} {L : Layout} {level : Fin L.levels} +variable (G : Packed Y P L level w) +local notation "N" => Y.positions * 2^b +local notation "T" => P.output w +local notation "U" => packedIncidence L w level N + +private theorem column_end (c : Fin 6) (stride : ℕ) : c.val*stride + stride ≤ 6*stride := by + simpa only [Nat.succ_mul] using Nat.mul_le_mul_right stride c.isLt + +include G + +private theorem destRoom : incidenceStart L level + 6*N < 2^w := + packed_incidence_room L G.fit level G.capacity + +private theorem scratchRoom : P.stop < 2^w := + G.apart.trans_lt ((Nat.le_add_right _ _).trans_lt G.destRoom) + +theorem sourceHead (c : Fin 6) : ((T).column c).val = P.next+c.val*P.capacity := by + rw [P.output_column] + have bound := column_end c P.capacity + have room : P.next+6*P.capacity < 2^w := G.scratchRoom + exact Nat.mod_eq_of_lt (by omega) + +theorem destinationHead (c : Fin 6) : ((U).column c).val = incidenceStart L level+c.val*N := by + rw [packed_column] + have bound := column_end c N + have room := G.destRoom + exact Nat.mod_eq_of_lt (by unfold incidenceBase; omega) + +private theorem source_end (c : Fin 6) : ((T).column c).val + rows Y c ≤ P.stop := by + rw [G.sourceHead] + have count := (rows_le_slots Y c).trans_eq G.slots + have bound := column_end c P.capacity + unfold Allocation.Plan.stop + omega + +private theorem destination_end (c : Fin 6) : + ((U).column c).val + rows Y c ≤ incidenceStart L level + 6*N := by + rw [G.destinationHead] + have count := rows_le_slots Y c + have bound := column_end c N + omega + +theorem roomT (c : Fin 6) : ((T).column c).val + rows Y c ≤ 2^w := + (G.source_end c).trans G.scratchRoom.le + +theorem roomU (c : Fin 6) : ((U).column c).val + rows Y c ≤ 2^w := + (G.destination_end c).trans G.destRoom.le + +theorem rowsFit (c : Fin 6) : rows Y c < 2^w := + (Nat.le_add_left ..).trans_lt ((G.destination_end c).trans_lt G.destRoom) + +theorem regions : Regions Y T U := + Regions.refresh_to_level Y P L level G.scratchRoom.le G.fit G.slots.le G.capacity (Or.inl G.apart) + +/-- Natural intervals of all live source and destination cells, in the +form used by the native copy worker's event footprint. -/ +theorem source (x : ℕ) (hx : ColumnCell Y T x) : P.next ≤ x ∧ x < P.stop := by + obtain ⟨c, lo, hi⟩ := hx + rw [G.sourceHead c] at lo + exact ⟨(Nat.le_add_right ..).trans lo, hi.trans_le (G.source_end c)⟩ + +theorem destination (x : ℕ) (hx : ColumnCell Y U x) : + incidenceStart L level ≤ x ∧ x < incidenceStart L level + 6*N := by + obtain ⟨c, lo, hi⟩ := hx + rw [G.destinationHead c] at lo + exact ⟨(Nat.le_add_right ..).trans lo, hi.trans_le (G.destination_end c)⟩ + +theorem sourceAbove (x : ℕ) (hx : ColumnCell Y T x) : levelStart L 0 ≤ x := + G.lower.trans (G.source x hx).1 + +theorem destinationAbove (x : ℕ) (hx : ColumnCell Y U x) : levelStart L 0 ≤ x := + (levelStart_mono L (Nat.zero_le level.val)).trans + ((Nat.le_add_right ..).trans (G.destination x hx).1) + +end Packed + +variable {a g a₀ dH w : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a + g)) (E : RegularArcGraph (Fin (2 ^ a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2 ^ a₀) K K') + (hD : 1 < 2 ^ a) (hd : dH + 1 ≤ 2 ^ a₀) (choice : DyadicRefreshChoice X E hdH conn F) + +local notation "Y" => dyadicRefreshNext X E hdH conn F hD hd choice + +theorem base_count : Fintype.card (Y).Base = Fintype.card X.Base * 2^a := by + change Fintype.card (X.Base × Fin (2^a)) = _ + simp + +theorem slot_count (ties stride start : ℕ) : + (Y).positions * 2^a₀ = (Allocation.plan X a₀ dH ties stride start).capacity := by + rw [State.positions, Fintype.card_prod, base_count X E hdH conn F hD hd choice, + Fintype.card_congr (bitWordFinEquiv g), Fintype.card_fin] + rfl + +variable (ties stride : ℕ) (L : Layout) (old : ℕ) (level : Fin L.levels) +local notation "P" => Allocation.plan X a₀ dH ties stride (arrayBase L old) + +/-- For the actual branch, the old level's array head locates the scratch +plan above the controller, and the two bounded allocations justify every +source and destination address in the copy. -/ +theorem packed (apart : (P).stop ≤ incidenceStart L level) (fit : endAddress L < 2 ^ w) + (capacity : (Y).positions * 2 ^ a₀ ≤ slotCapacity L) : Packed Y P L level w := by + refine ⟨slot_count X E hdH conn F hD hd choice ties stride _, capacity, apart, fit, ?_⟩ + have lo := levelStart_mono L (Nat.zero_le old) + have h : levelStart L old ≤ (P).start := by + change levelStart L old ≤ arrayBase L old + unfold arrayBase incidenceStart + omega + exact (lo.trans h).trans (by + simp only [Allocation.Plan.next, Allocation.Plan.reverseSlot, Allocation.Plan.targetPort, + Allocation.Plan.supply, Allocation.Plan.term, Allocation.Plan.demand] + omega) + +end CompressorRecords.PortRefresh.CopyGeometry + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshCopyGroup.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshCopyGroup.lean new file mode 100644 index 0000000000..197e6a4675 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshCopyGroup.lean @@ -0,0 +1,173 @@ +import OAI.Computability.VPVNP.CompressorRefreshCopyPackets +import OAI.Computability.VPVNP.CompressorRefreshCopyGeometry +import OAI.Computability.VPVNP.CompressorRefreshCopyHeader +import OAI.Computability.VPVNP.CompressorBlockLevelFit +import OAI.Computability.VPVNP.CompressorRecordRefreshLifetime + +/-! +# The canonical successor incidence of the selected refresh + +The fixed block allocates the temporary output in table zero of the old level. +The six actual copy packets read it and populate the new level's incidence +arrays. Every old record and both levels' published heads survive these copies. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshCopyPackets + +open BurstRAM BlockPlanner DescriptorSpace Schedule Compression Compression.Refresh + Compression.DegreeRefresh +open SourceTransport SourceOnline CopyIncidence PortRefresh +open scoped Fin.CommRing + +/-- Exact post-memory, physical footprint, and native charge of the six-copy group. -/ +structure CopyResult {w a g : ℕ} (state : State a g) (plan : Allocation.Plan) (layout : Layout) + (nextLevel : ℕ) (m : Memory w) (rs : List (Report w)) : Prop where + reports_eq : rs = reports state (plan.output w) + (packedIncidence layout w nextLevel (state.positions * 2 ^ a)) allColumns m + stop_before : plan.stop ≤ incidenceStart layout nextLevel + stop_fits : plan.stop < 2 ^ w + represents : (packedIncidence layout w nextLevel (state.positions * 2 ^ a)).Represents state + (after m (eventLog rs)) + read : Reads (fun x => plan.next ≤ x ∧ x < plan.stop) (eventLog rs) + write : Writes (fun x => incidenceStart layout nextLevel ≤ x ∧ + x < incidenceStart layout nextLevel + 6 * (state.positions * 2 ^ a)) (eventLog rs) + calls : rs.length = 3 * (Fintype.card state.Base * 2 ^ a) + 3 * (state.positions * 2 ^ a) + charge : RAMBuckets.cost Report.probes rs = 3 * rs.length + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + {w g : ℕ} (base : BurstRAM.Word w) (positions blocks t : ℕ) (X : State S.portExponent + (S.portExponent + g)) + +local notation "s" => RefreshBlockPlan.shape B +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "first" => Script.levelsPerBlock scr * t +local notation "cur" => first + S.steps +local notation "nxt" => first + (S.steps + 1) +local notation "start" => arrayBase L cur +local notation "P" => Allocation.plan X (S.degreeExponent 0) (LevelRecipe.Shape.dH s) + (LevelRecipe.Shape.ties s) (LevelRecipe.Shape.stride s) start +local notation "T" => Allocation.Plan.output P w +local notation "hC" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "hE" => Nat.two_pow_pos S.expanderExponent +variable (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) +local notation "Y" => dyadicRefreshNext X S.graph hE hC B.refresh S.port_order + (And.right S.degree_bounds) choice +local notation "N" => State.positions Y * 2 ^ (S.degreeExponent 0) +local notation "U" => packedIncidence L w nxt N + +/-- Specializes the six-column copy result to the selected refresh state, allocation and next +descriptor level. -/ +abbrev Copied (m : Memory w) (rs : List (Report w)) := CopyResult Y P L nxt m rs + +section Frame + +variable {B base positions blocks t X choice} + +theorem Copied.frame {m : Memory w} {rs : List (Report w)} (copied : Copied B base positions + blocks t X choice m rs) + (x : ℕ) (away : x < incidenceStart L nxt ∨ incidenceStart L nxt + 6 * (N) ≤ x) : + after m (eventLog rs) x = m x := after_outside m copied.write (by omega) + +/-- The original typed demands, grid coordinates, repetitions and payloads remain +available to the later selected-branch DFS traversal. -/ +theorem Copied.stored {m : Memory w} {rs : List (Report w)} + (copied : Copied B base positions blocks t X choice m rs) {segmentFit} + (data : Build.Stored X S.graph hE hC B.refresh choice (RefreshBlockPlan.order B) start + (s).stride segmentFit m) : + Build.Stored X S.graph hE hC B.refresh choice (RefreshBlockPlan.order B) start + (s).stride segmentFit + (after m (eventLog rs)) := by + apply data.transfer (a₀ := S.degreeExponent 0) le_rfl copied.stop_fits.le + intro x _ upper + have before : (P).supply ≤ (P).stop := by + unfold Allocation.Plan.stop Allocation.Plan.next Allocation.Plan.reverseSlot + Allocation.Plan.targetPort + omega + exact after_outside m copied.write (fun h => (upper.trans_le + (before.trans copied.stop_before)).not_ge h.1) + +end Frame + +/-- The old header, canonical successor head bank and physically populated +temporary graph suffice for all six real online launches. The block size +bound places their source and destination in disjoint reserved intervals. -/ +theorem group (cap : ℕ) (m : Memory w) (old : IncidenceDirectory w) + (ht : t < blocks) (size : X.positions ≤ positions) (fit : endAddress L < 2 ^ w) + (rowsCell : m (pt).rows.val = (directoryRows L : BurstRAM.Word w)) + (pitch : m ((pt).directory - 1).val = (levelWords L : BurstRAM.Word w)) + (clock : scanCap scr 12 ≤ cap) + (header : RefreshCore.Header (Fintype.card X.Base) g (levelStart L cur) start old m) + (successor : TraversalHeaders.HeadBank L nxt (N) m) (rep : (T).Represents Y m) : + ∃ ps : List (Packet scr w), Group scr L base cap + ((scr).initial.length + t * (scr).block.length + (window B).before.length) + (directoryRows L) m ps ∧ + ps.map (fun p => p.stage.phase) = (window B).indices ∧ + Copied B base positions blocks t X choice m (ps.flatMap SourceWalk.Packet.reports) := by + have nextLive : nxt < (L).levels := by + have h := Nat.mul_le_mul_left (S.steps + 1) ht + change (S.steps + 1) * t + (S.steps + 1) < 1 + (S.steps + 1) * blocks + rw [Nat.mul_succ] at h; omega + let current : Fin (L).levels := ⟨cur, by omega⟩ + let next : Fin (L).levels := ⟨nxt, nextLive⟩ + have endOfPlan := (BlockLevelFit.refresh B base.val positions blocks current rfl X size + fit).1.next + have table0 : BlockLevelFit.tableStart L cur 0 = start := by + simp only [BlockLevelFit.tableStart, Nat.zero_mul, Nat.add_zero] + change (Allocation.plan X (S.degreeExponent 0) (s).dH (s).ties (s).stride + (BlockLevelFit.tableStart L cur 0)).stop ≤ + levelStart L ((cur) + 1) at endOfPlan + rw [table0, show (cur) + 1 = nxt by omega] at endOfPlan + have separate := endOfPlan.trans (Nat.le_add_right (levelStart L nxt) (levelHeaderWords L)) + have count := dyadicRefreshNext_positions X S.graph hE hC B.refresh S.port_order + (And.right S.degree_bounds) choice + have degree := (Finset.le_sup (f := fun j : Fin (S.steps + 1) => 2 ^ S.degreeExponent j) + (Finset.mem_univ 0)).trans (le_max_right (2 ^ S.portExponent) _) + have capacity : N ≤ slotCapacity L := Nat.mul_le_mul (count.le.trans size) degree + have geometry := CopyGeometry.packed X S.graph hE hC B.refresh S.port_order + (And.right S.degree_bounds) choice + (s).ties (s).stride L cur next separate fit capacity + have earlier := levelStart_mono L (show cur ≤ nxt by omega) + have firstHead := levelStart_mono L (show 0 ≤ nxt from Nat.zero_le _) + have low := Window.lowCells (A := scr) L base rfl rfl ((levelStart_mono L + (Nat.zero_le _)).trans_lt fit) + have headerLength : levelHeaderWords L = 66 := rfl + have data (mem : Memory w) (retained : ∀ x < incidenceStart L nxt, mem x = m x) (c : Fin 6) : + Operands B base positions blocks t Y T U mem c := by + have oldRead := header.keep (fun i hi => retained _ (by unfold incidenceStart; omega)) + have newRead := successor.keep (fun i hi => retained _ (by unfold incidenceStart; omega)) + have pitch' := (retained _ (low.2.trans_le (firstHead.trans (Nat.le_add_right ..)))).trans pitch + have card := CopyGeometry.base_count X S.graph hE hC B.refresh S.port_order + (And.right S.degree_bounds) choice + obtain ⟨stop, bank, supp⟩ := RefreshCopyHeader.operands B X Y start old base positions blocks + t mem + oldRead newRead pitch' ht fit card geometry.slots c + exact ⟨stop, bank, supp⟩ + obtain ⟨ps, packets, phases, hreports⟩ := group_of_operands B base positions blocks t Y T U m + (incidenceStart L nxt) cap ht fit rowsCell pitch clock (firstHead.trans (Nat.le_add_right ..)) + geometry.roomT geometry.roomU geometry.rowsFit geometry.sourceAbove (fun x h => + (geometry.destination x h).1) data + obtain ⟨run, rep', calls, cost, _, _⟩ := copy_directory Y T U m geometry.regions rep + have access := run.footprint geometry.roomT geometry.roomU + refine ⟨ps, packets, phases, ?_⟩ + rw [hreports] + exact ⟨rfl, separate, endOfPlan.trans_lt ((levelStart_mono L nextLive.le).trans_lt fit), rep', + fun a v hv => geometry.source _ (access.1 a v hv), + fun a v hv => geometry.destination _ (access.2 a v hv), calls, cost.trans (congrArg + (3 * ·) calls.symm)⟩ + +end CompressorRecords.RefreshCopyPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshCopyHeader.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshCopyHeader.lean new file mode 100644 index 0000000000..c6436e9ce8 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshCopyHeader.lean @@ -0,0 +1,165 @@ +import OAI.Computability.VPVNP.CompressorRefreshCoreHeader +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorWindowPrepared +import OAI.Computability.VPVNP.CompressorRecordsCopyIncidence + +/-! +# Planner operands of the six native refresh column copies + +The input header supplies the old vertex count, residual lanes and scratch origin. +The output header supplies each canonical destination pointer. The first three scans +copy one word per promoted base port and the last three copy one word per actual slot. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshCopyHeader + +open BurstRAM Compression DescriptorSpace PhaseRecipe BlockPlanner Schedule +open PortRefresh LevelRecipe NewSlots +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {g w : ℕ} (X : State S.portExponent (S.portExponent + g)) + (Y : State (S.degreeExponent 0) g) +variable (start : ℕ) (old : IncidenceDirectory w) + +local notation "geom" => BlockProgram.geometry B +local notation "shapeR" => RefreshBlockPlan.shape B +local notation "inputR" => RefreshBlockPlan.input geom S.steps (0 : Fin 6) +local notation "P" => Allocation.plan X (LevelRecipe.Shape.a₀ shapeR) (LevelRecipe.Shape.dH shapeR) + (LevelRecipe.Shape.ties shapeR) (LevelRecipe.Shape.stride shapeR) start +local notation "visit" => RefreshBlockPlan.copyColumn B geom S.steps inputR + +private theorem column_reads {s : LevelRecipe.Shape} {I : Input} {C : Context w} {D : ℕ → Prop} + (h : InputReads D C.pub C.state C.memory I) (i : Fin 6) : + (column s I i).ReadsFrom D C.pub C.state C.memory := by + let R := Expr.ReadsFrom D C.pub C.state C.memory + have ps : R (sites s I) := ⟨⟨h.vertices, trivial⟩, h.lanes⟩ + have bl : R (blocks I) := ⟨h.vertices, h.lanes⟩ + have dem : R (demandStart s I) := ⟨h.start, trivial, ps, trivial⟩ + have term : R (termStart s I) := ⟨dem, bl, trivial⟩ + have sup : R (supplyStart s I) := ⟨term, bl, trivial⟩ + have target : R (targetPort s I) := ⟨sup, ps, trivial⟩ + have rev : R (reverseSlot s I) := ⟨target, trivial, trivial⟩ + exact ⟨⟨rev, trivial, trivial⟩, trivial, ps, trivial⟩ + +variable {L : Layout} {first rows : ℕ} (C : Context w) +local notation "next" => first + (S.steps + 1) +local notation "U" => packedIncidence L w (next) rows + +/-- Stop and parameter words at the actual copy visit. The count equalities identify +its two scan lengths with those of the refreshed state. -/ +theorem eval (entry : LevelFields.Entry L first C.pub C.state C.memory) + (header : RefreshCore.Header (Fintype.card X.Base) g (levelStart L (first + S.steps)) + start old C.memory) + (successor : TraversalHeaders.HeadBank L (next) rows C.memory) + (fields : L.shape.scalarFields = 54) + (room : levelStart L (next) + 59 < 2 ^ w) + (baseCount : Fintype.card Y.Base = Fintype.card X.Base * 2 ^ S.portExponent) + (actualCount : Y.positions * 2 ^ (S.degreeExponent 0) = (P).capacity) (c : Fin 6) : + C.eval ((visit c).stop) = word (CopyIncidence.rows Y c) ∧ + ∀ j : Fin 3, C.eval ((visit c).params j) = + CopyIncidence.copyPublic (((P).output w).column c) ((U).column c) j := by + have data : Describes (s := shapeR) inputR C X start old := + RefreshCore.Header.describes (F := geom) rfl (0 : Fin 6) rfl entry header + have h := addresses (s := shapeR) inputR C X start old data + have dest : C.eval (LevelFields.incidence geom (S.steps + 1) c) = (U).column c := by + rw [packed_column] + have read := LevelFields.eval_scalar entry (S.steps + 1) (54 + c.val) (by have := c.isLt; omega) + exact read.trans (by + simpa only [incidenceHead, fields, Nat.add_assoc] using successor.incidence c) + constructor + · change C.eval (RefreshBlockPlan.columnCount B inputR c) = _ + by_cases small : c.val < 3 + · simp only [RefreshBlockPlan.columnCount,CopyIncidence.rows,small,↓reduceIte,baseCount] + exact (counters (s := shapeR) inputR C X start old data (.base : Stage shapeR)).2 + · simp only [RefreshBlockPlan.columnCount,CopyIncidence.rows,small,↓reduceIte,actualCount] + exact h.capacity_eq + · intro j + fin_cases j + · rfl + · exact h.column_eq c + · exact dest + +/-- Support in a general preserved memory region follows from the old header cells, +the new pointer cells, and the single pitch read. -/ +theorem reads {D : ℕ → Prop} (entry : LevelFields.Entry L first C.pub C.state C.memory) + {V : ℕ} (header : RefreshCore.Header V g (levelStart L (first + S.steps)) + start old C.memory) + (room : levelStart L (next) + 59 < 2 ^ w) (pitch : D (C.pub 1 - 1).val) + (oldCells : ∀ n ≤ 60, D (levelStart L (first + S.steps) + n)) + (newCells : ∀ c : Fin 6, D (levelStart L (next) + (54 + c.val))) (c : Fin 6) : + HeaderOperands.Supported D C.pub C.state C.memory (visit c) := by + have data : InputReads D C.pub C.state C.memory inputR := + RefreshCore.Header.reads (F := geom) rfl (0 : Fin 6) rfl entry header pitch oldCells + refine ⟨trivial, ?_, ?_⟩ + · change (RefreshBlockPlan.columnCount B inputR c).ReadsFrom D C.pub C.state C.memory + unfold RefreshBlockPlan.columnCount + split + · exact ⟨⟨data.vertices, trivial⟩, trivial⟩ + · exact ⟨⟨⟨data.vertices, trivial⟩, data.lanes⟩, trivial⟩ + · intro j + fin_cases j + · trivial + · exact column_reads (C := C) data c + · exact GreedyVisit.scalar_support D L first (S.steps + 1) (54 + c.val) entry pitch + (newCells c) (by have := c.isLt; omega) + +section Physical + +variable (base : Word w) (positions blocks t : ℕ) +local notation "scr" => BlockProgram.script B +local notation "lay" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Schedule.Ports.data pt +local notation "idx" => Script.levelsPerBlock scr * t +local notation "st" => (levelStart lay (idx) : Word w) +local notation "succIdx" => (idx) + (S.steps + 1) +local notation "dest" => packedIncidence lay w (succIdx) rows + +/-- The six installed scans use the native parameters and only read cells permitted +by the physical calendar. The old and new publications are read at this visit's memory. -/ +theorem operands (m : Memory w) + (header : RefreshCore.Header (Fintype.card X.Base) g (levelStart lay ((idx) + S.steps)) + start old m) + (successor : TraversalHeaders.HeadBank lay (succIdx) rows m) + (pitch : m (pub 1 - 1).val = (levelWords lay : Word w)) (live : t < blocks) + (fit : endAddress lay < 2 ^ w) + (baseCount : Fintype.card Y.Base = Fintype.card X.Base * 2 ^ S.portExponent) + (actualCount : Y.positions * 2 ^ (S.degreeExponent 0) = (P).capacity) (c : Fin 6) : + (visit c).stop.eval pub st m = word (CopyIncidence.rows Y c) ∧ + (∀ j : Fin 3, ((visit c).params j).eval pub st m = + CopyIncidence.copyPublic (((P).output w).column c) ((dest).column c) j) ∧ + HeaderOperands.Supported (Window.operandRegion scr lay base) pub st m (visit c) := by + have liveNext : succIdx < (lay).levels := by + have bound := Nat.mul_le_mul_left (S.steps + 1) live + change (S.steps + 1) * t + (S.steps + 1) < 1 + (S.steps + 1) * blocks + rw [Nat.mul_succ] at bound; omega + have room : levelStart lay (succIdx) + 59 < 2 ^ w := by + have h := DescriptorSpace.level_room lay fit ⟨succIdx, liveNext⟩ + change levelStart lay ((succIdx) + 1) < 2 ^ w at h + have size : levelHeaderWords lay = 66 := rfl + simp only [levelStart, Nat.succ_mul, levelWords, size] at h ⊢; omega + let C : Context w := ⟨pub, st, m⟩ + have entry : LevelFields.Entry lay (idx) C.pub C.state C.memory := ⟨rfl, pitch⟩ + obtain ⟨stop, params⟩ := + eval B X Y start old C entry header successor rfl room baseCount actualCount c + refine ⟨stop, params, reads B start old C entry header room (Or.inr (Or.inl rfl)) ?_ ?_ c⟩ + · intro n _ + exact Or.inr (Or.inr ((levelStart_mono lay (Nat.zero_le _)).trans (Nat.le_add_right ..))) + · intro j + exact Or.inr (Or.inr ((levelStart_mono lay (Nat.zero_le _)).trans (Nat.le_add_right ..))) + +end Physical +end CompressorRecords.RefreshCopyHeader + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshCopyPackets.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshCopyPackets.lean new file mode 100644 index 0000000000..c4b30bbc5c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshCopyPackets.lean @@ -0,0 +1,145 @@ +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorShrinkSlotFootprint +import OAI.Computability.VPVNP.CompressorWindowPackets +import OAI.Computability.VPVNP.CompressorSourceScanned + +/-! +# The six successor - incidence copy launches in the refresh script + +Each column resets its own cursor and reads its source and destination pointers +from the persisted physical headers. The fixed packet window copies the three +base - port columns and the three actual - port columns at their respective lengths. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshCopyPackets + +open BurstRAM BlockPlanner DescriptorSpace Schedule Compression SourceTransport SourceOnline + CopyIncidence +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- The scheduled visit that copies column c from the selected refresh output into the next +incidence directory. -/ +abbrev visit (c : Fin 6) := RefreshBlockPlan.copyColumn B (BlockProgram.geometry B) S.steps + (RefreshBlockPlan.input (BlockProgram.geometry B) S.steps (0 : Fin 6)) c +/-- The six column-copy visits in increasing column order. -/ +abbrev visits := List.ofFn (visit B) +/-- The contiguous interval of the block script occupied by the six refresh output copies. -/ +abbrev window : Window (BlockProgram.script B) (visits B) := BlockGroups.refresh B 2 + +variable {w g : ℕ} (base : Word w) (positions blocks t : ℕ) (Y : State (S.degreeExponent 0) g) + (T U : IncidenceDirectory w) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Ports.data pt +local notation "first" => Script.levelsPerBlock scr * t +local notation "st" => (levelStart L (first) : Word w) +local notation "head" => levelStart L 0 +local notation "dataRegion" => Window.operandRegion scr L base + +/-- Certifies the copy visit's row count, source and destination operand bank, and the region +from which its planner may read. -/ +structure Operands (m : Memory w) (c : Fin 6) : Prop where + stop : (visit B c).stop.eval pub st m = (rows Y c : Word w) + bank : ∀ i : Fin 3, ((visit B c).params i).eval pub st m = copyPublic (T.column c) (U.column c) i + supported : HeaderOperands.Supported dataRegion pub st m (visit B c) + +open private row_spec from OAI.Computability.VPVNP.CompressorRecordsCopyIncidence + +private theorem scanned (src dst : Word w) (j n : ℕ) (m : Memory w) : + StageFrame.Scanned j (j + n) (scan src dst j n m) := by + induction n generalizing j m with + | zero => exact .done _ + | succ n ih => + refine .next (by omega) (row_spec src dst j m).2.1 ?_ + simpa only [show j + 1 + n = j + (n + 1) by omega] using ih (j + 1) (after m + (row src dst j m).events) + +private theorem column_access (m : Memory w) (c : Fin 6) + (roomT : ∀ c, (T.column c).val + rows Y c ≤ 2 ^ w) (roomU : ∀ c, + (U.column c).val + rows Y c ≤ 2 ^ w) : + LogAccess (ColumnCell Y T) (ColumnCell Y U) (columnScan Y T U c m) := by + simpa only [reports, List.append_nil] using (reports_run Y T U [c] m).footprint roomT roomU + +/-- Evaluate the chronological columns in their actual input memories. The +source and successor headers are below the copied cells throughout the run. -/ +theorem raw (m : Memory w) (boundary : ℕ) (headBefore : head ≤ boundary) + (roomT : ∀ c, (T.column c).val + rows Y c ≤ 2 ^ w) (roomU : ∀ c, + (U.column c).val + rows Y c ≤ 2 ^ w) + (fit : ∀ c, rows Y c < 2 ^ w) + (source : ∀ x, ColumnCell Y T x → head ≤ x) (destination : ∀ x, ColumnCell Y U x → boundary ≤ x) + (operands : ∀ mem : Memory w, (∀ x < boundary, mem x = m x) → + ∀ c, Operands B base positions blocks t Y T U mem c) : + SourceWalk (Window.Raw (A := scr) L base t 12) (visits B) m (reports Y T U allColumns m) := by + have loop (cs : List (Fin 6)) (mem : Memory w) (retained : ∀ x < boundary, mem x = m x) : + SourceWalk (Window.Raw (A := scr) L base t 12) (cs.map (visit B)) mem + (reports Y T U cs mem) := by + induction cs generalizing mem with + | nil => exact .done _ + | cons c cs ih => + let rs := columnScan Y T U c mem + have access := column_access Y T U mem c roomT roomU + have op := operands mem retained c + have initial : (visit B c).initial.eval pub st mem = 0 := rfl + have native := (scan_native (T.column c) (U.column c) 0 (rows Y c) mem).1 + refine .next (rs := rs) ⟨12, List.replicate (rows Y c) [], le_rfl, ?_, op.supported⟩ + (ih _ (fun x hx => (after_outside mem access.2 (fun h => + (destination x h).not_gt hx)).trans (retained x hx))) + refine ⟨by decide, ?_, ?_, fun a v h => source _ (access.1 a v h), + fun a v h => headBefore.trans (destination _ (access.2 a v h))⟩ + · change runSegment (copyPass.table.instantiate w (fun i => + ((visit B c).params i).eval pub st mem)).program + 12 (some ((visit B c).initial.eval pub st mem)) mem _ = _ + rw [funext op.bank, initial] + exact native + · rw [op.stop, initial] + simpa only [rs, columnScan, Nat.zero_add, Nat.cast_zero] using + (scanned (T.column c) (U.column c) 0 (rows Y c) mem).toProgress (by simpa using fit c) + have order : (allColumns.map (visit B)) = visits B := rfl + exact order ▸ loop allColumns m (fun _ _ => rfl) + +/-- Attach the six checked copies at their global program ordinals and retain +the exact reports whose post-memory contains the canonical successor graph. -/ +theorem group_of_operands (m : Memory w) (boundary cap : ℕ) (ht : t < blocks) + (endFit : endAddress L < 2 ^ w) (rowsCell : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory - 1).val = (levelWords L : Word w)) (clock : scanCap scr 12 ≤ cap) + (headBefore : head ≤ boundary) (roomT : ∀ c, (T.column c).val + rows Y c ≤ 2 ^ w) + (roomU : ∀ c, (U.column c).val + rows Y c ≤ 2 ^ w) (fit : ∀ c, rows Y c < 2 ^ w) + (source : ∀ x, ColumnCell Y T x → head ≤ x) (destination : ∀ x, ColumnCell Y U x → boundary ≤ x) + (operands : ∀ mem : Memory w, (∀ x < boundary, mem x = m x) → + ∀ c, Operands B base positions blocks t Y T U mem c) : + ∃ ps : List (Packet scr w), Group scr L base cap + ((scr).initial.length + t * (scr).block.length + (window B).before.length) + (directoryRows L) m ps ∧ + ps.map (fun p => p.stage.phase) = (window B).indices ∧ + ps.flatMap SourceWalk.Packet.reports = reports Y T U allColumns m := by + have Hfit : head < 2 ^ w := (levelStart_mono L (Nat.zero_le _)).trans_lt endFit + have bounds (j : Fin (scr).size) := SourceOnline.scanCap_clocks + (p := ⟨HeaderPacket.attach scr j pub st m 12 [], m, []⟩) 12 le_rfl clock + have live (j : Fin (visits B).length) : Window.ordinal (A := scr) t + ((window B).index j) < directoryRows L := by + rw [(window B).ordinal_index, BlockProgram.directory_rows, (scr).calendar_total] + have pos := ((window B).position j).isLt + have mul := Nat.mul_le_mul_right (scr).block.length ht + rw [Nat.succ_mul] at mul + omega + exact (window B).group L base t rfl rfl Hfit cap 12 m _ (raw B base positions blocks t Y T U m + boundary + headBefore roomT roomU fit source destination operands) rowsCell pitch live + (fun j _ => (bounds j).1) (fun j _ => (bounds j).2) + +end CompressorRecords.RefreshCopyPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshCoreBuild.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshCoreBuild.lean new file mode 100644 index 0000000000..e976011308 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshCoreBuild.lean @@ -0,0 +1,158 @@ +import OAI.Computability.VPVNP.CompressorRefreshWindowRun +import OAI.Computability.VPVNP.CompressorBlockLevelFit + +/-! +# Online realization of the selected refresh's descriptor arrays + +The graph at the old canonical incidence columns is the only graph read by +the source. Its size controls the packed allocation. The resulting packets +occupy exactly group one of the refresh calendar and retain both the +successor incidence and the chosen local motif records. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +set_option quotPrecheck false + +namespace CompressorRecords.RefreshCore + +open BurstRAM BlockPlanner Schedule DescriptorSpace Compression Compression.DegreeRefresh +open Compression.Refresh +open PortRefresh PortRefresh.Allocation PortRefresh.LevelRecipe SourceTransport SourceOnline +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {w g : ℕ} (base : BurstRAM.Word w) (positions blocks t : ℕ) +variable (X : State S.portExponent (S.portExponent + g)) +variable (c : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos + S.port_order).1 B.refresh) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "cur" => Script.levelsPerBlock scr * t + S.steps +local notation "start" => arrayBase L cur +local notation "s₀" => RefreshBlockPlan.shape B +local notation "ties" => RefreshBlockPlan.order B +local notation "P" => plan X (S.degreeExponent 0) (s₀).dH (s₀).ties (s₀).stride start +local notation "hC" => (S.port_bound.connected_and_pos S.port_order).1 +local notation "hE" => Nat.two_pow_pos S.expanderExponent +local notation "Y" => dyadicRefreshNext X S.graph hE hC B.refresh S.port_order S.degree_bounds.2 c +local notation "N" => X.positions * 2 ^ S.portExponent +local notation "old" => packedIncidence L w cur N +local notation "W" => BlockGroups.refresh B 1 + +/-- Certificate that the native refresh implements the selected branch, stores its terms, +represents its output incidence, and confines writes to the arena. The total charge, one +per report plus its probes, is bounded by a fixed factor times the number of input +positions. -/ +structure Built (termCap : ℕ) (m : Memory w) (rs : List (Report w)) : Prop where + fits : (P).segments ≤ 2 ^ w + source : ∃ alloc, Build.Run X S.graph hE hC B.refresh S.port_order S.degree_bounds.2 c ties old + start + (s₀).stride termCap alloc m rs + represents : ((P).output w).Represents Y (after m (eventLog rs)) + stored : Build.Stored X S.graph hE hC B.refresh c ties start (s₀).stride fits (after m + (eventLog rs)) + writes : Writes (TermDataFrame.InArena P) (eventLog rs) + charge : RAMBuckets.cost Report.probes rs ≤ Build.chargeFactor S.graph hE hC B.refresh + (s₀).ties * X.positions + +/-- The upper bound and origin of every old source column, with room for all +physical slots of the incoming graph before the first scratch cell. -/ +theorem source_region (current : Fin (L).levels) (idx : current.val = cur) + (size : X.positions ≤ positions) (fit : endAddress L < 2 ^ w) (j : Fin 6) : + levelStart L 0 ≤ ((old).column j).val ∧ ((old).column j).val + (P).segments ≤ start := by + have degree : 2 ^ S.portExponent ≤ slotDegree S := le_max_left .. + have capacity : N ≤ slotCapacity L := Nat.mul_le_mul size degree + have room := packed_incidence_room L fit current capacity + rw [idx] at room + have hj := Nat.mul_le_mul_right (N) j.isLt + rw [Nat.succ_mul] at hj + have head : ((old).column j).val = incidenceStart L cur + j.val * (N) := by + rw [packed_column] + exact Nat.mod_eq_of_lt (by change incidenceStart L cur + j.val * (N) < 2 ^ w; omega) + have seg : (P).segments = N := congrArg (· * 2 ^ S.portExponent) + (bundleCount_positions X (IncidenceDirectory.baseOrder X)) + rw [head,seg] + refine ⟨(levelStart_mono L (Nat.zero_le _)).trans ((Nat.le_add_right ..).trans + (Nat.le_add_right ..)),?_⟩ + change incidenceStart L cur + j.val * (N) + (N) ≤ incidenceStart L cur + 6 * slotCapacity L + exact (by omega : incidenceStart L cur + j.val * (N) + (N) ≤ incidenceStart L cur + 6 * (N)).trans + (Nat.add_le_add_left (Nat.mul_le_mul_left 6 capacity) _) + +set_option maxHeartbeats 900000 in +-- The calendar walk reuses the chosen graph and its typed motif grid. +theorem build_group (termCap cap : ℕ) (m : Memory w) (ht : t < blocks) (size : X.positions ≤ + positions) + (fit : endAddress L < 2 ^ w) (rows : m (pt).rows.val = (directoryRows L : BurstRAM.Word w)) + (pitch : m ((pt).directory - 1).val = (levelWords L : BurstRAM.Word w)) + (clock : scanCap scr (max 64 termCap) ≤ cap) + (header : Header (Fintype.card X.Base) g (levelStart L cur) start old m) + (represented : (old).Represents X m) + (termBits : termConstant S.graph hE hC B.refresh ties + 4 * Nat.clog 2 (X.maxWireWidth + 1) ≤ w) + (nextWidth : (Y).maxWireWidth < 2 ^ w) + (budget : TermWorker.budget B.refresh (s₀).ties ((s₀).ports * (s₀).dH) w X.maxWireWidth ≤ + termCap) + (positive : 0 < termCap) : + ∃ ps : List (Packet scr w), SourceOnline.Group scr L base cap ((scr).initial.length + t * + (scr).block.length + (W).before.length) + (directoryRows L) m ps ∧ ps.map (fun p ↦ p.stage.phase) = (W).indices ∧ + Built B base positions blocks t X c termCap m (ps.flatMap SourceWalk.Packet.reports) := by + have idx : cur < (L).levels := by + have bound := Nat.mul_le_mul_left (S.steps + 1) ht + rw [Nat.mul_succ] at bound + change (S.steps + 1) * t + S.steps < 1 + (S.steps + 1) * blocks + omega + let current : Fin (L).levels := ⟨cur,idx⟩ + have source := source_region B base positions blocks t X current rfl size fit + have room := (BlockLevelFit.refresh B base.val positions blocks current rfl X size fit).1.word + change (plan X (S.degreeExponent 0) (s₀).dH (s₀).ties (s₀).stride (start + 0 * tableWords + L)).stop < 2 ^ w at room + simp only [Nat.zero_mul,Nat.add_zero] at room + let alloc := prepare_layout X old (S.degreeExponent 0) (s₀).dH (s₀).ties (s₀).stride start + (fun j ↦ (source j).2) room + obtain ⟨rs,run,rep,stored,_,charge⟩ := Build.build X S.graph hE hC B.refresh S.port_order + S.degree_bounds.2 c + ties old start (s₀).stride m represented (fun j ↦ (source j).2) le_rfl room termBits nextWidth + termCap budget + have native := Scheduled.verified_sources X S.graph hE hC B.refresh S.port_order + S.degree_bounds.2 c + ties old start (s₀).stride (levelStart L 0) termCap alloc m rs represented + (fun j ↦ (source j).1) (fun j ↦ (source j).2) le_rfl room termBits nextWidth budget run + have before : levelStart L cur + 60 < start := by + change levelStart L cur + 60 < levelStart L cur + 66 + 6 * slotCapacity L + omega + have Hfit := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + obtain ⟨raw,wr⟩ := raw_window B X c old start termCap base positions blocks t m rs header pitch + positive room before Hfit native + have clocks (j : Fin (scr).size) := scanCap_clocks + (p := ⟨HeaderPacket.attach scr j (pt).data 0 m (max 64 termCap) [],m,[]⟩) _ le_rfl clock + have existsPart : 1 < (BlockGroups.refreshParts B).length := by + rw [BlockGroups.refreshParts_length] + decide + have live (j : Fin ((BlockGroups.refreshParts B)[1]'existsPart).length) : + Window.ordinal (A := scr) t ((W).index j) < directoryRows L := by + rw [(W).ordinal_index,BlockProgram.directory_rows,(scr).calendar_total] + have pos := ((W).position j).isLt + have mul := Nat.mul_le_mul_right (scr).block.length ht + rw [Nat.succ_mul] at mul + omega + obtain ⟨ps,grp,phases,logs⟩ := (W).group L base t rfl rfl Hfit cap (max 64 termCap) m rs raw + rows pitch live (fun j _ ↦ (clocks j).1) (fun j _ ↦ (clocks j).2) + refine ⟨ps,grp,phases,?_⟩ + rw [logs] + exact ⟨alloc.regions.fits,⟨alloc,run⟩,rep,stored,wr,charge.trans + (Build.charge_le_positions (t := (s₀).ties) X S.graph hE hC B.refresh S.port_order + S.degree_bounds.2 c)⟩ + +end CompressorRecords.RefreshCore + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshCoreHeader.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshCoreHeader.lean new file mode 100644 index 0000000000..f8f08e2f26 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshCoreHeader.lean @@ -0,0 +1,99 @@ +import OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders +import OAI.Computability.VPVNP.CompressorRefreshStageSupport +import OAI.Computability.VPVNP.CompressorGreedyPlannerFootprint + +/-! +# Current header readback for the native refresh + +The scalar publisher supplies the old vertex and residual lane counts. The +pointer publisher supplies the old incidence columns and the scratch origin. +These cells precede the first refresh array, so all stages of the native +refresh continue to read them at their original values. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshCore + +open BurstRAM Compression PhaseRecipe DescriptorSpace LevelFields PortRefresh NewSlots LevelRecipe +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Specifies the vertex count, residual-lane count, six incidence column heads and scratch +start in a level header that fits in memory. -/ +structure Header (vertices g head start : ℕ) (old : IncidenceDirectory w) + (m : Memory w) : Prop where + room : head + 60 < 2 ^ w + vertices_eq : m (head + 0) = word vertices + residual : m (head + 3) = word (2 ^ g) + incidence : ∀ c : Fin 6, m (head + 54 + c.val) = old.column c + scratch : m (head + 60) = word start + +theorem Header.keep {V g head start : ℕ} {old : IncidenceDirectory w} {m m' : Memory w} + (h : Header V g head start old m) (keep : ∀ n ≤ 60, m' (head + n) = m (head + n)) : + Header V g head start old m' := by + refine ⟨h.room,(keep 0 (by decide)).trans h.vertices_eq,(keep 3 (by decide)).trans h.residual, + fun c ↦ ?_,(keep 60 le_rfl).trans h.scratch⟩ + rw [Nat.add_assoc,keep _ (by have := c.isLt; omega),← Nat.add_assoc] + exact h.incidence c + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + +/-- The live scalar and pointer publications produce the exact header used +by the refresh, including the packed old - slot incidence table. -/ +theorem Header.ofPublished {L : Layout} {i dH : ℕ} {m : Memory w} {v : SelectedLevel B f hf} + (h : Published L i v dH m) (bank : TraversalHeaders.HeadBank L i v.oldSlots m) + (fields : L.shape.scalarFields = 54) (tables : 0 < L.shape.tables) + (room : levelStart L i + 60 < 2 ^ w) : + Header (Fintype.card v.input.Base) v.outputLanes (levelStart L i) (arrayBase L i) + (packedIncidence L w i v.oldSlots) m := by + refine ⟨room,h.vertices,h.residual,fun c ↦ ?_,?_⟩ + · rw [packed_column] + simpa only [incidenceHead,fields] using bank.incidence c + · simpa [tableHead,tableBase,fields,Nat.add_assoc] using bank.tables ⟨0,tables⟩ + +variable {L : Layout} {first step start g : ℕ} {C : Context w} +variable {s : LevelRecipe.Shape} {X : State s.a (s.a + g)} {old : IncidenceDirectory w} +variable {F : DescriptorSpace.Shape} (field : F.scalarFields = 54) (j : Fin F.tables) + (zero : j.val = 0) + +include field zero in +theorem Header.describes (e : Entry L first C.pub C.state C.memory) + (h : Header (Fintype.card X.Base) g (levelStart L (first + step)) start old C.memory) : + Describes (s := s) (RefreshBlockPlan.input F step j) C X start old := by + let head := levelStart L (first + step) + have read (n : ℕ) (hn : n ≤ 60) : C.eval (scalar step n) = C.memory (head + n) := + eval_scalar e step n ((Nat.add_le_add_left hn _).trans_lt h.room) + have arr : C.eval (table F step j) = C.memory (head + 60) := by + simpa only [table,field,zero,Nat.reduceAdd,Nat.add_zero] using read 60 le_rfl + have inc (c : Fin 6) : C.eval (LevelFields.incidence F step c) = old.column c := by + unfold LevelFields.incidence + rw [field,read _ (by have := c.isLt; omega),← Nat.add_assoc] + exact h.incidence c + exact ⟨arr.trans h.scratch,(read 0 (by decide)).trans h.vertices_eq, + (read 3 (by decide)).trans h.residual,inc 0,inc 2,inc 5⟩ + +include field zero in +/-- Operand support of the six physical level-header loads. -/ +theorem Header.reads (e : Entry L first C.pub C.state C.memory) {D : ℕ → Prop} + {V lanes : ℕ} (h : Header V lanes (levelStart L (first + step)) start old C.memory) + (pitch : D (C.pub 1 - 1).val) (region : ∀ n ≤ 60, D (levelStart L (first + step) + n)) : + InputReads D C.pub C.state C.memory (RefreshBlockPlan.input F step j) := by + have read (n : ℕ) (hn : n ≤ 60) : (scalar step n).ReadsFrom D C.pub C.state C.memory := + GreedyVisit.scalar_support D L first step n e pitch (region n hn) + ((Nat.add_le_add_left hn _).trans_lt h.room) + refine ⟨?_,read 0 (by decide),read 3 (by decide),?_,?_,?_⟩ + all_goals + simp only [RefreshBlockPlan.input,table,LevelFields.incidence,field,zero,Fin.val_zero, + Nat.reduceAdd,Nat.add_zero] + exact read _ (by decide) + +end CompressorRecords.RefreshCore + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshCorePackets.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshCorePackets.lean new file mode 100644 index 0000000000..1fc9f5e1b3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshCorePackets.lean @@ -0,0 +1,102 @@ +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorRefreshStageVisits +import OAI.Computability.VPVNP.CompressorScriptWindow + +/-! +# Actual expander-refresh packets in the complete compressor script + +The calendar index includes all preceding shrinking levels and the three +refresh header publishers. At each index the script table is the native +worker used by the degree - refresh proof. The packet sequence reads the +original term tape and leaves the verified refreshed incidence and motif +arrays in its shared data memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshCore + +open BurstRAM BlockPlanner Compression Compression.Refresh Compression.DegreeRefresh +open PortRefresh LevelRecipe SourceOnline + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- The block template's dimensions used to enumerate the refresh core stages. -/ +abbrev shape := RefreshBlockPlan.shape B +/-- Level-header expressions at the block's refresh step, with table zero as the refresh arena. -/ +abbrev input := RefreshBlockPlan.input (BlockProgram.geometry B) S.steps (0 : Fin 6) +/-- The ordered native stages of the refresh core for this template. -/ +abbrev stages := LevelRecipe.order (shape B) +/-- The block-planner visits obtained by compiling each refresh core stage against the selected +level input. -/ +abbrev entries := (stages B).map (RefreshBlockPlan.stage B (input B)) + +/-- The precise contiguous range of native refresh stages in one block. -/ +def window : BlockPlanner.Window (BlockProgram.script B) (entries B) := BlockGroups.refresh B 1 + +/-- Embeds a stage's ordinal within the refresh core into the full block script. -/ +def index (i : Fin (stages B).length) : Fin (BlockProgram.script B).size := + (window B).index (Fin.cast (List.length_map (RefreshBlockPlan.stage B (input B))).symm i) + +theorem index_visit (i : Fin (stages B).length) : (BlockProgram.script B).visit (index B i) = + RefreshBlockPlan.stage B (input B) ((stages B)[i.val]) := by + have h := (window B).visit (Fin.cast (List.length_map (RefreshBlockPlan.stage B + (input B))).symm i) + simpa only [index,entries,List.getElem_map,Fin.val_cast] using h + +theorem index_worker (i : Fin (stages B).length) : (BlockProgram.script B).catalog (index B i) = + ((stages B)[i.val]).worker S.degree_bounds.2 (RefreshBlockPlan.term B) := + congrArg BlockPlanner.Visit.worker (index_visit B i) + +variable {g w : ℕ} (X : State S.portExponent (S.portExponent + g)) +private abbrev connected := (S.port_bound.connected_and_pos S.port_order).1 +local notation "hC" => connected (S := S) +local notation "Tₛ" => RefreshBlockPlan.order B +local notation "F" => B.refresh +variable (c : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) +variable (old : IncidenceDirectory w) (start cap : ℕ) + +/-- The source execution of one indexed core stage with its native worker, cursor interval, +fuel, public operands and choice tapes. -/ +def visit (i : Fin (stages B).length) : SourceOnline.Visit (BlockProgram.script B) w := + let j := (stages B)[i.val] + let T := RefreshBlockPlan.term B + let data := j.nativeBank S.degree_bounds.2 S.graph Tₛ X start old + (TermWorker.motifData F Tₛ finProdFinEquiv.symm w) + SourceOnline.Visit.ofWorker (A := BlockProgram.script B) (index B i) (j.worker S.degree_bounds.2 + T) (index_worker B i) + (Scheduled.fuel S.degree_bounds.2 cap j) (Fin.ofNat _ j.first) (Fin.ofNat _ (j.limit X start)) + (fun z ↦ data (Fin.cast (j.worker_params S.degree_bounds.2 T) z)) + (Scheduled.tapes (w := w) X S.graph (Nat.two_pow_pos _) hC F c start (shape B).stride j) + +/-- The full native refresh source appears at its actual global program +indices, with no extra branch or reorder between the term worker and the +incidence scans. -/ +theorem walk (L : Allocation.PrepareLayout X old (shape B).a₀ (shape B).dH (shape B).ties + (shape B).stride start) + (m : Memory w) (rs : List (Report w)) + (run : Build.Run X S.graph (Nat.two_pow_pos _) hC F S.port_order S.degree_bounds.2 c Tₛ old + start + (shape B).stride cap L m rs) : SourceWalk (SourceOnline.Visit.Runs + (A := BlockProgram.script B)) (List.ofFn (visit B X c old start cap)) m rs := by + have raw := Scheduled.sources X S.graph (Nat.two_pow_pos _) hC F S.port_order S.degree_bounds.2 + c Tₛ old start + (shape B).stride cap L m rs run + apply raw.mapAt (visit B X c old start cap) + intro i mem reports workerRun + unfold visit + apply (SourceOnline.Visit.ofWorker_runs (A := BlockProgram.script B) ..).mpr + exact workerRun + +end CompressorRecords.RefreshCore + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshDiagonalFrame.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshDiagonalFrame.lean new file mode 100644 index 0000000000..7e5e6fcf9c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshDiagonalFrame.lean @@ -0,0 +1,145 @@ +import OAI.Computability.VPVNP.CompressorRefreshOperandInputs +import OAI.Computability.VPVNP.CompressorRecordRegisterSetup +import OAI.Computability.VPVNP.PairRefreshDiagonalArguments + +/-! +# Native setup of the two diagonal comparisons at a refresh site + +The six computed registers contain both old half-wire intervals and both starts in the +parent's external bundles. All offsets come from the constructed segment tables. The +expression program hands control directly to the linked comparison code. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.DiagonalFrame + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh +open PhaseRecipe NewSlots PairSimulation NodeArguments RefreshMapOperands OperandInputs +open scoped Fin.CommRing + +variable {a b g dH w pcs regs params d₀ : ℕ} + +/-- Computes the old outgoing and incoming interval endpoints and the corresponding segment +starts in the new external half-wires. -/ +def fields (degree : ℕ) (external : Fin d₀) (I : OperandInputs.Input) : Fin 6 → Expr := + let z := I.parent.siteOrd + let slot := ArgumentSite.portIndex degree z I.lanes + let idx := ArgumentSite.diagonal degree z I.lanes + let oldOut := ArgumentAddress.field degree I.child false slot + let oldIn := ArgumentAddress.field degree I.child true slot + let extOut := ArgumentAddress.fieldStatic I.parent false external + let extIn := ArgumentAddress.fieldStatic I.parent true external + ![oldOut,oldOut.add (.load (I.widthOut.add idx)),extOut.add (.load (I.offOut.add idx)), + oldIn,oldIn.add (.load (I.widthIn.add idx)),extIn.add (.load (I.offIn.add idx))] + +/-- The output-bank indices in the existing diagonal comparison program. -/ +def register : Fin 6 → Fin 10 := ![0,1,2,7,8,9] + +variable (X : State a (a+g)) (p : (X.Base × BitWord g) × Fin (2^a)) + (P : SlotGraph (Fin (2^a)) dH) (hD : 1 < 2^a) (hd : dH+1 ≤ 2^b) + (internal : X.Base × BitWord g → Fin (2^a) × Fin dH → ℕ) (A : Arena) (child parent : ℕ) + (old next : IncidenceDirectory w) (q : Fin 8 → W w) (demand term : W w) (I : OperandInputs.Input) + (pub : Fin 5 → W w) (state : W w) (m : Memory w) + +local notation "Y" => newState X P hD hd internal +local notation "G" => splitSlots X +local notation "port" => bitWordFinEquiv a +local notation "ws" => groupedWidths port (splitWidths X) +local notation "perm" => oldPortMatching G port +local notation "S" => Fintype.card X.Base * 2^a * 2^g * 2^a +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "f" => fields (2^a) (refreshSlots hd (Sum.inl 0)) I +local notation "args" => RefreshDiagonal.argumentPointers X p P hD hd internal A child parent + +private theorem encode {u : W w} {n : ℕ} (h : u.val = n) : u = (n : W w) := + Fin.ext (h.trans (Nat.mod_eq_of_lt (h ▸ u.isLt)).symm) + +/-- Evaluating the fixed setup formulas uses the actual old and new slot layouts. +Incoming half-wires keep their own lengths and their source-bundle ordering. -/ +theorem values {fit : S ≤ 2^w} (h : Describes I pub state m X p P hD hd internal A child parent old next q demand term) + (oldRows : old.ActualColumns X m) (newRows : next.ActualColumns Y m) (data : SegmentFields X q fit m) + (wide : 2^a < 2^w) : + let v : RefreshDiagonal.Pointers w := args + ∀ i, (f i).eval pub state m = ![v.oldOut,v.oldOut+(ws (p,p.2) : W w),v.externalOut, + v.oldIn,v.oldIn+(ws ((perm).symm (p,p.2)) : W w),v.externalIn] i := by + let slot := ArgumentSite.portIndex (2^a) I.parent.siteOrd I.lanes + let idx := ArgumentSite.diagonal (2^a) I.parent.siteOrd I.lanes + have id : idx.eval pub state m = idWord O fit (p,p.2) := + ArgumentSite.diagonal_eval X p pub state m I.parent.siteOrd I.lanes h.site h.lanes wide fit + have sj : slot.eval pub state m = CursorRAM.encode w p.2.val := + ArgumentSite.portIndex_eval X p pub state m I.parent.siteOrd I.lanes h.site h.lanes wide + have oldAt (dir : Bool) := ArgumentAddress.eval_field h.childRep oldRows dir slot p.2 wide sj + have newAt (dir : Bool) := ArgumentAddress.eval_fieldStatic h.parentRep newRows dir (refreshSlots hd (.inl 0)) + have pair := Readback.interval_spec X q m data (p,p.2) + let i := idWord O fit (p,p.2) + have wo : m (q 1+i).val = (ws (p,p.2) : W w) := encode (congrArg Prod.fst pair.1) + have oo : m (q 5+i).val = ((outgoingRecord G port (splitWidths X) (p,p.2)).offset : W w) := encode (congrArg Prod.snd pair.1) + have wi : m (q 7+i).val = (ws ((perm).symm (p,p.2)) : W w) := encode (congrArg Prod.fst pair.2) + have oi : m (q 6+i).val = ((incomingRecord G port (splitWidths X) (p,p.2)).offset : W w) := encode (congrArg Prod.snd pair.2) + have read (head : Expr) (c : Fin 8) (hc : head.eval pub state m = q c) : + (Expr.load (head.add idx)).eval pub state m = m (q c+i).val := by + change m ((head.eval pub state m)+(idx.eval pub state m)).val = _ + rw [hc,id] + dsimp only + intro j + fin_cases j + · exact oldAt false + · exact congrArg₂ (·+·) (oldAt false) ((read _ _ h.widthOut).trans wo) + · have eq := congrArg₂ (·+·) (newAt false) ((read _ _ h.offOut).trans oo) + exact eq.trans (Nat.cast_add ..).symm + · exact oldAt true + · exact congrArg₂ (·+·) (oldAt true) ((read _ _ h.widthIn).trans wi) + · have eq := congrArg₂ (·+·) (newAt true) ((read _ _ h.offIn).trans oi) + exact eq.trans (Nat.cast_add ..).symm + +/-- The native setup's exit satisfies the six-register ABI consumed by +`RefreshDiagonal.compare_arguments`. Its only external accesses are reads. -/ +theorem setup_trace {fit : S ≤ 2^w} (M : Machine w pcs regs params) (c : Config w pcs regs) + (inputs : Fin 6 → Fin regs) (vm : Fin (RegisterSetup.regCount f) ↪ Fin regs) (reg : Fin 10 ↪ Fin regs) + (pc : ℕ → Fin pcs) (link : RegisterSetup.Linked vm inputs M pc (RegisterSetup.lines f)) + (safe : ∀ i j, vm i ≠ inputs j) (outputs : ∀ i, vm (RegisterSetup.output f i) = reg (register i)) + (atStart : c.pc = pc 0) + (h : Describes I (fun i => c.reg (inputs i.castSucc)) (c.reg (inputs (Fin.last 5))) m X p P hD hd internal + A child parent old next q demand term) + (oldRows : old.ActualColumns X m) (newRows : next.ActualColumns Y m) (data : SegmentFields X q fit m) + (wide : 2^a < 2^w) : + ∃ ev d, ev.length = (RegisterSetup.lines f).length ∧ countProbes ev = (∑ i, (f i).loads) ∧ choiceBits ev = [] ∧ + d.pc = pc (RegisterSetup.lines f).length ∧ + d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧ + (args).Ready reg d (ws (p,p.2)) (ws ((perm).symm (p,p.2))) ∧ + (∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j) ∧ + ∀ fuel bs, execute M.program (fuel+ev.length) c m bs = + (execute M.program fuel d m bs).map (fun rep => ⟨ev++rep.events,rep.result⟩) := by + obtain ⟨ev,d,len,probes,paths,ep,priv,pers,vals,frame,run⟩ := RegisterSetup.execute_setup_trace f inputs vm M m pc link safe c atStart + have val (i) := (vals i).trans (values X p P hD hd internal A child parent old next q demand term I _ _ m + h oldRows newRows data wide i) + simp only [outputs] at val + exact ⟨ev,d,len,probes,paths,ep,priv,pers,⟨⟨val 0,val 1,val 2⟩,⟨val 3,val 4,val 5⟩⟩,frame,run⟩ + +/-- Register and continuation postconditions for the physical operand setup. -/ +theorem setup {fit : S ≤ 2^w} (M : Machine w pcs regs params) (c : Config w pcs regs) + (inputs : Fin 6 → Fin regs) (vm : Fin (RegisterSetup.regCount f) ↪ Fin regs) (reg : Fin 10 ↪ Fin regs) + (pc : ℕ → Fin pcs) (link : RegisterSetup.Linked vm inputs M pc (RegisterSetup.lines f)) + (safe : ∀ i j, vm i ≠ inputs j) (outputs : ∀ i, vm (RegisterSetup.output f i) = reg (register i)) + (atStart : c.pc = pc 0) + (h : Describes I (fun i => c.reg (inputs i.castSucc)) (c.reg (inputs (Fin.last 5))) m X p P hD hd internal + A child parent old next q demand term) + (oldRows : old.ActualColumns X m) (newRows : next.ActualColumns Y m) (data : SegmentFields X q fit m) + (wide : 2^a < 2^w) : + ∃ ev d, ev.length = (RegisterSetup.lines f).length ∧ d.pc = pc (RegisterSetup.lines f).length ∧ + d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧ + (args).Ready reg d (ws (p,p.2)) (ws ((perm).symm (p,p.2))) ∧ + (∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j) ∧ + ∀ fuel bs, execute M.program (fuel+ev.length) c m bs = + (execute M.program fuel d m bs).map (fun rep => ⟨ev++rep.events,rep.result⟩) := by + obtain ⟨ev,d,len,_,_,result⟩ := setup_trace X p P hD hd internal A child parent old next q demand term I m M c inputs vm reg pc link safe outputs atStart h oldRows newRows data wide + exact ⟨ev,d,len,result⟩ + +end CompressorRecords.PortRefresh.DiagonalFrame + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshEmit.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshEmit.lean new file mode 100644 index 0000000000..7579927852 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshEmit.lean @@ -0,0 +1,148 @@ +import OAI.Computability.VPVNP.CompressorRefreshEmitBranchOrder +import OAI.Computability.VPVNP.CompressorRefreshEmitSources +import OAI.Computability.VPVNP.CompressorRefreshEmitAfter +import OAI.Computability.VPVNP.CompressorRefreshResidentAdvance +import OAI.Computability.VPVNP.CompressorRefreshGroupSplit + +/-! # All seven windows of the physical degree refresh -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshEmit + +open BurstRAM BlockPlanner Compression DescriptorSpace PassTimeline Schedule SourceOnline +open ScheduledTrace PairSimulation.TraversalRoles PairSimulation.LocalHistory PortRefresh +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable (f : B.Entry → R) (hf : B.IsSolution f) {g w : ℕ} (base : Word w) +variable (positions blocks t cap n : ℕ) (initial : TaggedLayer) (initialFrame : Fin 8 → Word w) +variable (past : List (SelectedLevel B f hf)) (X : State S.portExponent (S.portExponent + g)) + +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "fl" => Script.levelsPerBlock scr * t +local notation "cur" => fl + S.steps +local notation "nxt" => fl + (S.steps + 1) +local notation "loc" => Located.mk t (Pass.refresh (steps := S.steps)) +local notation "start" => Located.first loc B +local notation "ord" => List.length (Script.initial scr) + t * List.length (Script.block scr) +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "he" => Nat.two_pow_pos S.expanderExponent +local notation "hd" => And.right S.degree_bounds +local notation "Choice" => Refresh.DyadicRefreshChoice X S.graph he hc B.refresh +local notation "shape" => RefreshBlockPlan.shape B +local notation "sites" => LevelRecipe.Shape.ports shape +local notation "expDeg" => LevelRecipe.Shape.dH shape +local notation "numTies" => LevelRecipe.Shape.ties shape +local notation "o" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "role" => Scalars.Pass.refresh S.portExponent (S.degreeExponent 0) S.expanderExponent +local notation "hr" => ScheduledRates.headerRate (BlockProgram.geometry B) role +local notation "cr" => Build.chargeFactor S.graph he hc B.refresh numTies +local notation "res" => + CompiledResident.resident B f hf base positions blocks n initial initialFrame +local notation "P" => SourceOnline.Packet scr w +local notation "logs" => (fun ps : List P => List.flatMap SourceWalk.Packet.reports ps) + +variable (encode : Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh → List Bool) +variable (m : Memory w) (termCap : ℕ) +local notation "fits" => termConstant S.graph he hc B.refresh (RefreshBlockPlan.order B) + + 4 * Nat.clog 2 (X.maxWireWidth + 1) ≤ w +local notation "workerBudget" => + TermWorker.budget B.refresh numTies (sites * expDeg) w X.maxWireWidth + +/-- The common prefix and every selected suffix are constructed by running +the native workers. All post-selector records inhabit the output memory of +that selector, including the completed current graph and traversal history. -/ +theorem build (index : past.length = cur) (live : t < blocks) (size : X.positions ≤ positions) + (fit : endAddress L < 2 ^ w) (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory - 1).val = (levelWords L : Word w)) + (headerClock : scanCap scr (ScheduledRates.headerCap (BlockProgram.geometry B) role) ≤ cap) + (termClock : scanCap scr (max 64 termCap) ≤ cap) (siteRoom : X.positions < 2 ^ w) + (degree : slotDegree S < 2 ^ w) (demandWidth : 2 ^ S.portExponent * X.maxWireWidth < 2 ^ w) + (bits : fits) (nextWidth : ∀ c : Choice, + (Refresh.dyadicRefreshNext X S.graph he hc B.refresh S.port_order hd c).maxWireWidth < 2 ^ w) + (budget : workerBudget ≤ termCap) (positive : 0 < termCap) (stored : res past X m) : + ∃ hs ds term tail, Sources B f hf base positions blocks t cap n initial initialFrame past X + encode m hs ds term tail := by + classical + have curr : CurrentGraph.Current L (cur) X n m := index ▸ stored.1.2.1 + obtain ⟨hs, ds, before⟩ := RefreshBefore.run B f hf base positions blocks t X termCap cap + m n live size fit rows pitch headerClock termClock curr siteRoom degree demandWidth positive + have baseEq : start = ord + (RefreshHeaders.window B).before.length := by + rw [RefreshBefore.Before.start_offset]; rfl + have first := before.group + rw [← baseEq] at first + let headerMem := post m hs + have entry : RefreshCore.EntryState B base positions blocks t X headerMem := + ⟨before.inputHeader, before.headerRows, before.headerPitch⟩ + have clock : scanCap scr 42 ≤ cap := by unfold scanCap at termClock ⊢; omega + have branch (c : Choice) : ∃ (p : P) (tail : List P), + SourceOnline.Group scr L base cap (start + (hs ++ ds).length) (directoryRows L) + (post m (hs ++ ds)) [p] ∧ + SourceOnline.Group scr L base cap (start + (hs ++ ds).length + 1) (directoryRows L) + p.output tail ∧ + p.stage.choices = List.ofFn (workerTapes o w c) ∧ + (∀ q ∈ tail, q.stage.choices = List.replicate q.stage.choices.length []) ∧ + start + (hs ++ ds).length + 1 + tail.length = (loc).finish B ∧ + res (past ++ [RefreshPlacement.selectedLevel B f hf X c (encode c)]) + (Refresh.dyadicRefreshNext X S.graph he hc B.refresh S.port_order hd c) + (post p.output tail) ∧ + RAMBuckets.cost Report.probes (logs ((hs ++ ds) ++ p :: tail)) ≤ + hr + cr * X.positions + X.positions * (18 * 2 ^ (S.degreeExponent 0) + 4) + 27 := by + obtain ⟨pre, p, rest, split, built⟩ := RefreshCore.build_split B f hf base positions blocks t + X c termCap cap headerMem live size fit entry before.represented bits (nextWidth c) + budget positive termClock + let u := RefreshPlacement.selectedLevel B f hf X c (encode c) + have hheader := before.headers_eq c (encode c) + have hh := before.header_for c (encode c) + have counts := before.counts_for c (encode c) + have align := before.matches c (encode c) (out := post headerMem pre) + (rs := logs pre) (fit := split.fits) (by rw [← hheader]; exact split.prepare) + obtain ⟨_, middle, input, suffix⟩ := split.groups + have ordSel := selector_ordinal before split + have middle' : SourceOnline.Group scr L base cap (start + (hs ++ ds).length) + (directoryRows L) (post m (hs ++ ds)) [p] := by + rw [ordSel, align.2]; exact middle + let raw := after headerMem (eventLog (logs (pre ++ p :: rest))) + have rawEq : raw = post p.output rest := by + change post headerMem (pre ++ p :: rest) = _ + rw [post_append, ← input] + simp only [post, List.flatMap_cons, SourceWalk.after_append, SourceWalk.Packet.output] + obtain ⟨copies, pubs, finished⟩ := after_core B base positions blocks t cap f hf X c (encode c) + termCap headerMem (logs (pre ++ p :: rest)) live size fit clock before.headerRows + before.headerPitch _ counts before.atOldHeads before.atNewHeads built + obtain ⟨_, atCopy, finish⟩ := branch_ordinals before split (copies ++ pubs) finished.count + have joined := suffix.append (by rw [← rawEq, atCopy]; exact finished.group) + have stateEq : post p.output (rest ++ (copies ++ pubs)) = post (post raw copies) pubs := by + rw [post_append, ← rawEq, post_append] + have next : res (past ++ [u]) (u.pass.next u.term) + (post p.output (rest ++ (copies ++ pubs))) := by + rw [stateEq] + exact RefreshPayloadHistory.advance B base positions blocks t f hf X c (encode c) + ⟨cur, before.oldLive⟩ ⟨nxt, before.newLive⟩ rfl (Nat.add_assoc ..).symm index live size fit + stored hh hheader before.represented before.atNewHeads built finished.copied + finished.installed + refine ⟨p, rest ++ (copies ++ pubs), middle', ?_, split.selTapes, ?_, ?_, next, ?_⟩ + · rw [ordSel]; exact joined + · intro q hq + exact (List.mem_append.mp hq).elim (split.tailQuiet q) (finished.quiet q) + · exact finish + · exact aggregate B X f hf base positions blocks t cap termCap c before align.1 built + finished.charge + choose term tail middle last choices quiet lengths next charge using branch + exact ⟨hs, ds, term, tail, before, first, middle, last, choices, quiet, lengths, next, charge⟩ + +end CompressorRecords.RefreshEmit + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshEmitAfter.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitAfter.lean new file mode 100644 index 0000000000..aa0a0981f3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitAfter.lean @@ -0,0 +1,199 @@ +import OAI.Computability.VPVNP.CompressorRefreshPlacementEmission +import OAI.Computability.VPVNP.CompressorRefreshCoreBuild +import OAI.Computability.VPVNP.CompressorRefreshCopyGroup +import OAI.Computability.VPVNP.CompressorRefreshPayloadSpace +import OAI.Computability.VPVNP.CompressorDeterministicGroup + +/-! # The canonical incidence and traversal output following a selected refresh -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshEmit + +open BurstRAM BlockPlanner Compression DescriptorSpace PortRefresh PhaseRecipe Schedule +open SourceOnline SourceTransport +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable {g w : ℕ} (base : Word w) (positions blocks t cap : ℕ) +variable (f : B.Entry → R) (hf : B.IsSolution f) (X : State S.portExponent (S.portExponent + g)) +local notation "he" => Nat.two_pow_pos S.expanderExponent +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "hd" => And.right S.degree_bounds +variable (c : Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) + +local notation "level" => RefreshPlacement.selectedLevel B f hf X c sel +local notation "Y" => Refresh.dyadicRefreshNext X S.graph he hc B.refresh S.port_order hd c +local notation "N" => State.positions Y * 2 ^ (S.degreeExponent 0) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "first" => Script.levelsPerBlock scr * t +local notation "cur" => (first) + S.steps +local notation "nxt" => (first) + (S.steps + 1) +local notation "head" => levelStart L (cur) +local notation "start" => arrayBase L (cur) +local notation "orig" => packedIncidence L w (cur) (SelectedLevel.oldSlots level) +local notation "shape" => RefreshBlockPlan.shape B +local notation "P" => Allocation.plan X (S.degreeExponent 0) (LevelRecipe.Shape.dH shape) + (LevelRecipe.Shape.ties shape) (LevelRecipe.Shape.stride shape) start +local notation "W₂" => BlockGroups.refresh B 2 +local notation "W₃" => BlockGroups.refresh B 3 +local notation "W₄" => BlockGroups.refresh B 4 +local notation "W₅" => BlockGroups.refresh B 5 +local notation "W₆" => BlockGroups.refresh B 6 +local notation "off" => List.length (Script.initial scr) + t * List.length (Script.block scr) + +/-- Reports and data readbacks for the six incidence copies and the nine +placement and traversal publications, in their actual order. -/ +structure After (m : Memory w) (copies publications : List (Packet scr w)) : Prop where + group : SourceOnline.Group scr L base cap (off + (W₂).before.length) (directoryRows L) m + (copies ++ publications) + phases : (copies ++ publications).map (fun p => p.stage.phase) = + (W₂).indices ++ (((W₃).indices ++ (W₄).indices) ++ ((W₅).indices ++ (W₆).indices)) + count : (copies ++ publications).length = 15 + quiet : ∀ p ∈ copies ++ publications, p.stage.choices = List.replicate p.stage.choices.length [] + charge : RAMBuckets.cost Report.probes ((copies ++ publications).flatMap SourceWalk.Packet.reports) ≤ + X.positions * (18 * 2 ^ (S.degreeExponent 0) + 4) + 27 + copied : RefreshCopyPackets.Copied B base positions blocks t X c m (copies.flatMap SourceWalk.Packet.reports) + installed : RefreshPlacement.TailResult B base positions blocks t cap f hf X c sel + (post m copies) publications + +/-- The six canonical copies charge three units per populated cell. The remaining +nine visits contribute the placement scan and the fixed header publications. -/ +theorem After.charge_eq {m : Memory w} {copies publications : List (Packet scr w)} + (out : After B base positions blocks t cap f hf X c sel m copies publications) : + RAMBuckets.cost Report.probes ((copies ++ publications).flatMap SourceWalk.Packet.reports) = + 9 * (Fintype.card (Y).Base * 2^(S.degreeExponent 0)) + + 9 * (X.positions * 2^(S.degreeExponent 0)) + 4 * X.positions + 27 := by + rw [List.flatMap_append,RAMBuckets.cost_append,out.copied.charge,out.copied.calls,out.installed.charge, + Refresh.dyadicRefreshNext_positions X S.graph he hc B.refresh S.port_order hd c] + omega + +private theorem published_keep {layout : Layout} {idx dH : ℕ} {v : SelectedLevel B f hf} + {m m' : Memory w} (old : LevelFields.Published layout idx v dH m) + (kept : ∀ n < 6, m' (levelStart layout idx + n) = m (levelStart layout idx + n)) : + LevelFields.Published layout idx v dH m' := + ⟨old.room, (kept 0 (by decide)).trans old.vertices, (kept 1 (by decide)).trans old.degree, + (kept 2 (by decide)).trans old.lanes, (kept 3 (by decide)).trans old.residual, + (kept 4 (by decide)).trans old.nextDegree, (kept 5 (by decide)).trans old.expander⟩ + +private theorem copy_paths {a b : ℕ} (Z : State a b) (T U : IncidenceDirectory w) (m : Memory w) : + let rs := CopyIncidence.reports Z T U CopyIncidence.allColumns m + branchPaths rs = List.replicate rs.length [] := by + intro rs + have h := (CopyIncidence.reports_work Z T U CopyIncidence.allColumns m).2.2 + exact List.map_eq_replicate_iff.mpr (fun r hr => (h r hr).2.2) + +open private offset_length from OAI.Computability.VPVNP.CompressorBlockHeadSequence + +set_option maxHeartbeats 900000 in +private theorem after_of_groups (mid : Memory w) (qs ps : List (Packet scr w)) + (grp : SourceOnline.Group scr L base cap (off + (W₂).before.length) (directoryRows L) mid qs) + (lab : qs.map (fun p => p.stage.phase) = (W₂).indices) + (copied : RefreshCopyPackets.Copied B base positions blocks t X c mid (qs.flatMap SourceWalk.Packet.reports)) + (done : RefreshPlacement.TailResult B base positions blocks t cap f hf X c sel (post mid qs) ps) : + After B base positions blocks t cap f hf X c sel mid qs ps := by + have len : qs.length = 6 := by + have h := congrArg List.length lab + simp only [List.length_map, Window.indices, List.length_ofFn] at h + exact h + have nps : ps.length = 9 := by + have h := congrArg List.length done.phases + simp only [List.length_map, List.length_append, Window.indices, List.length_ofFn] at h + exact h.trans (by rfl) + have offNext : off + (W₂).before.length + qs.length = off + (W₃).before.length := by + have step := offset_length (BlockGroups.refreshParts B) 2 + (by rw [BlockGroups.refreshParts_length]; decide) + have six : ((BlockGroups.refreshParts B)[2]'(by rw [BlockGroups.refreshParts_length]; decide)).length = 6 := + List.length_ofFn .. + rw [six] at step + rw [len, BlockGroups.refresh_offset, BlockGroups.refresh_offset] + change off + (_ + ((BlockGroups.refreshParts B).take 2).flatten.length) + 6 = + off + (_ + ((BlockGroups.refreshParts B).take 3).flatten.length) + rw [step]; omega + have qbits := PublishedHeads.chronological_tapes mid qs grp.chronological + rw [copied.reports_eq, copy_paths] at qbits + have allSites := Refresh.dyadicRefreshNext_positions X S.graph he hc B.refresh S.port_order hd c + have vertices : Fintype.card (Y).Base ≤ (Y).positions := by + unfold State.positions + rw [Fintype.card_prod]; exact Nat.le_mul_of_pos_right _ Fintype.card_pos + have calls := copied.calls + have le := Nat.mul_le_mul_right (2 ^ S.degreeExponent 0) vertices + rw [allSites] at calls le + have nextGroup : SourceOnline.Group scr L base cap (off + (W₂).before.length + qs.length) + (directoryRows L) (post mid qs) ps := + Eq.mp (congrArg (fun i => SourceOnline.Group scr L base cap i (directoryRows L) (post mid qs) ps) offNext.symm) done.group + refine ⟨grp.append nextGroup, ?_, ?_, ?_, ?_, copied, done⟩ + · rw [List.map_append, lab, done.phases] + · rw [List.length_append, len, nps] + · intro p hp + rcases List.mem_append.mp hp with h | h + · exact ScheduledTrace.packet_quiet_of_flat qbits p h + · exact ScheduledTrace.packet_quiet_of_flat done.tapes p h + · rw [List.flatMap_append, RAMBuckets.cost_append, copied.charge, done.charge, Nat.mul_add] + have h := Nat.mul_le_mul_left 3 le + linarith only [calls, h] + + +set_option maxHeartbeats 950000 in +/-- Complete every post-core window from the actual core's stored temporary graph. -/ +theorem after_core (termCap : ℕ) (m : Memory w) (rs : List (Report w)) (live : t < blocks) + (size : X.positions ≤ positions) (fit : endAddress L < 2 ^ w) + (clock : scanCap scr 42 ≤ cap) (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory - 1).val = (levelWords L : Word w)) + (dH : ℕ) (old : LevelFields.Published L (cur) level dH m) + (oldHeads : TraversalHeaders.HeadBank L (cur) (level).oldSlots m) + (newHeads : TraversalHeaders.HeadBank L (nxt) N m) + (built : RefreshCore.Built B base positions blocks t X c termCap m rs) : + ∃ copies publications, + After B base positions blocks t cap f hf X c sel (after m (eventLog rs)) copies publications := by + let mid := after m (eventLog rs) + have space := RefreshPayloadHistory.Space.ofLayout B base positions blocks t X live size fit + have next : cur + 1 = nxt := Nat.add_assoc .. + have headerLo := space.header_before + have stop := space.scratch_next + rw [next] at stop + have lo (x : ℕ) (hx : x < start) : mid x = m x := + after_outside m built.writes (fun h => hx.not_ge h.1) + have hi (x : ℕ) (hx : levelStart L (nxt) ≤ x) : mid x = m x := + after_outside m built.writes (fun h => h.2.not_ge (stop.trans hx)) + have bank₁ := newHeads.keep (fun n _ => hi _ (Nat.le_add_right ..)) + have hdrFit := PublishedHeads.level_room B base positions blocks t S.steps live le_rfl fit + have header := RefreshCore.Header.ofPublished old oldHeads rfl (show 0 < 6 by decide) (by omega) + have data₁ := header.keep (m' := mid) (fun n hn => lo _ (by omega)) + have ctl := Window.lowCells (A := scr) L base rfl rfl + ((levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit) + have low := space.header_first + have rows₁ := (lo _ (ctl.1.trans_le (by omega))).trans rows + have pitch₁ := (lo _ (ctl.2.trans_le (by omega))).trans pitch + have cap12 : scanCap scr 12 ≤ cap := by unfold scanCap at clock ⊢; omega + obtain ⟨qs, grp, lab, copied⟩ := RefreshCopyPackets.group B base positions blocks t X c cap + mid orig live size fit rows₁ pitch₁ cap12 data₁ bank₁ built.represents + let out := post mid qs + have tableEarly := space.array_before + rw [next] at tableEarly + have keep (x : ℕ) (hx : x < start) : out x = m x := by + apply (copied.frame x (.inl (hx.trans_le (tableEarly.trans (Nat.le_add_right ..))))).trans + exact lo x hx + have hnew := published_keep B f hf old + (m' := out) (fun n hn => keep _ (by omega)) + have heads₂ := oldHeads.keep (m' := out) (fun n hn => keep _ (by change n < 66 at hn; omega)) + have rows₂ := (keep _ (ctl.1.trans_le (by omega))).trans rows + have pitch₂ := (keep _ (ctl.2.trans_le (by omega))).trans pitch + obtain ⟨ps, done⟩ := RefreshPlacement.install_tail B base positions blocks t cap f hf X c sel + out live size fit rows₂ pitch₂ clock dH hnew heads₂ + exact ⟨qs, ps, after_of_groups B base positions blocks t cap f hf X c sel mid qs ps grp lab copied done⟩ + +end CompressorRecords.RefreshEmit + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshEmitBranchOrder.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitBranchOrder.lean new file mode 100644 index 0000000000..f5b6b2180e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitBranchOrder.lean @@ -0,0 +1,101 @@ +import OAI.Computability.VPVNP.CompressorRefreshBeforeMatch +import OAI.Computability.VPVNP.CompressorRefreshGroupSplit +import OAI.Computability.VPVNP.CompressorPassTimeline +import OAI.Computability.VPVNP.CompressorBlockHeadSequence + +/-! # Ordinal boundaries of an actual selected refresh + +The common header and demand packets reach the same selector ordinal as the +selected native core. Its remaining workers end where the six incidence copies +begin. The nine traversal publications following those copies end the refresh. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.RefreshEmit + +open BurstRAM Compression BlockPlanner PassTimeline PortRefresh SourceOnline +open scoped Fin.CommRing +open private offset_length from OAI.Computability.VPVNP.CompressorBlockHeadSequence + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} {B : S.Templates} +variable {f : B.Entry → R} {hf : B.IsSolution f} {g w : ℕ} {base : Word w} +variable {positions blocks t cap termCap : ℕ} {X : State S.portExponent (S.portExponent+g)} +variable {c : Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh} +local notation "scr" => BlockProgram.script B +local notation "sh" => RefreshBlockPlan.shape B +local notation "d" => LevelRecipe.Shape.ports sh +local notation "h" => LevelRecipe.Shape.dH sh +local notation "ties" => LevelRecipe.Shape.ties sh +local notation "deg" => LevelRecipe.Shape.degree sh +local notation "loc" => Located.mk t (Pass.refresh (steps := S.steps)) +local notation "start" => Located.first loc B +local notation "ord" => List.length (Script.initial scr)+t*List.length (Script.block scr) +local notation "coreStart" => ord+List.length (Window.before (BlockGroups.refresh B 1)) +local notation "copyStart" => ord+List.length (Window.before (BlockGroups.refresh B 2)) +local notation "Pkt" => Packet scr w + +private theorem header_end : start+3 = coreStart := by + change ord+((List.finRange S.steps).flatMap (BlockProgram.shrink B)).length+3 = _ + rw [BlockGroups.refresh_offset,Nat.add_assoc] + rfl + +private theorem core_end : coreStart+(6+ties+d*h+deg) = copyStart := by + have parts := BlockGroups.refreshParts_length B + have next := offset_length (BlockGroups.refreshParts B) 1 (by rw [parts]; decide) + have size : ((BlockGroups.refreshParts B)[1]'(by rw [parts]; decide)).length = 6+ties+d*h+deg := by + change ((LevelRecipe.order sh).map _).length = _ + rw [List.length_map,RefreshCore.stage_split] + simp only [RefreshPrepare.stages,RefreshCore.afterTerm,List.length_append,List.length_cons, + List.length_nil,List.length_finRange,List.length_map] + omega + rw [size] at next + rw [BlockGroups.refresh_offset,BlockGroups.refresh_offset] + change ord+(_+((BlockGroups.refreshParts B).take 1).flatten.length)+_ = + ord+(_+((BlockGroups.refreshParts B).take 2).flatten.length) + rw [next]; omega + +variable {m m' : Memory w} {hs ds pre rest : List (Packet (BlockProgram.script B) w)} + {packet : Packet (BlockProgram.script B) w} +variable (before : RefreshBefore.Before B f hf base positions blocks t X cap m hs ds) +variable (split : RefreshCore.SelectedSplit B f hf base positions blocks t X c termCap cap m' pre packet rest) + +include before split + +/-- Both physical prefixes launch their selector at the same global row. -/ +theorem selector_ordinal : start+(hs++ds).length = coreStart+pre.length := by + have header := header_end (B := B) (t := t) + rw [before.length,split.preCount] + omega + +/-- The absolute selector, first copy, and one-past-end row of a selected +refresh, with the actual fifteen post-core packets in their original order. -/ +theorem branch_ordinals (extra : List Pkt) (count : extra.length = 15) : + start+(hs++ds).length = coreStart+pre.length ∧ + coreStart+pre.length+1+rest.length = copyStart ∧ + start+(hs++ds).length+1+(rest++extra).length = (loc).finish B := by + have nr : rest.length = 2+d*h+deg := by + have num := congrArg List.length split.tailPhases + simp only [List.length_map,Window.indices,List.length_ofFn] at num + change rest.length = (RefreshCore.afterTerm B).length at num + simp only [RefreshCore.afterTerm,List.length_map,List.length_finRange,List.length_append, + List.length_cons,List.length_nil] at num + omega + refine ⟨selector_ordinal before split,?_,?_⟩ + · have endOf := core_end (B := B) (t := t) + rw [split.preCount,nr]; omega + · change _ = start+(BlockProgram.refresh B).length + rw [before.length,List.length_append,count,nr,BlockProgram.refresh_length] + omega + +end CompressorRecords.RefreshEmit + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshEmitCost.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitCost.lean new file mode 100644 index 0000000000..984da6179b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitCost.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.CompressorRefreshBeforeGroup +import OAI.Computability.VPVNP.CompressorNativePassRates + +/-! +# Communication cost of the entire refresh pass + +The three header publications, the selected native core, six incidence copies, +and the traversal publications account for all source reports. Their combined +charge is linear in the number of positions of the old graph. Calendar costs +use the number of actual visits in the fixed block. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.RefreshEmit + +open BurstRAM BlockPlanner Schedule Compression DescriptorSpace SourceOnline ScheduledTrace +open PortRefresh PairSimulation.LocalHistory +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +local notation "scr" => BlockProgram.script B +local notation "role" => Scalars.Pass.refresh S.portExponent (S.degreeExponent 0) S.expanderExponent +local notation "headerRate" => ScheduledRates.headerRate (BlockProgram.geometry B) role +local notation "coreRate" => Build.chargeFactor S.graph (Nat.two_pow_pos S.expanderExponent) + (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh (LevelRecipe.Shape.ties (RefreshBlockPlan.shape B)) +local notation "copyRate" => 18*2^(S.degreeExponent 0)+4 + +/-- One fixed source charge per old position. The two additive publication +costs are absorbed because every incoming state has at least one position. -/ +def rawRate : ℕ := headerRate + coreRate + copyRate + 27 + +/-- Bound the actual combined source charge by the uniform per-position rate. -/ +theorem raw_le {a g : ℕ} (X : State a g) {work : ℕ} + (actual : work ≤ headerRate + coreRate*X.positions + X.positions*copyRate + 27) : + work ≤ rawRate B * X.positions := by + have hdr := Nat.le_mul_of_pos_right headerRate X.positions_pos + have pub := Nat.le_mul_of_pos_right 27 X.positions_pos + rw [rawRate,Nat.add_mul,Nat.add_mul,Nat.add_mul] + rw [Nat.mul_comm X.positions copyRate] at actual + omega + +variable {g w : ℕ} (X : State S.portExponent (S.portExponent+g)) +local notation "Pkt" => Packet scr w +local notation "logs" => (fun ps : List Pkt ↦ List.flatMap SourceWalk.Packet.reports ps) + +/-- The online recipe and frame probes of the shared prefix, selected worker +and remaining packets are included in the same linear bound. -/ +theorem groupCost_bound (pre : List Pkt) (term : Pkt) (tail : List Pkt) + (visits : (pre++term::tail).length ≤ (scr).block.length) + (source : RAMBuckets.cost Report.probes (logs (pre++term::tail)) ≤ + headerRate + coreRate*X.positions + X.positions*copyRate + 27) : + groupCost scr pre + groupCost scr [term] + groupCost scr tail ≤ nativePassRate scr (rawRate B)*X.positions := by + rw [← groupCost_split_selector] + exact groupCost_nativeRate scr _ (rawRate B) X.positions X.positions_pos visits (raw_le B X source) + +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) +variable (base : Word w) (positions blocks t cap termCap : ℕ) +variable (c : Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) + +/-- The deterministic prefix and the selected prefix may have distinct packet +records. Their reports agree at the actual selector, so the original core +bound pays for the shared prefix exactly once. -/ +theorem aggregate {m first : Memory w} {hs ds pre tail copies publications : List Pkt} {term : Pkt} + (before : RefreshBefore.Before B f hf base positions blocks t X cap m hs ds) + (same : logs ds = logs pre) + (core : RefreshCore.Built B base positions blocks t X c termCap first (logs (pre++term::tail))) + (finish : RAMBuckets.cost Report.probes (logs (copies++publications)) ≤ X.positions*copyRate+27) : + RAMBuckets.cost Report.probes (logs ((hs++ds)++term::(tail++(copies++publications)))) ≤ + headerRate + coreRate*X.positions + X.positions*copyRate + 27 := by + have hdr := RefreshBefore.header_charge B f hf base positions blocks X m + ((scr).levelsPerBlock*t+S.steps) ((scr).levelsPerBlock*t+(S.steps+1)) + have hhdr : RAMBuckets.cost Report.probes (logs hs) = headerRate := by + rw [before.headerReports]; exact hdr + have all : logs ((hs++ds)++term::(tail++(copies++publications))) = + logs hs ++ logs (pre++term::tail) ++ logs (copies++publications) := by + simp only [List.flatMap_append,List.flatMap_cons,List.append_assoc] at same ⊢ + rw [same] + rw [all,RAMBuckets.cost_append,RAMBuckets.cost_append,hhdr] + have c₁ := core.charge + have c₂ := finish + omega + +end CompressorRecords.RefreshEmit + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshEmitSources.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitSources.lean new file mode 100644 index 0000000000..0722f381b0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitSources.lean @@ -0,0 +1,67 @@ +import OAI.Computability.VPVNP.CompressorRefreshBeforeMatch +import OAI.Computability.VPVNP.CompressorRefreshEmitCost +import OAI.Computability.VPVNP.CompressorCompiledResident +import OAI.Computability.VPVNP.CompressorPassTimeline + +/-! # Source packets of a complete refresh occurrence -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshEmit + +open BurstRAM BlockPlanner Compression DescriptorSpace PassTimeline Schedule SourceOnline +open ScheduledTrace PairSimulation.TraversalRoles PairSimulation.LocalHistory PortRefresh +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable (f : B.Entry → R) (hf : B.IsSolution f) {g w : ℕ} (base : Word w) +variable (positions blocks t cap n : ℕ) (initial : TaggedLayer) (initialFrame : Fin 8 → Word w) +variable (past : List (SelectedLevel B f hf)) (X : State S.portExponent (S.portExponent + g)) + +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "loc" => (Located.mk t (Pass.refresh (steps := S.steps))) +local notation "start" => Located.first loc B +local notation "o" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "he" => Nat.two_pow_pos S.expanderExponent +local notation "Choice" => Refresh.DyadicRefreshChoice X S.graph he hc B.refresh +local notation "P" => SourceOnline.Packet scr w +local notation "logs" => (fun ps : List P => List.flatMap SourceWalk.Packet.reports ps) +local notation "hr" => ScheduledRates.headerRate (BlockProgram.geometry B) + (Scalars.Pass.refresh S.portExponent (S.degreeExponent 0) S.expanderExponent) +local notation "cr" => Build.chargeFactor S.graph he hc B.refresh + (LevelRecipe.Shape.ties (RefreshBlockPlan.shape B)) +local notation "res" => + CompiledResident.resident B f hf base positions blocks n initial initialFrame + +/-- All branches begin at the same completed preparation. The only choice +packet is the native motif selector, with the term's own encoded choices. -/ +structure Sources (encode : Choice → List Bool) (m : Memory w) (hs ds : List P) + (term : Choice → P) (tail : Choice → List P) : Prop where + before : RefreshBefore.Before B f hf base positions blocks t X cap m hs ds + first : SourceOnline.Group scr L base cap start (directoryRows L) m (hs ++ ds) + middle : ∀ c, SourceOnline.Group scr L base cap (start + (hs ++ ds).length) (directoryRows L) + (post m (hs ++ ds)) [term c] + last : ∀ c, SourceOnline.Group scr L base cap (start + (hs ++ ds).length + 1) (directoryRows L) + (term c).output (tail c) + termBits : ∀ c, (term c).stage.choices = List.ofFn (workerTapes o w c) + emptyTail : ∀ c, ∀ p ∈ tail c, p.stage.choices = List.replicate p.stage.choices.length [] + lengths : ∀ c, start + (hs ++ ds).length + 1 + (tail c).length = (loc).finish B + stored : ∀ c, res (past ++ [RefreshPlacement.selectedLevel B f hf X c (encode c)]) + (Refresh.dyadicRefreshNext X S.graph he hc B.refresh S.port_order (And.right S.degree_bounds) c) + (post (term c).output (tail c)) + rawCharge : ∀ c, RAMBuckets.cost Report.probes (logs ((hs ++ ds) ++ term c :: tail c)) ≤ + hr + cr * X.positions + X.positions * (18 * 2 ^ (S.degreeExponent 0) + 4) + 27 + +end CompressorRecords.RefreshEmit + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshEmitter.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitter.lean new file mode 100644 index 0000000000..2227a67d0d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshEmitter.lean @@ -0,0 +1,84 @@ +import OAI.Computability.VPVNP.CompressorRefreshPassRun +import OAI.Computability.VPVNP.CompressorCanonicalWorkerFit +import OAI.Computability.VPVNP.CompressorScheduledPassCases +import OAI.Computability.VPVNP.CompressorBlockClock + +/-! +# A uniform native refresh emitter for the advised field + +One input-length threshold suffices for every current graph, its true +partial history, every term, the coefficient interpretation, and the live +memory. The incoming and all selected outgoing widths satisfy the bounds +carried by the iterated compression. The emitted pass charges the actual +compiled refresh worker rate. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshPass + +open Compression BlockPlanner DescriptorSpace Schedule CursorBounds Filter +open BurstRAM PairSimulation.TraversalRoles PairSimulation.LocalHistory ScheduledTrace +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +set_option maxHeartbeats 1400000 in +-- The port-motif choice and the scheduled pass share a dependent finite index. +theorem eventually_emitAt (factor : ℕ) (hb : 1 ≤ factor) : ∀ᶠ n : ℕ in atTop, + ∀ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) + {g : ℕ} (X : State S.portExponent (S.portExponent + g)) + (pub : Fin 11 → Word (wordBits factor n)) (blocks round cap : ℕ) + (shrinking : Fin S.steps → ℕ) (initial : TaggedLayer) + (initialFrame : Fin 8 → Word (wordBits factor n)), + let positions := initialPositions factor n + let A := BlockProgram.script B + let L := BlockProgram.layout B (pub 2).val positions blocks + let small := BlockClock.small B factor n + let rate := nativePassRate A (commonRawRate shrinking (RefreshEmit.rawRate B)) * positions + let resident := + CompiledResident.resident B f hf (pub 2) positions blocks n initial initialFrame + endAddress L < 2 ^ (wordBits factor n) → small ≤ cap → + Online.Run.ControlBounds A.plan small (w := wordBits factor n) → + EmitAt resident pub (levelWords L : Word (wordBits factor n)) (directoryRows L) + cap small rate blocks positions n (PassOrigin.refresh X) ⟨round,.refresh⟩ := by + have sizes := CursorRAM.eventual_word_room factor hb (CursorRAM.bounded_positions factor) + have degrees := CursorRAM.eventual_word_room factor hb (PolynomiallyBounded.const (slotDegree S)) + have widths := CursorRAM.eventual_word_room factor hb + ((PolynomiallyBounded.const (2 ^ S.portExponent)).mul PolynomiallyBounded.id) + filter_upwards [sizes,degrees,widths,CanonicalWorker.eventually_fit B factor hb, + PrefixLevelScale.eventually_refresh B factor hb] with n hpos hdeg hport hterm hnat + intro R _ f hf g X pub blocks round cap shrinking initial initialFrame positions A L small rate + resident room clock little encode past m live index size width outputs ready + let w := wordBits factor n + let o := PassOrigin.refresh (B := B) (f := f) (hf := hf) X + let termCap := SelectedTermWorker.clock B w + let first := defaultSelection o + have nativeFit := hnat R f hf X first width (outputs first).2 + have positive : 0 < termCap := by + change 0 < (SelectedTerms.stepConstant B + 7) * (2 * w + 1) + exact Nat.mul_pos (Nat.succ_pos _) (Nat.succ_pos _) + have big : Online.Run.ControlBounds A.plan cap (w := w) := + ⟨little.tags,little.calendar.trans clock,little.launch.trans clock⟩ + have depth : past.length = A.levelsPerBlock * round + S.steps := by + rw [show A.levelsPerBlock = S.steps + 1 from rfl] + simpa only [PassTimeline.Located.depth,Nat.mul_comm round] using index + have fixed := BlockClock.fixed B factor n + exact realize B f hf pub positions blocks round n X initial initialFrame termCap cap small + shrinking encode past m live depth size room clock big little ready fixed.2.2.1 + (BlockClock.dynamic B factor n).2 (size.trans_lt hpos) hdeg + ((Nat.mul_le_mul_left (2 ^ S.portExponent) width).trans_lt hport) + (hterm o size width).2.1 nativeFit.1 nativeFit.2.1 positive + (fun c ↦ (hnat R f hf X c width (outputs c).2).2.2) + +end CompressorRecords.RefreshPass + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshExternalReplay.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshExternalReplay.lean new file mode 100644 index 0000000000..05412306c6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshExternalReplay.lean @@ -0,0 +1,70 @@ +import OAI.Computability.VPVNP.CompressorRefreshFrontFrame +import OAI.Computability.VPVNP.CompressorRecordRefreshInputs + +/-! +# Replaying the three ordered external refresh scans + +The prepared old incidence data determine the intermediate bundle table and the +initial segment cursor. Uniqueness of each deterministic run identifies these states +in the particular raw reports selected by the complete degree-refresh execution. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.FrontFrame +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh StageFrame SourceTransport Allocation NewSlots +open RefreshRAM (AtCursor) + +variable {w a g : ℕ} (X : State a (a+g)) (T : IncidenceDirectory w) (a₀ dH t stride start : ℕ) +local notation "P" => plan X a₀ dH t stride start +local notation "Q" => Plan.scratch P w +local notation "S" => Plan.segments P +local notation "N" => Plan.sites P +local notation "L" => (word (bits := w) (2^g)) +local notation "O" => IncidenceDirectory.baseOrder X + +/-- Each stage of the actual physical prepass returns consecutive ordinals and +accesses only its proven footprint, before a scheduler installs its own frame. -/ +theorem external_scans (before : ∀ c, (T.column c).val+S ≤ start) (room : (P).stop < 2^w) + (widths : ∀ b, (∑ j, bundleWidths (bitWordFinEquiv a) (splitWidths X) b j) < 2^w) + (m : Memory w) (rep : T.Represents X m) (rg rd re : List (Report w)) + (fit : S ≤ 2^w) (raw : ExternalReports X O Q L T.width T.baseOut T.shift m fit rg rd re) : + (Scanned 0 S rg ∧ Reads (OldCell T S) (eventLog rg) ∧ Writes (LevelCell P) (eventLog rg)) ∧ + (Scanned 0 N rd ∧ Reads (OldCell T S) (eventLog rd) ∧ Writes (LevelCell P) (eventLog rd)) ∧ + (Scanned 0 S re ∧ Reads (LevelCell P) (eventLog re) ∧ Writes (LevelCell P) (eventLog re)) := by + have layout := prepare_layout X T a₀ dH t stride start before room + have ns : N ≤ S := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a) + have nb := (Nat.le_mul_of_pos_right (Fintype.card X.Base*2^a) (Nat.two_pow_pos g)).trans (ns.trans fit) + have nl : 2^(a+g) ≤ 2^w := by + rw [pow_add] + have lim : Fintype.card X.Base * (2^a * 2^g) ≤ 2^w := by rw [← Nat.mul_assoc]; exact ns.trans fit + exact (Nat.le_mul_of_pos_left _ Fintype.card_pos).trans lim + let gw := gatherWords Q L T.width + let dw := directoryWords Q L T.baseOut T.shift + have base := rep.refresh_base X T m dw layout.lanes rfl rfl nb nl + obtain ⟨rg',rd',re',raw',mid,init⟩ := external_phases_stages X O Q L T.width T.baseOut T.shift + layout.degree layout.lanes layout.regions layout.directory m (rep.refresh_widths X T m gw rfl widths) + base layout.gather layout.baseApart widths + obtain ⟨hg,hd,he,_⟩ := raw + obtain ⟨hg',hd',_,_⟩ := raw' + have eg : rg' = rg := Option.some.inj (hg'.symm.trans hg) + subst rg' + have ed : rd' = rd := Option.some.inj (hd'.symm.trans hd) + subst rd' + let ord := bundleOrder g O + let A : RefreshRAM.Input w := graphInput (splitSlots X) ord (splitWidths X) + have dir : Directory (splitSlots X) ord (splitWidths X) Q A fit := + graphInput_directory (splitSlots X) ord (splitWidths X) Q layout.degree widths + have leg := directory_legal (splitSlots X) ord (splitWidths X) Q A dir widths + obtain ⟨vg,_,gg⟩ := gather_scan X T a₀ dH t stride start before room m rg hg + obtain ⟨vd,_,gd⟩ := bundles_scan X T a₀ dH t stride start before room _ mid rd hd + obtain ⟨ve,_,ge⟩ := offsets_scan X a₀ dH t stride start room layout.regions A leg _ init re he + exact ⟨⟨vg,gg⟩,⟨vd,gd⟩,ve,ge⟩ + +end CompressorRecords.PortRefresh.FrontFrame + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshFrontFrame.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshFrontFrame.lean new file mode 100644 index 0000000000..810a90f26e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshFrontFrame.lean @@ -0,0 +1,172 @@ +import OAI.Computability.VPVNP.CompressorRefreshStageFrame +import OAI.Computability.VPVNP.CompressorRecordRefreshPrepareAllocation + +/-! +# Guarded refresh gather, directory and segment scans + +The first two scans read only the old incidence columns. The offset scan reads the new +scratch columns, using the translated destination stored by the bundle scan. All three +write inside the selected level's allocation and return consecutive ordinal cursors. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.FrontFrame + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.Refresh +open SourceTransport StageFrame Allocation NewSlots +open scoped Fin.CommRing + +open private gather_step from OAI.Computability.VPVNP.CompressorRecordRefreshOldWidths +open private step from OAI.Computability.VPVNP.CompressorRecordRefreshDirectory +open private bundle_le destination_at from OAI.Computability.VPVNP.CompressorRecordRefreshScan + +variable {w a g : ℕ} + +/-- An address in one of the six old incidence columns within the specified segment count. -/ +def OldCell (T : IncidenceDirectory w) (segments x : ℕ) : Prop := + ∃ c : Fin 6, (T.column c).val ≤ x ∧ x < (T.column c).val + segments + +/-- An address in the half-open interval allocated to this refresh level. -/ +def LevelCell (P : Plan) (x : ℕ) : Prop := P.start ≤ x ∧ x < P.stop + +private theorem demand_le (P : Plan) : P.demand ≤ P.stop := by + dsimp only [Plan.stop, Plan.next, Plan.reverseSlot, Plan.targetPort, Plan.supply, Plan.term] + omega + +private theorem segments_lt (P : Plan) (room : P.stop < 2^w) : P.segments < 2^w := by + have := demand_le P + dsimp only [Plan.demand] at this + omega + +private theorem old_cell (P : Plan) (T : IncidenceDirectory w) (room : P.stop < 2^w) + (before : ∀ c, (T.column c).val+P.segments ≤ P.start) (c : Fin 6) (i : BurstRAM.Word w) (hi : i.val < P.segments) : + OldCell T P.segments (T.column c+i).val := by + have hd := demand_le P + dsimp only [Plan.demand] at hd + have := before c + rw [Fin.val_add, Nat.mod_eq_of_lt (by omega)] + exact ⟨c,by omega,by omega⟩ + +private theorem scratch_cell (P : Plan) (room : P.stop < 2^w) (c : Fin 8) (hc : c ≠ 0) (i : BurstRAM.Word w) + (hi : i.val < P.segments) : LevelCell P (P.scratch w c+i).val := by + have hd := demand_le P + obtain ⟨low,high⟩ := P.scratch_interval (hd.trans room.le) c hc i hi + exact ⟨low,high.trans_le hd⟩ + +variable (X : State a (a+g)) (T : IncidenceDirectory w) (a₀ dH t stride start : ℕ) +local notation "P" => plan X a₀ dH t stride start +local notation "Q" => Plan.scratch P w +local notation "S" => Plan.segments P +local notation "N" => Plan.sites P +local notation "L" => (word (bits := w) (2^g)) +local notation "G" => gatherWords Q L T.width +local notation "B" => directoryWords Q L T.baseOut T.shift +local notation "O" => IncidenceDirectory.baseOrder X + +/-- The entire gather reads the old width permutation and writes only inside the selected level. -/ +theorem gather_scan (before : ∀ c, (T.column c).val+S ≤ start) (room : (P).stop < 2^w) + (m : Memory w) (rs : List (Report w)) + (run : runSegment ((template RefreshGather.gather 0).instantiate w G).program 24 + (some 0) m (List.replicate S []) = some rs) : + Scanned 0 S rs ∧ RefreshGather.Gathered G m (after m (eventLog rs)) S ∧ + Reads (OldCell T S) (eventLog rs) ∧ Writes (LevelCell P) (eventLog rs) := by + let data := G + have alloc := prepare_layout X T a₀ dH t stride start before room + have fit := segments_lt (P) room + apply scan _ 24 0 S (fun j n ↦ RefreshGather.Gathered G m n j) (RefreshGather.events data) + (OldCell T S) (LevelCell P) (fun j _ _ m ↦ RefreshGather.gather_native data m j) _ (Nat.zero_le _) m rs + ⟨fun _ h ↦ (Nat.not_lt_zero _ h).elim,fun _ _ ↦ rfl⟩ (by simpa only [Nat.sub_zero,Nat.cast_zero] using run) + intro j _ hj m' h + let i : BurstRAM.Word w := j + have hv : i.val = j := Nat.mod_eq_of_lt (hj.trans fit) + have hi : i.val < S := hv ▸ hj + have hold := gather_index_lt (Q 0) L i (Fintype.card X.Base) + (by rw [alloc.degree]; exact Nat.two_pow_pos _) (by rw [alloc.lanes]; exact Nat.two_pow_pos _) + (by rw [alloc.degree,alloc.lanes]; exact hi) + rw [alloc.degree,alloc.lanes] at hold + have old : OldCell T S (RefreshGather.widthAddress data i).val := old_cell (P) T room before 5 _ hold + have fresh : LevelCell P (data 3+i).val := scratch_cell (P) room 1 (by decide) i hi + refine ⟨?_,?_,?_⟩ + · simpa only [RefreshGather.gather_after,hv] using gather_step alloc.gather i hi (hv ▸ h) + · intro addr v mem + simp [RefreshGather.events] at mem + exact mem.1 ▸ old + · intro addr v mem + simp [RefreshGather.events] at mem + exact mem.1 ▸ fresh + +/-- Every bundle reads an old target and displacement, initializes three scratch cells, +and advances the ordinal and the genuine partial-directory invariant. -/ +theorem bundles_scan (before : ∀ c, (T.column c).val+S ≤ start) (room : (P).stop < 2^w) + (m : Memory w) (source : BundleDirectory.BaseTables (splitSlots X) O B m) (rs : List (Report w)) + (run : runSegment ((template BundleDirectory.visit 0).instantiate w B).program 28 + (some 0) m (List.replicate N []) = some rs) : + Scanned 0 N rs ∧ BundleDirectory.Prefix (splitSlots X) O B (after m (eventLog rs)) N ∧ + Reads (OldCell T S) (eventLog rs) ∧ Writes (LevelCell P) (eventLog rs) := by + let data := B + have alloc := prepare_layout X T a₀ dH t stride start before room + have ns : N ≤ S := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a) + have fit := ns.trans_lt (segments_lt (P) room) + apply scan _ 28 0 N (fun j m ↦ BundleDirectory.Prefix (splitSlots X) O B m j) (BundleDirectory.events data) + (OldCell T S) (LevelCell P) (fun j _ _ m ↦ BundleDirectory.visit_native data m j) _ (Nat.zero_le _) m rs + ⟨source,fun _ h ↦ (Nat.not_lt_zero _ h).elim⟩ (by simpa only [Nat.sub_zero,Nat.cast_zero] using run) + intro j _ hj m' h + let i : BurstRAM.Word w := j + have hv : i.val = j := Nat.mod_eq_of_lt (hj.trans fit) + have hi : i.val < N := hv ▸ hj + have arc : (BundleDirectory.sourceArc data i).val < S := + ((Nat.mod_le ..).trans (Nat.div_le_self ..)).trans_lt (hi.trans_le ns) + have a₁ : OldCell T S (data 1+BundleDirectory.sourceArc data i).val := old_cell (P) T room before 0 _ arc + have a₅ : OldCell T S (data 5+BundleDirectory.sourceArc data i).val := old_cell (P) T room before 2 _ arc + have a₂ : LevelCell P (data 2+i).val := scratch_cell (P) room 2 (by decide) i (hi.trans_le ns) + have a₃ : LevelCell P (data 3+i).val := scratch_cell (P) room 3 (by decide) i (hi.trans_le ns) + have a₄ : LevelCell P (data 4+i).val := scratch_cell (P) room 4 (by decide) i (hi.trans_le ns) + refine ⟨?_,?_,?_⟩ + · simpa only [BundleDirectory.events_after,hv] using step (splitSlots X) O B alloc.directory m' i hi (hv ▸ h) + · intro addr v mem + simp [BundleDirectory.events] at mem + rcases mem with ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> assumption + · intro addr v mem + simp [BundleDirectory.events] at mem + rcases mem with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> assumption + +/-- The selected segment permutation stays inside the scratch arrays in every prefix. -/ +theorem offsets_scan (room : (P).stop < 2^w) (reg : RefreshRAM.Regions Q S) + (A : RefreshRAM.Input w) (legal : RefreshRAM.Legal Q S A) (m : Memory w) + (init : RefreshRAM.AtCursor Q S A m 0) (rs : List (Report w)) + (run : runSegment ((template RefreshRAM.visit 0).instantiate w Q).program 33 + (some 0) m (List.replicate S []) = some rs) : + Scanned 0 S rs ∧ RefreshRAM.AtCursor Q S A (after m (eventLog rs)) S ∧ + Reads (LevelCell P) (eventLog rs) ∧ Writes (LevelCell P) (eventLog rs) := by + have fit := segments_lt (P) room + apply scan _ 33 0 S (fun j m ↦ RefreshRAM.AtCursor Q S A m j) (RefreshRAM.events Q) + (LevelCell P) (LevelCell P) (fun j _ _ m ↦ RefreshRAM.visit_native Q m j) _ (Nat.zero_le _) m rs init + (by simpa only [Nat.sub_zero,Nat.cast_zero] using run) + intro j _ hj m' h + let i : BurstRAM.Word w := j + have hv : i.val = j := Nat.mod_eq_of_lt (hj.trans fit) + have hi : i.val < S := hv ▸ hj + have hb := (bundle_le Q i).trans_lt hi + have hd : (RefreshRAM.destination Q m' i).val < S := destination_at h i hi ▸ legal.dst_lt i hi + have out (c : Fin 8) (hc : c ≠ 0) := scratch_cell (P) room c hc i hi + have bnd (c : Fin 8) (hc : c ≠ 0) := scratch_cell (P) room c hc (RefreshRAM.bundle Q i) hb + have dst (c : Fin 8) (hc : c ≠ 0) := scratch_cell (P) room c hc (RefreshRAM.destination Q m' i) hd + refine ⟨?_,?_,?_⟩ + · simpa only [RefreshRAM.events_after,hv] using RefreshRAM.cursor_step reg legal i hi (hv ▸ h) + · intro addr v mem + simp [RefreshRAM.events] at mem + rcases mem with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ + exacts [bnd 2 (by decide),bnd 3 (by decide),out 1 (by decide),bnd 4 (by decide)] + · intro addr v mem + simp [RefreshRAM.events] at mem + rcases mem with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ + exacts [out 5 (by decide),dst 6 (by decide),dst 7 (by decide),bnd 4 (by decide)] + +end CompressorRecords.PortRefresh.FrontFrame + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshGroupSplit.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshGroupSplit.lean new file mode 100644 index 0000000000..2b6c8abd71 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshGroupSplit.lean @@ -0,0 +1,213 @@ +import OAI.Computability.VPVNP.CompressorRefreshSplitWindows +import OAI.Computability.VPVNP.CompressorPublishedHeadWindows + +/-! +# The real refresh group on both sides of its selector + +The prefix, singleton selector and suffix consume the original refresh +reports in order. Their online ordinals are consecutive. The prefix is the +choice-independent graph preparation, the singleton contains precisely +the canonical term choice, and each suffix packet consumes empty tapes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +set_option quotPrecheck false + +namespace CompressorRecords.RefreshCore + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PhaseRecipe BlockPlanner Schedule +open DescriptorSpace PortRefresh PortRefresh.LevelRecipe PortRefresh.Allocation SourceTransport SourceOnline +open PairSimulation.LocalHistory +open scoped Fin.CommRing Classical + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) +variable {w g : ℕ} (base : BurstRAM.Word w) (positions blocks t : ℕ) +variable (X : State S.portExponent (S.portExponent+g)) +variable (c : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1 B.refresh) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "cur" => Script.levelsPerBlock scr*t+S.steps +local notation "head" => levelStart L cur +local notation "H" => levelStart L 0 +local notation "start" => arrayBase L cur +local notation "old" => packedIncidence L w cur (X.positions*2^S.portExponent) +local notation "sh" => RefreshBlockPlan.shape B +local notation "P" => plan X (sh).a₀ (sh).dH (sh).ties (sh).stride start +local notation "hc" => (S.port_bound.connected_and_pos S.port_order).1 +local notation "he" => Nat.two_pow_pos S.expanderExponent +local notation "hd" => S.degree_bounds.2 +local notation "ties" => RefreshBlockPlan.order B +local notation "dst" => NewSlots.word (bits := w) (Plan.term P) +local notation "W" => BlockGroups.refresh B 1 +local notation "ord" => (scr).initial.length+t*(scr).block.length+(W).before.length +local notation "total" => directoryRows L +local notation "Pkt" => SourceOnline.Packet scr w +local notation "o" => PassOrigin.refresh (B:=B) (f:=f) (hf:=hf) X + +/-- Three exact consecutive packet ranges of the compiled refresh. -/ +structure SelectedSplit (termCap cap : ℕ) (m : Memory w) (pre : List Pkt) (sel : Pkt) (tail : List Pkt) : Prop where + whole : Group scr L base cap ord total m (pre++sel::tail) + prePhases : pre.map (fun p => p.stage.phase) = (RefreshPrepare.window B).indices + selPhase : sel.stage.phase = index B (CanonicalWorker.refreshTermIndex B) + tailPhases : tail.map (fun p => p.stage.phase) = (finishWindow B).indices + preCount : pre.length = 3+(sh).ties + preQuiet : ∀ p ∈ pre, p.stage.choices = List.replicate p.stage.choices.length [] + selTapes : sel.stage.choices = List.ofFn (workerTapes o w c) + tailQuiet : ∀ p ∈ tail, p.stage.choices = List.replicate p.stage.choices.length [] + fits : (P).segments ≤ 2^w + prepare : PrepareRun X old ((P).scratch w) (NewSlots.word (bits := w) (P).demand) ties (NewSlots.word (2^g)) + fits m (post m pre) (pre.flatMap SourceWalk.Packet.reports) + selected : termRun S.graph he hc B.refresh ties X (NewSlots.word (P).demand) dst (sh).stride termCap + (blockTapes S.graph he hc B.refresh X c w) sel.input = some sel.reports + finished : Finish.Run X S.graph he hc B.refresh S.port_order hd c dst (sh).stride ((P).inputs w) ((P).output w) + sel.output (tail.flatMap SourceWalk.Packet.reports) + +variable {B f hf base positions blocks t X c} +theorem SelectedSplit.groups {termCap cap : ℕ} {m : Memory w} {pre tail : List Pkt} {sel : Pkt} + (h : SelectedSplit B f hf base positions blocks t X c termCap cap m pre sel tail) : + Group scr L base cap ord total m pre ∧ Group scr L base cap (ord+pre.length) total (post m pre) [sel] ∧ + sel.input=post m pre ∧ Group scr L base cap (ord+pre.length+1) total sel.output tail := + h.whole.split_at_selector + +variable (B f hf base positions blocks t X c) + +private theorem quiet_packets {A : Script} {u : Memory w} {ps : List (SourceOnline.Packet A w)} {rs : List (Report w)} + (chron : SourceWalk.Chronological SourceOnline.Visit.Runs u ps) (logs : ps.flatMap SourceWalk.Packet.reports = rs) + (empty : branchPaths rs = List.replicate rs.length []) : + ∀ p ∈ ps, p.stage.choices = List.replicate p.stage.choices.length [] := + ScheduledTrace.packet_quiet_of_flat (((PublishedHeads.chronological_tapes u ps chron).trans + (congrArg branchPaths logs)).trans empty) + +private theorem one_packet {A : Script} {ps : List (SourceOnline.Packet A w)} (h : ps.length = 1) : + ∃ p, ps = [p] := by + cases ps with + | nil => simp at h + | cons p ps => + have hl : ps.length=0 := by rw [List.length_cons] at h; omega + exact ⟨p,by rw [List.eq_nil_iff_length_eq_zero.mpr hl]⟩ + +set_option maxHeartbeats 1500000 in +/-- Install the three actual windows for a specified already-verified +refresh run. Their concatenated packets reproduce its exact report list. -/ +theorem split_verified (termCap cap : ℕ) (m : Memory w) (rs : List (Report w)) + (ht : t < blocks) (fit : H < 2^w) (room : (P).stop < 2^w) (before : head+60 < start) + (positive : 0 < termCap) (clock : scanCap scr (max 64 termCap) ≤ cap) + (entry : EntryState B base positions blocks t X m) + (alloc : PrepareLayout X old (sh).a₀ (sh).dH (sh).ties (sh).stride start) + (build : Build.Run X S.graph he hc B.refresh S.port_order hd c ties old start (sh).stride termCap alloc m rs) + (actual : SourceWalk (fun j u logs => Scheduled.Source X S.graph he hc B.refresh hd c ties old start (sh).stride termCap j u logs ∧ + Scheduled.StageBounds (t := (sh).ties) X S.graph he hc B.refresh start (sh).stride H j u logs) + (LevelRecipe.order sh) m rs) : + ∃ pre sel tail, SelectedSplit B f hf base positions blocks t X c termCap cap m pre sel tail ∧ + (pre++sel::tail).flatMap SourceWalk.Packet.reports = rs := by + obtain ⟨rp,rt,rf,all,bp,bt,bf,prep,term,finish⟩ := split_logs B X c old start termCap H alloc build actual + let prefixMem := after m (eventLog rp) + let suffixMem := after prefixMem (eventLog rt) + obtain ⟨pre,hp,pLab,pLog,next⟩ := attach_part B base positions blocks t X c termCap (RefreshPrepare.stages B) + (RefreshPrepare.window B) entry ht fit room before positive cap clock bp + obtain ⟨ss,hs,sLab,sLog,last⟩ := attach_part B base positions blocks t X c termCap [.term] + (selectWindow B) next ht fit room before positive cap clock (.singleton bt) + obtain ⟨tail,htail,tLab,tLog,_⟩ := attach_part B base positions blocks t X c termCap (afterTerm B) + (finishWindow B) last ht fit room before positive cap clock bf + have npre : pre.length = (RefreshPrepare.stages B).length := by + simpa only [List.length_map,Window.indices,List.length_ofFn] using congrArg List.length pLab + have one : ss.length = 1 := by simpa only [List.length_map,Window.indices,List.length_ofFn,List.length_cons,List.length_nil] using congrArg List.length sLab + obtain ⟨sel,rfl⟩ := one_packet one + have slog : sel.reports=rt := by simpa only [List.flatMap_cons,List.flatMap_nil,List.append_nil] using sLog + have ppost : post m pre = prefixMem := by rw [post,pLog] + have sinput : sel.input = prefixMem := hs.chronological.1 + have sout : sel.output = suffixMem := by rw [SourceWalk.Packet.output,sinput,slog] + have ord₁ : (scr).initial.length+t*(scr).block.length+(selectWindow B).before.length = ord+pre.length := by + rw [select_before,npre]; omega + have ord₂ : (scr).initial.length+t*(scr).block.length+(finishWindow B).before.length = ord+pre.length+1 := by + rw [finish_before,npre]; omega + have hp' : Group scr L base cap ord total m pre := hp + have hs' : Group scr L base cap (ord+pre.length) total (post m pre) [sel] := by rw [ppost,← ord₁]; exact hs + have ht' : Group scr L base cap (ord+pre.length+1) total (post (post m pre) [sel]) tail := by + rw [← ord₂,ppost,post,List.flatMap_cons,List.flatMap_nil,List.append_nil,slog]; exact htail + have rest := hs'.append ht' + have whole : Group scr L base cap ord total m (pre++sel::tail) := hp'.append rest + have index' : sel.stage.phase=(selectWindow B).index 0 := by + simp only [List.map_cons,List.map_nil,Window.indices,List.ofFn_succ,List.ofFn_zero,List.cons.injEq,and_true] at sLab + exact sLab.trans (congrArg (selectWindow B).index (Fin.ext (by rfl))) + have qp := side_quiet B X c old start termCap H (by + intro j hj + rintro rfl + simp [RefreshPrepare.stages] at hj) bp + have qt := side_quiet B X c old start termCap H (by + intro j hj; rintro rfl + simp [afterTerm] at hj) bf + have sc : branchPaths sel.reports = sel.stage.choices := ((runSegment_iff ..).mp hs.chronological.2.1).2.2 + have tape : sel.stage.choices = List.ofFn (workerTapes o w c) := sc.symm.trans + ((congrArg branchPaths slog).trans (CanonicalWorker.refresh_branches B f hf X c w old start termCap bt.1)) + refine ⟨pre,sel,tail,⟨whole,pLab,index'.trans (select_index B),tLab,?_,quiet_packets hp.chronological pLog qp, + tape,quiet_packets htail.chronological tLog qt,alloc.regions.fits,?_,?_,?_⟩,?_⟩ + · rw [npre]; simp [RefreshPrepare.stages]; omega + · rw [ppost,pLog]; exact prep + · rw [sinput,slog]; exact term + · rw [sout,tLog]; exact finish + · simp only [List.flatMap_append,List.flatMap_cons,pLog,slog,tLog,List.append_assoc] at all ⊢ + exact all.symm + +set_option maxHeartbeats 1400000 in +/-- Split a complete refresh construction already produced by the core +builder. Its report list and final stored memory are the same after packet +attachment. The prefix and singleton now retain their individual reports. -/ +theorem split_built (termCap cap : ℕ) (m : Memory w) (rs : List (Report w)) + (ht : t < blocks) (size : X.positions ≤ positions) (fit : endAddress L < 2^w) + (entry : EntryState B base positions blocks t X m) + (represented : (old).Represents X m) + (termBits : termConstant S.graph he hc B.refresh ties+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (nextWidth : (dyadicRefreshNext X S.graph he hc B.refresh S.port_order hd c).maxWireWidth < 2^w) + (budget : TermWorker.budget B.refresh (sh).ties ((sh).ports*(sh).dH) w X.maxWireWidth ≤ termCap) + (positive : 0 < termCap) (clock : scanCap scr (max 64 termCap) ≤ cap) + (built : Built B base positions blocks t X c termCap m rs) : + ∃ pre sel tail, SelectedSplit B f hf base positions blocks t X c termCap cap m pre sel tail ∧ + (pre++sel::tail).flatMap SourceWalk.Packet.reports = rs := by + have idx : cur < (L).levels := by + have h := Nat.mul_le_mul_left (S.steps+1) ht + rw [Nat.mul_succ] at h + change (S.steps+1)*t+S.steps < 1+(S.steps+1)*blocks; omega + let current : Fin (L).levels := ⟨cur,idx⟩ + have source := source_region B base positions blocks t X current rfl size fit + have room := (BlockLevelFit.refresh B base.val positions blocks current rfl X size fit).1.word + change (plan X (S.degreeExponent 0) (sh).dH (sh).ties (sh).stride (start+0*tableWords L)).stop < 2^w at room + simp only [Nat.zero_mul,Nat.add_zero] at room + obtain ⟨alloc,run⟩ := built.source + have actual := Scheduled.verified_sources X S.graph he hc B.refresh S.port_order hd c ties old start + (sh).stride H termCap alloc m rs represented (fun j => (source j).1) (fun j => (source j).2) + le_rfl room termBits nextWidth budget run + have before : head+60 < start := by change head+60 < head+66+6*slotCapacity L; omega + exact split_verified B f hf base positions blocks t X c termCap cap m rs ht + ((levelStart_mono L (Nat.zero_le _)).trans_lt fit) room before positive clock entry alloc run actual + +/-- Execute the complete selected refresh and retain its exact selector +split alongside the represented next graph and all stored history fields. -/ +theorem build_split (termCap cap : ℕ) (m : Memory w) (ht : t < blocks) (size : X.positions ≤ positions) + (fit : endAddress L < 2^w) (entry : EntryState B base positions blocks t X m) + (represented : (old).Represents X m) + (termBits : termConstant S.graph he hc B.refresh ties+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (nextWidth : (dyadicRefreshNext X S.graph he hc B.refresh S.port_order hd c).maxWireWidth < 2^w) + (budget : TermWorker.budget B.refresh (sh).ties ((sh).ports*(sh).dH) w X.maxWireWidth ≤ termCap) + (positive : 0 < termCap) (clock : scanCap scr (max 64 termCap) ≤ cap) : + ∃ pre sel tail, SelectedSplit B f hf base positions blocks t X c termCap cap m pre sel tail ∧ + Built B base positions blocks t X c termCap m ((pre++sel::tail).flatMap SourceWalk.Packet.reports) := by + obtain ⟨ps,_,_,built⟩ := build_group B base positions blocks t X c termCap cap m ht size fit entry.rows entry.pitch + clock entry.header represented termBits nextWidth budget positive + obtain ⟨pre,sel,tail,h,hr⟩ := split_built B f hf base positions blocks t X c termCap cap m _ ht size fit entry + represented termBits nextWidth budget positive clock built + exact ⟨pre,sel,tail,h,hr ▸ built⟩ + +end CompressorRecords.RefreshCore + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshHeaderGroup.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshHeaderGroup.lean new file mode 100644 index 0000000000..ee8624fd76 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshHeaderGroup.lean @@ -0,0 +1,161 @@ +import OAI.Computability.VPVNP.CompressorCurrentGraph +import OAI.Computability.VPVNP.CompressorRefreshPlacementPacket +import OAI.Computability.VPVNP.CompressorScheduledGreedyRates +import OAI.Computability.VPVNP.CompressorWindowPackets + +/-! +# The three live refresh header publications + +The current graph's terminal header becomes the input header of the refresh. +The following two native reports publish the successor dimensions and the +successor's canonical incidence and scratch pointers. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +set_option quotPrecheck false + +namespace CompressorRecords.RefreshHeaders + +open BurstRAM Compression BlockPlanner DescriptorSpace BlockHeaderRun Schedule SourceOnline +open PortRefresh.TraversalHeaders +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable (f : B.Entry → R) (hf : B.IsSolution f) {w g : ℕ} (base : Word w) (positions blocks t : ℕ) +variable (X : State S.portExponent (S.portExponent + g)) +variable (c : Compression.Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) + +local notation "v" => RefreshPlacement.selectedLevel B f hf X c sel +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Schedule.Ports.data pt +local notation "fl" => Script.levelsPerBlock scr * t +local notation "st" => (levelStart L fl : Word w) +local notation "oldIdx" => fl + S.steps +local notation "newIdx" => fl + (S.steps + 1) +local notation "role" => Scalars.Pass.refresh S.portExponent (S.degreeExponent 0) S.expanderExponent +local notation "bound" => ScheduledRates.headerCap (BlockProgram.geometry B) role +local notation "ls" => BlockHeaderPlan.substep (BlockProgram.geometry B) S.steps role +/-- The interval at the beginning of the refresh group that publishes the level headers. -/ +def window : Window scr ls := BlockGroups.refresh B 0 +local notation "win" => window B +local notation "fitSix" => (by change 6 ≤ 54; decide) + +set_option maxHeartbeats 700000 in +-- The three publisher port banks use the scalar types of the selected refresh. +private theorem header_walk (old new : Fin (L).levels) (hOld : oldIdx = old.val) + (hNew : newIdx = new.val) + (m : Memory w) (run : Substep v L old new fitSix m) (fit : endAddress L < 2 ^ w) + (entry : LevelFields.Entry L fl pub st m) (head : BlockHeaderPlan.firstHeader.eval pub st m = + header w L 0) + (pitch : (pub 1 - 1).val < levelStart L old) (count : (pub 3).val < levelStart L old) : + SourceWalk (Window.Raw (A := scr) L base t bound) ls m (reports v L old new m) ∧ + branchPaths (reports v L old new m) = [[],[],[]] := by + let mid := inputMemory v L old m + let next := outputMemory v L old new m + let r₀ := scalarReport (inputRow v) (header w L old) (header w L old) m + let r₁ := scalarReport (outputRow v) (header w L old) (header w L new) mid + let r₂ := headReport L new next + let q := ls + have qlen : q.length = 3 := rfl + have hq₀ : 0 < q.length := by omega + have hq₁ : 1 < q.length := by omega + have hq₂ : 2 < q.length := by omega + obtain ⟨h₀,h₁,h₂⟩ := HeaderPacket.substep v run fit fl S.steps hOld hNew pub st entry head pitch + count + have support (mem : Memory w) (j : Fin q.length) : + HeaderOperands.Supported (Window.operandRegion scr L base) pub st mem q[j.val] := + HeaderOperands.substep _ _ _ _ _ _ _ (.inl rfl) (.inr (.inl rfl)) _ (List.getElem_mem ..) + have c₀ : (inputRow v).recipe.code.length + 1 ≤ bound := le_max_left .. + have c₁ : (outputRow v).recipe.code.length + 1 ≤ bound := (le_max_left ..).trans (le_max_right ..) + have c₂ : (DescriptorHeads.publisher (L).shape).recipe.code.length + 1 ≤ bound := + (le_max_right ..).trans (le_max_right ..) + constructor + · change SourceWalk _ [q[0]'hq₀,q[1]'hq₁,q[2]'hq₂] m ([r₀] ++ ([r₁]++[r₂])) + refine SourceWalk.next (rs := [r₀]) ⟨_,_,c₀,h₀,support m ⟨0,hq₀⟩⟩ ?_ + simp only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] + refine SourceWalk.next (rs := [r₁]) ⟨_,_,c₁,h₁,support mid ⟨1,hq₁⟩⟩ ?_ + simp only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] + exact SourceWalk.singleton ⟨_,_,c₂,h₂,support next ⟨2,hq₂⟩⟩ + · have a := ((runSegment_iff ..).mp h₀.execute).2.2 + have b := ((runSegment_iff ..).mp h₁.execute).2.2 + have d := ((runSegment_iff ..).mp h₂.execute).2.2 + exact congrArg₂ (· ++ ·) a (congrArg₂ (· ++ ·) b d) + +set_option maxHeartbeats 800000 in +-- Publishing the header in the global script identifies both packed incidence directories. +/-- Native group zero of the installed refresh, including the post-memory +used by the input graph, the incidence copies and the DFS placement rows. -/ +theorem install (m : Memory w) (n cap : ℕ) (ht : t < blocks) (size : X.positions ≤ positions) + (fit : endAddress L < 2 ^ w) (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory - 1).val = (levelWords L : Word w)) (clock : scanCap scr bound ≤ cap) + (current : CurrentGraph.Current L oldIdx X n m) (sites : X.positions < 2 ^ w) + (degree : slotDegree S < 2 ^ w) : + ∃ (old new : Fin (L).levels) (ps : List (Packet scr w)), + old.val = oldIdx ∧ new.val = newIdx ∧ + SourceOnline.Group scr L base cap ((scr).initial.length + t * (scr).block.length + + (win).before.length) + (directoryRows L) m ps ∧ ps.map (fun p ↦ p.stage.phase) = (win).indices ∧ + ps.flatMap SourceWalk.Packet.reports = reports v L old new m ∧ + branchPaths (reports v L old new m) = [[],[],[]] ∧ + Substep v L old new fitSix m ∧ + (packedIncidence L w old (v).oldSlots).Represents X (post m ps) ∧ + HeadBank L old (v).oldSlots (post m ps) ∧ HeadBank L new (v).outputSlots (post m ps) := by + have hNext : newIdx < (L).levels := by + have h := Nat.mul_le_mul_left (S.steps + 1) ht + rw [Nat.mul_succ] at h + change (S.steps + 1) * t + (S.steps + 1) < 1 + (S.steps + 1) * blocks + omega + let old : Fin (L).levels := ⟨oldIdx,by omega⟩ + let new : Fin (L).levels := ⟨newIdx,hNext⟩ + have slot : IncidenceDirectory.slotCount X = (v).oldSlots := by + change Fintype.card X.Base * 2 ^ (S.portExponent + g) * 2 ^ S.portExponent = X.positions * 2 ^ + S.portExponent + rw [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv + (S.portExponent + g)),Fintype.card_fin] + have capacity : IncidenceDirectory.slotCount X ≤ slotCapacity L := slot ▸ Nat.mul_le_mul size + (le_max_left ..) + have adj : old.val + 1 = new.val := by + change fl + S.steps + 1 = fl + (S.steps + 1) + omega + obtain ⟨run,rep,oldBank,newBank⟩ := current.publish v old new adj fitSix fit capacity sites degree + have Hfit := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + have low := Window.lowCells (A := scr) L base rfl rfl Hfit + have hold := levelStart_mono L (Nat.zero_le old.val) + have entry : LevelFields.Entry L fl pub st m := ⟨rfl,pitch⟩ + have head := BlockHeaderPlan.firstHeader_eval L base m st (Fin.ofNat_val_eq_self base).symm rows + obtain ⟨raw,quiet⟩ := header_walk B f hf base positions blocks t X c sel old new rfl rfl m run + fit entry head + (low.2.trans_le hold) (low.1.trans_le hold) + have clocks (j : Fin (scr).size) := scanCap_clocks + (p := ⟨HeaderPacket.attach scr j pub st m bound [],m,[]⟩) _ le_rfl clock + have live (j : Fin (ls).length) : Window.ordinal (A := scr) t ((win).index j) < directoryRows + L := by + rw [(win).ordinal_index,BlockProgram.directory_rows,(scr).calendar_total] + have pos := ((win).position j).isLt + have mul := Nat.mul_le_mul_right (scr).block.length ht + rw [Nat.succ_mul] at mul + omega + obtain ⟨ps,grp,phases,logs⟩ := (win).group L base t rfl rfl Hfit cap bound m + (reports v L old new m) raw + rows pitch live (fun j _ ↦ (clocks j).1) (fun j _ ↦ (clocks j).2) + have same : post m ps = finalMemory v L old new m := by rw [post,logs,reports_after] + refine ⟨old,new,ps,rfl,rfl,grp,phases,logs,quiet,run,?_,?_,?_⟩ + all_goals rw [same] + · simpa only [← slot] using rep + · simpa only [← slot] using oldBank + · exact newBank + +end CompressorRecords.RefreshHeaders + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshHookRetained.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshHookRetained.lean new file mode 100644 index 0000000000..ceb548191e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshHookRetained.lean @@ -0,0 +1,101 @@ +import OAI.Computability.VPVNP.CompressorCompiledResident +import OAI.Computability.VPVNP.PairTerminalPackedPrefix + +/-! +# Selected refresh data in the physical DFS memory + +The calendar history identifies the producing refresh by its chronological index. +The terminal prefix writes outside its retained cells. Its vertex-entry headers +locate the old graph and the row base used by the child decoder. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshHookRetained + +open BurstRAM Compression Compression.Refresh DescriptorSpace PairSimulation +open LocalHistory TraversalRows TraversalControllerInputs TraversalRoles NodeArguments +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) +variable {w g : ℕ} (workspace : BurstRAM.Word w) (positions blocks n : ℕ) +variable (X : State S.portExponent (S.portExponent + g)) +variable (choice : DyadicRefreshChoice (a₀ := S.degreeExponent 0) (g := g) X S.graph + (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) +local notation "L" => BlockProgram.layout B workspace.val positions blocks +local notation "payload" => CompiledResident.payload B f hf workspace positions blocks n + +/-- All physical fields produced for one selected refresh at the given memory. -/ +abbrev LevelData (i : ℕ) (m : Memory w) := + CompiledResident.RefreshPayload (g := g) B workspace positions blocks n i X choice m + +/-- Recover the selected branch's source fields at its occurrence in the calendar. -/ +theorem ofPast {past : List (SelectedLevel B f hf)} {m : Memory w} + (retained : SelectedPayloadHistory.Past B f hf L payload past m) (i : Fin past.length) + (bits : List Bool) (selected : past[i] = + RefreshPlacement.selectedLevel (g := g) B f hf X choice bits) : + LevelData B workspace positions blocks n X choice i.val m := by + have data := CompiledResident.read (B := B) (f := f) (hf := hf) (workspace := workspace) + (positions := positions) (blocks := blocks) (n := n) retained i + apply (CompiledResident.refresh_payload (g := g) B f hf workspace positions blocks n i.val + X choice bits m).mp + exact Eq.mp (congrArg (fun v : SelectedLevel B f hf => payload i.val v m) selected) data + +variable {lanes : ℕ} (budget : blocks * S.laneBits ≤ lanes) +variable (initial : State (S.degreeExponent 0) lanes) +variable (branch : (B.execute f hf blocks budget initial).Choices) +local notation "levels" => executeLevels B f hf blocks budget initial branch +local notation "tags" => TraversalRoles.selected B f hf blocks budget initial branch +variable {tab : Fin (BlockProgram.layout B workspace.val positions blocks).shape.tables} +variable {baseBits laneBits : ℕ} {pub : Fin 11 → BurstRAM.Word w} +variable {calendar frozen : Memory w} +variable {wireBits : Fin (StateExecution.finalState + (B.execute f hf blocks budget initial) branch).totalWidth → Bool} +local notation "Vertex" => TerminalProgram.VertexEntry (w := w) (S := S) (n := lanes) + B f hf blocks budget initial branch L tab baseBits laneBits pub calendar frozen wireBits + +/-- The frozen memory after the real bootstrap, final offset scan, traversal rows and +shared bits still contains both incidence directories and every selected term field. -/ +theorem atVertex (entry : Vertex) + (retained : SelectedPayloadHistory.Past B f hf L payload levels calendar) + (i : Fin (levels).length) (bits : List Bool) (selected : (levels)[i] = + RefreshPlacement.selectedLevel (g := g) B f hf X choice bits) : + LevelData B workspace positions blocks n X choice i.val frozen := by + have live : (selectedLayers B f hf blocks budget initial branch).dropLast.length < + (L).levels := by + rw [TerminalBootstrap.selected_prior_length, BlockProgram.actual_level_count, + Nat.mul_comm blocks] + omega + exact ofPast B f hf workspace positions blocks n X choice + (entry.payload (data := payload) B f hf blocks budget initial branch live retained) + i bits selected + +/-- The row base read at this occurrence is the one computed by the native +traversal. Together with the saved six metadata words it gives the actual child +operand bank at the locator used by the role. -/ +theorem childAtVertex (entry : Vertex) (i : Fin (levels).length) + (data : LevelData B workspace positions blocks n X choice i.val frozen) : + (ChildScan.directory S.portExponent (layerBase B.recordLimit (endAddress L) tags i.val) + B.recordLimit ⟨n, frameStride (slotDegree S) n⟩ + (packedIncidence L w i.val (X.positions * 2 ^ S.portExponent))).Stored frozen + (levelHead pub frozen i.val + 14) := by + rw [entry.level_head B f hf blocks budget initial branch] + apply data.child.bank + obtain ⟨ds, resident⟩ := entry.directories + have row := resident.currentBase i.val (by + simpa only [levelFibers, List.length_ofFn] using i.isLt.le) + rw [levelFibers_tags levels ds] at row + simpa only [levelStart, Nat.zero_mul, Nat.add_zero, TraversalRoles.selected] using row + +end CompressorRecords.RefreshHookRetained + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshIncidenceWorkerSafety.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshIncidenceWorkerSafety.lean new file mode 100644 index 0000000000..2a17f42872 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshIncidenceWorkerSafety.lean @@ -0,0 +1,389 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshPrepareAllocation +import OAI.Computability.VPVNP.CompressorRefreshStageFrame +import OAI.Computability.VPVNP.CompressorSourceTransport + +/-! +# Per-call memory regions of refreshed incidence workers + +The actual-slot worker reads the scratch directory, ROM or selected supplies +below the output incidence region. Its three writes are in the output +columns. The lane-zero base worker then uses one actual-output read and +three base-column writes inside that same region. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.IncidenceWorkerSafety + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh +open SpectralGeometry MotifConversion NewSlots Allocation SourceTransport + +variable {w : ℕ} + +/-- An inclusive lower bound and exclusive upper bound in the packed allocation. -/ +def interval (lo hi x : ℕ) := lo ≤ x ∧ x < hi + +private theorem packed_lt {q Q i d : ℕ} (hq : q List.replicate n (Event.tick : Event w) + let read := fun a : W w => Event.read a (m a.val) + match kind with + | .external => ticks 3 ++ [read (p 5+i)] ++ ticks 2 ++ [read (p 6+i)] ++ ticks 3 + | .expander => + let j := BinaryOp.mod.eval (BinaryOp.div.eval i (p 3)) (p 0) + let e := j*p 1+p 4 + ticks 14 ++ [read (p 7+e)] ++ ticks 2 ++ [read (p 8+e)] ++ ticks 7 ++ + [read (p 9+(i*p 1+p 4))] ++ ticks 8 + | .padding => ticks 24 + +private theorem split_events (kind : Kind) (p : Public w) (m : Memory w) (i : W w) : + let s := row kind p m i + let ticks := fun n => List.replicate n (Event.tick : Event w) + NewSlots.events kind p m i = readPart kind p m i ++ ticks 2 ++ [.write (p 10+s.src) s.dst] ++ + ticks 2 ++ [.write (p 11+s.dst) s.src] ++ ticks 2 ++ [.write (p 12+s.src) s.width] ++ ticks 2 := by + cases kind <;> rfl + +private theorem port_event_reads (kind : Kind) (p : Public w) (m : Memory w) (i : W w) + (region : ℕ → Prop) (hr : ∀ a ∈ inputs kind p i, region a.val) : + Reads region (NewSlots.events kind p m i) := by + intro addr v h + rw [split_events] at h + cases kind with + | external => + simp [readPart] at h + rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> apply hr <;> simp [inputs] + | expander => + simp [readPart] at h + rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ <;> apply hr <;> simp [inputs] + | padding => simp [readPart] at h + +private theorem port_event_writes (kind : Kind) (p : Public w) (m : Memory w) (i : W w) + (region : ℕ → Prop) (hw : ∀ c, region ((row kind p m i).address p c).val) : + Writes region (NewSlots.events kind p m i) := by + intro addr v h + rw [split_events] at h + cases kind <;> simp [readPart] at h + all_goals rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ + all_goals first | exact hw .outgoing | exact hw .incoming | exact hw .width + +section Slots + +variable {a g a₀ dH t stride start : ℕ} {K : Type*} [_root_.Field K] {c₁ c₂ : ℝ} + (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) + (hdH : 0 < dH) (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock K (expanderSupply E hdH conn) (2^a₀) c₁ c₂) + (hd : dH+1 ≤ 2^a₀) (choice : DyadicRefreshChoice X E hdH conn F) + +local notation "P" => plan X a₀ dH t stride start +local notation "N" => Fintype.card X.Base * 2^a * 2^g +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "int" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) E hdH conn F choice +local notation "I" => Plan.inputs P w +local notation "T" => Plan.output P w +local notation "bank" => AllSlots.words (2^a) (2^g) I T + +private theorem input_range (c : RefreshSlot dH (2^a₀)) (fit : AllSlots.Fits (a₀ := a₀) X w) + (room : (P).stop ≤ 2^w) (i : Fin N) (addr : W w) + (used : addr ∈ inputs (kindOf c) (bank c) (word i.val)) : interval start (P).next addr.val := by + have hs : start ≤ (P).demand := Nat.le_add_right .. + have hdt : (P).demand ≤ (P).supply := by dsimp only [Plan.supply,Plan.term]; omega + have hst : (P).supply + N*dH = (P).targetPort := rfl + have htr : (P).targetPort + 2^a*dH = (P).reverseSlot := rfl + have hrn : (P).reverseSlot + 2^a*dH = (P).next := rfl + have hn : (P).next ≤ 2^w := by dsimp only [Plan.stop] at room; omega + let b := word (bits := w) i.val + have hb := encoded_lt (w := w) i.isLt + cases c with + | inl c => + change addr ∈ [(P).scratch w 2+b,(P).scratch w 4+b] at used + have hj : b.val < (P).segments := hb.trans_le (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a)) + rcases List.mem_cons.mp used with rfl | h + · have hr := Plan.scratch_interval P (by omega) 2 (by decide) b hj + exact ⟨hr.1,hr.2.trans_le (by omega)⟩ + · obtain rfl := List.mem_singleton.mp h + have hr := Plan.scratch_interval P (by omega) 4 (by decide) b hj + exact ⟨hr.1,hr.2.trans_le (by omega)⟩ + | inr c => + cases c with + | inr _ => exact (List.not_mem_nil used).elim + | inl k => + let p := bank (.inr (.inl k) : RefreshSlot dH (2^a₀)) + let v := BinaryOp.mod.eval (BinaryOp.div.eval b (p 3)) (p 0) + have hv : v.val < 2^a := by + change (_ % (word (bits := w) (2^a)).val) % 2^w < _ + rw [show (word (bits := w) (2^a)).val = 2^a from Nat.mod_eq_of_lt fit.ports] + exact (Nat.mod_le ..).trans_lt (Nat.mod_lt _ (Nat.two_pow_pos a)) + let e := v*p 1+p 4 + let z := b*p 1+p 4 + have he : e.val < 2^a*dH := word_key _ _ hv (encoded_lt k.isLt) + have hz : z.val < N*dH := word_key _ _ hb (encoded_lt k.isLt) + change addr ∈ [word (P).targetPort+e,word (P).reverseSlot+e,word (P).supply+z] at used + rcases List.mem_cons.mp used with rfl | used + · have ⟨lo,hi⟩ := address_in (base := (P).targetPort) (by omega) e he + constructor <;> omega + rcases List.mem_cons.mp used with rfl | used + · have ⟨lo,hi⟩ := address_in (base := (P).reverseSlot) (by omega) e he + constructor <;> omega + obtain rfl := List.mem_singleton.mp used + have ⟨lo,hi⟩ := address_in (base := (P).supply) (by omega) z hz + constructor <;> omega + +include hd in +private theorem output_bounds (c : RefreshSlot dH (2^a₀)) (fit : AllSlots.Fits (a₀ := a₀) X w) + (ref : Memory w) (initial : AllSlots.SourceTables X E hdH conn F choice I ref) (i : Fin N) : + let r := row (kindOf c) (bank c) ref (word i.val) + r.src.val < (P).capacity ∧ r.dst.val < (P).capacity := by + let s := (O).symm i + have hi : i = O s := ((O).apply_symm_apply i).symm + let p := bank c + have dims : Dimensions p (Fintype.card X.Base) (2^a) (2^g) dH (2^a₀) := + ⟨Nat.mod_eq_of_lt fit.ports, Nat.mod_eq_of_lt (by have := fit.degree; omega), + Nat.mod_eq_of_lt fit.degree,Nat.mod_eq_of_lt fit.lanes,fit.ids⟩ + have h : NewSlots.Represents X.baseIndex (bitWordFinEquiv g) (row (kindOf c) p ref (word i.val)) + (slotRecord (splitSlots X) (bitWordFinEquiv a) (splitWidths X) E.toSlotGraph hd int s c) := by + rw [hi] + rcases c with k | k | k + · cases Subsingleton.elim k 0 + exact external_record X.baseIndex (bitWordFinEquiv g) hd dims (splitSlots X) (bitWordFinEquiv a) + (splitWidths X) E.toSlotGraph int s (initial.target s) (initial.total s) + · exact expander_record X.baseIndex (bitWordFinEquiv g) hd dims (splitSlots X) (bitWordFinEquiv a) + (splitWidths X) E.toSlotGraph int s k (Nat.mod_eq_of_lt (by change k.val < 2^w; have := fit.degree; have := k.isLt; omega)) + (initial.targetPort (s.2,k)) (initial.reverseSlot (s.2,k)) (initial.supply s k) + · exact padding_record X.baseIndex (bitWordFinEquiv g) hd dims (splitSlots X) (bitWordFinEquiv a) + (splitWidths X) E.toSlotGraph int s k (Nat.mod_eq_of_lt (by change k.val < 2^w; have := fit.degree; have := k.isLt; omega)) + exact ⟨h.1 ▸ (arcs X.baseIndex (bitWordFinEquiv g) _).isLt,h.2.1 ▸ (arcs X.baseIndex (bitWordFinEquiv g) _).isLt⟩ + +/-- Throughout one slot scan, the complete read interval still agrees with +the reference memory at the beginning of that scan. -/ +def SlotInvariant (alloc : Allocation.Plan) (ref m : Memory w) : Prop := Agree (interval alloc.start alloc.next) ref m + +include hd in +theorem slot_step (c : RefreshSlot dH (2^a₀)) (fit : AllSlots.Fits (a₀ := a₀) X w) + (room : (P).stop ≤ 2^w) (ref : Memory w) (initial : AllSlots.SourceTables X E hdH conn F choice I ref) + (j : ℕ) (hj : j simp [inputs] at same + · simp only [row,same.1,same.2] + · simp only [row,same.1,same.2.1,same.2.2] + · rfl + have h := output_bounds X E hdH conn F hd choice c fit ref initial i + have bound (col : Column) : interval (P).next (P).stop ((row (kindOf c) p m (word j)).address p col).val := by + rw [hr] + cases col with + | outgoing => exact (P).column_interval room 3 _ h.1 + | incoming => exact (P).column_interval room 4 _ h.2 + | width => exact (P).column_interval room 5 _ h.1 + have writes := port_event_writes (kindOf c) p m (word j) _ bound + have order : start ≤ (P).next := by + dsimp only [Plan.next,Plan.reverseSlot,Plan.targetPort,Plan.supply,Plan.term,Plan.demand] + change start ≤ start+_+_+_+_+_+_ + omega + have stop : (P).next ≤ (P).stop := Nat.le_add_right .. + refine ⟨fun x hx => (inv x hx).trans (SourceTransport.after_outside m writes (by + intro he; exact (Nat.not_lt_of_ge he.1) hx.2)).symm,?_,fun x v hx => ?_⟩ + · apply port_event_reads + intro a ha + have hh := input_range X c fit room i a ha + exact ⟨hh.1,hh.2.trans_le stop⟩ + · obtain ⟨lo,hi⟩ := writes x v hx + exact ⟨order.trans lo,hi⟩ + +open Schedule OrdinalRun + +include hd in +/-- The raw genuine slot reports carry the dense ordinal sequence and their +full footprint before scheduler cells are installed. -/ +theorem slot_scan (c : RefreshSlot dH (2^a₀)) (fit : AllSlots.Fits (a₀ := a₀) X w) + (room : (P).stop ≤ 2^w) (ref m : Memory w) (initial : AllSlots.SourceTables X E hdH conn F choice I ref) + (inv : SlotInvariant P ref m) (rs : List (Report w)) + (run : let M := (template (code (kindOf c)) 0).instantiate w (bank c) + runSegment M.program (1+(code (kindOf c)).length) (some 0) m (List.replicate N []) = some rs) : + StageFrame.Scanned 0 N rs ∧ SlotInvariant P ref (after m (eventLog rs)) ∧ + Reads (interval start (P).stop) (eventLog rs) ∧ Writes (interval start (P).stop) (eventLog rs) := by + let M := (template (code (kindOf c)) 0).instantiate w (bank c) + exact StageFrame.scan M.program (1+(code (kindOf c)).length) 0 N + (fun _ m => SlotInvariant P ref m) (NewSlots.events (kindOf c) (bank c)) + (interval start (P).stop) (interval start (P).stop) + (fun j _ _ m => NewSlots.native _ _ m (word j)) + (fun j _ hj m hin => slot_step X E hdH conn F hd choice c fit room ref initial j hj m hin) + (Nat.zero_le _) m rs inv (by simpa using run) + +set_option maxHeartbeats 600000 in +include hd in +/-- Replay one complete fixed-slot pass inside a guarded row. The memory may +differ from the reference before the allocation, including the active frame. -/ +theorem slot_valid {d : ℕ} (C : Catalog d) (worker : Fin d) (ports : Ports w) + (pub : Fin (C worker).params → W w) (c : RefreshSlot dH (2^a₀)) (fit : AllSlots.Fits (a₀ := a₀) X w) + (room : (P).stop ≤ 2^w) (ref m : Memory w) (initial : AllSlots.SourceTables X E hdH conn F choice I ref) + (inv : SlotInvariant P ref m) + (separate : ∀ x, ControlCell (C worker).params ports x → ¬ interval start (P).stop x) + (ready : Ready C worker ports pub (word N) m) (rs : List (Report w)) + (run : let M := (template (code (kindOf c)) 0).instantiate w (bank c) + runSegment M.program (1+(code (kindOf c)).length) (some 0) m (List.replicate N []) = some rs) : + ValidTrace C worker ports pub (word N) 0 m rs ∧ SlotInvariant P ref (after m (eventLog rs)) ∧ + Reads (interval start (P).stop) (eventLog rs) ∧ Writes (interval start (P).stop) (eventLog rs) ∧ + Preserved (C worker).params ports m (after m (eventLog rs)) := by + have npos : 0 < (P).capacity := by change 0 < N * 2^a₀; positivity + have nfit : N < 2^w := by + have hn : N ≤ (P).capacity := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos a₀) + change (P).next+6*(P).capacity ≤ _ at room + omega + obtain ⟨shape,last,rd,wr⟩ := slot_scan X E hdH conn F hd choice c fit room ref m initial inv rs run + obtain ⟨valid,keep⟩ := StageFrame.Scanned.guarded C worker ports pub shape nfit _ wr separate m ready + exact ⟨valid,last,rd,wr,keep⟩ + +end Slots + +section Base + +open IncidenceDirectory + +variable {a l : ℕ} (alloc : Allocation.Plan) (Y : State a l) +local notation "T" => alloc.output w +local notation "p" => BaseOutput.params T a l + +private theorem base_source_lt (cap : BaseOutput.actualCount Y = alloc.capacity) (room : alloc.stop ≤ 2^w) + (j : ℕ) (hj : j < BaseOutput.baseCount Y) : (BaseOutput.source p (word j)).val < alloc.capacity := by + have fits : alloc.capacity < 2^w := by + have hp : 0 < alloc.capacity := cap ▸ (by dsimp only [BaseOutput.actualCount]; positivity) + change alloc.next+6*alloc.capacity ≤ 2^w at room; omega + have hb := Nat.mul_le_mul_right (2^a) (Nat.le_mul_of_pos_right (Fintype.card Y.Base) (Nat.two_pow_pos l)) + change BaseOutput.baseCount Y ≤ BaseOutput.actualCount Y at hb + have hD : (2^a) < 2^w := + (Nat.le_mul_of_pos_left _ Fintype.card_pos).trans_lt (hb.trans_lt (cap ▸ fits)) + have hi := hj.trans (hb.trans_lt (cap ▸ fits)) + have hd : (p 0).val = 2^a := Nat.mod_eq_of_lt hD + have hval : (word (bits := w) j).val = j := Nat.mod_eq_of_lt hi + have hv : j / 2^a < Fintype.card Y.Base := (Nat.div_lt_iff_lt_mul (Nat.two_pow_pos a)).mpr hj + have hm : j % 2^a < 2^a := Nat.mod_lt _ (Nat.two_pow_pos a) + have div : (BinaryOp.div.eval (word (bits := w) j) (p 0)).val = j / 2^a := by + change ((word (bits := w) j).val/(p 0).val) % _ = _ + rw [hval,hd]; exact Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt hi) + have rem : (BinaryOp.mod.eval (word (bits := w) j) (p 0)).val = j % 2^a := by + change ((word (bits := w) j).val % (p 0).val) % _ = _ + rw [hval,hd]; exact Nat.mod_eq_of_lt (hm.trans hD) + have slot : ((BinaryOp.div.eval (word (bits := w) j) (p 0))*(p 1)).val < Fintype.card Y.Base*2^l := by + rw [Fin.val_mul,div] + exact (Nat.mod_le ..).trans_lt ((Nat.mul_le_mul_left _ (Nat.mod_le (2^l) _)).trans_lt + (Nat.mul_lt_mul_of_pos_right hv (Nat.two_pow_pos l))) + rw [← cap] + exact word_key _ _ slot (rem ▸ hm) + +theorem base_step (cap : BaseOutput.actualCount Y = alloc.capacity) (room : alloc.stop ≤ 2^w) + (layout : (T).Layout Y) (j : ℕ) (hj : j BaseOutput.Prefix T Y m j) (BaseOutput.events p) + (interval alloc.start alloc.stop) (interval alloc.start alloc.stop) + (fun j _ _ m => BaseOutput.visit_native p m (word j)) + (fun j _ hj m hin => base_step alloc Y cap room layout j hj m hin) (Nat.zero_le _) m rs + ⟨actual,fun _ h => (Nat.not_lt_zero _ h).elim⟩ (by simpa using run) + +set_option maxHeartbeats 600000 in +/-- The lane-zero base pass preserves its actual columns and its growing +prefix under the scheduler guards, using the same raw report sequence. -/ +theorem base_valid {d : ℕ} (C : Catalog d) (worker : Fin d) (ports : Ports w) + (pub : Fin (C worker).params → W w) (cap : BaseOutput.actualCount Y = alloc.capacity) + (room : alloc.stop ≤ 2^w) (layout : (T).Layout Y) + (separate : ∀ x, ControlCell (C worker).params ports x → ¬ interval alloc.start alloc.stop x) + (m : Memory w) (actual : (T).ActualColumns Y m) (ready : Ready C worker ports pub (word (BaseOutput.baseCount Y)) m) + (rs : List (Report w)) (run : let M := (template BaseOutput.visit 0).instantiate w p + runSegment M.program 29 (some 0) m (List.replicate (BaseOutput.baseCount Y) []) = some rs) : + ValidTrace C worker ports pub (word (BaseOutput.baseCount Y)) 0 m rs ∧ + BaseOutput.Prefix T Y (after m (eventLog rs)) (BaseOutput.baseCount Y) ∧ + Reads (interval alloc.start alloc.stop) (eventLog rs) ∧ Writes (interval alloc.start alloc.stop) (eventLog rs) ∧ + Preserved (C worker).params ports m (after m (eventLog rs)) := by + have pos : 0 < alloc.capacity := cap ▸ (by dsimp only [BaseOutput.actualCount]; positivity) + have lt : alloc.capacity < 2^w := by change alloc.next+6*alloc.capacity ≤ _ at room; omega + have le := Nat.mul_le_mul_right (2^a) (Nat.le_mul_of_pos_right (Fintype.card Y.Base) (Nat.two_pow_pos l)) + change BaseOutput.baseCount Y ≤ BaseOutput.actualCount Y at le + obtain ⟨shape,last,rd,wr⟩ := base_scan alloc Y cap room layout m actual rs run + obtain ⟨valid,keep⟩ := StageFrame.Scanned.guarded C worker ports pub shape ((le.trans cap.le).trans_lt lt) + _ wr separate m ready + exact ⟨valid,last,rd,wr,keep⟩ + +end Base + +end CompressorRecords.PortRefresh.IncidenceWorkerSafety + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshLevelDirectory.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshLevelDirectory.lean new file mode 100644 index 0000000000..63091cb0b7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshLevelDirectory.lean @@ -0,0 +1,95 @@ +import OAI.Computability.VPVNP.CompressorRefreshPlacementRows +import OAI.Computability.VPVNP.CompressorRecordRefreshOldWidths +import OAI.Computability.VPVNP.PairTraversalScanDirectory + +/-! +# The selected refresh's immediate-preimage directory + +The binary port coordinates become part of the new base without changing +the ordinal of a position. Consequently the physical singleton rows +produced by the refresh placement worker are exactly the preimages of the +chosen mathematical term in both states' stored orders. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshPlacement + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PairSimulation.LocalHistory +open PairSimulation.TraversalRows +open scoped Classical +set_option maxHeartbeats 1500000 + +variable {w g : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f) +variable (X : State S.portExponent (S.portExponent+g)) + +local notation "a" => S.portExponent +local notation "p₀" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +private abbrev actualPass := dyadicRefreshPass X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2 + (f ∘ Sum.inr) ((B.solution_iff f).mp hf).2 + +local notation "p" => actualPass f hf X + +variable (c : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) + +private def promoted : X.network.Site ≃ ((p).next c).network.Site := + ((Equiv.refl X.Base).prodCongr (splitBitWord a g).toEquiv).trans (refreshPositions (bitWordFinEquiv a)) + +/-- A refresh placement preserves the machine's physical identifier exactly, +including the high-order promoted port and low-order residual lane fields. -/ +theorem placement_identity : RepresentsPlacement (w := w) (siteOrder X) (siteOrder ((p).next c)) + ((p).step.term c).place id := by + rintro ⟨base,lane⟩ + unfold siteWord + apply congrArg (Fin.ofNat (2^w)) + change (bitWordFinEquiv (a+g) lane).val + 2^(a+g) * (X.baseIndex base).val = + (bitWordFinEquiv g ((splitBitWord a g lane).2)).val + 2^g * + ((bitWordFinEquiv a ((splitBitWord a g lane).1)).val + 2^a*(X.baseIndex base).val) + rw [splitBitWord_number,pow_add] + ring + +theorem fiber_card_le_one (u : ((p).step.term c).output.Site) : + Fintype.card (((p).step.term c).Preimage u) ≤ 1 := by + apply Fintype.card_le_one_iff_subsingleton.mpr + constructor + intro x y + apply Subtype.ext + exact (promoted f hf X c).injective (x.property.symm.trans y.property) + +theorem site_counts : + (siteOrder X).length = X.positions ∧ (siteOrder ((p).next c)).length = X.positions := by + have eqn {a' g' : ℕ} (Y : State a' g') : (siteOrder Y).length = Y.positions := by + change (siteOrder Y).length = Fintype.card Y.network.Site + simpa only [Fintype.card_fin] using Fintype.card_congr (siteOrder Y).entries + exact ⟨eqn _,(eqn _).trans (dyadicRefreshNext_positions X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh _ _ c)⟩ + +/-- The directory accepted by the traversal kernel after the selected +refresh's native singleton-table scan. It can occupy a single packed +arena with three consecutive subarrays. -/ +def directory (sel : List Bool) (pub : Fin 6 → BurstRAM.Word w) (mem : Memory w) (limit : ℕ) + (regions : RowRegions pub) (oldCount : (pub 0).val = X.positions) (newCount : (pub 2).val = X.positions) + (capacity : (pub 4).val = 1) (below : (pub 5).val + (pub 2).val ≤ limit) : + let v : SelectedLevel B f hf := ⟨_,_,_,_,X,p,p₀,c,sel⟩ + LevelDirectory v (after mem (eventLog (log pub 0 X.positions))) limit := by + intro v + have hc := site_counts f hf X c + exact Directory.ofPhysical ((p).step.term c) (siteOrder X) (siteOrder ((p).next c)) pub _ limit + (oldCount.trans hc.1.symm) (newCount.trans hc.2.symm) regions (by simpa only [capacity,Nat.mul_one] using below) + id (placement_identity f hf X c) (hc.1 ▸ (collected regions oldCount newCount capacity mem).1) + (fun v ↦ (fiber_card_le_one f hf X c v).trans_eq capacity.symm) + +end CompressorRecords.RefreshPlacement + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshLevelRecipe.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshLevelRecipe.lean new file mode 100644 index 0000000000..bd6612a2b2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshLevelRecipe.lean @@ -0,0 +1,546 @@ +import OAI.Computability.VPVNP.CompressorTermWorkerRecipe +import OAI.Computability.VPVNP.CompressorRecordRefreshAllocation +import OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe + +/-! +# Online row planners for a complete degree refresh + +The old base-vertex and residual-lane counts, allocation start, and three +input incidence pointers are expressions over the current level header. The +port degrees, motif strides, role order and expander are fixed for a block. +Every worker's stop cursor and public bank are computed in the planner +before dispatch, in the order used by the native refresh proofs. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.LevelRecipe + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh +open SpectralGeometry PhaseRecipe NewSlots + +/-- Dynamic values obtained from the current level header or its inputs. -/ +structure Input where + /-- Expression for the first word of the refresh level's allocation. -/ + start : Expr + /-- Expression for the number of base vertices in the incoming network. -/ + vertices : Expr + /-- Expression for the number of residual lanes after the port bits have been split off. -/ + lanes : Expr + /-- Expression for the head of the incoming state's base outgoing incidence column. -/ + oldOut : Expr + /-- Expression for the head of the incoming state's lane-shift column. -/ + oldShift : Expr + /-- Expression for the head of the incoming state's wire-width column. -/ + oldWidth : Expr + +/-- The fixed combinatorial and arithmetic parameters of a refresh. -/ +structure Shape where + /-- Number of port bits split from an incoming lane to form the promoted base vertex. -/ + a : ℕ + /-- Exponent of the dyadic slot degree in the refreshed state. -/ + a₀ : ℕ + /-- Degree of the expander on the refresh ports. -/ + dH : ℕ + /-- Number of demand ties enumerated in each base-vertex and residual-lane block. -/ + ties : ℕ + /-- Number of words reserved for each block's stored motif term. -/ + stride : ℕ + /-- Width in bits of a selector in the fixed refresh template. -/ + selectors : ℕ + +/-- The number of promoted ports, equal to two raised to the input port exponent. -/ +abbrev Shape.ports (s : Shape) := 2^s.a +/-- The number of output slots per refreshed vertex, equal to two raised to the new degree +exponent. -/ +abbrev Shape.degree (s : Shape) := 2^s.a₀ + +/-- The dispatcher's physical worker tags. All copies of a fixed worker use +one tag, including every demand row and each public expander ROM row. -/ +structure Tags where + /-- Worker tag for gathering old segment widths. -/ + gather : ℕ + /-- Worker tag for constructing the directory of external bundles. -/ + bundles : ℕ + /-- Worker tag for scanning the segment offsets. -/ + offsets : ℕ + /-- Shared worker tag for the demand scans indexed by ties. -/ + demand : ℕ + /-- Worker tag for the strided motif-term pass. -/ + term : ℕ + /-- Worker tag for the scan that reads the selected terms and writes expander supply data. -/ + supply : ℕ + /-- Shared worker tag for publishing the fixed expander's reverse-incidence entries. -/ + rom : ℕ + /-- Worker tag for writing the refreshed external slot. -/ + external : ℕ + /-- Worker tag for writing an internal expander slot. -/ + expander : ℕ + /-- Worker tag for writing a padding slot of the refreshed degree. -/ + padding : ℕ + /-- Worker tag for publishing the refreshed base-incidence columns. -/ + base : ℕ + +variable (s : Shape) (I : Input) + +/-- Expression counting base-vertex, promoted-port and residual-lane triples. -/ +def sites := (I.vertices.mul (.lit s.ports)).mul I.lanes +/-- Expression counting base-vertex and residual-lane pairs, one per motif-term record. -/ +def blocks := I.vertices.mul I.lanes +/-- Expression counting one old port segment per port at every promoted site. -/ +def segments := (sites s I).mul (.lit s.ports) +/-- Expression counting all output incidence slots over the promoted sites. -/ +def capacity := (sites s I).mul (.lit s.degree) +/-- Head of the dense demand table, following the seven segment-sized scratch columns. -/ +def demandStart := I.start.add ((Expr.lit 7).mul (segments s I)) +/-- Head of the strided term records, following all blocks' demand ties. -/ +def termStart := (demandStart s I).add ((blocks I).mul (.lit s.ties)) +/-- Head of the supply table, following the block term records. -/ +def supplyStart := (termStart s I).add ((blocks I).mul (.lit s.stride)) +/-- Head of the expander target-port table, following the site-by-expander-slot supply table. -/ +def targetPort := (supplyStart s I).add ((sites s I).mul (.lit s.dH)) +/-- Head of the expander reverse-slot table, immediately after the target-port table. -/ +def reverseSlot := (targetPort s I).add ((Expr.lit s.ports).mul (.lit s.dH)) +/-- Head of the refreshed incidence output, immediately after the expander reverse-slot table. -/ +def outputStart := (reverseSlot s I).add ((Expr.lit s.ports).mul (.lit s.dH)) +/-- Exclusive end of the level allocation after all six output columns. -/ +def allocationStop := (outputStart s I).add ((Expr.lit 6).mul (capacity s I)) +/-- Base address expression for the indexed output column, spaced by the full incidence +capacity. -/ +def column (i : Fin 6) := (outputStart s I).add ((Expr.lit i.val).mul (capacity s I)) + +/-- The eight scratch operands, consisting of the port count followed by the heads of seven +segment-sized columns. -/ +def scratch (i : Fin 8) := + if i = 0 then Expr.lit s.ports else I.start.add ((Expr.lit (i.val-1)).mul (segments s I)) + +/-- The demand head and tie count followed by the term head and stride, supplied to the motif +worker. -/ +def termHeads : Fin 4 → Expr := ![demandStart s I,.lit s.ties,termStart s I,.lit s.stride] + +/-- A stage of the native refresh calendar, with separate occurrences for each demand tie, +expander ROM entry and output slot. -/ +inductive Stage (s : Shape) where + | gather | bundles | offsets | demand (k : Fin s.ties) | term | supply + | rom (i : Fin (s.ports*s.dH)) | slot (k : Fin s.degree) | base + +/-- The execution order from width gathering and demand scans through term selection, supply, +ROM publication, slot writing and base output. -/ +def order : List (Stage s) := + [.gather,.bundles,.offsets] ++ (List.finRange s.ties).map Stage.demand ++ [.term,.supply] ++ + (List.finRange (s.ports*s.dH)).map Stage.rom ++ (List.finRange s.degree).map Stage.slot ++ [.base] + +variable {s} (tags : Tags) (hd : s.dH+1 ≤ s.degree) + +/-- Selects the dispatch tag for a stage, distinguishing the external, expander and padding +cases of a slot. -/ +def Stage.tag : Stage s → ℕ + | .gather => tags.gather + | .bundles => tags.bundles + | .offsets => tags.offsets + | .demand _ => tags.demand + | .term => tags.term + | .supply => tags.supply + | .rom _ => tags.rom + | .slot k => match kindOf ((refreshSlots hd).symm k) with + | .external => tags.external + | .expander => tags.expander + | .padding => tags.padding + | .base => tags.base + +/-- Number of public operand words used by a stage's native worker, parameterized by the motif +worker's arity. -/ +def Stage.arity (termPorts : ℕ) : Stage s → ℕ + | .gather => 4 + | .bundles | .offsets | .demand _ => 8 + | .term => termPorts + | .supply => 7 + | .rom _ => 5 + | .slot _ => 13 + | .base => 6 + +/-- Planner expression for the initial worker cursor, equal to the entry ordinal on a ROM stage +and zero on the other stages. -/ +def Stage.initial : Stage s → Expr + | .rom i => .lit i.val + | _ => .lit 0 + +/-- Planner expression for the exclusive stop cursor of a stage, sized to the table it scans. -/ +def Stage.stop : Stage s → Expr + | .gather | .offsets => segments s I + | .bundles | .slot _ => sites s I + | .demand _ | .term => blocks I + | .supply => (sites s I).mul (.lit s.dH) + | .rom i => .lit (i.val+1) + | .base => (I.vertices.mul (.lit s.ports)).mul (.lit s.degree) + +private def copy {dH d₀ : ℕ} : RefreshSlot dH d₀ → ℕ + | .inl _ => 0 + | .inr (.inl k) | .inr (.inr k) => k.val + +variable {termPorts G : ℕ} + (E : RegularArcGraph (Fin s.ports) s.dH) (tieOrder : Fin s.ties ≃ Tie s.ports) + (termBank : (Fin 4 → Expr) → Fin termPorts → Expr) + +/-- The public operand expressions of a native stage, including its layout addresses and fixed +expander or tie indices. -/ +def Stage.bank : (j : Stage s) → Fin (j.arity termPorts) → Expr + | .gather => ![scratch s I 0,I.lanes,I.oldWidth,scratch s I 1] + | .bundles => ![I.lanes,I.oldOut,scratch s I 2,scratch s I 3,scratch s I 4,I.oldShift,.lit 0,.lit 0] + | .offsets => scratch s I + | .demand k => + let e := tieOrder k + ![I.lanes,.lit s.ports,.lit (tieTarget e).val,.lit (tieSource e).val,.lit s.ties,.lit k.val, + if e.1 then scratch s I 1 else scratch s I 7,demandStart s I] + | .term => termBank (termHeads s I) + | .supply => ![.lit s.ports,I.lanes,.lit s.dH,termStart s I,.lit s.stride,.lit s.selectors,supplyStart s I] + | .rom i => + let dst := E.reverse (finProdFinEquiv.symm i) + ![.lit i.val,.lit dst.1.val,.lit dst.2.val,targetPort s I,reverseSlot s I] + | .slot k => ![.lit s.ports,.lit s.dH,.lit s.degree,I.lanes,.lit (copy ((refreshSlots hd).symm k)), + scratch s I 2,scratch s I 4,targetPort s I,reverseSlot s I,supplyStart s I,column s I 3,column s I 4,column s I 5] + | .base => ![.lit s.degree,I.lanes,column s I 3,column s I 0,column s I 1,column s I 2] + +private def opPass {r k : ℕ} (ops : List (PrimedStackRAM.Op r k)) (result : Fin r) : Schedule.Pass := + ⟨_,_,_,PrimedStackRAM.template ops result⟩ + +/-- Actual native instruction table of this calendar occurrence. The ROM and +demand tables vary their public literals across occurrences. -/ +def Stage.worker (term : Schedule.Pass) : Stage s → Schedule.Pass + | .gather => opPass RefreshGather.gather 0 + | .bundles => opPass BundleDirectory.visit 0 + | .offsets => Schedule.refreshPass + | .demand _ => opPass DemandScan.visit 0 + | .term => term + | .supply => opPass SupplyScan.visit 0 + | .rom _ => opPass ExpanderROM.put 0 + | .slot k => opPass (NewSlots.code (kindOf ((refreshSlots hd).symm k))) 0 + | .base => opPass BaseOutput.visit 0 + +theorem Stage.worker_params (term : Schedule.Pass) (j : Stage s) : + (j.worker hd term).params = j.arity term.params := by cases j <;> rfl + +/-- Operand formulas indexed directly by the actual worker table's ports. -/ +def Stage.workerBank (term : Schedule.Pass) + (terms : (Fin 4 → Expr) → Fin term.params → Expr) (j : Stage s) : + Fin (j.worker hd term).params → Expr := + fun i => j.bank I hd E tieOrder terms (Fin.cast (j.worker_params hd term) i) + +private theorem arity_le (room : max 13 termPorts ≤ G) (j : Stage s) : j.arity termPorts ≤ G := by + cases j <;> simp only [Stage.arity] <;> omega + +/-- The phase installed by the expression compiler for one fixed stage. -/ +def phase (room : max 13 termPorts ≤ G) (j : Stage s) : Phase G := + Phase.ofParams (arity_le room j) (j.tag tags hd) j.initial (j.stop I) (j.bank I hd E tieOrder termBank) + +/-- The entire fixed list of online planners, including one strided term scan. -/ +def phases (room : max 13 termPorts ≤ G) : List (Phase G) := + (order s).map (phase I tags hd E tieOrder termBank room) + +/-- A refresh adds a fixed number of rows to the block calendar regardless of +the incoming network size and the word width. -/ +theorem phases_length (room : max 13 termPorts ≤ G) : + (phases I tags hd E tieOrder termBank room).length = + 6 + s.ties + s.ports*s.dH + s.degree := by + simp [phases,order]; omega + +/-- The public inputs, state word and memory against which a level's planner expressions are +evaluated. -/ +structure Context (w : ℕ) where + /-- The five public input words available to a refresh planner expression. -/ + pub : Fin 5 → W w + /-- The state word available to the refresh planner during expression evaluation. -/ + state : W w + /-- The memory read by load expressions in the refresh level planner. -/ + memory : Memory w + +variable {w g : ℕ} (C : Context w) + +/-- Evaluates a planner expression with the context's public words, state and memory. -/ +abbrev Context.eval (e : Expr) := e.eval C.pub C.state C.memory + +/-- Meaning of the six dynamic expressions. The rest of the row values +follow from these six input words and the fixed template. -/ +structure Describes (X : State s.a (s.a+g)) (start : ℕ) (old : IncidenceDirectory w) : Prop where + start_eq : C.eval I.start = word start + vertices_eq : C.eval I.vertices = word (Fintype.card X.Base) + lanes_eq : C.eval I.lanes = word (2^g) + oldOut_eq : C.eval I.oldOut = old.baseOut + oldShift_eq : C.eval I.oldShift = old.shift + oldWidth_eq : C.eval I.oldWidth = old.width + +variable (X : State s.a (s.a+g)) (start : ℕ) (old : IncidenceDirectory w) +local notation "P" => Allocation.plan X s.a₀ s.dH s.ties s.stride start + +private theorem eval_lit (n : ℕ) : C.eval (.lit n) = word n := rfl +private theorem eval_add (x y : Expr) : C.eval (x.add y) = C.eval x + C.eval y := rfl +private theorem eval_mul (x y : Expr) : C.eval (x.mul y) = C.eval x * C.eval y := rfl +private theorem word_add (x y : ℕ) : word x + word y = word (bits := w) (x+y) := + Fin.ext (Nat.add_mod x y _).symm +private theorem word_mul (x y : ℕ) : word x * word y = word (bits := w) (x*y) := + Fin.ext (Nat.mul_mod x y _).symm + +/-- Correspondence of the computed addresses with the packed allocation +used by the descriptor correctness proof. Word reduction is valid at every +intermediate arithmetic operation. -/ +structure Addresses (p : Allocation.Plan) : Prop where + sites_eq : C.eval (sites s I) = word p.sites + blocks_eq : C.eval (blocks I) = word p.blocks + segments_eq : C.eval (segments s I) = word p.segments + capacity_eq : C.eval (capacity s I) = word p.capacity + demand_eq : C.eval (demandStart s I) = word p.demand + term_eq : C.eval (termStart s I) = word p.term + supply_eq : C.eval (supplyStart s I) = word p.supply + target_eq : C.eval (targetPort s I) = word p.targetPort + reverse_eq : C.eval (reverseSlot s I) = word p.reverseSlot + output_eq : C.eval (outputStart s I) = word p.next + stop_eq : C.eval (allocationStop s I) = word p.stop + scratch_eq : ∀ i, C.eval (scratch s I i) = p.scratch w i + column_eq : ∀ i, C.eval (column s I i) = (p.output w).column i + +theorem addresses (h : Describes I C X start old) : Addresses (s := s) I C P := by + have hs : C.eval (sites s I) = word (P).sites := by + simp only [sites,eval_mul,eval_lit,h.vertices_eq,h.lanes_eq,word_mul]; rfl + have hb : C.eval (blocks I) = word (P).blocks := by + simp only [blocks,eval_mul,h.vertices_eq,h.lanes_eq,word_mul]; rfl + have seg : C.eval (segments s I) = word (P).segments := by + simp only [segments,eval_mul,hs,eval_lit,word_mul]; rfl + have cap : C.eval (capacity s I) = word (P).capacity := by + simp only [capacity,eval_mul,hs,eval_lit,word_mul]; rfl + have dem : C.eval (demandStart s I) = word (P).demand := by + simp only [demandStart,eval_add,eval_mul,h.start_eq,eval_lit,seg,word_mul,word_add]; rfl + have trm : C.eval (termStart s I) = word (P).term := by + simp only [termStart,eval_add,eval_mul,dem,hb,eval_lit,word_mul,word_add]; rfl + have sup : C.eval (supplyStart s I) = word (P).supply := by + simp only [supplyStart,eval_add,eval_mul,trm,hb,eval_lit,word_mul,word_add]; rfl + have tgt : C.eval (targetPort s I) = word (P).targetPort := by + simp only [targetPort,eval_add,eval_mul,sup,hs,eval_lit,word_mul,word_add]; rfl + have rev : C.eval (reverseSlot s I) = word (P).reverseSlot := by + simp only [reverseSlot,eval_add,eval_mul,tgt,eval_lit,word_mul,word_add]; rfl + have nxt : C.eval (outputStart s I) = word (P).next := by + simp only [outputStart,eval_add,eval_mul,rev,eval_lit,word_mul,word_add]; rfl + have stop : C.eval (allocationStop s I) = word (P).stop := by + simp only [allocationStop,eval_add,eval_mul,nxt,eval_lit,cap,word_mul,word_add]; rfl + refine ⟨hs,hb,seg,cap,dem,trm,sup,tgt,rev,nxt,stop,fun i => ?_,fun i => ?_⟩ + · by_cases hi : i=0 <;> simp only [scratch,Allocation.Plan.scratch,hi,↓reduceIte,eval_add,eval_mul, + eval_lit,h.start_eq,seg,word_mul,word_add] <;> rfl + · rw [Allocation.Plan.output_column] + simp only [column,eval_add,eval_mul,nxt,eval_lit,cap,word_mul,word_add] + +/-- The natural starting cursor used by the native stage, with a ROM entry starting at its own +ordinal. -/ +def Stage.first : Stage s → ℕ + | .rom i => i.val + | _ => 0 + +/-- The exclusive natural cursor bound for a native stage, computed from the incoming state and +the level allocation. -/ +def Stage.limit : Stage s → ℕ + | .gather | .offsets => (P).segments + | .bundles | .slot _ => (P).sites + | .demand _ | .term => (P).blocks + | .supply => (P).sites * s.dH + | .rom i => i.val+1 + | .base => Fintype.card X.Base * s.ports * s.degree + +/-- The public words consumed by the already checked native worker proofs. -/ +def Stage.nativeBank (termWords : (Fin 4 → W w) → Fin termPorts → W w) : + (j : Stage s) → Fin (j.arity termPorts) → W w + | .gather => gatherWords ((P).scratch w) (word (2^g)) old.width + | .bundles => directoryWords ((P).scratch w) (word (2^g)) old.baseOut old.shift + | .offsets => (P).scratch w + | .demand k => DemandScan.words (r := 2^g) tieOrder ((P).scratch w) (word (P).demand) k + | .term => termWords ![word (P).demand,word s.ties,word (P).term,word s.stride] + | .supply => SupplyScan.params s.ports (2^g) s.dH (word (P).term) s.stride s.selectors (word (P).supply) + | .rom i => ExpanderROM.words E ((P).inputs w) i + | .slot k => AllSlots.words s.ports (2^g) ((P).inputs w) ((P).output w) ((refreshSlots hd).symm k) + | .base => BaseOutput.params ((P).output w) s.a₀ g + +theorem counters (h : Describes I C X start old) (j : Stage s) : + C.eval j.initial = word j.first ∧ C.eval (j.stop I) = word (j.limit X start) := by + have ha := addresses I C X start old h + cases j with + | supply => exact ⟨rfl,by simp only [Stage.stop,Stage.limit,eval_mul,ha.sites_eq,eval_lit,word_mul]⟩ + | base => exact ⟨rfl,by simp only [Stage.stop,Stage.limit,eval_mul,eval_lit,h.vertices_eq,word_mul]⟩ + | gather | offsets => exact ⟨rfl,ha.segments_eq⟩ + | bundles | slot _ => exact ⟨rfl,ha.sites_eq⟩ + | demand _ | term => exact ⟨rfl,ha.blocks_eq⟩ + | rom _ => exact ⟨rfl,rfl⟩ + +theorem termHeads_eq (h : Describes I C X start old) : + (fun i => C.eval (termHeads s I i)) = ![word (P).demand,word s.ties,word (P).term,word s.stride] := by + have ha := addresses I C X start old h + funext i + fin_cases i <;> first | exact ha.demand_eq | exact ha.term_eq | rfl + +variable (termWords : (Fin 4 → W w) → Fin termPorts → W w) + +theorem banks (h : Describes I C X start old) + (ht : (fun i => C.eval (termBank (termHeads s I) i)) = termWords (fun i => C.eval (termHeads s I i))) + (j : Stage s) (i : Fin (j.arity termPorts)) : + C.eval (j.bank I hd E tieOrder termBank i) = j.nativeBank hd E tieOrder X start old termWords i := by + have ha := addresses I C X start old h + cases j with + | gather => + fin_cases i <;> first | exact ha.scratch_eq 0 | exact ha.scratch_eq 1 | exact h.lanes_eq | exact h.oldWidth_eq + | bundles => + fin_cases i <;> first + | exact ha.scratch_eq 2 | exact ha.scratch_eq 3 | exact ha.scratch_eq 4 + | exact h.lanes_eq | exact h.oldOut_eq | exact h.oldShift_eq | rfl + | offsets => exact ha.scratch_eq i + | demand k => + have choice : + C.eval (if (tieOrder k).1 then scratch s I 1 else scratch s I 7) = + (if (tieOrder k).1 then (P).scratch w 1 else (P).scratch w 7) := by + cases (tieOrder k).1 <;> first | exact ha.scratch_eq 1 | exact ha.scratch_eq 7 + fin_cases i <;> first | exact h.lanes_eq | exact choice | exact ha.demand_eq | rfl + | term => exact (congrFun ht i).trans (congrFun (congrArg termWords (termHeads_eq I C X start old h)) i) + | supply => + fin_cases i <;> first | exact h.lanes_eq | exact ha.term_eq | exact ha.supply_eq | rfl + | rom _ => + fin_cases i <;> first | exact ha.target_eq | exact ha.reverse_eq | rfl + | slot k => + fin_cases i <;> first + | exact h.lanes_eq | exact ha.target_eq | exact ha.reverse_eq | exact ha.supply_eq + | exact ha.scratch_eq 2 | exact ha.scratch_eq 4 | exact ha.column_eq _ | rfl + | base => fin_cases i <;> first | exact h.lanes_eq | exact ha.column_eq _ | rfl + +/-- Exact field list installed by the compiled planner for this native worker. +The common catalog bank is zero-padded past the worker's own arity. -/ +def Stage.fields (j : Stage s) : List (W w) := + word (j.tag tags hd) :: word j.first :: word (j.limit X start) :: List.ofFn (fun i : Fin G => + if h : i.val < j.arity termPorts then j.nativeBank hd E tieOrder X start old termWords ⟨i.val,h⟩ else 0) + +theorem compiled_fields (h : Describes I C X start old) + (ht : (fun i => C.eval (termBank (termHeads s I) i)) = termWords (fun i => C.eval (termHeads s I i))) + (room : max 13 termPorts ≤ G) (j : Stage s) : + (phase I tags hd E tieOrder termBank room j).recipe.words C.pub C.state C.memory = + j.fields (G := G) tags hd E tieOrder X start old termWords := by + rw [recipe_words] + obtain ⟨lo,hi⟩ := counters I C X start old h j + change word (j.tag tags hd) :: C.eval j.initial :: C.eval (j.stop I) :: + List.ofFn (fun i : Fin G => C.eval ((phase I tags hd E tieOrder termBank room j).params i)) = _ + rw [lo,hi] + unfold Stage.fields + congr 3 + apply congrArg List.ofFn + funext i + by_cases used : i.val < j.arity termPorts + · simp only [phase,Phase.ofParams,used,↓reduceDIte] + exact banks I hd E tieOrder termBank C X start old termWords h ht j ⟨i.val,used⟩ + · simp only [phase,Phase.ofParams,used,↓reduceDIte] + rfl + +/-- With sufficient cursor space, the planner's two counter fields are the +exact natural start and stop, including the singleton ROM interval. -/ +theorem counter_values (h : Describes I C X start old) (j : Stage s) + (fits : j.limit X start < 2^w) : + (C.eval j.initial).val = j.first ∧ (C.eval (j.stop I)).val = j.limit X start := by + obtain ⟨lo,hi⟩ := counters I C X start old h j + rw [lo,hi] + have le : j.first ≤ j.limit X start := by cases j <;> simp [Stage.first,Stage.limit] + exact ⟨Nat.mod_eq_of_lt (le.trans_lt fits),Nat.mod_eq_of_lt fits⟩ + +include hd in +/-- Every stop cursor fits whenever the complete level allocation fits. The +proof includes the last expander ROM cursor and the lane-zero base pass. -/ +theorem limit_fits (allocated : (P).stop ≤ 2^w) (j : Stage s) : j.limit X start < 2^w := by + have capPos : 0 < (P).capacity := by + change 0 < Fintype.card X.Base * 2^s.a * 2^g * 2^s.a₀ + positivity + have capLt : (P).capacity < 2^w := by change (P).next+6*(P).capacity ≤ _ at allocated; omega + have segLt : (P).segments < 2^w := by + dsimp only [Allocation.Plan.stop,Allocation.Plan.next,Allocation.Plan.reverseSlot, + Allocation.Plan.targetPort,Allocation.Plan.supply,Allocation.Plan.term,Allocation.Plan.demand] at allocated + omega + have siteLe : (P).sites ≤ (P).capacity := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _) + have blockLe : (P).blocks ≤ (P).sites := by + exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _)) + have supplyLe : (P).sites * s.dH ≤ (P).capacity := Nat.mul_le_mul_left _ (by omega : s.dH ≤ s.degree) + have portLe : s.ports ≤ (P).sites := (Nat.le_mul_of_pos_left _ Fintype.card_pos).trans + (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g)) + cases j with + | gather | offsets => exact segLt + | bundles | slot _ => exact siteLe.trans_lt capLt + | demand _ | term => exact (blockLe.trans siteLe).trans_lt capLt + | supply => exact supplyLe.trans_lt capLt + | rom i => + exact ((Nat.succ_le_of_lt i.isLt).trans (Nat.mul_le_mul_right _ portLe)).trans_lt (supplyLe.trans_lt capLt) + | base => + exact (Nat.mul_le_mul_right s.degree + (Nat.le_mul_of_pos_right (Fintype.card X.Base * s.ports) (Nat.two_pow_pos g))).trans_lt capLt + +open MotifConversion + +variable {k : Type*} [_root_.Field k] {K K' : ℝ} (hdH : 0 < s.dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) s.degree K K') + +theorem base_limit_eq (hD : 1 < s.ports) (choice : DyadicRefreshChoice X E hdH conn F) : + (Stage.base : Stage s).limit X start = BaseOutput.baseCount (dyadicRefreshNext X E hdH conn F hD hd choice) := by + change Fintype.card X.Base * s.ports * s.degree = Fintype.card (X.Base × Fin s.ports) * s.degree + simp [Fintype.card_prod] + +theorem supply_bank_eq (selectorWidth : s.selectors = F.selectorBits) : + (Stage.supply : Stage s).nativeBank hd E tieOrder X start old termWords = + SupplyScan.params s.ports (2^g) s.dH (word (P).term) s.stride F.selectorBits (word (P).supply) := by + change SupplyScan.params _ _ _ _ _ s.selectors _ = _ + rw [selectorWidth] + +/-- The motif worker supplies one phase for all blocks. Its address prefix is +computed online and the remaining grid and arithmetic operands are fixed +natural literals, independent of word width. -/ +noncomputable def motifPhases + (room : max 13 (TermWorker.motifPass F tieOrder (s.ports*s.dH)).params ≤ G) : List (Phase G) := + phases I tags hd E tieOrder (TermWorker.motifExprs F tieOrder finProdFinEquiv.symm) room + +theorem motif_compiled_fields (h : Describes I C X start old) + (room : max 13 (TermWorker.motifPass F tieOrder (s.ports*s.dH)).params ≤ G) (j : Stage s) : + let terms := TermWorker.motifExprs F tieOrder finProdFinEquiv.symm + (phase I tags hd E tieOrder terms room j).recipe.words C.pub C.state C.memory = + j.fields (G := G) tags hd E tieOrder X start old (TermWorker.motifData F tieOrder finProdFinEquiv.symm w) := + compiled_fields I tags hd E tieOrder _ C X start old _ h + (TermWorker.eval_motifExprs F tieOrder finProdFinEquiv.symm (termHeads s I) C.pub C.state C.memory) room j + +/-- The occurrence-indexed registry may assign the tag after enumerating the +stages. Its public operands still agree pointwise with the native proof for +the fused motif worker or the selected deterministic worker. -/ +theorem motif_workerBank_eq (h : Describes I C X start old) (j : Stage s) : + let term := TermWorker.motifPass F tieOrder (s.ports*s.dH) + let terms := TermWorker.motifExprs F tieOrder finProdFinEquiv.symm + ∀ i : Fin (j.worker hd term).params, C.eval (j.workerBank I hd E tieOrder term terms i) = + j.nativeBank hd E tieOrder X start old (TermWorker.motifData F tieOrder finProdFinEquiv.symm w) + (Fin.cast (j.worker_params hd term) i) := by + intro term terms i + exact banks I hd E tieOrder terms C X start old _ h + (TermWorker.eval_motifExprs F tieOrder finProdFinEquiv.symm (termHeads s I) C.pub C.state C.memory) j _ + +/-- The native planner installs the checked public operands, start and stop +for any selected stage of the fixed motif schedule. -/ +theorem execute_motif_phase (h : Describes I C X start old) + (room : max 13 (TermWorker.motifPass F tieOrder (s.ports*s.dH)).params ≤ G) (j : Stage s) + (cap : ℕ) (budget : (phase I tags hd E tieOrder + (TermWorker.motifExprs F tieOrder finProdFinEquiv.symm) room j).recipe.code.length < cap) + (rowRoom : (Controller.rowBase G C.pub C.memory).val + (G+3) ≤ 2^w) : + let ph := phase I tags hd E tieOrder (TermWorker.motifExprs F tieOrder finProdFinEquiv.symm) room j + let M := ph.recipe.acceptTable.instantiate w C.pub + let es := (ph.recipe.report C.pub C.state C.memory).events + execute M.program cap (M.program.start C.state) C.memory [] = some ⟨es,none⟩ ∧ + Greedy.Stores (after C.memory es) (Controller.rowBase G C.pub C.memory) + (j.fields (G := G) tags hd E tieOrder X start old (TermWorker.motifData F tieOrder finProdFinEquiv.symm w)) ∧ + (∀ a, a < (Controller.rowBase G C.pub C.memory).val ∨ (Controller.rowBase G C.pub C.memory).val + (G+3) ≤ a → + after C.memory es a = C.memory a) ∧ countProbes es = ph.recipe.reads+(G+3) ∧ choiceBits es = [] := by + intro ph M es + have exactRow := motif_compiled_fields I tags hd E tieOrder C X start old hdH conn F h room j + change ph.recipe.words C.pub C.state C.memory = _ at exactRow + rw [recipe_words] at exactRow + rw [← exactRow] + exact execute_phase ph C.pub C.state C.memory cap budget rowRoom + +end CompressorRecords.PortRefresh.LevelRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshMapCall.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshMapCall.lean new file mode 100644 index 0000000000..274091174a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshMapCall.lean @@ -0,0 +1,105 @@ +import OAI.Computability.VPVNP.CompressorRefreshMapCallData +import OAI.Computability.VPVNP.CompressorRefreshMapWorkspace +import OAI.Computability.VPVNP.CompressorRefreshArgumentPlan +import OAI.Computability.VPVNP.PairSimulationMapArgumentInput + +/-! +# Publishing the raw refresh call into the private map interpreter + +The linked writer computes every fixed argument from its six live input registers and the +constructed external level. It publishes a private descriptor for the selected map call. +The resulting config meets the interpreter's full raw input specification, including all +demand bits and all supply selector suffixes. The mathematical call supplies no descriptor +or bitstream to the writer. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.MapCall + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh PhaseRecipe NewSlots +open OperandInputs PairSimulation PairSimulation.LocalHistory NodeArguments RefreshMapOperands MotifConversion MotifSelector MotifEntry + +variable {bits g t histCount pcs regs params : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} + (B : S.Templates) (X : State S.portExponent (S.portExponent+g)) + (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) + (p : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ) + (oldDir newDir : IncidenceDirectory bits) (ties : Fin t ≃ Tie (2^S.portExponent)) + (start stride : ℕ) (m : Memory bits) (I : OperandInputs.Input) (J : MapCallWords.WorkHeads) + (old : X.network.Half (oldSite X p)) + (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) + B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites p)) + (grid : B.refresh.grid.demands) (L : MapEntryTable.Allocation B.refresh grid p.2 regs params) + (loc : L.Address → Fin pcs) + (order : MapCallSetup.Arg (Tie (2^S.portExponent)) (Fin (2^S.portExponent) × Fin (2^S.expanderExponent)) ≃ + Fin (Fintype.card (MapCallSetup.Arg (Tie (2^S.portExponent)) (Fin (2^S.portExponent) × Fin (2^S.expanderExponent))))) + (ptr : Expr) + +local notation "D" => 2^S.portExponent +local notation "H" => 2^S.expanderExponent +local notation "P" => S.graph.toSlotGraph +local notation "hD" => S.port_order +local notation "hd" => And.right S.degree_bounds +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice +local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice +local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t stride start +local notation "Q" => Allocation.Plan.scratch Pₗ bits +local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ) +local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ) +local notation "N" => Fintype.card X.Base*D*2^g*D +local notation "E₀" => entryInput B X choice p old new +local notation "u" => repetitions B.refresh (EntryInput.demand E₀) +local notation "d" => MotifEntry.demandBits tieSource tieTarget (Prod.snd p) (EntryInput.demandBits E₀) +local notation "x" => mapHalf S.portSupply (fun _ => MotifEntry.inputBits) (EntryInput.supplyBits E₀) +local notation "f" => (MapCallWords.fields P hd ties stride I J ∘ Equiv.symm order) +local notation "argc" => Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H)) + +set_option maxHeartbeats 1400000 in +/-- A successful straight-line publication yields the raw interpreter input. It consumes +zero branch bits and charges exactly the reads appearing in the fixed expression bank. -/ +theorem publish {fit : N ≤ 2^bits} {n limit : ℕ} (R : MapWorkspace.Regions (Tie D) (Fin D × Fin H)) + (capacity : MapWorkspace.Capacity B.refresh bits n limit) (copyBound : u ≤ n) + (ordered : MapWorkspace.Ordered (L.program loc) (E₀).demand (E₀).payload R u histCount limit) + (bases : R.base = operandBase X p P hD hd internal A child parent) + (vm : Fin (RegisterSetup.regCount (MapArgumentWriter.recipes ptr f)) ↪ Fin regs) + (inputs : Fin 6 → Fin regs) (aux : Fin 3 ↪ Fin regs) + (place : MapArgumentWriter.Address ptr f → Fin pcs) (done : Fin pcs) + (M : Machine bits pcs regs params) (link : ∀ a, M.code (place a) = + (MapArgumentWriter.text ptr f vm inputs aux place done a).resize bits) + (safe : ∀ i j, vm i ≠ inputs j) (apart : ∀ i j, vm i ≠ aux j) (c : Config bits pcs regs) + (entry : c.pc = MapArgumentWriter.setupPC ptr f place 0) + (oldCols : oldDir.ActualColumns X m) (newCols : newDir.ActualColumns Y m) + (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) + (oldData : NodeFields A child X (oldSite X p) old c.privateMem) + (newData : NodeFields A parent Y (promotedSites p) new c.privateMem) (wide : D < 2^bits) : + let pub := fun j : Fin 5 => c.reg (inputs j.castSucc) + let state := c.reg (inputs (Fin.last 5)) + let addr := ptr.eval pub state m + let Wk := MapWorkspace.workspace (L.program loc) R d x capacity copyBound ordered + Describes I pub state m X p P hD hd internal A child parent oldDir newDir Q src term → + J.directory.eval pub state m = word R.directory → J.source.eval pub state m = word R.source → + J.target.eval pub state m = word R.target → J.hist.eval pub state m = word R.hist → + R.directory ≤ addr.val → addr.val+argc ≤ 2^bits → + ∃ ev out, ev.length = MapArgumentWriter.clock ptr f ∧ countProbes ev = (∑ j, ((MapArgumentWriter.recipes ptr f) j).loads) ∧ + choiceBits ev = [] ∧ out.pc = done ∧ out.reg (aux 0) = addr ∧ + MapCallSetup.Input L order loc Wk (aux 0) out ∧ out.persistent = c.persistent ∧ + (∀ a : W bits, a.val < addr.val ∨ addr.val+argc ≤ a.val → out.privateMem a = c.privateMem a) ∧ + (∀ j, (∀ i, j ≠ vm i) → (∀ i, j ≠ aux i) → out.reg j = c.reg j) ∧ + ∀ fuel bs, execute M.program (fuel+ev.length) c m bs = + (execute M.program fuel out m bs).map (fun r => ⟨ev++r.events,r.result⟩) := by + intro pub state addr Wk args directory source target hist early room + apply MapArgumentWriter.native_input L order loc Wk ptr (MapCallWords.fields P hd ties stride I J) + vm inputs aux place done M link safe apart c m entry room + · exact MapCallWords.values_eq B X choice p A child parent oldDir newDir ties start stride pub state m I J old new + grid L loc Wk args oldCols newCols stored wide bases directory source target hist + · exact MapCallData.resident_packed B X choice p A child parent old new grid L loc ties start stride m c.privateMem + R capacity copyBound ordered addr early stored oldData newData bases + +end CompressorRecords.PortRefresh.MapCall + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshMapCallData.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshMapCallData.lean new file mode 100644 index 0000000000..e75d59fa00 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshMapCallData.lean @@ -0,0 +1,188 @@ +import OAI.Computability.VPVNP.CompressorRefreshMapCallWords +import OAI.Computability.VPVNP.PairSimulationMapWorkspace +import OAI.Computability.VPVNP.PairSimulationMapArgumentInput + +/-! +# Physical input of the selected refresh map call + +The private descriptor and the old and new node frames supply the map's register setup. +Demand reads use their two independent halves. The agreement scan reads each full +supply, including its selector suffix. The private directory follows the complete input +interval, so the directory initializer preserves those data cells. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshMapOperands + +open Compression PairSimulation.NodeArguments BurstRAM + +/-- Writes outside a packed node's interval preserve all independent half-wire bits +in its argument bank. -/ +theorem NodeFields.transfer {a g w : ℕ} {A : Arena} {node : ℕ} {X : State a g} {v : X.network.Site} + {z : X.network.Half v} {before after : Word w → Word w} (fields : NodeFields A node X v z before) + (frame : ∀ addr, A.base node ≤ addr → addr < A.base node + (packed X v z).length → + after (Fin.ofNat (2^w) addr) = before (Fin.ofNat (2^w) addr)) : NodeFields A node X v z after := by + intro dir j i + have lo : A.base node ≤ A.fieldAddress X v node dir j := Nat.le_add_right .. + have endLe := field_end_le X v z A node dir j + have hold := frame (A.fieldAddress X v node dir j+i.val) (by omega) (by have := i.isLt; omega) + exact hold.trans (fields dir j i) + +end CompressorRecords.RefreshMapOperands + +namespace CompressorRecords.PortRefresh.MapCallData + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh NewSlots +open PairSimulation PairSimulation.LocalHistory PairSimulation.NodeArguments RefreshMapOperands MotifConversion MotifSelector +open MapEntryTable MapPortAgreement MapResidentAgreement MapLookup MotifEntry +open scoped Fin.CommRing + +variable {bits g t histCount pcs regs params : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} + (B : S.Templates) (X : State S.portExponent (S.portExponent+g)) + (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) + (p : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ) + (old : X.network.Half (oldSite X p)) + (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) + B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites p)) + (grid : B.refresh.grid.demands) (L : MapEntryTable.Allocation B.refresh grid p.2 regs params) (loc : L.Address → Fin pcs) + (ties : Fin t ≃ Tie (2^S.portExponent)) (start stride : ℕ) (m : Memory bits) + +local notation "D" => 2^S.portExponent +local notation "H" => 2^S.expanderExponent +local notation "P" => S.graph.toSlotGraph +local notation "hD" => S.port_order +local notation "hd" => And.right S.degree_bounds +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice +local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice +local notation "I" => entryInput B X choice p old new +local notation "u" => repetitions B.refresh (EntryInput.demand I) +local notation "d" => demandBits tieSource tieTarget (Prod.snd p) (EntryInput.demandBits I) +local notation "x" => mapHalf S.portSupply (fun _ => inputBits) (EntryInput.supplyBits I) +local notation "N" => Fintype.card X.Base*D*2^g*D +local notation "base" => operandBase X p P hD hd internal A child parent +local notation "pb" => supplyPortBase B X choice p A child parent +local notation "Raw" => MapWorkspace.rawWidth (EntryInput.demand I) (EntryInput.payload I) B.refresh.selectorBits u + +variable (priv : W bits → W bits) + +private def segmentData (priv : W bits → W bits) (start : ℕ) (f : (n : ℕ) × (Fin n → Bool)) : Prop := + ∀ i : Fin f.1, priv ((start+i.val : ℕ) : W bits) = PrimedInputRAM.encodeBit bits (f.2 i) + +private theorem demand_data (oldData : NodeFields A child X (oldSite X p) old priv) + (newData : NodeFields A parent Y (promotedSites p) new priv) (q : Bool × Tie D) : + ∀ l : Fin (MapRow.endpoint tieSource tieTarget p.2 (I).demand d q).1, + priv ((base (.inl q)+l.val : ℕ) : W bits) = + PrimedInputRAM.encodeBit bits ((MapRow.endpoint tieSource tieTarget p.2 (I).demand d q).2 l) := by + change segmentData priv (base (.inl q)) (MapRow.endpoint tieSource tieTarget p.2 (I).demand d q) + obtain ⟨b,e⟩ := q + cases b <;> rw [MapRow.endpoint] + · split + · rename_i he; exact demand_out_read X p P hD hd internal A child parent old new priv oldData e he + · intro i; exact i.elim0 + · split + · rename_i he; exact demand_in_read X p P hD hd internal A child parent old new priv newData e he + · intro i; exact i.elim0 + +private theorem demand_len (q : Bool × Tie D) : + (MapRow.endpoint tieSource tieTarget p.2 (I).demand d q).1 ≤ (I).demand q.2 := by + obtain ⟨b,e⟩ := q + cases b <;> rw [MapRow.endpoint] <;> split <;> simp + +/-- The raw data of the selected refresh, before the writer publishes the private +descriptor. Every live cell precedes both the directory and the descriptor. -/ +theorem resident {fit : N ≤ 2^bits} (Wk : MapCallWords.Workspace B X choice p old new grid L loc histCount bits) + (addr : W bits) (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) + (oldData : NodeFields A child X (oldSite X p) old priv) + (newData : NodeFields A parent Y (promotedSites p) new priv) + (bases : Wk.base = base) (portBases : Wk.portBase = pb) + (fieldEnd : ∀ f, Wk.base f + Raw f ≤ Wk.directory.val) + (directoryRoom : Wk.directory.val + (ports S.portSupply p.2 L.edgeOrder).length ≤ 2^bits) + (beforeDescriptor : Wk.directory.val ≤ addr.val) : + MapArgumentWriter.ResidentFields L loc Wk addr priv := by + have portEq (t : Port S.portSupply p.2) : + Wk.portBase t = (Wk.base (MapDirectoryInit.portField t) : W bits) := by + rw [portBases,bases]; cases t <;> rfl + have separated (cell : W bits) (hcell : cell.val < Wk.directory.val) : + MapArgumentWriter.separated L loc Wk addr cell := by + refine ⟨Or.inl (hcell.trans_le beforeDescriptor),fun a => ?_⟩ + have hi : a.val < (ports S.portSupply p.2 L.edgeOrder).length := a.isLt + apply Fin.ne_of_val_ne + rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (show a.val < 2^bits by omega),Nat.mod_eq_of_lt (by omega)] + omega + refine ⟨?_,portEq,?_,?_⟩ + · intro e + have h := (stored.readback p.1).2.2 (finProdFinEquiv e) + rw [Equiv.symm_apply_apply] at h + change (choice p.1).val e < 2^bits + rw [← h]; exact Fin.isLt _ + · intro t l + constructor + · rw [portBases] + exact selectorCells B X choice p old new A child parent priv newData t l + · apply separated + have hlen : Raw (MapDirectoryInit.portField t) = (I).payload (edge t) + u*B.refresh.selectorBits := by + cases t <;> rfl + have lo := fieldEnd (MapDirectoryInit.portField t) + rw [hlen] at lo + rw [portEq,← Nat.cast_add] + exact (Nat.mod_le ..).trans_lt ((Nat.add_lt_add_left l.isLt _).trans_le lo) + · intro q l + constructor + · rw [bases] + exact demand_data B X choice p A child parent old new priv oldData newData q l + · apply separated + have hl := l.isLt.trans_le (demand_len B X choice p old new q) + have bound := fieldEnd (.inl q) + change Wk.base (.inl q)+(I).demand q.2 ≤ Wk.directory.val at bound + exact (Nat.mod_le ..).trans_lt ((Nat.add_lt_add_left hl _).trans_le bound) + +/-- Specialize the resident data contract to the packed workspace. The ordering of +its scratch and operand regions supplies all bit/descriptor and bit/directory separation. -/ +theorem resident_packed {fit : N ≤ 2^bits} {limit n : ℕ} + (R : MapWorkspace.Regions (Tie D) (Fin D × Fin H)) + (C : MapWorkspace.Capacity B.refresh bits n limit) (hu : u ≤ n) + (ordered : MapWorkspace.Ordered (L.program loc) (I).demand (I).payload R u histCount limit) + (addr : W bits) (beforeDescriptor : R.directory ≤ addr.val) + (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) + (oldData : NodeFields A child X (oldSite X p) old priv) + (newData : NodeFields A parent Y (promotedSites p) new priv) (bases : R.base = base) : + let Wk := MapWorkspace.workspace (L.program loc) R d x C hu ordered + MapArgumentWriter.ResidentFields L loc Wk addr priv := by + let Wk := MapWorkspace.workspace (L.program loc) R d x C hu ordered + have hdir : R.directory + (ports S.portSupply p.2 L.edgeOrder).length ≤ 2^bits := + ordered.directoryEnd.trans ((Nat.le_add_right ..).trans (ordered.selectorEnd.trans + ((Nat.le_add_right ..).trans (ordered.labelEnd.trans C.room.le)))) + have hdr : Wk.directory.val = R.directory := + Nat.mod_eq_of_lt (show R.directory < 2^bits by + have := ordered.directoryEnd; have := ordered.selectorEnd; have := ordered.labelEnd; have := C.room; omega) + apply resident B X choice p A child parent old new grid L loc ties start stride m priv Wk addr stored oldData newData bases + · funext t + change (R.base (MapDirectoryInit.portField t) : W bits) = _ + rw [bases]; cases t <;> rfl + · intro f; rw [hdr]; exact ordered.inputEnd f + · rw [hdr]; exact hdir + · rw [hdr]; exact beforeDescriptor + +variable (args : MapCallSetup.Arg (Tie (2^S.portExponent)) (Fin (2^S.portExponent) × Fin (2^S.expanderExponent)) ≃ + Fin (Fintype.card (MapCallSetup.Arg (Tie (2^S.portExponent)) (Fin (2^S.portExponent) × Fin (2^S.expanderExponent))))) + (ptr : Fin regs) (c : Config bits pcs regs) + +/-- If the descriptor has already been written, resident fields at the same config +give the ordinary initializer input directly. -/ +theorem input {addr : W bits} (Wk : MapCallWords.Workspace B X choice p old new grid L loc histCount bits) + (descriptor : ∀ a, c.privateMem (c.reg ptr + ((args a).val : W bits)) = MapCallSetup.values L loc Wk a) + (cells : MapArgumentWriter.ResidentFields L loc Wk addr c.privateMem) : + MapCallSetup.Input L args loc Wk ptr c := + ⟨descriptor,cells.payloadFit,cells.supplyBase,fun t i => (cells.supply t i).1, + fun q i => (cells.demandCells q i).1,fun t i => (cells.supply t i).2.2, + fun q i => (cells.demandCells q i).2.2⟩ + +end CompressorRecords.PortRefresh.MapCallData + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshMapCallWords.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshMapCallWords.lean new file mode 100644 index 0000000000..6cd69e0a85 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshMapCallWords.lean @@ -0,0 +1,136 @@ +import OAI.Computability.VPVNP.CompressorRefreshMapFrameFields +import OAI.Computability.VPVNP.PairSimulationMapCallSetup + +/-! +# The raw private descriptor of a refresh map call + +The descriptor carries the actual field starts, all demand and selected payload widths, +the stored repetition word, and four private workspace heads. Its width words are +unmasked: the local port and the fixed motif determine which incident slices the map +driver subsequently uses. The integer words are recovered from the physical term and +demand tables of the selected refresh. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.MapCallWords + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh NewSlots PhaseRecipe +open OperandInputs PairSimulation PairSimulation.NodeArguments RefreshMapOperands MotifConversion MotifSelector +open scoped Fin.CommRing + +/-- Expressions for the four workspace addresses passed to the refresh map interpreter. -/ +structure WorkHeads where + /-- Expression for the address of the map interpreter's workspace directory. -/ + directory : Expr + /-- Expression for the base address of the map's source buffer. -/ + source : Expr + /-- Expression for the base address of the map's target buffer. -/ + target : Expr + /-- Expression for the base address of the map's history buffer. -/ + hist : Expr + +/-- Reads the repetition count from word one of the selected block's strided term record. -/ +def copies (degree stride : ℕ) (I : Input) : Expr := + let block := ArgumentSite.blockIndex degree I.parent.siteOrd I.lanes + .load ((I.termBase.add (block.mul (.lit stride))).add (.lit 1)) + +/-- Builds the map-call setup operands from the node field bases, stored demand and payload +widths, repetition count and workspace heads. -/ +def fields {d d₀ dH t : ℕ} (P : SlotGraph (Fin d) dH) (hd : dH+1 ≤ d₀) + (ties : Fin t ≃ Tie d) (stride : ℕ) (I : Input) (J : WorkHeads) : MapCallSetup.Arg (Tie d) (Fin d × Fin dH) → Expr + | .base f => MapFrameFields.base P hd I f + | .demand e => MapFrameFields.storedWidth (dH := dH) ties stride I (.inl (false,e)) + | .payload e => MapFrameFields.storedWidth ties stride I (.inr (false,e)) + | .copies => copies d stride I + | .directory => J.directory + | .source => J.source + | .target => J.target + | .hist => J.hist + +variable {bits g t histCount pcs regs params : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} + (B : S.Templates) (X : State S.portExponent (S.portExponent+g)) + (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) + (p : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ) + (oldDir newDir : IncidenceDirectory bits) (ties : Fin t ≃ Tie (2^S.portExponent)) + (start stride : ℕ) (pub : Fin 5 → W bits) (state : W bits) (m : Memory bits) (I : Input) (J : WorkHeads) + (old : X.network.Half (oldSite X p)) + (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) + B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites p)) + (grid : B.refresh.grid.demands) (L : MapEntryTable.Allocation B.refresh grid p.2 regs params) (loc : L.Address → Fin pcs) + +local notation "D" => 2^S.portExponent +local notation "H" => 2^S.expanderExponent +local notation "P" => S.graph.toSlotGraph +local notation "hD" => S.port_order +local notation "hd" => And.right S.degree_bounds +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice +local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice +local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t stride start +local notation "Q" => Allocation.Plan.scratch Pₗ bits +local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ) +local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ) +local notation "N" => Fintype.card X.Base*D*2^g*D + +/-- The map interpreter's ordinary numerical workspace, specialized to the chosen +refresh entry and to its actual incident wire arguments. -/ +noncomputable abbrev Workspace (histCount bits : ℕ) := + let E := entryInput B X choice p old new + MapEntry.Program.Workspace (L.program loc) E.demand E.payload + (MotifEntry.demandBits tieSource tieTarget p.2 E.demandBits) + (mapHalf S.portSupply (fun _ => MotifEntry.inputBits) E.supplyBits) histCount bits + +private theorem copies_eq {fit : N ≤ 2^bits} (args : Describes I pub state m X p P hD hd internal A child parent + oldDir newDir Q src term) (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) + (wide : D < 2^bits) : + (copies D stride I).eval pub state m = + word (repetitions B.refresh (blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) p.1)) := by + let b := ArgumentSite.blockIndex D I.parent.siteOrd I.lanes + let row := SupplyScan.recordBase X term stride p.1 + have hb : b.eval pub state m = word (DemandScan.blocks X p.1).val := + ArgumentSite.blockIndex_eval X p pub state m _ _ args.site args.lanes wide + have head : term + word (DemandScan.blocks X p.1).val * word stride = row := by rw [DemandScan.blocks_val]; rfl + have room := stored.terms.fits p.1 + change row.val+2+D*H < 2^bits at room + have one : (1 : W bits).val = 1 := Nat.mod_eq_of_lt (show 1 < 2^bits by omega) + have atRep : (row+1).val = row.val+1 := by rw [Fin.val_add,one,Nat.mod_eq_of_lt (by change row.val+1 < 2^bits; omega)] + change m (I.termBase.eval pub state m + b.eval pub state m * word stride + 1).val = _ + rw [args.termBase,hb,head,atRep] + exact stored.terms.repetitions p.1 + +/-- Each descriptor word computed from the level arrays is exactly the word the native +map setup expects at that ordinal. -/ +theorem values_eq {fit : N ≤ 2^bits} (Wk : Workspace B X choice p old new grid L loc histCount bits) + (args : Describes I pub state m X p P hD hd internal A child parent oldDir newDir Q src term) + (oldCols : oldDir.ActualColumns X m) (newCols : newDir.ActualColumns Y m) + (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) + (wide : D < 2^bits) (bases : Wk.base = operandBase X p P hD hd internal A child parent) + (directory : J.directory.eval pub state m = Wk.directory) (source : J.source.eval pub state m = word Wk.source) + (target : J.target.eval pub state m = word Wk.target) (hist : J.hist.eval pub state m = word Wk.hist) : + ∀ a, (fields P hd ties stride I J a).eval pub state m = MapCallSetup.values L loc Wk a := by + intro a + cases a with + | base f => + change (MapFrameFields.base P hd I f).eval pub state m = word (Wk.base f) + rw [bases]; exact MapFrameFields.base_eval X p P hD hd internal A child parent oldDir newDir Q src term pub state m I + args oldCols newCols stored.segments wide f + | demand e => + exact MapFrameFields.storedWidth_eval B X choice p A child parent oldDir newDir ties start stride pub state m I + args stored wide (.inl (false,e)) + | payload e => + exact MapFrameFields.storedWidth_eval B X choice p A child parent oldDir newDir ties start stride pub state m I + args stored wide (.inr (false,e)) + | copies => exact copies_eq B X choice p A child parent oldDir newDir ties start stride pub state m I args stored wide + | directory => exact directory + | source => exact source + | target => exact target + | hist => exact hist + +end CompressorRecords.PortRefresh.MapCallWords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshMapFrameFields.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshMapFrameFields.lean new file mode 100644 index 0000000000..2c2e37227e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshMapFrameFields.lean @@ -0,0 +1,235 @@ +import OAI.Computability.VPVNP.CompressorRefreshOperandInputs +import Mathlib.Data.LawfulXor.Basic + +/-! +# Native operand bases and lengths of the refresh motif + +The same field descriptor table serves all promoted ports. Old demand endpoints read +their designated old slot, while new endpoints read the appropriate slice of the packed +external word. Supply endpoints read their designated expander slot. Lengths select the +payload part of the incident fields using the port computed from the current site. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.MapFrameFields + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh +open PhaseRecipe NewSlots OperandInputs PairSimulation PairSimulation.NodeArguments MapLookup RefreshMapOperands +open MotifSelector MotifConversion SpectralGeometry +open scoped Fin.CommRing + +variable {D d₀ dH t bits : ℕ} + +/-- A source or target endpoint field of a demand tie or a directed expander supply incidence. -/ +abbrev FieldId (D dH : ℕ) := LabelField (Tie D) (Fin D × Fin dH) + +/-- Local base pointer of a map-row field. The table uses the fixed reverse incidence +of a supply and the stored segment offset at either end of an external demand. -/ +def base (P : SlotGraph (Fin D) dH) (hd : dH+1 ≤ d₀) (I : Input) : FieldId D dH → Expr + | .inl (false,e) => ArgumentAddress.fieldStatic I.child (!e.1) (tieTarget e) + | .inl (true,e) => + let loc := ArgumentAddress.fieldStatic I.parent (!e.1) (refreshSlots hd (.inl 0)) + let index := ArgumentSite.segment D I.parent.siteOrd (.lit (tieSource e).val) + loc.add (.load ((if !e.1 then I.offIn else I.offOut).add index)) + | .inr (false,e) => ArgumentAddress.fieldStatic I.parent false (refreshSlots hd (.inr (.inl e.2))) + | .inr (true,e) => ArgumentAddress.fieldStatic I.parent true (refreshSlots hd (.inr (.inl (P.target e).2))) + +/-- A present endpoint gives one and an absent endpoint gives zero. -/ +def present (port : Expr) (endpoint : Fin D) : Expr := + (.lit 1 : Expr).div ((Expr.binary .bitXor port (.lit endpoint.val)).add (.lit 1)) + +/-- The port at which the indexed demand or supply endpoint is incident. -/ +def endpoint (P : SlotGraph (Fin D) dH) : FieldId D dH → Fin D + | .inl (false,e) => tieSource e + | .inl (true,e) => tieTarget e + | .inr (false,e) => e.1 + | .inr (true,e) => (P.target e).1 + +/-- Recover the stored demand width or chosen supply payload for a fixed motif role. +The grid and repetition headers precede the payload vector. -/ +def storedWidth (ties : Fin t ≃ Tie D) (stride : ℕ) (I : Input) : FieldId D dH → Expr + | .inl (_,e) => + let b := ArgumentSite.blockIndex D I.parent.siteOrd I.lanes + .load ((I.demandBase.add (b.mul (.lit t))).add (.lit (ties.symm e).val)) + | .inr (_,e) => + let b := ArgumentSite.blockIndex D I.parent.siteOrd I.lanes + .load ((I.termBase.add (b.mul (.lit stride))).add (.lit (2+e.1.val*dH+e.2.val))) + +/-- Only the endpoint incident to the runtime port contributes a readable slice. -/ +def length (P : SlotGraph (Fin D) dH) (ties : Fin t ≃ Tie D) (stride : ℕ) (I : Input) (f : FieldId D dH) : Expr := + (present (ArgumentSite.portIndex D I.parent.siteOrd I.lanes) (endpoint P f)).mul (storedWidth ties stride I f) + +private theorem word_add (x y : ℕ) : word x + word y = word (bits := bits) (x+y) := + Fin.ext (Nat.add_mod x y _).symm + +private theorem word_mul (x y : ℕ) : word x * word y = word (bits := bits) (x*y) := + Fin.ext (Nat.mul_mod x y _).symm + +private theorem of_val (x : W bits) {n : ℕ} (h : x.val = n) : x = word n := + Fin.ext (h.trans (Nat.mod_eq_of_lt (h ▸ x.isLt)).symm) + +theorem present_eval {a : ℕ} (pub : Fin 5 → W bits) (state : W bits) (m : Memory bits) + (port : Expr) (j k : Fin (2^a)) (dFit : 2^a < 2^bits) (rep : port.eval pub state m = word j.val) : + (present port k).eval pub state m = if j=k then (1 : W bits) else 0 := by + have hj : (port.eval pub state m).val = j.val := (congrArg Fin.val rep).trans (Nat.mod_eq_of_lt (j.isLt.trans dFit)) + have hk : ((k.val : W bits)).val = k.val := Nat.mod_eq_of_lt (k.isLt.trans dFit) + let x := j.val ^^^ k.val + have hl : x < 2^a := Nat.xor_lt_two_pow j.isLt k.isLt + have hw : 1 < 2^bits := (Nat.one_le_two_pow).trans_lt dFit + have hone : (1 : W bits).val = 1 := Nat.mod_eq_of_lt hw + have hxor : (BinaryOp.bitXor.eval (port.eval pub state m) (k.val : W bits)).val = x := by + change ((port.eval pub state m).val ^^^ (k.val : W bits).val) % _ = _ + rw [hj,hk]; exact Nat.mod_eq_of_lt (hl.trans dFit) + change Fin.ofNat _ ((1 : W bits).val / (BinaryOp.bitXor.eval (port.eval pub state m) (k.val : W bits)+1).val) = _ + rw [Fin.val_add,hxor,hone,Nat.mod_eq_of_lt (by omega)] + by_cases he : j=k + · subst k; simp [x] + · have hn : x ≠ 0 := fun h => he (Fin.ext (xor_eq_zero_iff.mp h)) + rw [ite_eq_right he,Nat.div_eq_of_lt (by omega)] + rfl + +section Base + +variable {a g a₀ : ℕ} (X : State a (a+g)) (p : (X.Base × BitWord g) × Fin (2^a)) + (P : SlotGraph (Fin (2^a)) dH) (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) + (internal : X.Base × BitWord g → Fin (2^a) × Fin dH → ℕ) (A : Arena) (child parent : ℕ) + (old next : IncidenceDirectory bits) (q : Fin 8 → W bits) (demand term : W bits) + (pub : Fin 5 → W bits) (state : W bits) (m : Memory bits) (I : Input) + +local notation "Y" => newState X P hD hd internal +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) +local notation "N" => Fintype.card X.Base*2^a*2^g*2^a + +/-- Every operand expression evaluates to the independent slot or packed-segment base +used by the resident map call, including its unselected fields. -/ +theorem base_eval {fit : N ≤ 2^bits} + (args : Describes I pub state m X p P hD hd internal A child parent old next q demand term) + (oldCols : old.ActualColumns X m) (newCols : next.ActualColumns Y m) + (segments : SegmentFields X q fit m) (dFit : 2^a < 2^bits) (f : FieldId (2^a) dH) : + (base P hd I f).eval pub state m = word (operandBase X p P hD hd internal A child parent f) := by + rcases f with ⟨dir,e⟩ | ⟨dir,e⟩ + · cases dir with + | false => exact ArgumentAddress.eval_fieldStatic args.childRep oldCols _ _ + | true => + let idx := ArgumentSite.segment (2^a) I.parent.siteOrd (.lit (tieSource e).val) + have he : idx.eval pub state m = idWord O fit (p,tieSource e) := + ArgumentSite.segment_eval X p pub state m _ args.site (.lit (tieSource e).val) (tieSource e) + (Nat.mod_eq_of_lt ((tieSource e).isLt.trans dFit)) fit + have hread : m (((if !e.1 then I.offIn else I.offOut).eval pub state m) + idx.eval pub state m).val = + word (externalOffset X p (!e.1) (tieSource e)) := by + obtain ⟨ho,hi⟩ := Readback.interval_spec X q m segments (p,tieSource e) + cases h : e.1 + · rw [he] + simp only [Bool.not_false,ite_true,args.offIn] + exact of_val _ (congrArg Prod.snd hi) + · rw [he] + change m (I.offOut.eval pub state m + idWord O fit (p,tieSource e)).val = _ + rw [args.offOut] + exact of_val _ (congrArg Prod.snd ho) + change (ArgumentAddress.fieldStatic I.parent (!e.1) (refreshSlots hd (.inl 0))).eval pub state m + + m (((if !e.1 then I.offIn else I.offOut).eval pub state m)+idx.eval pub state m).val = _ + rw [ArgumentAddress.eval_fieldStatic args.parentRep newCols,hread] + exact word_add _ _ + · cases dir <;> exact ArgumentAddress.eval_fieldStatic args.parentRep newCols _ _ + +end Base + +section Selected + +variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {g : ℕ} + (X : State S.portExponent (S.portExponent+g)) + (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) + (p : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ) + (oldDir newDir : IncidenceDirectory bits) (ties : Fin t ≃ Tie (2^S.portExponent)) (start stride : ℕ) + (pub : Fin 5 → W bits) (state : W bits) (m : Memory bits) (I : Input) + +local notation "D" => 2^S.portExponent +local notation "H" => 2^S.expanderExponent +local notation "P" => S.graph.toSlotGraph +local notation "hD" => S.port_order +local notation "hd" => And.right S.degree_bounds +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice +local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice +local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t stride start +local notation "Q" => Allocation.Plan.scratch Pₗ bits +local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ) +local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ) +local notation "N" => Fintype.card X.Base*D*2^g*D +local notation "dem" => blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) + +/-- The demand width or supply payload width of a field before restriction to the runtime port. -/ +def nominal (d : Tie D → ℕ) (v : Fin D × Fin H → ℕ) : FieldId D H → ℕ + | .inl (_,e) => d e + | .inr (_,e) => v e + +/-- The live reads of the dense demand and strided term columns recover the selected +integer lengths in the fixed coordinate ordering. -/ +theorem storedWidth_eval {fit : N ≤ 2^bits} + (args : Describes I pub state m X p P hD hd internal A child parent oldDir newDir Q src term) + (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) + (dFit : D < 2^bits) (f : FieldId D H) : + (storedWidth ties stride I f).eval pub state m = word (nominal (dem p.1) (choice p.1).val f) := by + let b := ArgumentSite.blockIndex D I.parent.siteOrd I.lanes + have hb : b.eval pub state m = word (DemandScan.blocks X p.1).val := + ArgumentSite.blockIndex_eval X p pub state m _ _ args.site args.lanes dFit + rcases f with ⟨dir,e⟩ | ⟨dir,e⟩ + · change m (I.demandBase.eval pub state m + b.eval pub state m * word t + word (ties.symm e).val).val = _ + rw [args.demandBase,hb,word_mul] + exact of_val _ (congrFun (stored.demands p.1) e) + · let head := SupplyScan.recordBase X term stride p.1 + let slot := finProdFinEquiv e + have hs : slot.val = e.1.val*H+e.2.val := by change e.2.val+H*e.1.val = _; ring + have hb' : term + word (DemandScan.blocks X p.1).val * word stride = head := by rw [DemandScan.blocks_val]; rfl + have room := stored.terms.fits p.1 + change head.val + 2 + D*H < 2^bits at room + have hi := slot.isLt + have index : (head + word (2+e.1.val*H+e.2.val)).val = head.val+2+slot.val := by + rw [Fin.val_add,Fin.val_ofNat] + have eqn : 2+e.1.val*H+e.2.val = 2+slot.val := by omega + rw [eqn,Nat.mod_eq_of_lt (show 2+slot.val < 2^bits by omega), + Nat.mod_eq_of_lt (show head.val+(2+slot.val) < 2^bits by omega),Nat.add_assoc] + change m (I.termBase.eval pub state m + b.eval pub state m * word stride + word (2+e.1.val*H+e.2.val)).val = _ + rw [args.termBase,hb,hb',index] + exact of_val _ (congrFun (Readback.payload_eq X m S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride stored p.1) e) + +variable (old : X.network.Half (oldSite X p)) (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) + (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites p)) + (grid : B.refresh.grid.demands) (θ : Fin (repetitions B.refresh (entryInput B X choice p old new).demand) → Selector B.refresh) + +/-- A field at the wrong local port has length zero. At its correct port the stored +demand or payload gives the length of the exact resident buffer of the refresh call. -/ +theorem length_eval {fit : N ≤ 2^bits} + (args : Describes I pub state m X p P hD hd internal A child parent oldDir newDir Q src term) + (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) + (dFit : D < 2^bits) (f : FieldId D H) : + (length P ties stride I f).eval pub state m = + word ((buffers B X choice p old new A child parent grid θ 0).len f) := by + let port := ArgumentSite.portIndex D I.parent.siteOrd I.lanes + have hp : port.eval pub state m = word p.2.val := + ArgumentSite.portIndex_eval X p pub state m _ _ args.site args.lanes dFit + change (present port (endpoint P f)).eval pub state m * (storedWidth ties stride I f).eval pub state m = _ + rw [present_eval pub state m port p.2 _ dFit hp, + storedWidth_eval B X choice p A child parent oldDir newDir ties start stride pub state m I args stored dFit] + rcases f with ⟨dir,e⟩ | ⟨dir,e⟩ + · cases dir with + | false => by_cases he : p.2 = tieSource e <;> + simp [endpoint,nominal,buffers,MapRowLoop.buffers,MapRow.endpoint,entryInput,he] + | true => by_cases he : p.2 = tieTarget e <;> + simp [endpoint,nominal,buffers,MapRowLoop.buffers,MapRow.endpoint,entryInput,he] + · cases dir with + | false => by_cases he : p.2 = e.1 <;> + simp [endpoint,nominal,buffers,MapRowLoop.buffers,MapRow.endpoint,entryInput,BlockSchedule.portSupply,expanderSupply,he] + | true => by_cases he : p.2 = (S.graph.reverse e).1 <;> + simp [endpoint,nominal,buffers,MapRowLoop.buffers,MapRow.endpoint,entryInput,BlockSchedule.portSupply,expanderSupply, + SpectralGeometry.RegularArcGraph.toSlotGraph,he] + +end Selected +end CompressorRecords.PortRefresh.MapFrameFields + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshMapOperands.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshMapOperands.lean new file mode 100644 index 0000000000..1a0d87886a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshMapOperands.lean @@ -0,0 +1,478 @@ +import OAI.Computability.VPVNP.PairSimulationRecordedMapCalls +import OAI.Computability.VPVNP.PairNodeArguments +import OAI.Computability.VPVNP.CompressorRecordRefresh +import OAI.Computability.VPVNP.PairSimulationMapRowLoop +import OAI.Computability.VPVNP.PairSimulationMapResidentAgreement + +/-! +# Operand slices of the degree-refresh map + +The two old half-wires are stored independently at the child node. The +two external payloads and the internal expander halves belong to its parent +node. Both ends of an external segment use the prefix offset in the original +outgoing bundle, even when port translation permutes the incoming slots. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshMapOperands + +open Compression Compression.Refresh Compression.DegreeRefresh NetworkKernel +open PairSimulation PairSimulation.NodeArguments PairSimulation.LocalHistory +open scoped Fin.CommRing + +variable {a b l w : ℕ} + +/-- The independent slot vectors in the private argument buffer of a node. -/ +def NodeFields (A : Arena) (node : ℕ) (X : State a l) (v : X.network.Site) + (z : X.network.Half v) (mem : BurstRAM.Word w → BurstRAM.Word w) : Prop := + ∀ dir j (i : Fin (X.halfWidth v dir j)), + mem ((A.fieldAddress X v node dir j+i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w (fieldBits X v z dir j i) + +theorem nodeFields_store (A : Arena) (node : ℕ) (X : State a l) (v : X.network.Site) + (z : X.network.Half v) (mem : BurstRAM.Word w → BurstRAM.Word w) + (fit : A.base node+(packed X v z).length ≤ 2^w) : + NodeFields A node X v z (PrivateFields.storeBits (A.base node) (packed X v z) mem) := + stored_member X v A node z mem fit + +private theorem read_word {A : Arena} {node : ℕ} {X : State a l} {v : X.network.Site} + {z : X.network.Half v} {mem : BurstRAM.Word w → BurstRAM.Word w} + (rep : NodeFields A node X v z mem) (dir : Bool) (j : Fin (2^a)) {n : ℕ} + (word : Word n) (same : List.ofFn (fieldBits X v z dir j) = List.ofFn word) + (i : Fin n) : mem ((A.fieldAddress X v node dir j+i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w (word i) := by + have hlen : X.halfWidth v dir j = n := by simpa only [List.length_ofFn] using congrArg List.length same + subst n + have h : fieldBits X v z dir j = word := List.ofFn_injective same + rw [← h] + exact rep dir j i + +private theorem incoming_congr {X : State a l} {u : X.network.Site} (z : X.network.Half u) + {e e' : X.network.Edge} (he : e = e') (h : u = X.network.dst e) (h' : u = X.network.dst e') : + List.ofFn (z.2 e h) = List.ofFn (z.2 e' h') := by cases he; rfl + +/-- The original site whose lanes are promoted to this port. -/ +def oldSite (X : State a (a+l)) (p : (X.Base × BitWord l) × Fin (2^a)) : X.network.Site := + (p.1.1,(splitBitWord a l).symm ((bitWordFinEquiv a).symm p.2,p.1.2)) + +/-- Pulls the incoming half-wire assignment back to the port-split coordinates of the selected +site. -/ +noncomputable abbrev oldHalf (X : State a (a+l)) (p : (X.Base × BitWord l) × Fin (2^a)) + (z : X.network.Half (oldSite X p)) := + (originalIso (splitSlots X) (bitWordFinEquiv a) (splitWidths X)).pullHalf p + ((relaneIso X.slots (splitBitWord a l) X.width).pullHalf (originalSites (bitWordFinEquiv a) p) z) + +variable (X : State a (a+l)) (p : (X.Base × BitWord l) × Fin (2^a)) +local notation "G" => splitSlots X +local notation "port" => bitWordFinEquiv a +local notation "widths" => groupedWidths port (splitWidths X) +local notation "matchOld" => oldPortMatching G port + +theorem old_out_read (A : Arena) (node : ℕ) (z : X.network.Half (oldSite X p)) + (mem : BurstRAM.Word w → BurstRAM.Word w) (rep : NodeFields A node X _ z mem) + (j : Fin (2^a)) (i : Fin (widths ((p.1,j),p.2))) : + mem ((A.fieldAddress X (oldSite X p) node false j+i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w ((oldHalf X p z).1 ((p.1,j),p.2) rfl i) := by + exact read_word rep false j _ rfl i + +private theorem oldIncoming_edge (j : Fin (2^a)) : + let e := (matchOld).symm ((p.1,j),p.2) + let old := originalIso G port (splitWidths X) + let split := relaneIso X.slots (splitBitWord a l) X.width + ((incomingOrder X (oldSite X p)).entries j).val = split.edge (old.edge e) := by + intro e old split + change X.slots.actualGraph.target.symm (oldSite X p, j) = _ + apply X.slots.actualGraph.target.injective + rw [Equiv.apply_symm_apply] + apply Prod.ext + · have h := (congrArg source ((matchOld).apply_symm_apply ((p.1,j),p.2))).symm + exact (congrArg split.site ((congrArg old.site h).trans (old.dst e))).trans (split.dst (old.edge e)) + · exact (congrArg (fun a : Arc (X.Base × BitWord l) (2^a) ↦ a.1.2) + ((matchOld).apply_symm_apply ((p.1,j),p.2))).symm + +theorem old_in_read (A : Arena) (node : ℕ) (z : X.network.Half (oldSite X p)) + (mem : BurstRAM.Word w → BurstRAM.Word w) (rep : NodeFields A node X _ z mem) + (j : Fin (2^a)) (i : Fin (widths ((matchOld).symm ((p.1,j),p.2)))) : + mem ((A.fieldAddress X (oldSite X p) node true j+i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w (incomingHalf (R := ℤ) matchOld widths p.1 p.2 j (oldHalf X p z) i) := by + apply read_word rep true j _ _ i + exact incoming_congr z (oldIncoming_edge X p j) _ _ + +variable {dH : ℕ} (P : SlotGraph (Fin (2^a)) dH) (hD : 1 < 2^a) (hd : dH+1 ≤ 2^b) + (internal : X.Base × BitWord l → Fin (2^a) × Fin dH → ℕ) + +/-- The graph whose independent new halves the selected kernel receives. Taking +the selected block supply widths gives exactly the dyadic refresh output state. -/ +noncomputable def newState : State b l where + Base := X.Base × Fin (2^a) + baseFintype := inferInstance + baseNonempty := inferInstance + baseIndex := State.productIndex X.baseIndex (Equiv.refl (Fin (2^a))) + slots := degreeRefresh G P hD hd + width := actualWidths hd port (splitWidths X) internal + +local notation "Y" => newState X P hD hd internal + +/-- Identifies the promoted network with its refreshed wire coordinates, including the binary +encoding of each internal payload. -/ +noncomputable abbrev newIso := promotedIso G port (splitWidths X) P hD hd + (fun s e ↦ Fin (2^internal s e)) internal (fun s e ↦ (wordIndex (internal s e)).symm) + +/-- Pulls the output half-wire assignment at a promoted site back along the promotion +isomorphism. -/ +noncomputable abbrev newHalf (z : (Y).network.Half (promotedSites p)) := + (newIso X P hD hd internal).pullHalf p z + +/-- The outgoing external bundle of the promoted site's half-wire assignment. -/ +noncomputable abbrev externalOut (z : (Y).network.Half (promotedSites p)) := + (newHalf X p P hD hd internal z).1 (.inl p) rfl + +/-- The incoming external bundle indexed by the inverse bundle target at the promoted site. -/ +noncomputable abbrev externalIn (z : (Y).network.Half (promotedSites p)) := + (newHalf X p P hD hd internal z).2 (.inl ((bundleTarget G).symm p)) + ((bundleTarget G).apply_symm_apply p).symm + +/-- Splits the incoming and outgoing external bundles into the incident old-port segments of +this site. -/ +noncomputable abbrev segments (z : (Y).network.Half (promotedSites p)) := + incidentPortSegments (matchOld) (bundleTarget G) (oldPortMatching_bundle G port) widths p + (externalOut X p P hD hd internal z) (externalIn X p P hD hd internal z) + +private theorem cast_payload {A : Type} {m n : ℕ} (eqw : m = n) (f : A ≃ Word n) + (h : (A ≃ Word m) = (A ≃ Word n)) (v : A) : + List.ofFn ((h.mpr f) v) = List.ofFn (f v) := by subst m; rfl + +private theorem external_payload (e : (X.Base × BitWord l) × Fin (2^a)) + (v : Word (∑ j, widths (e,j))) : + List.ofFn ((newIso X P hD hd internal).payload (.inl e) v) = List.ofFn v := by + simp only [newIso, promotedIso] + apply cast_payload _ (Equiv.refl _) + change DegreeRefresh.newWidths hd (bundleWidths port (splitWidths X)) internal e (refreshSlots hd (.inl 0)) = _ + simp [DegreeRefresh.newWidths] + +private theorem incoming_external_edge : + ((incomingOrder Y (promotedSites p)).entries (refreshSlots hd (.inl 0))).val = + (newIso X P hD hd internal).edge (.inl ((bundleTarget G).symm p)) := by + let I := newIso X P hD hd internal + let e := (bundleTarget G).symm p + change (degreeRefresh G P hD hd).actualGraph.target.symm (promotedSites p, _) = + (promotedSites e,refreshSlots hd (.inl 0)) + apply (degreeRefresh G P hD hd).actualGraph.target.injective + rw [Equiv.apply_symm_apply, degreeRefresh_external] + exact Prod.ext (congrArg promotedSites ((bundleTarget G).apply_symm_apply p).symm) rfl + +theorem external_out_read (A : Arena) (node : ℕ) (z : (Y).network.Half (promotedSites p)) + (mem : BurstRAM.Word w → BurstRAM.Word w) (rep : NodeFields A node Y _ z mem) + (j : Fin (2^a)) (i : Fin (widths (p,j))) : + mem ((A.fieldAddress Y (promotedSites p) node false (refreshSlots hd (.inl 0)) + + (PortRefresh.outgoingRecord G port (splitWidths X) (p,j)).offset + i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w ((segments X p P hD hd internal z).1 j i) := by + let val := z.1 ((newIso X P hD hd internal).edge (.inl p)) rfl + let arg := externalOut X p P hD hd internal z + have e := external_payload X P hD hd internal p arg + change List.ofFn ((newIso X P hD hd internal).payload (.inl p) + (((newIso X P hD hd internal).payload (.inl p)).symm val)) = List.ofFn arg at e + have ev : List.ofFn val = List.ofFn arg := + (congrArg List.ofFn (((newIso X P hD hd internal).payload (.inl p)).apply_symm_apply val)).symm.trans e + obtain ⟨k,hk,hb⟩ := (PortRefresh.local_bit_reads G port (splitWidths X) p j arg + (externalIn X p P hD hd internal z)).1 i + rw [Nat.add_assoc, ← hk] + exact (read_word rep false _ arg ev k).trans (congrArg _ hb.symm) + +theorem external_in_read (A : Arena) (node : ℕ) (z : (Y).network.Half (promotedSites p)) + (mem : BurstRAM.Word w → BurstRAM.Word w) (rep : NodeFields A node Y _ z mem) + (j : Fin (2^a)) (i : Fin (widths ((matchOld).symm (p,j)))) : + mem ((A.fieldAddress Y (promotedSites p) node true (refreshSlots hd (.inl 0)) + + (PortRefresh.incomingRecord G port (splitWidths X) (p,j)).offset + i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w ((segments X p P hD hd internal z).2 j i) := by + let I := newIso X P hD hd internal + let edge : OutputEdge (X.Base × BitWord l) (Fin (2^a) × Fin dH) (2^a) (2^b-(dH+1)) := Sum.inl ((bundleTarget G).symm p) + have he : promotedSites p = (Y).network.dst (I.edge edge) := + (congrArg I.site ((bundleTarget G).apply_symm_apply p).symm).trans (I.dst edge) + let val := z.2 (I.edge edge) he + let arg := externalIn X p P hD hd internal z + have e := external_payload X P hD hd internal ((bundleTarget G).symm p) arg + change List.ofFn (I.payload edge ((I.payload edge).symm val)) = List.ofFn arg at e + have ev : List.ofFn val = List.ofFn arg := + (congrArg List.ofFn ((I.payload edge).apply_symm_apply val)).symm.trans e + obtain ⟨k,hk,hb⟩ := (PortRefresh.local_bit_reads G port (splitWidths X) p j + (externalOut X p P hD hd internal z) arg).2 i + rw [Nat.add_assoc, ← hk] + exact (read_word rep true _ arg ((incoming_congr z + (incoming_external_edge X p P hD hd internal) _ he).trans ev) k).trans (congrArg _ hb.symm) + +private theorem inputBits_eq {n : ℕ} (x : Fin (2^n)) : + MotifEntry.inputBits x = (wordIndex n).symm x := by + funext i + exact (CursorNetwork.addressWord_bit x i).symm + +theorem inputBits_wordIndex {n : ℕ} (x : Word n) : + MotifEntry.inputBits (wordIndex n x) = x := (inputBits_eq _).trans (Equiv.symm_apply_apply ..) + +/-- Extracts the selected port's expander supply half from the refreshed half-wire assignment. -/ +noncomputable abbrev supplyArg (z : (Y).network.Half (promotedSites p)) := + supplyHalf (R := ℤ) (bundleTarget G) widths Prod.fst (fun e ↦ (P.target e).1) + (fun s e ↦ Fin (2^internal s e)) (2^b-(dH+1)) p (newHalf X p P hD hd internal z) + +private theorem internal_payload (s : X.Base × BitWord l) (e : Fin (2^a) × Fin dH) + (x : Fin (2^internal s e)) : + List.ofFn ((newIso X P hD hd internal).payload (.inr (.inl (s,e))) x) = + List.ofFn (MotifEntry.inputBits x) := by + rw [inputBits_eq] + simp only [newIso, promotedIso] + apply cast_payload _ (wordIndex _).symm + change DegreeRefresh.newWidths hd (bundleWidths port (splitWidths X)) internal (s,e.1) + (refreshSlots hd (.inr (.inl e.2))) = _ + simp [DegreeRefresh.newWidths] + +theorem supply_out_read (A : Arena) (node : ℕ) (z : (Y).network.Half (promotedSites p)) + (mem : BurstRAM.Word w → BurstRAM.Word w) (rep : NodeFields A node Y _ z mem) + (e : Fin (2^a) × Fin dH) (he : p.2 = e.1) (i : Fin (internal p.1 e)) : + mem ((A.fieldAddress Y (promotedSites p) node false (refreshSlots hd (.inr (.inl e.2))) + + i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w (MotifEntry.inputBits ((supplyArg X p P hD hd internal z).1 e he) i) := by + rcases p with ⟨s,j⟩ + rcases e with ⟨j',t⟩ + change j = j' at he + subst j' + let I := newIso X P hD hd internal + let edge : OutputEdge (X.Base × BitWord l) (Fin (2^a) × Fin dH) (2^a) (2^b-(dH+1)) := + .inr (.inl (s,j,t)) + let val := z.1 (I.edge edge) rfl + let arg := (supplyArg X (s,j) P hD hd internal z).1 (j,t) rfl + have e := internal_payload X P hD hd internal s (j,t) arg + exact read_word rep false _ _ ((congrArg List.ofFn ((I.payload edge).apply_symm_apply val)).symm.trans e) i + +theorem supply_in_read (A : Arena) (node : ℕ) (z : (Y).network.Half (promotedSites p)) + (mem : BurstRAM.Word w → BurstRAM.Word w) (rep : NodeFields A node Y _ z mem) + (e : Fin (2^a) × Fin dH) (he : p.2 = (P.target e).1) (i : Fin (internal p.1 e)) : + mem ((A.fieldAddress Y (promotedSites p) node true (refreshSlots hd (.inr (.inl (P.target e).2))) + + i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w (MotifEntry.inputBits ((supplyArg X p P hD hd internal z).2 e he) i) := by + let I := newIso X P hD hd internal + let edge : OutputEdge (X.Base × BitWord l) (Fin (2^a) × Fin dH) (2^a) (2^b-(dH+1)) := + .inr (.inl (p.1,e)) + have hat : p = (p.1,(P.target e).1) := Prod.ext rfl he + have hh : promotedSites p = (Y).network.dst (I.edge edge) := + (congrArg I.site hat).trans (I.dst edge) + let val := z.2 (I.edge edge) hh + let arg := (supplyArg X p P hD hd internal z).2 e he + have hp := internal_payload X P hD hd internal p.1 e arg + have ev : List.ofFn val = List.ofFn (MotifEntry.inputBits arg) := + (congrArg List.ofFn ((I.payload edge).apply_symm_apply val)).symm.trans hp + let slot := refreshSlots hd (.inr (.inl (P.target e).2)) + have eqEdge : ((incomingOrder Y (promotedSites p)).entries slot).val = I.edge edge := by + change (degreeRefresh G P hD hd).actualGraph.target.symm (promotedSites p,slot) = _ + apply (degreeRefresh G P hD hd).actualGraph.target.injective + rw [Equiv.apply_symm_apply] + change (promotedSites p,slot) = (degreeRefresh G P hD hd).actualGraph.target + (((p.1.1,e.1),p.1.2),refreshSlots hd (.inr (.inl e.2))) + rw [degreeRefresh_internal] + exact Prod.ext (congrArg promotedSites hat) rfl + exact read_word rep true slot _ ((incoming_congr z eqEdge _ hh).trans ev) i + +/-- Builds the selected port's demand input from the incoming half-wire assignment and the +external segments of the refreshed assignment. -/ +noncomputable abbrev demandArg (old : X.network.Half (oldSite X p)) + (new : (newState X P hD hd internal).network.Half (promotedSites p)) := + portInput (R := ℤ) (matchOld) widths p.1 p.2 (oldHalf X p old) + (segments X p P hD hd internal new) + +/-- The offset of port j's segment in the site's incoming or outgoing external bundle, +according to the direction bit. -/ +def externalOffset (dir : Bool) (j : Fin (2^a)) : ℕ := + if dir then (PortRefresh.incomingRecord G port (splitWidths X) (p,j)).offset + else (PortRefresh.outgoingRecord G port (splitWidths X) (p,j)).offset + +/-- Every endpoint has its own physical operand pointer. The old half of a +tie uses its destination slot. The new external half uses its source port as +the segment index. Incoming expander halves use the reverse edge's port. -/ +noncomputable def operandBase (A : Arena) (oldNode newNode : ℕ) : + MapLookup.LabelField (Tie (2^a)) (Fin (2^a) × Fin dH) → ℕ + | .inl (false,e) => A.fieldAddress X (oldSite X p) oldNode (!e.1) (tieTarget e) + | .inl (true,e) => A.fieldAddress Y (promotedSites p) newNode (!e.1) (refreshSlots hd (.inl 0)) + + externalOffset X p (!e.1) (tieSource e) + | .inr (false,e) => A.fieldAddress Y (promotedSites p) newNode false (refreshSlots hd (.inr (.inl e.2))) + | .inr (true,e) => A.fieldAddress Y (promotedSites p) newNode true + (refreshSlots hd (.inr (.inl (P.target e).2))) + +variable (A : Arena) (oldNode newNode : ℕ) + (old : X.network.Half (oldSite X p)) (new : (newState X P hD hd internal).network.Half (promotedSites p)) + (mem : BurstRAM.Word w → BurstRAM.Word w) + (oldData : NodeFields A oldNode X (oldSite X p) old mem) + (newData : NodeFields A newNode (newState X P hD hd internal) (promotedSites p) new mem) + +local notation "dArg" => demandArg X p P hD hd internal old new +local notation "base" => operandBase X p P hD hd internal A oldNode newNode + +private theorem encoded {n : ℕ} (x : Word n) (i : Fin n) : + PrimedInputRAM.encodeBit w (x i) = PrimedInputRAM.encodeBit w (MotifEntry.inputBits (wordIndex n x) i) := + congrArg _ (congrFun (inputBits_wordIndex x).symm i) + +include oldData in +theorem demand_out_read (e : Tie (2^a)) (he : p.2 = tieSource e) + (i : Fin (internalWidth (matchOld) widths p.1 e)) : + mem ((base (.inl (false,e))+i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w (MotifEntry.inputBits ((dArg).1 e he) i) := by + rcases p with ⟨s,j⟩ + rcases e with ⟨dir,⟨⟨source,target⟩,ne⟩⟩ + change j = source at he + subst source + cases dir + · exact (old_in_read X (s,j) A oldNode old mem oldData target i).trans (encoded _ i) + · exact (old_out_read X (s,j) A oldNode old mem oldData target i).trans (encoded _ i) + +include newData in +theorem demand_in_read (e : Tie (2^a)) (he : p.2 = tieTarget e) + (i : Fin (internalWidth (matchOld) widths p.1 e)) : + mem ((base (.inl (true,e))+i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w (MotifEntry.inputBits ((dArg).2 e he) i) := by + rcases p with ⟨s,j⟩ + rcases e with ⟨dir,⟨⟨source,target⟩,ne⟩⟩ + change j = target at he + subst target + cases dir + · exact (external_in_read X (s,j) P hD hd internal A newNode new mem newData source i).trans (encoded _ i) + · exact (external_out_read X (s,j) P hD hd internal A newNode new mem newData source i).trans (encoded _ i) + +end CompressorRecords.RefreshMapOperands + +namespace CompressorRecords.RefreshMapOperands + +open Compression Compression.Refresh Compression.DegreeRefresh PairSimulation PairSimulation.NodeArguments +open PairSimulation.LocalHistory MapLookup MotifSelector MotifEntry MotifConversion MapPortAgreement +open scoped Fin.CommRing + +private def AtSlice {w : ℕ} (mem : BurstRAM.Word w → BurstRAM.Word w) (addr : ℕ) + (s : (n : ℕ) × (Fin n → Bool)) : Prop := + ∀ i : Fin s.1, mem ((addr+i.val : ℕ) : BurstRAM.Word w) = PrimedInputRAM.encodeBit w (s.2 i) + +private theorem at_endpoint {I J : Type} [DecidableEq J] {w : ℕ} + (mem : BurstRAM.Word w → BurstRAM.Word w) (addr : Bool × I → ℕ) (src dst : I → J) + (party : J) (len : I → ℕ) (bits : DemandBits src dst len party) + (out : ∀ (e : I) h (i : Fin (len e)), mem ((addr (false,e)+i.val : ℕ) : BurstRAM.Word w) = PrimedInputRAM.encodeBit w (bits.1 e h i)) + (inc : ∀ (e : I) h (i : Fin (len e)), mem ((addr (true,e)+i.val : ℕ) : BurstRAM.Word w) = PrimedInputRAM.encodeBit w (bits.2 e h i)) + (f : Bool × I) : AtSlice mem (addr f) (MapRow.endpoint src dst party len bits f) := by + rcases f with ⟨dir,e⟩ + cases dir <;> rw [MapRow.endpoint] + · split + · exact out _ _ + · intro i; exact i.elim0 + · split + · exact inc _ _ + · intro i; exact i.elim0 + +section Selected +set_option maxHeartbeats 1000000 + +variable {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) {g w : ℕ} +variable (X : State S.portExponent (S.portExponent+g)) +variable (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) + +local notation "P" => S.graph.toSlotGraph +local notation "hD" => S.port_order +local notation "hd" => And.right S.degree_bounds +local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) + S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh choice +local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) + (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh hD hd choice + +variable (p : (X.Base × BitWord g) × Fin (2^S.portExponent)) + (old : X.network.Half (oldSite X p)) + (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) + B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites p)) + +/-- The exact input of the single motif map at the refreshed port, from the +independent old and new node halves. -/ +noncomputable def entryInput : EntryInput B.refresh := + ⟨blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) p.1, + (choice p.1).val, p.2, demandArg X p P hD hd internal old new, + supplyArg X p P hD hd internal new⟩ + +theorem recorded_call {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) : + let I := entryInput B X choice p old new + recordedRefreshCall B X f hf choice (promotedSites p) 0 I.demandBits I.supplyBits = + .refresh I le_rfl := by + simp [recordedRefreshCall, entryInput] + rfl + +variable (A : Arena) (oldNode newNode : ℕ) + +/-- The resident row buffer of the selected refresh invocation. Its supply +ranges stop at the payload ends while the full words (including their tag +suffixes) are separately available at the same bases. -/ +noncomputable abbrev buffers (z : B.refresh.grid.demands) + (θ : Fin (repetitions B.refresh (entryInput B X choice p old new).demand) → Selector B.refresh) (n : ℕ) := + let I := entryInput B X choice p old new + MapRowLoop.buffers B.refresh z p.2 I.demand I.payload + (MotifEntry.demandBits tieSource tieTarget p.2 I.demandBits) + (mapHalf S.portSupply (fun _ ↦ MotifEntry.inputBits) I.supplyBits) + (operandBase X p P hD hd internal A oldNode newNode) θ n + +/-- Each present demand and supply bit in the actual interpreter is recovered +from its physical node address. A nonincident endpoint has no readable bit. -/ +theorem operandData (z : B.refresh.grid.demands) + (θ : Fin (repetitions B.refresh (entryInput B X choice p old new).demand) → Selector B.refresh) + (n : ℕ) (mem : BurstRAM.Word w → BurstRAM.Word w) + (oldData : NodeFields A oldNode X (oldSite X p) old mem) + (newData : NodeFields A newNode Y (promotedSites p) new mem) : + let x := buffers B X choice p old new A oldNode newNode z θ n + ∀ f (i : Fin (x.len f)), mem ((x.base f+i.val : ℕ) : BurstRAM.Word w) = + PrimedInputRAM.encodeBit w (x.bits f i) := by + intro x f + let addr := operandBase X p P hD hd internal A oldNode newNode + let I := entryInput B X choice p old new + cases f with + | inl h => + apply at_endpoint mem (addr ∘ Sum.inl) tieSource tieTarget p.2 I.demand + (MotifEntry.demandBits tieSource tieTarget p.2 I.demandBits) _ _ h + · exact demand_out_read X p P hD hd internal A oldNode newNode old new mem oldData + · exact demand_in_read X p P hD hd internal A oldNode newNode old new mem newData + | inr h => + apply at_endpoint mem (addr ∘ Sum.inr) S.portSupply.src S.portSupply.dst p.2 I.payload + (mapHalf S.portSupply (fun _ ↦ payloadBits) + (mapHalf S.portSupply (fun _ ↦ MotifEntry.inputBits) I.supplyBits)) _ _ h + · intro e he i + exact supply_out_read X p P hD hd internal A newNode new mem newData e he + (Fin.castLE (Nat.le_add_right _ _) i) + · intro e he i + exact supply_in_read X p P hD hd internal A newNode new mem newData e he + (Fin.castLE (Nat.le_add_right _ _) i) + +/-- Full supply fields include selector bits above the payload. The pointers +used by the agreement scan refer to the same two physical halves used by +the map row, including different slot ordinals at opposite endpoints. -/ +noncomputable def supplyPortBase (t : Port S.portSupply p.2) : BurstRAM.Word w := + let addr := operandBase X p P hD hd internal A oldNode newNode + match t with + | .inl e => (addr (.inr (false,e.val)) : BurstRAM.Word w) + | .inr e => (addr (.inr (true,e.val)) : BurstRAM.Word w) + +theorem selectorCells (mem : BurstRAM.Word w → BurstRAM.Word w) + (newData : NodeFields A newNode Y (promotedSites p) new mem) : + let I := entryInput B X choice p old new + let full := mapHalf S.portSupply (fun _ ↦ MotifEntry.inputBits) I.supplyBits + ∀ (t : Port S.portSupply p.2) (i : Fin (I.payload (MapResidentAgreement.edge t) + + repetitions B.refresh I.demand * B.refresh.selectorBits)), + mem (supplyPortBase B X choice p A oldNode newNode t + (i.val : BurstRAM.Word w)) = + PrimedInputRAM.encodeBit w (MapResidentAgreement.field full t i) := by + intro I full t i + rcases t with ⟨e,h⟩ | ⟨e,h⟩ + · have v := supply_out_read X p P hD hd internal A newNode new mem newData e h i + rw [Nat.cast_add] at v + exact v + · have v := supply_in_read X p P hD hd internal A newNode new mem newData e h i + rw [Nat.cast_add] at v + exact v + +end Selected + +end CompressorRecords.RefreshMapOperands + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshMapRoute.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshMapRoute.lean new file mode 100644 index 0000000000..57bfb40ab6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshMapRoute.lean @@ -0,0 +1,109 @@ +import OAI.Computability.VPVNP.CompressorRefreshMapCallWords +import OAI.Computability.VPVNP.CompressorRecordRegisterSetup + +/-! +# Selecting the refresh map's grid row and port + +The grid ordinal is the header of the accepted term record. The second dispatch key is +the port consumed by the refresh, recovered from the promoted site ordinal and the +residual lane count. A fixed native register setup supplies both keys and the comparison +constants. The finite table order is the one used by the actual term writer. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.MapRoute + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.Refresh Compression.DegreeRefresh NewSlots PhaseRecipe +open OperandInputs PairSimulation NodeArguments RefreshMapOperands MotifConversion +open scoped Fin.CommRing + +/-- The route keys consisting of the stored grid ordinal, the runtime port ordinal, and the +literals zero and one. -/ +def fields (degree stride : ℕ) (I : Input) : Fin 4 → Expr := + let block := ArgumentSite.blockIndex degree I.parent.siteOrd I.lanes + ![.load (I.termBase.add (block.mul (.lit stride))),ArgumentSite.portIndex degree I.parent.siteOrd I.lanes, + .lit 0,.lit 1] + +variable {bits g t pcs regs params : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +/-- Enumerates the demand grid in its finite-set list order, retaining membership for each +route case. -/ +noncomputable def gridCases : List B.refresh.grid.demands := + List.ofFn fun i : Fin B.refresh.grid.demands.toList.length => + ⟨B.refresh.grid.demands.toList[i.val],Finset.mem_toList.mp (List.getElem_mem i.isLt)⟩ + +variable (X : State S.portExponent (S.portExponent+g)) + (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) + (p : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ) + (oldDir newDir : IncidenceDirectory bits) (ties : Fin t ≃ Tie (2^S.portExponent)) (start stride : ℕ) + (m : Memory bits) (I : Input) + +local notation "D" => 2^S.portExponent +local notation "H" => 2^S.expanderExponent +local notation "P" => S.graph.toSlotGraph +local notation "hD" => S.port_order +local notation "hd" => And.right S.degree_bounds +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice +local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t stride start +local notation "Q" => Allocation.Plan.scratch Pₗ bits +local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ) +local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ) +local notation "N" => Fintype.card X.Base*D*2^g*D +local notation "dem" => blockDemandWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) +local notation "f" => fields D stride I + +/-- Keys and comparison constants before the two decrement chains execute. -/ +structure Keys (r : Fin 4 → W bits) : Prop where + grid : ∃ j : Fin (gridCases B).length, r 0 = word j.val ∧ j.val < 2^bits ∧ + (gridCases B)[j.val] = demandGrid B.refresh (fun _ => zero_lt_one) (dem p.1) + party : r 1 = word p.2.val + zero : r 2 = 0 + one : r 3 = 1 + +theorem values {fit : N ≤ 2^bits} (pub : Fin 5 → W bits) (state : W bits) + (args : Describes I pub state m X p P hD hd internal A child parent oldDir newDir Q src term) + (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) + (wide : D < 2^bits) : Keys B X p (fun i => (f i).eval pub state m) := by + let block := ArgumentSite.blockIndex D I.parent.siteOrd I.lanes + let row := SupplyScan.recordBase X term stride p.1 + have hb : block.eval pub state m = word (DemandScan.blocks X p.1).val := + ArgumentSite.blockIndex_eval X p pub state m _ _ args.site args.lanes wide + have address : term + word (DemandScan.blocks X p.1).val * word stride = row := by rw [DemandScan.blocks_val]; rfl + have hkey : (f 0).eval pub state m = m row.val := by + change m (I.termBase.eval pub state m + block.eval pub state m * word stride).val = _ + rw [args.termBase,hb,address] + have ⟨hrow,hval⟩ := List.getElem?_eq_some_iff.mp (stored.readback p.1).1 + let i : Fin (gridCases B).length := ⟨(m row.val).val,by simpa [gridCases,row] using hrow⟩ + refine ⟨⟨i,?_,(m row.val).isLt,?_⟩,ArgumentSite.portIndex_eval X p pub state m _ _ args.site args.lanes wide,rfl,rfl⟩ + · exact hkey.trans (Fin.ext (Nat.mod_eq_of_lt (m row.val).isLt).symm) + · apply Subtype.ext + simp only [gridCases,List.getElem_ofFn,i,row] + convert! hval using 0 + +/-- The compiled key loader consumes no guesses and jumps to the first grid comparison. +Every probe is one of the loads in the four fixed expressions. -/ +theorem setup {fit : N ≤ 2^bits} (M : Machine bits pcs regs params) (c : Config bits pcs regs) + (inputs : Fin 6 → Fin regs) (vm : Fin (RegisterSetup.regCount f) ↪ Fin regs) (pc : ℕ → Fin pcs) + (link : RegisterSetup.Linked vm inputs M pc (RegisterSetup.lines f)) (safe : ∀ i j, vm i ≠ inputs j) + (entry : c.pc = pc 0) (args : Describes I (fun i => c.reg (inputs i.castSucc)) (c.reg (inputs (Fin.last 5))) m + X p P hD hd internal A child parent oldDir newDir Q src term) + (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) + (wide : D < 2^bits) : + ∃ ev d, ev.length = (RegisterSetup.lines f).length ∧ countProbes ev = (∑ i, (f i).loads) ∧ + choiceBits ev = [] ∧ d.pc = pc (RegisterSetup.lines f).length ∧ d.privateMem = c.privateMem ∧ + d.persistent = c.persistent ∧ Keys B X p (fun i => d.reg (vm (RegisterSetup.output f i))) ∧ + (∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j) ∧ ∀ fuel bs, execute M.program (fuel+ev.length) c m bs = + (execute M.program fuel d m bs).map (fun r => ⟨ev++r.events,r.result⟩) := by + obtain ⟨ev,d,len,probes,path,done,priv,pers,vals,frame,run⟩ := RegisterSetup.execute_setup_trace f inputs vm M m pc link safe c entry + exact ⟨ev,d,len,probes,path,done,priv,pers,(funext vals) ▸ values B X choice p A child parent oldDir newDir ties + start stride m I _ _ args stored wide,frame,run⟩ + +end CompressorRecords.PortRefresh.MapRoute + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshMapWorkspace.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshMapWorkspace.lean new file mode 100644 index 0000000000..98e4439bba --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshMapWorkspace.lean @@ -0,0 +1,179 @@ +import OAI.Computability.VPVNP.CompressorRefreshMapCallWords +import OAI.Computability.VPVNP.PairSimulationMapWorkspace +import OAI.Computability.VPVNP.PairSimulationNodeFieldSpace + +/-! +# Uniform private workspace bounds for the actual refresh operand slices + +All four kinds of physical operand start lie at most one maximum wire width beyond +the larger of the two node-buffer ends. Adding their raw width, including the full +selector suffix, needs at most one more wire width. The resulting bound also covers +absent endpoints, whose starts are nevertheless installed in the native descriptor. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.MapCallWords + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh NewSlots +open PairSimulation NodeArguments RefreshMapOperands MotifConversion MotifSelector PhaseRecipe OperandInputs +open scoped Fin.CommRing +open private copies_eq from OAI.Computability.VPVNP.CompressorRefreshMapCallWords + +variable {k : Type} [_root_.Field k] {S : BlockSchedule k} {g : ℕ} (B : S.Templates) + (X : State S.portExponent (S.portExponent+g)) + (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) + (p : (X.Base × BitWord g) × Fin (2^S.portExponent)) (A : Arena) (child parent : ℕ) + (old : X.network.Half (oldSite X p)) + (new : (dyadicRefreshNext X S.graph (Nat.two_pow_pos _) (And.left (S.port_bound.connected_and_pos S.port_order)) + B.refresh S.port_order S.degree_bounds.2 choice).network.Half (promotedSites p)) + +local notation "D" => 2^S.portExponent +local notation "H" => 2^S.expanderExponent +local notation "P" => S.graph.toSlotGraph +local notation "hD" => S.port_order +local notation "hd" => And.right S.degree_bounds +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "internal" => blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph (Nat.two_pow_pos _) hc B.refresh choice +local notation "Y" => dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh hD hd choice +local notation "E₀" => entryInput B X choice p old new +local notation "base" => operandBase X p P hD hd internal A child parent + +private theorem end_of_field {a l : ℕ} (Z : State a l) (u : Z.network.Site) (v : Z.network.Half u) + (A : Arena) (n : ℕ) (dir : Bool) (j : Fin (2^a)) : + A.fieldAddress Z u n dir j ≤ A.base n + (packed Z u v).length := + (Nat.le_add_right ..).trans (field_end_le Z u v A n dir j) + +private theorem selected_widths (b : (X.Base × BitWord g) × Fin D) : + (∑ j, bundleWidths (bitWordFinEquiv _) (splitWidths X) b j) ≤ (Y).maxWireWidth ∧ + ∀ h : Fin H, internal b.1 (b.2,h) ≤ (Y).maxWireWidth := by + have bound (slot : RefreshSlot H S.baseDegree) := (Y).width_le_maxWireWidth + (refreshedCoordinates.symm (b,refreshSlots hd slot)) + change ∀ slot, newWidths hd _ internal (refreshedCoordinates (refreshedCoordinates.symm _)).1 + (refreshedCoordinates (refreshedCoordinates.symm (b,refreshSlots hd slot))).2 ≤ (Y).maxWireWidth at bound + simp only [Equiv.apply_symm_apply,newWidths,Equiv.symm_apply_apply] at bound + exact ⟨bound (.inl 0),fun h => bound (.inr (.inl h))⟩ + +private theorem external_offset_le (dir : Bool) (j : Fin D) : + externalOffset X p dir j ≤ (Y).maxWireWidth := by + let G := splitSlots X + let port := bitWordFinEquiv S.portExponent + have h (e : Arc (X.Base × BitWord g) D) : (outgoingRecord G port (splitWidths X) e).offset ≤ (Y).maxWireWidth := + (Nat.le_add_right ..).trans ((segment_fits G port (splitWidths X) e).trans (selected_widths B X choice e.1).1) + cases dir + · exact h (p,j) + · change (incomingRecord G port (splitWidths X) (p,j)).offset ≤ _ + rw [incomingRecord_matching] + exact h _ + +set_option maxHeartbeats 1200000 in +/-- A single numerical address bound suffices for all raw fields, independent of their +presence at the local port and the values of the two private half-wires. -/ +theorem operand_input_end (top maxWidth : ℕ) (oldEnd : A.base child + (packed X (oldSite X p) old).length ≤ top) + (newEnd : A.base parent + (packed Y (promotedSites p) new).length ≤ top) + (oldWidth : X.maxWireWidth ≤ maxWidth) (newWidth : (Y).maxWireWidth ≤ maxWidth) : + ∀ f, base f + MapWorkspace.rawWidth (E₀).demand (E₀).payload B.refresh.selectorBits + (repetitions B.refresh (E₀).demand) f ≤ top+2*maxWidth := by + have oldAt (dir) (j) := (end_of_field X (oldSite X p) old A child dir j).trans oldEnd + have newAt (dir) (j) := (end_of_field Y (promotedSites p) new A parent dir j).trans newEnd + have dw (e : Tie D) : (E₀).demand e ≤ maxWidth := by + change internalWidth _ _ p.1 e ≤ _ + unfold internalWidth + split <;> exact (X.width_le_maxWireWidth _).trans oldWidth + have sw (e : Fin D × Fin H) : (E₀).payload e + repetitions B.refresh (E₀).demand * B.refresh.selectorBits ≤ maxWidth := + ((selected_widths B X choice (p.1,e.1)).2 e.2).trans newWidth + rintro (⟨dir,e⟩ | ⟨dir,e⟩) + · have hw := dw e + cases dir + · have ha := oldAt (!e.1) (tieTarget e) + change A.fieldAddress X (oldSite X p) child (!e.1) (tieTarget e) + (E₀).demand e ≤ _; omega + · have ha := newAt (!e.1) (refreshSlots hd (.inl 0)) + have ho := (external_offset_le B X choice p (!e.1) (tieSource e)).trans newWidth + change A.fieldAddress Y (promotedSites p) parent (!e.1) (refreshSlots hd (.inl 0)) + + externalOffset X p (!e.1) (tieSource e) + (E₀).demand e ≤ _; omega + · have hw := sw e + cases dir + · have ha := newAt false (refreshSlots hd (.inr (.inl e.2))) + change A.fieldAddress Y (promotedSites p) parent false (refreshSlots hd (.inr (.inl e.2))) + + ((E₀).payload e + repetitions B.refresh (E₀).demand*B.refresh.selectorBits) ≤ _; omega + · have ha := newAt true (refreshSlots hd (.inr (.inl ((P).target e).2))) + change A.fieldAddress Y (promotedSites p) parent true (refreshSlots hd (.inr (.inl ((P).target e).2))) + + ((E₀).payload e + repetitions B.refresh (E₀).demand*B.refresh.selectorBits) ≤ _; omega + +/-- Reserve the complete private descriptor or the expander pointer directory, whichever +needs more words. Both are consumed before the selector and label arrays. -/ +noncomputable def headCapacity (degree expander : ℕ) := max (2*(degree*expander)) + (Fintype.card (MapCallSetup.Arg (Tie degree) (Fin degree × Fin expander))) + +/-- Concrete scratch heads for a single refresh map. The histogram has its own +previously allocated range and may be shared across successive map calls. -/ +noncomputable def regions (directory hist : ℕ) : MapWorkspace.Regions (Tie D) (Fin D × Fin H) := + let source := directory + headCapacity D H + ⟨base,directory,source,source+repetitions B.refresh (E₀).demand,hist⟩ + +/-- Every array in the selected workspace meets its concrete address constraints. +The four scalar capacity bounds suffice for all selector choices and port incidences. -/ +theorem regions_ordered {pcs regs params histCount : ℕ} (grid : B.refresh.grid.demands) + (L : MapEntryTable.Allocation B.refresh grid p.2 regs params) (loc : L.Address → Fin pcs) + (top maxWidth directory hist limit : ℕ) + (oldEnd : A.base child + (packed X (oldSite X p) old).length ≤ top) + (newEnd : A.base parent + (packed Y (promotedSites p) new).length ≤ top) + (oldWidth : X.maxWireWidth ≤ maxWidth) (newWidth : (Y).maxWireWidth ≤ maxWidth) + (inputsEnd : top+2*maxWidth ≤ directory) + (histEnd : hist+histCount ≤ directory) + (workEnd : directory+headCapacity D H+2*repetitions B.refresh (E₀).demand ≤ limit) : + let R := regions B X choice p A child parent old new directory hist + MapWorkspace.Ordered (L.program loc) (E₀).demand (E₀).payload R (repetitions B.refresh (E₀).demand) histCount limit := by + have ports := MapPortAgreement.ports_length_le S.portSupply p.2 L.edgeOrder + rw [Fintype.card_prod,Fintype.card_fin,Fintype.card_fin] at ports + have cap := le_max_left (2*(D*H)) (Fintype.card (MapCallSetup.Arg (Tie D) (Fin D × Fin H))) + change 2*(D*H) ≤ headCapacity D H at cap + have inputEnd := operand_input_end B X choice p A child parent old new top maxWidth oldEnd newEnd oldWidth newWidth + constructor + · exact fun f => (inputEnd f).trans inputsEnd + · exact Nat.add_le_add_left (ports.trans cap) directory + · exact le_rfl + · change directory+headCapacity D H + repetitions B.refresh (E₀).demand + repetitions B.refresh (E₀).demand ≤ limit + omega + · change hist+histCount ≤ limit; omega + · exact Or.inr histEnd + +/-- Online evaluation of the source and target heads uses the same stored repetition +word that the raw descriptor publishes. Only the reserved directory and histogram bases +come from the outer private allocation. -/ +noncomputable def plannedHeads (degree expander stride : ℕ) (I : Input) (directory hist : Expr) : WorkHeads := + let source := directory.add (.lit (headCapacity degree expander)) + ⟨directory,source,source.add (copies degree stride I),hist⟩ + +variable {bits t : ℕ} (oldDir newDir : IncidenceDirectory bits) (ties : Fin t ≃ Tie (2^S.portExponent)) (start stride : ℕ) + (pub : Fin 5 → W bits) (state : W bits) (m : Memory bits) (I : Input) + +local notation "Pₗ" => Allocation.plan X (S.degreeExponent 0) H t stride start +local notation "Q" => Allocation.Plan.scratch Pₗ bits +local notation "src" => word (bits := bits) (Allocation.Plan.demand Pₗ) +local notation "term" => word (bits := bits) (Allocation.Plan.term Pₗ) +local notation "N" => Fintype.card X.Base*D*2^g*D + +theorem plannedHeads_eval {fit : N ≤ 2^bits} (directory histogram : Expr) (dir hist : ℕ) + (hdir : directory.eval pub state m = word dir) (hhist : histogram.eval pub state m = word hist) + (args : Describes I pub state m X p P hD hd internal A child parent oldDir newDir Q src term) + (stored : Build.Stored X S.graph (Nat.two_pow_pos _) hc B.refresh choice ties start stride fit m) (wide : D < 2^bits) : + let J := plannedHeads D H stride I directory histogram + let R := regions B X choice p A child parent old new dir hist + J.directory.eval pub state m = word R.directory ∧ J.source.eval pub state m = word R.source ∧ + J.target.eval pub state m = word R.target ∧ J.hist.eval pub state m = word R.hist := by + have count := copies_eq B X choice p A child parent oldDir newDir ties start stride pub state m I args stored wide + have srcEq : (directory.add (.lit (headCapacity D H))).eval pub state m = word (dir + headCapacity D H) := by + change directory.eval pub state m + (headCapacity D H : W bits) = _ + rw [hdir]; exact (Nat.cast_add ..).symm + refine ⟨hdir,srcEq,?_,hhist⟩ + change (directory.add (.lit (headCapacity D H))).eval pub state m + (copies D stride I).eval pub state m = _ + rw [srcEq,count]; exact (Nat.cast_add ..).symm + +end CompressorRecords.PortRefresh.MapCallWords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshMiddleRecords.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshMiddleRecords.lean new file mode 100644 index 0000000000..56cef3fdc5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshMiddleRecords.lean @@ -0,0 +1,94 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshDeterminism + +/-! +# Intermediate source records of a native degree refresh + +A complete native trace is split just before and just after the selected term pass. +The stored demand values, external segments and selected supply records are identified +in those same memories by determinism. The four output scans likewise use the +actual selected source tables and completed incidence columns. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.Build + +open BurstRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry +open NewSlots RefreshRAM Allocation +open private bounds demand_bound from OAI.Computability.VPVNP.CompressorRecordRefreshBuild + +variable {w a a₀ g dH t : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (c : DyadicRefreshChoice X E hdH conn F) + (ties : Fin t ≃ Tie (2^a)) (T : IncidenceDirectory w) (start stride : ℕ) +local notation "P" => plan X a₀ dH t stride start +local notation "Q" => Plan.scratch P w +local notation "D" => word (bits := w) (Plan.demand P) +local notation "M" => word (bits := w) (Plan.term P) +local notation "V" => dyadicRefreshNext X E hdH conn F hD hd c +local notation "Fₛ" => blockDemandWidths (splitSlots X) (bitWordFinEquiv a) (splitWidths X) + +/-- The old represented graph and the admitted branch establish both sources +needed by the deterministic post-term stages. -/ +theorem middle_records (L : PrepareLayout X T a₀ dH t stride start) (initial m₁ : Memory w) + (old : T.Represents X initial) (pre tr : List (Report w)) + (prep : PrepareRun X T Q D ties (word (2^g)) L.regions.fits initial m₁ pre) + (wide : 2+2^a*dH ≤ stride) (room : (P).stop < 2^w) + (termBits : termConstant E hdH conn F ties + 4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (nextWidth : (V).maxWireWidth < 2^w) (cap : ℕ) (capFit : TermWorker.budget F t (2^a*dH) w X.maxWireWidth ≤ cap) + (native : termRun E hdH conn F ties X D M stride cap (blockTapes E hdH conn F X c w) m₁ = some tr) : + (∀ s, DemandPreparation.demandAt ties (DemandScan.rowBase X t D s) m₁ = Fₛ s) ∧ + SegmentFields X Q L.regions.fits (after m₁ (eventLog tr)) ∧ + SupplyScan.TermFields X E hdH conn F c M stride (after m₁ (eventLog tr)) := by + have external := (bounds X E hdH conn F hD hd c nextWidth).1 + obtain ⟨p,m',hp,seg,dem,_,_⟩ := prepare_demands X T Q D ties initial old (word (2^g)) L.degree L.lanes + L.regions L.directory L.gather L.baseApart external L.demandRoom L.demandApart + have hm := (PrepareRun.deterministic hp prep).2 + subst m' + obtain ⟨terms,rt,termFields,_,frame,_,_⟩ := term_pass E hdH conn F ties X D M stride wide L.demandTerm + L.termRoom m₁ X.maxWireWidth termBits (demand_bound X) dem cap capFit c + obtain rfl := Option.some.inj (rt.symm.trans native) + have td : (P).demand ≤ (P).term := Nat.le_add_right .. + have ts : (P).term ≤ (P).stop := by dsimp only [Plan.stop,Plan.next,Plan.reverseSlot,Plan.targetPort,Plan.supply]; omega + have wordTerm : (M).val = (P).term := Nat.mod_eq_of_lt (ts.trans_lt room) + refine ⟨dem,seg.transfer X Q (fun j hj i hi ↦ ?_),termFields⟩ + apply frame + apply Or.inl + rw [wordTerm] + exact ((P).scratch_interval (td.trans (ts.trans room.le)) j hj i hi).2.trans_le td + +/-- The post-term scans consume the precise initialized tables. Their old and +new source memories are the actual prefix memories of the reported execution. -/ +theorem output_records (m : Memory w) (ss es os : List (Report w)) (wide : 2+2^a*dH ≤ stride) + (room : (P).stop < 2^w) (nextWidth : (V).maxWireWidth < 2^w) (fit : (P).segments ≤ 2^w) + (segments : SegmentFields X Q fit m) (terms : SupplyScan.TermFields X E hdH conn F c M stride m) + (srun : let b := SupplyScan.params (2^a) (2^g) dH M stride F.selectorBits ((P).inputs w).supply + runSegment ((template SupplyScan.visit 0).instantiate w b).program 34 (some 0) m + (List.replicate ((P).sites*dH) []) = some ss) + (erun : ExpanderROM.runRows E ((P).inputs w) (some 0) (after m (eventLog ss)) (List.finRange (2^a*dH)) = some es) + (orun : let kinds := fun j : Fin (2^a₀) ↦ kindOf ((refreshSlots hd).symm j) + let data := fun j : Fin (2^a₀) ↦ AllSlots.words (2^a) (2^g) ((P).inputs w) ((P).output w) ((refreshSlots hd).symm j) + AllSlots.Runs kinds data (P).sites (List.finRange (2^a₀)) (after (after m (eventLog ss)) (eventLog es)) os) : + let m₂ := after (after m (eventLog ss)) (eventLog es) + AllSlots.SourceTables X E hdH conn F c ((P).inputs w) m₂ ∧ ((P).output w).ActualColumns V (after m₂ (eventLog os)) := by + intro m₂ + have layout := finish_layout X E hdH conn F hD hd c t stride start wide room.le + have internal := (bounds X E hdH conn F hD hd c nextWidth).2 + obtain ⟨ss',es',hs,he,src,_,_,_⟩ := Finish.supply_and_rom X E hdH conn F hD hd c Q M stride + ((P).inputs w) ((P).output w) m fit segments terms layout internal + obtain rfl := Option.some.inj (hs.symm.trans srun) + obtain rfl := Option.some.inj (he.symm.trans erun) + obtain ⟨os',ro,actual,_,_⟩ := AllSlots.all_slots X E hdH conn F hD hd c ((P).inputs w) ((P).output w) m₂ + src layout.dims layout.incidence layout.slotReads + obtain rfl := AllSlots.Runs.deterministic ro orun + exact ⟨src,actual⟩ + +end CompressorRecords.PortRefresh.Build + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshOperandInputs.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshOperandInputs.lean new file mode 100644 index 0000000000..f06d25f97f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshOperandInputs.lean @@ -0,0 +1,75 @@ +import OAI.Computability.VPVNP.CompressorRecordRefreshArgumentAddress +import OAI.Computability.VPVNP.CompressorRecordRefreshArgumentSite +import OAI.Computability.VPVNP.CompressorRecordRefreshReadback + +/-! +# Operand addresses for a selected refresh site + +The child and parent carry independent private argument buffers. Their argument banks read +the old and new incidence widths, respectively. Both banks name the same physical site +ordinal. The four external segment heads describe independently oriented half-wires. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.OperandInputs + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PhaseRecipe NewSlots +open PairSimulation.NodeArguments RefreshMapOperands + +/-- Address expressions for a refresh site's old child and promoted parent argument buffers, +external segment tables, demand row and selected term record. -/ +structure Input where + /-- Address plan for the child's private arguments at the old site, using the input state's + incidence directory. -/ + child : ArgumentAddress.Input + /-- Address plan for the promoted parent's private arguments, using the output state's + incidence directory. -/ + parent : ArgumentAddress.Input + /-- Expression for the number of residual lane positions, equal to two to the residual lane + exponent. -/ + lanes : Expr + /-- Head of the outgoing segment-offset array, supplied by word five of the segment bank. -/ + offOut : Expr + /-- Head of the incoming segment-offset array, supplied by word six of the segment bank. -/ + offIn : Expr + /-- Head of the outgoing segment-width array, supplied by word one of the segment bank. -/ + widthOut : Expr + /-- Head of the incoming segment-width array, supplied by word seven of the segment bank. -/ + widthIn : Expr + /-- Expression evaluating to the base address of the gathered demand records. -/ + demandBase : Expr + /-- Expression evaluating to the base address of the selected refresh term records. -/ + termBase : Expr + +variable {a b g dH w : ℕ} (I : Input) (pub : Fin 5 → W w) (state : W w) (m : Memory w) + (X : State a (a+g)) (p : (X.Base × BitWord g) × Fin (2^a)) + (P : SlotGraph (Fin (2^a)) dH) (hD : 1 < 2^a) (hd : dH+1 ≤ 2^b) + (internal : X.Base × BitWord g → Fin (2^a) × Fin dH → ℕ) (A : Arena) (child parent : ℕ) + (old next : IncidenceDirectory w) (q : Fin 8 → W w) (demand term : W w) + +local notation "Y" => newState X P hD hd internal +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) + +/-- The child and promoted parent expressions represent their actual arguments and incidence +directories. The parent site ordinal, lane count and segment, demand and term heads +evaluate to the specified live words. -/ +structure Describes : Prop where + childRep : ArgumentAddress.Represents pub state m I.child X (oldSite X p) old A child + parentRep : ArgumentAddress.Represents pub state m I.parent Y (promotedSites p) next A parent + site : (I.parent.siteOrd.eval pub state m).val = (O p).val + lanes : (I.lanes.eval pub state m).val = 2^g + offOut : I.offOut.eval pub state m = q 5 + offIn : I.offIn.eval pub state m = q 6 + widthOut : I.widthOut.eval pub state m = q 1 + widthIn : I.widthIn.eval pub state m = q 7 + demandBase : I.demandBase.eval pub state m = demand + termBase : I.termBase.eval pub state m = term + +end CompressorRecords.PortRefresh.OperandInputs + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPassCalendar.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPassCalendar.lean new file mode 100644 index 0000000000..ddc317bdd7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPassCalendar.lean @@ -0,0 +1,47 @@ +import OAI.Computability.VPVNP.CompressorRefreshHeaderGroup +import OAI.Computability.VPVNP.CompressorPassTimeline + +/-! # The initial, selector and final ordinals of a refresh pass -/ + +namespace OAI +namespace Computability +namespace VPVNP + +set_option quotPrecheck false + +namespace CompressorRecords.RefreshPass + +open BurstRAM Compression DescriptorSpace BlockPlanner PassTimeline + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} +variable (B : S.Templates) (t : ℕ) +local notation "loc" => Located.mk (steps := S.steps) t .refresh +local notation "scr" => BlockProgram.script B + +theorem first_eq : (loc).first B = + (scr).initial.length + t * (scr).block.length + (RefreshHeaders.window B).before.length := by + change _ = _ + (BlockGroups.refresh B 0).before.length + rw [BlockGroups.refresh_offset] + change _ = _ + (((List.finRange S.steps).flatMap (BlockProgram.shrink B)).length + 0) + rw [Nat.add_zero] + rfl + +theorem finish_eq : (loc).finish B = (scr).initial.length + (t + 1) * (scr).block.length := by + change (scr).initial.length + t * (scr).block.length + + ((List.finRange S.steps).flatMap (BlockProgram.shrink B)).length + + (BlockProgram.refresh B).length = _ + have h : (scr).block.length = ((List.finRange S.steps).flatMap (BlockProgram.shrink B)).length + + (BlockProgram.refresh B).length := List.length_append .. + rw [Nat.add_mul, one_mul] + omega + +theorem finish_le_total (base positions blocks : ℕ) (ht : t < blocks) : + (loc).finish B ≤ directoryRows (BlockProgram.layout B base positions blocks) := by + rw [finish_eq, BlockProgram.directory_rows,(scr).calendar_total] + exact Nat.add_le_add_left (Nat.mul_le_mul_right _ ht) _ + +end CompressorRecords.RefreshPass + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPassRun.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPassRun.lean new file mode 100644 index 0000000000..f16be38d90 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPassRun.lean @@ -0,0 +1,80 @@ +import OAI.Computability.VPVNP.CompressorRefreshPassSegments +import OAI.Computability.VPVNP.CompressorRefreshEmit +import OAI.Computability.VPVNP.CompressorPrefixWorkerFit + +/-! # Executing every native packet of the refresh pass -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +set_option quotPrecheck false + +namespace CompressorRecords.RefreshPass + +open BurstRAM Compression DescriptorSpace BlockPlanner PassTimeline Schedule SourceTransport +open PairSimulation.LocalHistory PairSimulation.TraversalRoles ScheduledTrace +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) {g w : ℕ} +variable (pub : Fin 11 → Word w) (positions blocks t n : ℕ) +variable (X : State S.portExponent (S.portExponent + g)) +local notation "script" => BlockProgram.script B +local notation "L" => BlockProgram.layout B (pub 2).val positions blocks +local notation "loc" => (⟨t, .refresh⟩ : Located S.steps) +local notation "o" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "pass" => Refresh.dyadicRefreshPass X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2 + (f ∘ Sum.inr) ((B.solution_iff f).mp hf).2 +local notation "Choice" => (pass).step.Choice +local notation "pt" => Workspace.ports (arity (Script.catalog script)) (pub 2) +local notation "cur" => Script.levelsPerBlock script * t + S.steps +local notation "total" => directoryRows L + +variable (initial : TaggedLayer) (initialFrame : Fin 8 → Word w) +local notation "resident" => + CompiledResident.resident B f hf (pub 2) positions blocks n initial initialFrame +local notation "shape" => RefreshBlockPlan.shape B +local notation "role" => Scalars.Pass.refresh S.portExponent (S.degreeExponent 0) S.expanderExponent + +/-- Execute the common header and demand workers, the selected term worker, +and all succeeding copy and publication workers in the scheduled refresh. -/ +theorem realize (termCap cap small : ℕ) (shrinking : Fin S.steps → ℕ) + (encode : Choice → List Bool) (past : List (SelectedLevel B f hf)) (m : Memory w) + (ht : t < blocks) (depth : past.length = cur) + (size : X.positions ≤ positions) (room : endAddress L < 2 ^ w) + (clock : small ≤ cap) (big : Online.Run.ControlBounds (script).plan cap (w := w)) + (little : Online.Run.ControlBounds (script).plan small (w := w)) + (ready : Boundary resident pub (levelWords L : Word w) total ((loc).first B) past X m) + (headerClock : SourceOnline.scanCap script + (ScheduledRates.headerCap (BlockProgram.geometry B) role) ≤ small) + (termClock : SourceOnline.scanCap script (max 64 termCap) ≤ small) + (sitesWord : X.positions < 2 ^ w) (degreeWord : slotDegree S < 2 ^ w) + (portWidth : 2 ^ S.portExponent * X.maxWireWidth < 2 ^ w) + (selectorWidth : SelectedTermWorker.fitConstant B + 4 * Nat.clog 2 (X.maxWireWidth + 1) ≤ w) + (nativeWidth : PrefixLevelScale.refreshConstant B + 4 * Nat.clog 2 (X.maxWireWidth + 1) ≤ w) + (fuel : TermWorker.budget B.refresh (shape).ties ((shape).ports * (shape).dH) + w X.maxWireWidth ≤ termCap) + (positive : 0 < termCap) (outputWidth : ∀ c : Choice, ((pass).next c).maxWireWidth < 2 ^ w) : + Nonempty (PassRun resident pub (levelWords L : Word w) total cap small + (nativePassRate script (commonRawRate shrinking (RefreshEmit.rawRate B)) * positions) + loc o encode past m) := by + have rows : m (pt).rows.val = (total : Word w) := Fin.ext (ready.totalValue.trans + (Nat.mod_eq_of_lt (ready.totalValue ▸ (m (pt).rows.val).isLt)).symm) + obtain ⟨hs, ds, term, tail, src⟩ := RefreshEmit.build B f hf (pub 2) positions blocks t small n + initial initialFrame past X encode m termCap depth ht size room rows ready.stride + headerClock termClock sitesWord degreeWord portWidth nativeWidth outputWidth fuel positive + ready.stored + exact ofSources B f hf pub positions blocks t n X initial initialFrame shrinking m past encode + ready ht depth size room clock big little hs ds term tail src termCap selectorWidth + fuel termClock + +end CompressorRecords.RefreshPass + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPassSegments.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPassSegments.lean new file mode 100644 index 0000000000..17fff452eb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPassSegments.lean @@ -0,0 +1,118 @@ +import OAI.Computability.VPVNP.CompressorRefreshPassCalendar +import OAI.Computability.VPVNP.CompressorPacketPassRun +import OAI.Computability.VPVNP.CompressorNativePassRates +import OAI.Computability.VPVNP.CompressorRefreshEmitSources +import OAI.Computability.VPVNP.CompressorRefreshSelectorMount + +/-! # The selected refresh in the physical pass calendar + +The concrete header and demand packets fix one common prefix. The incoming +graph and the selected payload history are transferred to the returning +memory, with the cost charged to the fixed catalog over all visited rows. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +set_option quotPrecheck false + +namespace CompressorRecords.RefreshPass + +open BurstRAM Compression DescriptorSpace BlockPlanner PassTimeline Schedule SourceTransport +open PairSimulation.LocalHistory PairSimulation.TraversalRoles ScheduledTrace +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) {g w : ℕ} +variable (pub : Fin 11 → Word w) (positions blocks t n : ℕ) +variable (X : State S.portExponent (S.portExponent + g)) +local notation "script" => BlockProgram.script B +local notation "L" => BlockProgram.layout B (pub 2).val positions blocks +local notation "loc" => (⟨t, .refresh⟩ : Located S.steps) +local notation "o" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "pass" => Refresh.dyadicRefreshPass X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh S.port_order S.degree_bounds.2 + (f ∘ Sum.inr) ((B.solution_iff f).mp hf).2 +local notation "Choice" => (pass).step.Choice +local notation "cur" => Script.levelsPerBlock script * t + S.steps +local notation "total" => directoryRows L +local notation "pkt" => SourceOnline.Packet script w + +variable (initial : TaggedLayer) (initialFrame : Fin 8 → Word w) +local notation "resident" => + CompiledResident.resident B f hf (pub 2) positions blocks n initial initialFrame + +private theorem next_slots (size : X.positions ≤ positions) + (encode : Choice → List Bool) (c : Choice) : + IncidenceDirectory.slotCount ((pass).next c) ≤ slotCapacity L := by + let v := ScheduledTrace.level o encode c + have slots : v.outputSlots = IncidenceDirectory.slotCount (v.pass.next v.term) := by + rw [SelectedLevel.outputSlots, SelectedLevel.outputSites, State.positions, Fintype.card_prod, + Fintype.card_congr (bitWordFinEquiv _), Fintype.card_fin] + change IncidenceDirectory.slotCount (v.pass.next v.term) ≤ positions * slotDegree S + rw [← slots] + exact v.outputSlots_le.trans (Nat.mul_le_mul_right _ size) + +/-- Consume the actual common preparation and the verified raw suffix +returned for each selected term. The output retains the current graph and +every previous parser payload in the physical live memory. -/ +theorem ofSources {small cap : ℕ} (shrinking : Fin S.steps → ℕ) + (m : Memory w) (past : List (SelectedLevel B f hf)) (encode : Choice → List Bool) + (ready : Boundary resident pub (levelWords L : Word w) total ((loc).first B) past X m) + (ht : t < blocks) (depth : past.length = cur) + (size : X.positions ≤ positions) (fit : endAddress L < 2 ^ w) + (clock : small ≤ cap) (big : Online.Run.ControlBounds (script).plan cap (w := w)) + (bounds : Online.Run.ControlBounds (script).plan small (w := w)) + (hs ds : List pkt) (term : Choice → pkt) (tail : Choice → List pkt) + (src : RefreshEmit.Sources B f hf (pub 2) positions blocks t small n initial initialFrame + past X encode m hs ds term tail) + (termCap : ℕ) + (width : SelectedTermWorker.fitConstant B + 4 * Nat.clog 2 (X.maxWireWidth + 1) ≤ w) + (fuel : TermWorker.budget B.refresh (RefreshBlockPlan.shape B).ties + ((RefreshBlockPlan.shape B).ports * (RefreshBlockPlan.shape B).dH) w X.maxWireWidth ≤ termCap) + (scanClock : SourceOnline.scanCap script (max 64 termCap) ≤ small) : + Nonempty (PassRun resident pub (levelWords L : Word w) total cap small + (nativePassRate script (commonRawRate shrinking (RefreshEmit.rawRate B)) * positions) + loc o encode past m) := by + have selector : (loc).first B + (hs ++ ds).length = + (script).initial.length + t * (script).block.length + + (BlockIndex.blockRefresh B).index.val := by + rw [first_eq, Nat.add_assoc, + RefreshSelector.before_offset B f hf pub positions blocks t X src.before] + have endFit := finish_le_total B t (pub 2).val positions blocks ht + have preFit : (loc).first B + (hs ++ ds).length < total := by + rw [selector] + have inBlock : (BlockIndex.blockRefresh B).index.val < (script).block.length := + (BlockIndex.blockRefresh B).index.isLt + apply lt_of_lt_of_le _ endFit + rw [finish_eq, Nat.add_mul, one_mul] + change _ < (script).initial.length + (t * (script).block.length + (script).block.length) + omega + have dataStart : levelStart L 0 < 2 ^ w := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + apply PassRun.ofInstalledPacketGroups (hs ++ ds) term tail src.first src.middle src.last + src.before.quiet src.emptyTail src.termBits clock big bounds rfl rfl dataStart preFit endFit + src.lengths le_rfl (fun _ _ => rfl) ready + · intro mid agree _ htag ord rows stride + exact RefreshSelector.mountBefore B f hf pub positions blocks t X termCap small cap m hs ds + src.before ht size fit width fuel scanClock clock mid agree htag (ord.trans selector) + rows stride + · exact src.stored + · intro c u v agree h + have nextIndex : (past ++ [level o encode c]).length < (L).levels := by + simpa only [List.length_append, List.length_singleton, depth, Nat.add_assoc] using + src.before.newLive + exact DetailedResident.transfer h nextIndex fit (by change 14 ≤ 54; decide) + (next_slots B f hf pub positions blocks X size encode c) agree + · intro c + exact passCharges_le B X loc shrinking (RefreshEmit.rawRate B) positions size + (hs ++ ds) (term c) (tail c) (src.lengths c) (RefreshEmit.raw_le B X (src.rawCharge c)) + +end CompressorRecords.RefreshPass + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPayloadCapture.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPayloadCapture.lean new file mode 100644 index 0000000000..c735821018 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPayloadCapture.lean @@ -0,0 +1,140 @@ +import OAI.Computability.VPVNP.CompressorRefreshPayloadHistory +import OAI.Computability.VPVNP.CompressorRefreshPayloadSpace +import OAI.Computability.VPVNP.CompressorRefreshCoreBuild +import OAI.Computability.VPVNP.CompressorRefreshCopyGroup +import OAI.Computability.VPVNP.CompressorRefreshPlacementResults + +/-! +# Capturing the selected refresh in its final packet memory + +The core reports fill the selected segment and term records. Six column +copies install the successor graph, then the placement and publication +packets supply its traversal geometry. The frame of these batches retains +the input graph and the cells of every earlier selected pass. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshPayloadHistory + +open BurstRAM BlockPlanner Compression Compression.Refresh Compression.DegreeRefresh +open DescriptorSpace PortRefresh SourceOnline SourceTransport +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable {g w : ℕ} (base : BurstRAM.Word w) (positions blocks t : ℕ) +variable (f : B.Entry → R) (hf : B.IsSolution f) (X : State S.portExponent (S.portExponent+g)) +local notation "hE" => Nat.two_pow_pos S.expanderExponent +local notation "hC" => And.left (S.port_bound.connected_and_pos S.port_order) +variable (c : DyadicRefreshChoice (a₀ := S.degreeExponent 0) (g := g) X S.graph + (Nat.two_pow_pos S.expanderExponent) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) (sel : List Bool) + +local notation "Y" => dyadicRefreshNext X S.graph hE hC B.refresh S.port_order (And.right S.degree_bounds) c +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "first" => Script.levelsPerBlock scr * t +local notation "cur" => (first) + S.steps +local notation "nxt" => (cur) + 1 +local notation "head" => levelStart L (cur) +local notation "nextHead" => levelStart L (nxt) +local notation "start" => arrayBase L (cur) +local notation "place" => tableBase L (cur) (4 : Fin 6) +local notation "shape" => RefreshBlockPlan.shape B +local notation "P" => Allocation.plan X (S.degreeExponent 0) (LevelRecipe.Shape.dH shape) (LevelRecipe.Shape.ties shape) (LevelRecipe.Shape.stride shape) start +local notation "N" => State.positions Y * 2^(S.degreeExponent 0) +local notation "oldDir" => packedIncidence L w (cur) (X.positions*2^S.portExponent) + +/-- The core and the incidence copies agree with their common input below +the scratch and throughout the successor header. -/ +theorem core_copy_frame {termCap : ℕ} {m : Memory w} {core copy : List (Report w)} + (space : Space B base positions blocks t X) + (built : RefreshCore.Built B base positions blocks t X c termCap m core) + (copied : RefreshCopyPackets.Copied B base positions blocks t X c (after m (eventLog core)) copy) + (x : ℕ) (cell : x < start ∨ (nextHead ≤ x ∧ x < incidenceStart L (nxt))) : + after (after m (eventLog core)) (eventLog copy) x = m x := by + have high := space.array_before + have stop := space.scratch_next + have index : (first)+(S.steps+1) = nxt := (Nat.add_assoc ..).symm + have boundary : nextHead ≤ incidenceStart L (nxt) := Nat.le_add_right .. + refine (copied.frame x (.inl (index ▸ (by omega : x < incidenceStart L (nxt))))).trans + (after_outside m built.writes ?_) + change ¬ (start ≤ x ∧ x < (P).stop) + omega + +set_option maxHeartbeats 1600000 in +/-- Read back a selected native refresh at the end of all six post-header +groups. The earlier-cell and input-bank equalities extend the preceding +history across exactly these reports. -/ +theorem capture {cap termCap n : ℕ} {m : Memory w} {core copy : List (Report w)} + {tail : List (Packet scr w)} + (live : t < blocks) (size : X.positions ≤ positions) (room : endAddress L < 2^w) + (old : (oldDir).Represents X m) (length : m (levelStart L 0+29) = (n : BurstRAM.Word w)) + (bank : TraversalHeaders.HeadBank L (nxt) N m) + (built : RefreshCore.Built B base positions blocks t X c termCap m core) + (copied : RefreshCopyPackets.Copied B base positions blocks t X c (after m (eventLog core)) copy) + (installed : RefreshPlacement.TailResult B base positions blocks t cap f hf X c sel + (after (after m (eventLog core)) (eventLog copy)) tail) : + let out := post (after (after m (eventLog core)) (eventLog copy)) tail + Data B L (cur) n X c out ∧ (∀ x < head, out x = m x) ∧ Agree (SelectedPayloadHistory.GraphCells L (cur)) m out := by + intro out + let copiedMem := after (after m (eventLog core)) (eventLog copy) + have space := Space.ofLayout B base positions blocks t X live size room + have hdr := space.header_before + have high := space.array_before + have placed := space.placement_before + have scratch := space.scratch_before + have firstHdr := space.header_first + have table : start ≤ place := Nat.le_add_right .. + have nextInc : incidenceStart L (nxt) = nextHead+66 := rfl + have index : (first)+(S.steps+1) = nxt := (Nat.add_assoc ..).symm + have unchanged := core_copy_frame B base positions blocks t X c space built copied + have low (x : ℕ) (hx : x < start) : copiedMem x = m x := unchanged x (.inl hx) + have nextBank : TraversalHeaders.HeadBank L (nxt) N copiedMem := by + apply bank.keep + intro j hj + change j < 66 at hj + exact unchanged _ (.inr ⟨Nat.le_add_right .., by omega⟩) + have geom := installed.geometry n N ((low _ (by omega)).trans length) nextBank + have frame (x : ℕ) (site : x < place ∨ place+3*X.positions ≤ x) + (metadata : x < head+15 ∨ head+27 ≤ x) (next14 : x ≠ nextHead+14) + (next27 : x ≠ nextHead+27) (terms : x < head+36 ∨ head+41 ≤ x) : + out x = copiedMem x := + installed.frame x ⟨site,metadata,next14,next27⟩ terms + have below (x : ℕ) (hx : x < head) : out x = m x := + (frame x (.inl (by omega)) (.inl (by omega)) (by omega) (by omega) (.inl (by omega))).trans + (low x (by omega)) + have input (x : ℕ) (cell : SelectedPayloadHistory.GraphCells L (cur) x) : out x = m x := by + change head+54 ≤ x ∧ x < start at cell + exact (frame x (.inl (by omega)) (.inr (by omega)) (by omega) (by omega) (.inr (by omega))).trans + (low x cell.2) + have stored := copied.stored built.stored + have retained := stored.transfer (a₀ := S.degreeExponent 0) (m' := out) le_rfl copied.stop_fits.le + (fun x lo hi => by + have before : x < place := hi.trans_le scratch + exact frame x (.inl before) (.inr (by omega)) (by omega) (by omega) (.inr (by omega))) + let curr : Fin (L).levels := ⟨cur, Nat.lt_of_succ_lt space.live⟩ + let succ : Fin (L).levels := ⟨nxt,space.live⟩ + have oldSize : X.positions*2^S.portExponent ≤ slotCapacity L := + Nat.mul_le_mul size (le_max_left ..) + have count := dyadicRefreshNext_positions X S.graph hE hC B.refresh S.port_order (And.right S.degree_bounds) c + have degree : 2^(S.degreeExponent 0) ≤ slotDegree S := + (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ 0)).trans + (le_max_right ..) + have capacity : N ≤ slotCapacity L := Nat.mul_le_mul (count.le.trans size) degree + refine ⟨⟨built.fits,retained,keep_incidence curr X room oldSize old ?_, + keep_incidence succ Y room capacity (by simpa only [index] using copied.represents) ?_,geom⟩, + below,fun x hx => (input x hx).symm⟩ + · intro x lo hi + apply input x + exact ⟨(show head+54 ≤ incidenceStart L curr from by change head+54 ≤ head+66; omega).trans lo,hi⟩ + · intro x lo _ + change incidenceStart L (nxt) ≤ x at lo + exact frame x (.inr (by omega)) (.inr (by omega)) (by omega) (by omega) (.inr (by omega)) + +end CompressorRecords.RefreshPayloadHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPayloadHistory.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPayloadHistory.lean new file mode 100644 index 0000000000..a3fcc086f4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPayloadHistory.lean @@ -0,0 +1,126 @@ +import OAI.Computability.VPVNP.CompressorSelectedPayloadHistory +import OAI.Computability.VPVNP.CompressorCurrentGraph +import OAI.Computability.VPVNP.CompressorBlockLevelFit + +/-! +# Native refresh records retained by the selected history + +A refresh reads its selected demands and terms from its own level. The +successor contributes six incidence pointers and the packed graph itself. +The old header supplies the traversal arena and its frame stride. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshPayloadHistory + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh DescriptorSpace +open PortRefresh PortRefresh.Allocation SourceTransport +set_option maxHeartbeats 1600000 + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {w g : ℕ} (L : Layout) (i n : ℕ) (X : State S.portExponent (S.portExponent+g)) +local notation "hE" => Nat.two_pow_pos S.expanderExponent +local notation "hC" => And.left (S.port_bound.connected_and_pos S.port_order) +variable (choice : DyadicRefreshChoice (a₀ := S.degreeExponent 0) (g := g) X S.graph + (Nat.two_pow_pos S.expanderExponent) (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) +local notation "Y" => dyadicRefreshNext X S.graph hE hC B.refresh S.port_order (And.right S.degree_bounds) choice +local notation "s" => RefreshBlockPlan.shape B +local notation "start" => arrayBase L i +local notation "P" => plan X (S.degreeExponent 0) (LevelRecipe.Shape.dH s) (LevelRecipe.Shape.ties s) (LevelRecipe.Shape.stride s) start +local notation "oldDir" => packedIncidence L w i (X.positions*2^S.portExponent) +local notation "newDir" => packedIncidence L w (i+1) (State.positions Y*2^(S.degreeExponent 0)) + +/-- The selected refresh's native term, old and new graphs, and DFS arena. -/ +structure Data (m : Memory w) : Prop where + fits : (P).segments ≤ 2^w + stored : Build.Stored X S.graph hE hC B.refresh choice (RefreshBlockPlan.order B) start (s).stride fits m + old : (oldDir).Represents X m + new : (newDir).Represents Y m + geometry : TraversalHeaders.Geometry (Fintype.card X.Base) g (levelStart L i) (levelStart L (i+1)) start + ⟨n,PairSimulation.NodeArguments.frameStride (slotDegree S) n⟩ oldDir newDir m + +/-- Only the successor's six pointer words occur in the refresh header readback. -/ +theorem keep_geometry {V lanes oldHead newHead scratch : ℕ} {A : PairSimulation.NodeArguments.Arena} + {T U : IncidenceDirectory w} {m out : Memory w} + (h : TraversalHeaders.Geometry V lanes oldHead newHead scratch A T U m) + (old : ∀ j ≤ 60, out (oldHead+j) = m (oldHead+j)) + (new : ∀ c : Fin 6, out (newHead+54+c.val) = m (newHead+54+c.val)) : + TraversalHeaders.Geometry V lanes oldHead newHead scratch A T U out := by + refine ⟨h.oldRoom,h.newRoom,(old 0 (by decide)).trans h.vertices,(old 3 (by decide)).trans h.residual, + (old 17 (by decide)).trans h.arena,(old 18 (by decide)).trans h.stride,?_, + fun c => (new c).trans (h.newIncidence c),(old 60 le_rfl).trans h.scratch⟩ + intro c + rw [Nat.add_assoc,old _ (by have := c.isLt; omega),← Nat.add_assoc] + exact h.oldIncidence c + +/-- Transport a physical incidence directory whose row count is computed +from the state's positions, as in the native copy packet. -/ +theorem keep_incidence {L : Layout} {a l : ℕ} (j : Fin L.levels) (Z : State a l) + {m out : Memory w} (room : endAddress L < 2^w) (size : Z.positions*2^a ≤ slotCapacity L) + (h : (packedIncidence L w j (Z.positions*2^a)).Represents Z m) + (same : ∀ x, incidenceStart L j ≤ x → x < arrayBase L j → out x = m x) : + (packedIncidence L w j (Z.positions*2^a)).Represents Z out := by + have rows : Z.positions*2^a = IncidenceDirectory.slotCount Z := by + rw [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv l),Fintype.card_fin] + rw [rows] at size h ⊢ + exact CurrentGraph.incidence_keep L j Z room size h same + +variable {B L i n X choice} + +/-- On a native block layout the selected records survive every later write +that agrees on the completed level and the successor's graph cells. -/ +theorem Data.transfer {m out : Memory w} (data : Data B L i n X choice m) + {base positions blocks : ℕ} (layout : L = BlockProgram.layout B base positions blocks) + (live : i+1 < L.levels) (size : X.positions ≤ positions) (room : endAddress L < 2^w) + (same : Agree (SelectedPayloadHistory.Cells L i) m out) : Data B L i n X choice out := by + let cur : Fin L.levels := ⟨i,by omega⟩ + let nxt : Fin L.levels := ⟨i+1,live⟩ + have endpoint := (BlockLevelFit.refresh B base positions blocks cur layout X size room).1 + change BlockLevelFit.Endpoint w L i 0 + (plan X (S.degreeExponent 0) (s).dH (s).ties (s).stride (start+0*tableWords L)).stop at endpoint + simp only [Nat.zero_mul,Nat.add_zero] at endpoint + have before : (P).supply ≤ (P).stop := by + unfold Plan.stop Plan.next Plan.reverseSlot Plan.targetPort + omega + have fields : L.shape.scalarFields = 54 := layout ▸ rfl + have tables : L.shape.tables = 6 := layout ▸ rfl + have span : levelStart L i+60 < levelStart L (i+1) := by + simp only [levelStart,Nat.succ_mul,levelWords,levelHeaderWords,fields,tables] + omega + have oldEnd : start ≤ levelStart L (i+1) := by + simp only [arrayBase,incidenceStart,levelStart,Nat.succ_mul,levelWords] + omega + have lower : levelStart L i ≤ start := by unfold arrayBase incidenceStart; omega + have oldSize : X.positions*2^S.portExponent ≤ slotCapacity L := by + rw [layout] + exact Nat.mul_le_mul size (le_max_left ..) + have outputSize := dyadicRefreshNext_positions X S.graph hE hC B.refresh S.port_order (And.right S.degree_bounds) choice + have nextDegree : 2^(S.degreeExponent 0) ≤ slotDegree S := + (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ 0)).trans + (le_max_right ..) + have newSize : (Y).positions*2^(S.degreeExponent 0) ≤ slotCapacity L := by + rw [layout]; exact Nat.mul_le_mul (outputSize.le.trans size) nextDegree + refine ⟨data.fits,SelectedPayloadHistory.refresh_stored data.stored le_rfl endpoint.word.le lower (before.trans endpoint.next) same, + keep_incidence cur X room oldSize data.old ?_,keep_incidence nxt Y room newSize data.new ?_, + keep_geometry data.geometry ?_ ?_⟩ + · intro x lo hi + exact (same x (Or.inl ⟨(Nat.le_add_right ..).trans lo,hi.trans_le oldEnd⟩)).symm + · intro x lo hi + apply (same x (Or.inr ⟨?_,hi⟩)).symm + exact (by unfold incidenceStart levelHeaderWords; dsimp [nxt]; omega : _ ≤ incidenceStart L nxt).trans lo + · intro j hj + exact (same _ (Or.inl ⟨Nat.le_add_right ..,(Nat.add_le_add_left hj _).trans_lt span⟩)).symm + · intro c + apply (same _ (Or.inr ⟨?_,?_⟩)).symm + · rw [fields]; exact Nat.le_add_right .. + · unfold arrayBase incidenceStart levelHeaderWords + rw [fields,tables]; have := c.isLt; omega + +end CompressorRecords.RefreshPayloadHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPayloadSpace.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPayloadSpace.lean new file mode 100644 index 0000000000..9487cfa7a9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPayloadSpace.lean @@ -0,0 +1,67 @@ +import OAI.Computability.VPVNP.CompressorBlockLevelFit + +/-! +# Physical intervals of a selected refresh + +The old header and the refresh scratch precede the placement writes. +Both the scratch and placement fit before the live successor header. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshPayloadHistory + +open BurstRAM BlockPlanner Compression DescriptorSpace PortRefresh.Allocation + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {w g : ℕ} (base : Word w) (positions blocks t : ℕ) +variable (X : State S.portExponent (S.portExponent+g)) + +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "cur" => Script.levelsPerBlock (BlockProgram.script B)*t+S.steps +local notation "head" => levelStart L cur +local notation "start" => arrayBase L cur +local notation "place" => tableBase L cur (4 : Fin 6) +local notation "s" => RefreshBlockPlan.shape B +local notation "P" => plan X (S.degreeExponent 0) (PortRefresh.LevelRecipe.Shape.dH s) + (PortRefresh.LevelRecipe.Shape.ties s) (PortRefresh.LevelRecipe.Shape.stride s) start + +/-- Address bounds for preserving the selected refresh payload through its final visits. -/ +structure Space : Prop where + live : cur+1 < (L).levels + scratch_before : (P).supply ≤ place + header_before : head+66 ≤ start + array_before : start ≤ levelStart L (cur+1) + placement_before : place+3*X.positions ≤ levelStart L (cur+1) + header_first : levelStart L 0 ≤ head + scratch_next : (P).stop ≤ levelStart L (cur+1) + +/-- The compiled block layout supplies all of the bounds at each live repetition. -/ +theorem Space.ofLayout (ht : t < blocks) (size : X.positions ≤ positions) + (room : endAddress L < 2^w) : Space B base positions blocks t X := by + have live : cur+1 < (L).levels := by + have h := Nat.mul_le_mul_left (S.steps+1) ht + rw [Nat.mul_succ] at h + change (S.steps+1)*t+S.steps+1 < 1+(S.steps+1)*blocks + omega + let level : Fin (L).levels := ⟨cur,by omega⟩ + obtain ⟨scratch,placement⟩ := BlockLevelFit.refresh B base.val positions blocks level rfl X size room + change BlockLevelFit.Endpoint w L cur 0 + (plan X (S.degreeExponent 0) (s).dH (s).ties (s).stride (start+0*tableWords L)).stop at scratch + simp only [Nat.zero_mul,Nat.add_zero] at scratch + have supply : (P).supply ≤ (P).stop := by + unfold Plan.stop Plan.next Plan.reverseSlot Plan.targetPort + omega + have before := tableEnd_le_tableBase L cur (show (0 : Fin 6) < 4 by decide) + have zero : tableBase L cur (0 : Fin 6) = start := by simp [tableBase] + exact ⟨live,supply.trans (scratch.within.trans before),Nat.le_add_right .., + zero ▸ (Nat.le_add_right _ _).trans (tableEnd_le_nextLevel L cur (0 : Fin 6)), + placement.next,levelStart_mono L (Nat.zero_le _),scratch.next⟩ + +end CompressorRecords.RefreshPayloadHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementEmission.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementEmission.lean new file mode 100644 index 0000000000..498947fb31 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementEmission.lean @@ -0,0 +1,299 @@ +import OAI.Computability.VPVNP.CompressorRefreshPlacementResults +import OAI.Computability.VPVNP.CompressorShrinkScheduledTail +import OAI.Computability.VPVNP.CompressorRefreshPlacementPacket +import OAI.Computability.VPVNP.CompressorSelectedDirectoryEmission +import OAI.Computability.VPVNP.CompressorBlockMetadataWindows +import OAI.Computability.VPVNP.CompressorBlockHeadSequence +import OAI.Computability.VPVNP.CompressorRefreshCoreHeader +import OAI.Computability.VPVNP.CompressorRefreshPlacementGeometry + +/-! +# The directory and pointers emitted by the refresh + +The placement, DFS metadata and two pointer publications run consecutively. +The ordered singleton rows, their five traversal fields and the native term +table are all read from the final packet memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshPlacement + +open BurstRAM BlockPlanner Compression DescriptorSpace Schedule PhaseRecipe SourceOnline +open SelectedDirectoryHistory PairSimulation.TraversalRows SourceTransport +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable {g w : ℕ} (base : Word w) (positions blocks t cap : ℕ) +variable (f : B.Entry → R) (hf : B.IsSolution f) (X : State S.portExponent (S.portExponent + g)) +variable (c : Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) + +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Schedule.Ports.data pt +local notation "first" => Script.levelsPerBlock scr * t +local notation "cur" => (first) + S.steps +local notation "head" => levelStart L (cur) +local notation "nextHead" => levelStart L (cur + 1) +local notation "st" => (levelStart L (first) : Word w) +local notation "start" => tableBase L (cur) (4 : Fin 6) +local notation "level" => selectedLevel B f hf X c sel +local notation "data" => packed w start X.positions +local notation "W₃" => BlockGroups.refresh B 3 +local notation "W₄" => BlockGroups.refresh B 4 +local notation "W₅" => BlockGroups.refresh B 5 +local notation "W₆" => BlockGroups.refresh B 6 +local notation "off" => List.length (Script.initial scr) + t * List.length (Script.block scr) + +open private metaTapes from OAI.Computability.VPVNP.CompressorShrinkScheduledTail +open private space from OAI.Computability.VPVNP.CompressorRefreshPlacementPacket +open private offset_length from OAI.Computability.VPVNP.CompressorBlockHeadSequence + +private theorem offsets : + (W₄).before.length = (W₃).before.length + 1 ∧ + (W₅).before.length = (W₄).before.length + 3 := by + have len := BlockGroups.refreshParts_length B + have h := offset_length (BlockGroups.refreshParts B) 3 (by rw [len]; decide) + have k := offset_length (BlockGroups.refreshParts B) 4 (by rw [len]; decide) + have one : ((BlockGroups.refreshParts B)[3]'(by rw [len]; decide)).length = 1 := rfl + have three : ((BlockGroups.refreshParts B)[4]'(by rw [len]; decide)).length = 3 := rfl + rw [one] at h + rw [three] at k + constructor + · rw [BlockGroups.refresh_offset, BlockGroups.refresh_offset, Nat.add_assoc] + exact congrArg (Nat.add _) h + · rw [BlockGroups.refresh_offset, BlockGroups.refresh_offset, Nat.add_assoc] + exact congrArg (Nat.add _) k + +private theorem head_span : head + 66 ≤ start ∧ head + 66 ≤ nextHead := by + have len : levelHeaderWords L = 66 := rfl + have lo : head + 66 ≤ start := by unfold tableBase arrayBase incidenceStart; omega + exact ⟨lo, lo.trans ((Nat.le_add_right ..).trans (tableEnd_le_nextLevel L (cur) (4 : Fin 6)))⟩ + +private theorem placement_tapes (p : Fin 6 → Word w) (k n : ℕ) : + branchPaths (log p k n) = List.replicate n [] := by + induction n generalizing k with + | zero => rfl + | succ n ih => + change [] :: branchPaths (log p (k + 1) n) = _ + rw [ih, List.replicate_succ] + +set_option maxHeartbeats 850000 in +-- Matching the actual calendar windows compares the full compiled packet types. +/-- Run the selected singleton-directory scan immediately followed by the +three metadata publications, and identify the directory at their common output. -/ +theorem install_metadata (m : Memory w) (live : t < blocks) (size : X.positions ≤ positions) + (fit : endAddress L < 2 ^ w) (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m (pub 1 - 1).val = (levelWords L : Word w)) (clock : scanCap scr 42 ≤ cap) + (dH : ℕ) (header : LevelFields.Published L (cur) level dH m) + (pointers : PortRefresh.TraversalHeaders.HeadBank L (cur) (level).oldSlots m) : + ∃ ps, MetadataResult B base positions blocks t cap f hf X c sel m ps := by + have cap13 : scanCap scr 13 ≤ cap := by unfold scanCap at clock ⊢; omega + obtain ⟨ps, group₃, phase₃, log₃, ⟨dir, bank⟩, old, cols, frame₃⟩ := + install B base positions blocks t f hf X c sel cap m live size fit rows pitch cap13 + dH header pointers + let mid := post m ps + have span := head_span B base positions blocks t + have low := (levelStart_mono L (Nat.zero_le (cur))) + have ctl := Window.lowCells (A := scr) L base rfl rfl + ((levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit) + have nr := (frame₃ _ (.inl (ctl.1.trans_le (by omega)))).trans rows + have stride := (frame₃ _ (.inl (ctl.2.trans_le (by omega)))).trans pitch + have entry : LevelFields.Entry L (first) pub st mid := ⟨rfl, stride⟩ + obtain ⟨qs, group₄, phase₄, published⟩ := + BlockMetadata.refresh_group B base positions blocks t cap mid live fit nr stride clock + X.positions (LevelFields.eval_dimensions entry old).1 + have room := PublishedHeads.level_room B base positions blocks t S.steps live le_rfl fit + obtain ⟨h₀, h₂, _, h₃, h₅, h₄⟩ := + metadata_values B base positions blocks t f hf X c sel mid dH entry old cols room + have vals := SelectedDirectoryHistory.placement_words published + (bank ▸ ⟨h₀, h₂, h₃, h₅, h₄⟩ : + PlacementWords (fun j => (BlockMetadata.fieldExprs (L).shape S.steps B.recordLimit + (slotDegree S) (BlockMetadata.refreshFields B) j).eval pub st mid) dir.pub) + have lower := (packed_geometry B base positions blocks t X.positions size live fit + (by omega)).1 + let e := Emission.ofPublished (v := level) published dir (bank ▸ lower) vals + let e₀ := e.prepend (frame₃ _ (.inl (by omega))) (frame₃ _ (.inl (by omega))) + have pubEq : e₀.dir.pub = data := + (Emission.prepend_pub e (frame₃ _ (.inl (by omega))) (frame₃ _ (.inl (by omega)))).trans + ((Emission.ofPublished_pub (v := level) published dir (bank ▸ lower) vals).trans bank) + have emits : ∃ e : Emission L (cur) level m + (after mid (eventLog (qs.flatMap SourceWalk.Packet.reports))), + e.dir.pub = data := ⟨e₀, pubEq⟩ + have len : ps.length = 1 := by + have h := congrArg List.length phase₃ + simp only [List.length_map, Window.indices, List.length_ofFn] at h + exact h.trans (by rfl) + have index : off + (W₃).before.length + ps.length = off + (W₄).before.length := by + rw [(offsets B).1, len, Nat.add_assoc] + have afterEq : post m (ps ++ qs) = after mid (eventLog (qs.flatMap SourceWalk.Packet.reports)) := + post_append m ps qs + refine ⟨ps ++ qs, ?_⟩ + constructor + · apply group₃.append + change SourceOnline.Group scr L base cap (off + (W₃).before.length + ps.length) + (directoryRows L) mid qs + rw [index]; exact group₄ + · rw [List.map_append, phase₃, phase₄]; rfl + · rw [List.flatMap_append, RAMBuckets.cost_append, log₃, published.charge, + (cost data 0 X.positions).2.1] + · rw [afterEq]; exact emits + · rw [afterEq]; exact published.payload 0 + · intro n newRows hlen bankNext + rw [afterEq] + exact metadata_geometry B base positions blocks t f hf X c sel published live size fit + nr stride old cols frame₃ hlen bankNext + · intro n hlen + rw [afterEq] + exact SelectedChildDirectory.Stored.of_refresh f hf X c sel published entry old cols room nr + ((frame₃ _ (.inl (by omega))).trans hlen) + · have mb := metaTapes published.source + rw [published.length] at mb + rw [List.flatMap_append, PublishedHeads.chronological_tapes _ _ group₃.chronological, + PublishedHeads.chronological_tapes _ _ group₄.chronological, log₃, placement_tapes, mb, + List.replicate_add] + · rintro x ⟨hs, hh, hn, hr⟩ + rw [afterEq] + have hx := published.outside x hh (by rwa [← Nat.add_assoc]) (by rwa [← Nat.add_assoc]) + exact hx.trans (frame₃ x hs) + +local notation "shape" => RefreshBlockPlan.shape B +local notation "arena" => arrayBase L (cur) +local notation "tmp" => PortRefresh.Allocation.plan X (S.degreeExponent 0) + (PortRefresh.LevelRecipe.Shape.dH shape) (PortRefresh.LevelRecipe.Shape.ties shape) + (PortRefresh.LevelRecipe.Shape.stride shape) arena +local notation "termVals" => BlockHeadStability.refreshTerms B +local notation "nextVals" => (fun _ : Fin 1 => LevelFields.atLevel (S.steps + 1)) + +set_option maxHeartbeats 1600000 in +-- The selected term and traversal share the dependent block memory and packet types. +/-- The final five pointer publications retain the selected directory and +record the native refresh term bank and physical successor header. -/ +theorem install_tail (m : Memory w) (live : t < blocks) (size : X.positions ≤ positions) + (fit : endAddress L < 2 ^ w) (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m (pub 1 - 1).val = (levelWords L : Word w)) (clock : scanCap scr 42 ≤ cap) + (dH : ℕ) (header : LevelFields.Published L (cur) level dH m) + (pointers : PortRefresh.TraversalHeaders.HeadBank L (cur) (level).oldSlots m) : + ∃ ps, TailResult B base positions blocks t cap f hf X c sel m ps := by + obtain ⟨ps, old⟩ := install_metadata B base positions blocks t cap f hf X c sel + m live size fit rows pitch clock dH header pointers + let mid := post m ps + have span := head_span B base positions blocks t + have before (x : ℕ) (hx : x < head) : mid x = m x := old.frame _ ⟨.inl (by omega), + .inl (by omega), by omega, by omega⟩ + have lower := levelStart_mono L (Nat.zero_le (cur)) + have ctl := Window.lowCells (A := scr) L base rfl rfl + ((levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit) + have pitch₄ := (before _ (ctl.2.trans_le lower)).trans pitch + have ready : PublishedHeads.Ready B base positions blocks t cap mid := + ⟨live, fit, (before _ (ctl.1.trans_le lower)).trans rows, pitch₄, + by unfold scanCap at clock ⊢; omega⟩ + have pair := PublishedHeads.refresh_pair B ready + obtain ⟨qs, group, labels, logs, tapes⟩ := pair.online + have count : ps.length = 4 := by + have h := congrArg List.length old.phases + simp only [List.length_map, List.length_append, Window.indices, List.length_ofFn] at h + exact h.trans (by rfl) + have ord : off + (W₃).before.length + ps.length = off + (W₅).before.length := by + obtain ⟨a, b⟩ := offsets B; omega + let termMem := PublishedHeads.image pub st mid (head + 36) termVals + let finalMem := PublishedHeads.image pub st termMem (head + 40) nextVals + have eqn : post m (ps ++ qs) = finalMem := by + rw [post_append, post, logs, SourceWalk.after_append] + rfl + have keep (x : ℕ) (hx : x < head + 36 ∨ head + 41 ≤ x) : post m (ps ++ qs) x = mid x := + (congrFun eqn x).trans (pair.frame _ hx) + have hfit := (space B base positions blocks t size live fit) + have pfit := hfit.1.trans_lt hfit.2 + obtain ⟨em, emBank⟩ := old.emits + have owner : (em.dir.pub 1).val = start := by + rw [emBank]; exact (packed_values pfit (by have := header.room; omega)).2.1 + have arrays : Agree (Directory.cells em.dir.pub) mid (post m (ps ++ qs)) := by + intro x hx + have lo := (Directory.cells_interval em.dir hx).1 + rw [owner] at lo + exact (keep _ (.inr (by omega))).symm + let e := em.transfer arrays + (fun o ho => keep _ (.inl (by + simp only [List.mem_cons, List.not_mem_nil, or_false] at ho; omega))) + (fun o _ => keep _ (.inr (by omega))) + have cap₄ := PublishedHeads.level_room B base positions blocks t S.steps live le_rfl fit + have still (n : ℕ) (hn : n < 66) (hf : n < 15 ∨ 27 ≤ n) : mid (head + n) = m (head + n) := + old.frame _ ⟨.inl (by omega), by omega, by omega, by omega⟩ + have hdr : LevelFields.Published L (cur) level dH mid := + ⟨header.room, (still 0 (by decide) (.inl (by decide))).trans header.vertices, + (still 1 (by decide) (.inl (by decide))).trans header.degree, + (still 2 (by decide) (.inl (by decide))).trans header.lanes, + (still 3 (by decide) (.inl (by decide))).trans header.residual, + (still 4 (by decide) (.inl (by decide))).trans header.nextDegree, + (still 5 (by decide) (.inl (by decide))).trans header.expander⟩ + have bank₄ : PortRefresh.TraversalHeaders.HeadBank L (cur) (level).oldSlots mid := by + constructor + · intro j + have hj := j.isLt + have hj' := still (54 + j.val) (by omega) (.inr (by omega)) + simpa only [incidenceHead, show (L).shape.scalarFields = 54 from rfl, Nat.add_assoc] + using hj'.trans (by simpa only [incidenceHead, + show (L).shape.scalarFields = 54 from rfl, Nat.add_assoc] using pointers.incidence j) + · intro j + have hj : j.val < 6 := j.isLt + have h := still (54 + 6 + j.val) (by omega) (.inr (by omega)) + simpa only [tableHead, show (L).shape.scalarFields = 54 from rfl, Nat.add_assoc] + using h.trans (by simpa only [tableHead, + show (L).shape.scalarFields = 54 from rfl, Nat.add_assoc] using pointers.tables j) + let ctx : PortRefresh.LevelRecipe.Context w := ⟨pub, st, mid⟩ + have entry : LevelFields.Entry L (first) pub st mid := ⟨rfl, pitch₄⟩ + have rd := RefreshCore.Header.ofPublished hdr bank₄ rfl (show 0 < 6 by decide) (by omega) + have src := RefreshCore.Header.describes (s := shape) (X := X) (C := ctx) + (F := BlockProgram.geometry B) rfl (0 : Fin 6) rfl entry rd + have termAt := (PortRefresh.LevelRecipe.addresses (s := shape) + (RefreshBlockPlan.input (BlockProgram.geometry B) S.steps (0 : Fin 6)) ctx X arena + (packedIncidence L w (cur) (level).oldSlots) src).term_eq + have termRead (j : Fin 4) : post m (ps ++ qs) (head + 36 + j.val) = + (termVals j).eval pub st mid := by + rw [eqn] + have kept := pair.dataGroup.source.outside (head + 36 + j.val) + (Or.inl (by have := j.isLt; omega)) + exact kept.trans (pair.termGroup.source.stored j) + have midPitch := (pair.termGroup.source.outside (pub 1 - 1).val + (Or.inl (ctl.2.trans_le (by omega)))).trans pitch₄ + have termEntry : LevelFields.Entry L (first) pub st termMem := ⟨rfl, midPitch⟩ + have nextStored := pair.dataGroup.source.stored (0 : Fin 1) + have nextWord : post m (ps ++ qs) (head + 40) = (nextHead : Word w) := by + rw [eqn] + exact nextStored.trans ((LevelFields.eval_atLevel termEntry (S.steps + 1)).trans + (congrArg (fun n : ℕ => (levelStart L n : Word w)) (Nat.add_assoc ..).symm)) + refine ⟨ps ++ qs, ?_⟩ + constructor + · apply old.group.append + rw [ord]; exact group + · rw [List.map_append, old.phases, labels]; rfl + · rw [List.flatMap_append, RAMBuckets.cost_append, old.charge, logs, + PublishedHeads.pair_charge pub st mid head termVals nextVals] + · exact ⟨e, emBank⟩ + · exact (termRead 0).trans termAt + · exact termRead 1 + · exact termRead 2 + · exact termRead 3 + · exact nextWord + · exact (keep _ (.inl (by omega))).trans old.recordWords + · intro n newRows hlen bankNext + exact keep_geometry_heads (old.geometry n newRows hlen bankNext) span.2 keep + · intro n hlen + exact (old.child n hlen).keep (fun x _ hx => keep x (.inl (by omega))) + · rw [List.flatMap_append, old.tapes, tapes, ← List.replicate_add] + · exact fun x hx hx' => (keep x hx').trans (old.frame x hx) + +end CompressorRecords.RefreshPlacement + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementGeometry.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementGeometry.lean new file mode 100644 index 0000000000..c7fb0334b4 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementGeometry.lean @@ -0,0 +1,86 @@ +import OAI.Computability.VPVNP.CompressorBlockMetadataRefreshReadback +import OAI.Computability.VPVNP.CompressorRefreshPlacementPacket + +/-! +# Traversal geometry after the final refresh publications + +The placement scan fills table four before the metadata workers publish the +argument arena and stride. The final term and successor pointer publications +write offsets 36 through 40, disjoint from every traversal geometry field. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshPlacement + +open BurstRAM BlockPlanner Compression DescriptorSpace Schedule PortRefresh.TraversalHeaders +open scoped Fin.CommRing + +/-- Geometry after the term and successor-head packets, using their exact +five-word footprint in the old header. -/ +theorem keep_geometry_heads {w V g oldHead newHead start : ℕ} + {A : PairSimulation.NodeArguments.Arena} {T U : IncidenceDirectory w} {m out : Memory w} + (geom : Geometry V g oldHead newHead start A T U m) + (gap : oldHead+66 ≤ newHead) + (keep : ∀ x, x < oldHead+36 ∨ oldHead+41 ≤ x → out x = m x) : + Geometry V g oldHead newHead start A T U out := by + refine ⟨geom.oldRoom, geom.newRoom, (keep _ (.inl (by omega))).trans geom.vertices, + (keep _ (.inl (by omega))).trans geom.residual, (keep _ (.inl (by omega))).trans geom.arena, + (keep _ (.inl (by omega))).trans geom.stride, + fun c => (keep _ (.inr (by omega))).trans (geom.oldIncidence c), + fun c => (keep _ (.inr (by omega))).trans (geom.newIncidence c), + (keep _ (.inr (by omega))).trans geom.scratch⟩ + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable {g w : ℕ} (base : Word w) (positions blocks t : ℕ) +variable (f : B.Entry → R) (hf : B.IsSolution f) (X : State S.portExponent (S.portExponent+g)) +variable (c : Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) + +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "first" => Script.levelsPerBlock scr * t +local notation "cur" => (first) + S.steps +local notation "head" => levelStart L (cur) +local notation "start" => tableBase L (cur) (4 : Fin 6) +local notation "level" => selectedLevel B f hf X c sel + +open private space from OAI.Computability.VPVNP.CompressorRefreshPlacementPacket + +/-- Read back the actual metadata burst after its singleton placement scan. +The scan preserves the startup length word and the successor header bank. -/ +theorem metadata_geometry {m mid : Memory w} {rs : List (Report w)} {n newRows dH : ℕ} + (published : BlockMetadata.Published B base positions blocks t S.steps .refresh + (BlockMetadata.refreshFields B) mid X.positions rs) + (live : t < blocks) (size : X.positions ≤ positions) (fit : endAddress L < 2^w) + (rows : mid (pt).rows.val = (directoryRows L : Word w)) + (pitch : mid ((pt).directory-1).val = (levelWords L : Word w)) + (old : LevelFields.Published L (cur) level dH mid) + (oldBank : HeadBank L (cur) (level).oldSlots mid) + (frame : ∀ x, x < start ∨ start+3*X.positions ≤ x → mid x = m x) + (length : m (levelStart L 0+29) = (n : Word w)) + (new : HeadBank L (cur+1) newRows m) : + Geometry (Fintype.card X.Base) g head (levelStart L (cur+1)) (arrayBase L (cur)) + ⟨n, PairSimulation.NodeArguments.frameStride (slotDegree S) n⟩ + (packedIncidence L w (cur) (level).oldSlots) (packedIncidence L w (cur+1) newRows) + (after mid (eventLog rs)) := by + have upto := (space B base positions blocks t size live fit).1 + have lower := levelStart_mono L (Nat.zero_le (cur)) + have headerLen : levelHeaderWords L = 66 := rfl + have before : head + 66 ≤ start := by unfold tableBase arrayBase incidenceStart; omega + have saved := (frame _ (.inl (by omega : levelStart L 0+29 < start))).trans length + have bank := new.keep (m' := mid) (fun i _ => frame _ (.inr (upto.trans (Nat.le_add_right ..)))) + let entry : LevelFields.Entry L (first) (pt).data (levelStart L (first) : Word w) mid := ⟨rfl,pitch⟩ + have native := BlockMetadata.Published.refresh_geometry B level base positions blocks t published + live fit rows pitch (LevelFields.eval_dimensions entry old).1 saved old oldBank + (by simpa only [← Nat.add_assoc] using bank) + simpa only [← Nat.add_assoc] using native + +end CompressorRecords.RefreshPlacement + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementPacket.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementPacket.lean new file mode 100644 index 0000000000..c7c20292d1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementPacket.lean @@ -0,0 +1,232 @@ +import OAI.Computability.VPVNP.CompressorRefreshPlacementTrace +import OAI.Computability.VPVNP.CompressorRefreshLevelDirectory +import OAI.Computability.VPVNP.CompressorBlockHeadWindows +import OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders +import OAI.Computability.VPVNP.CompressorBlockCapacity + +/-! +# The selected refresh placement packet + +The fourth refresh window fills three consecutive arrays in table four. +The old scalar header gives the number of sites and its native table-head +bank gives the base. The output identifies the singleton preimages of the +selected term and retains the headers and controller words. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshPlacement + +open BurstRAM BlockPlanner Compression Compression.DegreeRefresh +open DescriptorSpace PhaseRecipe Schedule SourceTransport SourceOnline +open PairSimulation.TraversalRows +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {g w : ℕ} (base : Word w) (positions blocks t : ℕ) + +/-- The refresh pass that installs the singleton immediate-preimage directory in table four of +the refresh level. -/ +abbrev stage := BlockProgram.refreshPlacement S.steps (BlockProgram.arena B S.steps 4) + +/-- Occurrence of the singleton-directory scan in the compiled block. -/ +def window : Window (BlockProgram.script B) [stage B] := BlockGroups.refresh B 3 + +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Schedule.Ports.data pt +local notation "first" => Script.levelsPerBlock scr * t +local notation "cur" => (first) + S.steps +local notation "st" => (levelStart L (first) : Word w) +local notation "H" => levelStart L 0 +local notation "D" => Window.operandRegion scr L base +local notation "start" => tableBase L (cur) (4 : Fin 6) +local notation "V" => stage B +local notation "W" => window B + +private theorem space {N : ℕ} (hN : N ≤ positions) (live : t < blocks) + (fit : endAddress L < 2 ^ w) : + start + 3 * N ≤ levelStart L (cur + 1) ∧ levelStart L (cur + 1) < 2 ^ w := by + have size : 3 * N ≤ tableWords L := by + rw [Nat.mul_comm] + change N * 3 ≤ positions * (L).shape.slots * (L).shape.fields + rw [Nat.mul_assoc] + exact Nat.mul_le_mul hN (BlockProgram.field_rates B base.val positions blocks).2.2.2 + have active : cur + 1 ≤ (L).levels := by + have bound := Nat.mul_le_mul_left (S.steps + 1) live + change (S.steps + 1) * t + S.steps + 1 ≤ 1 + (S.steps + 1) * blocks + rw [Nat.mul_succ] at bound; omega + exact ⟨(Nat.add_le_add_left size _).trans (tableEnd_le_nextLevel L (cur) (4 : Fin 6)), + (levelStart_mono L active).trans_lt fit⟩ + +/-- The packed owner column is beyond the metadata publishers' header cells +and the row array ends before the successor header. -/ +theorem packed_geometry (N : ℕ) (size : N ≤ positions) (live : t < blocks) + (fit : endAddress L < 2 ^ w) (one : 1 < 2 ^ w) : + let p := packed w start N + levelStart L (cur) + 28 ≤ (p 1).val ∧ (p 5).val + (p 2).val ≤ levelStart L (cur + 1) := by + intro p + obtain ⟨span, next⟩ := space B base positions blocks t size live fit + obtain ⟨_, owner, count, _, _, row⟩ := packed_values (span.trans_lt next) one + rw [show p = packed w start N from rfl, owner, count, row] + have header : levelHeaderWords L = 66 := rfl + constructor + · unfold tableBase arrayBase incidenceStart; omega + · omega + +open private field from OAI.Computability.VPVNP.CompressorBlockHeadReads + +/-- The native singleton-row run together with the reads of its physical planner. -/ +theorem raw (N : ℕ) (m : Memory w) (entry : LevelFields.Entry L (first) pub st m) + (room : levelStart L (cur) + 66 ≤ 2 ^ w) (fit : start + 3 * N < 2 ^ w) + (count : (LevelFields.sites S.steps).eval pub st m = (N : Word w)) + (arena : (BlockProgram.arena B S.steps 4).eval pub st m = (start : Word w)) : + Window.Raw (A := scr) L base t 13 V m (log (packed w start N) 0 N) := by + let p := packed w start N + have args : (fun j => ((V).params j).eval pub st m) = bank p := by + funext j + fin_cases j + · exact arena + · change (BlockProgram.arena B S.steps 4).eval pub st m + + (LevelFields.sites S.steps).eval pub st m = ((start + N : ℕ) : Word w) + rw [arena, count, Nat.cast_add] + · change (BlockProgram.arena B S.steps 4).eval pub st m + + (2 : Word w) * (LevelFields.sites S.steps).eval pub st m = + ((start + 2 * N : ℕ) : Word w) + rw [arena, count, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat] + have ss : (V).stop.eval pub st m = (N : Word w) := count + have rs := packed_log_access fit (Nat.zero_add N).le + have low : H ≤ start := (levelStart_mono L (Nat.zero_le (cur))).trans (by + unfold tableBase arrayBase incidenceStart; omega) + have fuel : HeaderPacket.Run L pub st V m (log p 0 N) 13 (List.replicate N []) := by + refine ⟨by decide, ?_, ?_, fun a v hv => (rs.1 a v hv).elim, + fun a v hv => low.trans (rs.2 a v hv).1⟩ + · dsimp only + rw [args] + exact run p 0 N m + · rw [ss] + change Progress (N : Word w) ((0 : ℕ) : Word w) _ + simpa only [Nat.zero_add] using log_progress p 0 N (by omega) + have sites : (LevelFields.sites S.steps).ReadsFrom D pub st m := + ⟨field entry room 0 (by decide), + field entry room 2 (by decide)⟩ + have table : (BlockProgram.arena B S.steps 4).ReadsFrom D pub st m := + field entry room 64 (by decide) + refine ⟨13, List.replicate N [], le_rfl, fuel, ⟨trivial, sites, ?_⟩⟩ + intro j + fin_cases j + · exact table + · exact ⟨table, sites⟩ + · exact ⟨table, trivial, sites⟩ + +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) +variable (X : State S.portExponent (S.portExponent + g)) +variable (c : Compression.Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) + +/-- The chosen pass with its actual promoted port order and branch selector. -/ +abbrev selectedLevel : SelectedLevel B f hf := + ⟨_, _, _, _, X, _, PassOrigin.refresh (B := B) (f := f) (hf := hf) X, c, sel⟩ + +local notation "level" => selectedLevel B f hf X c sel +local notation "heads" => PortRefresh.TraversalHeaders.HeadBank +local notation "data" => packed w start X.positions +local notation "trace" => log data 0 X.positions + +/-- Metadata offsets six through eleven name the six words of the +physical preimage directory, in the order used by the DFS handler. -/ +theorem metadata_values (m : Memory w) (dH : ℕ) + (entry : LevelFields.Entry L (first) pub st m) + (header : LevelFields.Published L (cur) level dH m) + (pointers : heads L (cur) (level).oldSlots m) + (room : levelStart L (cur) + 66 ≤ 2 ^ w) : + let vals := BlockMetadata.fieldExprs (L).shape S.steps B.recordLimit (slotDegree S) + (.refresh S.steps (BlockProgram.arena B S.steps 4)) + let ev := fun j : Fin 12 => (vals j).eval pub st m + ev 6 = data 0 ∧ ev 7 = data 2 ∧ ev 8 = data 1 ∧ ev 9 = data 3 ∧ ev 10 = data 5 ∧ + ev 11 = data 4 := by + intro vals ev + have n := (LevelFields.eval_dimensions entry header).1 + have a : (BlockProgram.arena B S.steps 4).eval pub st m = (start : Word w) := + (LevelFields.eval_scalar entry S.steps 64 (by omega)).trans (pointers.tables (4 : Fin 6)) + refine ⟨n, n, a, ?_, ?_, rfl⟩ + · change (BlockProgram.arena B S.steps 4).eval pub st m + + (LevelFields.sites S.steps).eval pub st m = ((start + X.positions : ℕ) : Word w) + rw [a, n, Nat.cast_add] + · change (BlockProgram.arena B S.steps 4).eval pub st m + + (LevelFields.sites S.steps).eval pub st m + (LevelFields.sites S.steps).eval pub st m = + ((start + 2 * X.positions : ℕ) : Word w) + rw [a, n, Nat.cast_add, Nat.cast_mul, Nat.cast_ofNat]; ring + +/-- The online group uses the complete native scan. In its output memory the +traversal can read the chosen term's directory with the exact packed bases. +The frame states which cells are available to every subsequent group. -/ +theorem install (cap : ℕ) (m : Memory w) (live : t < blocks) (size : X.positions ≤ positions) + (fit : endAddress L < 2 ^ w) (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m (pub 1 - 1).val = (levelWords L : Word w)) (clock : scanCap scr 13 ≤ cap) + (dH : ℕ) (header : LevelFields.Published L (cur) level dH m) + (pointers : heads L (cur) (level).oldSlots m) : + ∃ ps : List (SourceOnline.Packet scr w), + Group scr L base cap ((scr).initial.length + t * (scr).block.length + (W).before.length) + (directoryRows L) m ps ∧ + ps.map (fun p => p.stage.phase) = (W).indices ∧ + ps.flatMap SourceWalk.Packet.reports = trace ∧ + (∃ dir : LevelDirectory level (post m ps) (levelStart L (cur + 1)), + dir.pub = data) ∧ + LevelFields.Published L (cur) level dH (post m ps) ∧ + heads L (cur) (level).oldSlots (post m ps) ∧ + (∀ x, x < start ∨ start + 3 * X.positions ≤ x → post m ps x = m x) := by + obtain ⟨endBound, nextFit⟩ := space B base positions blocks t size live fit + have fit₃ := endBound.trans_lt nextFit + have hdrFit := PublishedHeads.level_room B base positions blocks t S.steps live le_rfl fit + have entry : LevelFields.Entry L (first) pub st m := ⟨rfl, pitch⟩ + have sites := (LevelFields.eval_dimensions entry header).1 + have arena : (BlockProgram.arena B S.steps 4).eval pub st m = (start : Word w) := + (LevelFields.eval_scalar entry S.steps 64 (by omega)).trans (pointers.tables (4 : Fin 6)) + have rawRun := raw B base positions blocks t X.positions m entry hdrFit fit₃ sites arena + have rawWalk : SourceWalk (Window.Raw (A := scr) L base t 13) [V] m trace := by + simpa only [List.append_nil] using SourceWalk.next rawRun (SourceWalk.done _) + have budgets (j : Fin (scr).size) : + ((scr).plan.recipes j).2.code.length + 1 + 2 * Online.N (scr).size (scr).size + 5 ≤ cap ∧ + 13 + 3 + 4 * (((scr).catalog j).params + 1) + 2 * Online.N (scr).size (scr).size + 5 ≤ + cap := by + let p := HeaderPacket.attach scr j pub st m 13 (List.replicate X.positions []) + exact SourceOnline.scanCap_clocks (p := ⟨p, m, []⟩) 13 le_rfl clock + obtain ⟨ps, group, phases, logs⟩ := (W).group L base t rfl rfl + ((levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit) cap 13 m trace rawWalk rows pitch + (PublishedHeads.windowLive B base positions blocks t W live) + (fun j _ => (budgets j).1) (fun j _ => (budgets j).2) + have same : post m ps = after m (eventLog trace) := by rw [post, logs] + have access := packed_log_access fit₃ (Nat.zero_add X.positions).le + have frame (x : ℕ) (outside : x < start ∨ start + 3 * X.positions ≤ x) : + post m ps x = m x := by + rw [same] + exact after_outside _ access.2 (by omega) + have old (n : ℕ) (hn : n < levelHeaderWords L) : + post m ps (levelStart L (cur) + n) = m (levelStart L (cur) + n) := by + apply frame _ (.inl ?_) + unfold tableBase arrayBase incidenceStart; omega + have len : levelHeaderWords L = 66 := rfl + have kept : LevelFields.Published L (cur) level dH (post m ps) := + ⟨header.room, (old 0 (by omega)).trans header.vertices, (old 1 (by omega)).trans header.degree, + (old 2 (by omega)).trans header.lanes, (old 3 (by omega)).trans header.residual, + (old 4 (by omega)).trans header.nextDegree, (old 5 (by omega)).trans header.expander⟩ + refine ⟨ps, group, phases, logs, ?_, kept, pointers.keep old, frame⟩ + rw [same] + have one : 1 < 2 ^ w := by omega + obtain ⟨h₀, _, h₂, _, h₄, h₅⟩ := packed_values fit₃ one + exact ⟨directory f hf X c sel data m (levelStart L (cur + 1)) (packed_regions fit₃) h₀ h₂ h₄ + (by rw [h₅, h₂]; omega), rfl⟩ + +end CompressorRecords.RefreshPlacement + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementResults.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementResults.lean new file mode 100644 index 0000000000..810881b406 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementResults.lean @@ -0,0 +1,111 @@ +import OAI.Computability.VPVNP.CompressorRefreshPlacementPacket +import OAI.Computability.VPVNP.CompressorSelectedDirectoryEmission +import OAI.Computability.VPVNP.CompressorSelectedChildDirectory + +/-! +# Readback of the refresh placement and publication packets + +The placement and metadata reports publish the selected directory, child +operands and traversal geometry. The final two windows add the term and +successor pointers while retaining the published words. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshPlacement + +open BurstRAM BlockPlanner Compression DescriptorSpace Schedule PhaseRecipe SourceOnline +open SelectedDirectoryHistory PairSimulation.TraversalRows SourceTransport +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable {g w : ℕ} (base : Word w) (positions blocks t cap : ℕ) +variable (f : B.Entry → R) (hf : B.IsSolution f) (X : State S.portExponent (S.portExponent + g)) +variable (c : Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) + +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "first" => Script.levelsPerBlock scr * t +local notation "cur" => (first) + S.steps +local notation "head" => levelStart L (cur) +local notation "nextHead" => levelStart L (cur + 1) +local notation "start" => tableBase L (cur) (4 : Fin 6) +local notation "level" => selectedLevel B f hf X c sel +local notation "data" => packed w start X.positions +local notation "W₃" => BlockGroups.refresh B 3 +local notation "W₄" => BlockGroups.refresh B 4 +local notation "W₅" => BlockGroups.refresh B 5 +local notation "W₆" => BlockGroups.refresh B 6 +local notation "off" => List.length (Script.initial scr) + t * List.length (Script.block scr) + +/-- Exact frame of the singleton scan and its three metadata publications. -/ +def OutsideMetadata (n x : ℕ) : Prop := + (x < start ∨ start + 3 * n ≤ x) ∧ (x < head + 15 ∨ head + 27 ≤ x) ∧ + x ≠ nextHead + 14 ∧ x ≠ nextHead + 27 + +set_option maxHeartbeats 1200000 in +/-- The two consecutive windows have filled a directory and published its +header. The physical directory ends before the successor header. -/ +structure MetadataResult (m : Memory w) (ps : List (Packet scr w)) : Prop where + group : SourceOnline.Group scr L base cap (off + (W₃).before.length) (directoryRows L) m ps + phases : ps.map (fun p => p.stage.phase) = (W₃).indices ++ (W₄).indices + charge : RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) = + 4 * X.positions + 17 + emits : ∃ e : Emission L (cur) level m (post m ps), e.dir.pub = data + recordWords : post m ps (head + 15) = ((B.recordLimit + 2 : ℕ) : Word w) + geometry : ∀ (n newRows : ℕ), m (levelStart L 0 + 29) = (n : Word w) → + PortRefresh.TraversalHeaders.HeadBank L (cur + 1) newRows m → + PortRefresh.TraversalHeaders.Geometry (Fintype.card X.Base) g head nextHead (arrayBase L (cur)) + ⟨n, PairSimulation.NodeArguments.frameStride (slotDegree S) n⟩ + (packedIncidence L w (cur) (level).oldSlots) (packedIncidence L w (cur + 1) newRows) + (post m ps) + child : ∀ n : ℕ, m (levelStart L 0+29) = (n : Word w) → + SelectedChildDirectory.Stored B L (cur) n X (post m ps) + tapes : ps.flatMap (fun p => p.stage.choices) = List.replicate (X.positions+3) [] + frame : ∀ x, OutsideMetadata B base positions blocks t X.positions x → post m ps x = m x + +local notation "shape" => RefreshBlockPlan.shape B +local notation "arena" => arrayBase L (cur) +local notation "tmp" => PortRefresh.Allocation.plan X (S.degreeExponent 0) + (PortRefresh.LevelRecipe.Shape.dH shape) (PortRefresh.LevelRecipe.Shape.ties shape) + (PortRefresh.LevelRecipe.Shape.stride shape) arena + +set_option maxHeartbeats 1200000 in +/-- Readback and source-group accounting for all four trailing windows. -/ +structure TailResult (m : Memory w) (ps : List (Packet scr w)) : Prop where + group : SourceOnline.Group scr L base cap (off + (W₃).before.length) (directoryRows L) m ps + phases : ps.map (fun p => p.stage.phase) = + ((W₃).indices ++ (W₄).indices) ++ ((W₅).indices ++ (W₆).indices) + charge : RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) = + 4 * X.positions + 27 + emits : ∃ e : Emission L (cur) level m (post m ps), e.dir.pub = data + termHead : post m ps (head + 36) = ((tmp).term : Word w) + termStride : post m ps (head + 37) = ((shape).stride : Word w) + side : post m ps (head + 38) = 0 + absolute : post m ps (head + 39) = 0 + successorHead : post m ps (head + 40) = (nextHead : Word w) + recordWords : post m ps (head + 15) = ((B.recordLimit + 2 : ℕ) : Word w) + geometry : ∀ (n newRows : ℕ), m (levelStart L 0 + 29) = (n : Word w) → + PortRefresh.TraversalHeaders.HeadBank L (cur + 1) newRows m → + PortRefresh.TraversalHeaders.Geometry (Fintype.card X.Base) g head nextHead (arrayBase L (cur)) + ⟨n, PairSimulation.NodeArguments.frameStride (slotDegree S) n⟩ + (packedIncidence L w (cur) (level).oldSlots) (packedIncidence L w (cur + 1) newRows) + (post m ps) + child : ∀ n : ℕ, m (levelStart L 0+29) = (n : Word w) → + SelectedChildDirectory.Stored B L (cur) n X (post m ps) + tapes : ps.flatMap (fun p => p.stage.choices) = List.replicate (X.positions+8) [] + frame : ∀ x, OutsideMetadata B base positions blocks t X.positions x → + (x < head + 36 ∨ head + 41 ≤ x) → post m ps x = m x + +end CompressorRecords.RefreshPlacement + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementRows.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementRows.lean new file mode 100644 index 0000000000..6ef7bdf8e1 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementRows.lean @@ -0,0 +1,214 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleLists +import OAI.Computability.VPVNP.CompressorRecordsSchedule +import OAI.Computability.VPVNP.CompressorSourceTransport + +/-! +# Physical immediate-preimage rows of a degree refresh + +The promoted port keeps its old site ordinal. One reset call per site +writes its owner, the singleton list length and the old identifier in +the corresponding child row. The resulting tables feed the same traversal +reader as the shrinking placement tables. The scan initializes each live +cell explicitly, irrespective of its initial contents. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshPlacement + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Three public array bases, each with a unit stride. -/ +def code : List (Op 4 3) := + [.stateWord 0,.constant 1 1, + .publicWord 2 0,.binary .add 2 2 0,.write 2 0, + .publicWord 2 1,.binary .add 2 2 0,.write 2 1, + .publicWord 2 2,.binary .add 2 2 0,.write 2 0, + .binary .add 0 0 1] + +/-- Scheduled worker that writes one promoted site's owner, singleton preimage length and child +identifier from its cursor. -/ +def worker : Schedule.Pass := ⟨_,_,_,template code 0⟩ + +/-- Select the three destination heads from operand positions one, three and five of the +refresh placement packet. -/ +def bank (p : Fin 6 → Word w) : Fin 3 → Word w := ![p 1,p 3,p 5] + +/-- Word address of one site's entry in the selected owner, length or child array. -/ +def cell (p : Fin 6 → Word w) (c : Fin 3) (i : Word w) : Word w := bank p c + i + +/-- Value written for this site. The owner and sole child receive its ordinal, and the preimage +length receives one. -/ +def value (c : Fin 3) (i : Word w) := if c = 1 then 1 else i + +/-- Exact private ticks and three external writes that install the singleton preimage row at +cursor i. -/ +def events (p : Fin 6 → Word w) (i : Word w) : List (Event w) := + [.tick,.tick,.tick,.tick,.write (cell p 0 i) i,.tick,.tick,.write (cell p 1 i) 1, + .tick,.tick,.write (cell p 2 i) i,.tick] + +/-- The placement worker's write trace and its returned successor cursor i+1. -/ +def report (p : Fin 6 → Word w) (i : Word w) : Report w := ⟨events p i,some (i+1)⟩ + +theorem native (p : Fin 6 → Word w) (m : Memory w) (i : Word w) : + let M := worker.table.instantiate w (bank p) + execute M.program 13 (M.program.start i) m [] = some (report p i) := by + let M := (template code 0).instantiate w (bank p) + change execute M.program (1+code.length) ⟨M.entry,i,fun _ => 0,fun _ => 0⟩ m [] = _ + rw [execute_template,run_eq_trace] + simp (config := {decide := true}) [code,trace,Op.effect,BinaryOp.eval,report,events,cell,bank,Function.update] + +/-- Consecutive placement reports for the indicated number of sites, starting at cursor k. -/ +def log (p : Fin 6 → Word w) (k : ℕ) : ℕ → List (Report w) + | 0 => [] + | n+1 => report p (Fin.ofNat _ k) :: log p (k+1) n + +theorem run (p : Fin 6 → Word w) (k n : ℕ) (m : Memory w) : + runSegment (worker.table.instantiate w (bank p)).program 13 (some (Fin.ofNat _ k)) m + (List.replicate n []) = some (log p k n) := by + induction n generalizing k m with + | zero => rfl + | succ n ih => + rw [List.replicate_succ,runSegment,native] + change (runSegment _ _ (some ((Fin.ofNat (2^w) k)+1)) _ _).map _ = _ + rw [show ((Fin.ofNat (2^w) k)+1) = Fin.ofNat _ (k+1) from by apply Fin.ext; simp [Fin.val_add]] + rw [ih]; rfl + +theorem cost (p : Fin 6 → Word w) (k n : ℕ) : + (log p k n).length = n ∧ RAMBuckets.cost Report.probes (log p k n) = 4*n ∧ + ∀ r ∈ log p k n, r.events.length+1 = 13 ∧ r.probes = 3 := by + induction n generalizing k with + | zero => simp [log,RAMBuckets.cost] + | succ n ih => + obtain ⟨h₁,h₂,h₃⟩ := ih (k+1) + refine ⟨by rw [log,List.length_cons,h₁],?_,?_⟩ + · change 1+3+RAMBuckets.cost Report.probes (log p (k+1) n) = _ + rw [h₂,Nat.mul_succ]; omega + · intro r hr + rcases List.mem_cons.mp hr with rfl | h + · exact ⟨rfl,rfl⟩ + · exact h₃ _ h + +private theorem bounds {p : Fin 6 → Word w} {N : ℕ} (reg : RowRegions p) + (h₀ : (p 0).val = N) (h₂ : (p 2).val = N) (h₄ : (p 4).val = 1) (c : Fin 3) : + (bank p c).val+N ≤ 2^w := by + obtain ⟨hc,hr,hf⟩ := reg + rw [h₀] at hc; rw [h₂] at hr; rw [h₂,h₄,Nat.mul_one] at hf + fin_cases c + · change (p 1).val+N ≤ _; omega + · change (p 3).val+N ≤ _; omega + · change (p 5).val+N ≤ _; omega + +private theorem cell_val {p : Fin 6 → Word w} {N : ℕ} (reg : RowRegions p) + (h₀ : (p 0).val = N) (h₂ : (p 2).val = N) (h₄ : (p 4).val = 1) + (c : Fin 3) (i : ℕ) (hi : i fin_cases d <;> simp [bank] <;> omega + +private theorem saved (p : Fin 6 → Word w) (m : Memory w) (i : Word w) (j : ℕ) + (h : ∀ c, j ≠ (cell p c i).val) : after m (events p i) j = m j := by + simp [after,events,update,writeMemory,h] + +private theorem written {p : Fin 6 → Word w} {N : ℕ} (reg : RowRegions p) + (h₀ : (p 0).val = N) (h₂ : (p 2).val = N) (h₄ : (p 4).val = 1) + (m : Memory w) (i : ℕ) (hi : i simp (config := {decide := true}) [after,events,update,writeMemory,value,heq'] + +private theorem scan_fields {p : Fin 6 → Word w} {N : ℕ} (reg : RowRegions p) + (h₀ : (p 0).val = N) (h₂ : (p 2).val = N) (h₄ : (p 4).val = 1) (m : Memory w) + (k n : ℕ) (hk : k+n ≤ N) : + let out := after m (eventLog (log p k n)) + (∀ i, k ≤ i → i < k+n → ∀ c, out (cell p c (Fin.ofNat _ i)).val = value c (Fin.ofNat _ i)) ∧ + (∀ addr, (∀ i, k ≤ i → i < k+n → ∀ c, addr ≠ (cell p c (Fin.ofNat _ i)).val) → out addr = m addr) := by + induction n generalizing k m with + | zero => exact ⟨fun i h h' => by omega,fun _ _ ↦ rfl⟩ + | succ n ih => + let mid := after m (events p (Fin.ofNat _ k)) + have hs := ih mid (k+1) (by omega) + intro out + change (∀ i, _ → _ → ∀ c, after mid (eventLog (log p (k+1) n)) _ = _) ∧ + ∀ addr, _ → after mid (eventLog (log p (k+1) n)) addr = _ + constructor + · intro i hi hj c + rcases eq_or_lt_of_le hi with rfl | hgt + · rw [hs.2] + · exact written reg h₀ h₂ h₄ m _ (by omega) c + · intro j hj₁ hj₂ d he + have same := (unique reg h₀ h₂ h₄ (by omega) (by omega)).mp he + omega + · exact hs.1 i hgt (by omega) c + · intro addr ha + rw [hs.2 addr (fun i hi hj c ↦ ha i (by omega) (by omega) c)] + exact saved p m _ _ (ha k le_rfl (by omega)) + +private theorem preimage_singleton {N : ℕ} (hN : N ≤ 2^w) (v : Word w) (hv : v.val have hm := (mem v).2 rfl; simp [h] at hm + | cons x xs => + have hx := (mem x).1 (by simp [h]); subst x + cases xs with + | nil => rfl + | cons y ys => + have hy := (mem y).1 (by simp [h]); subst y + rw [h,List.pairwise_cons] at pair + exact (lt_irrefl _ (pair.1 v (by simp))).elim + +/-- The post-memory has the complete ordered list at each new identifier, +and every address outside the three placement arrays keeps its old value. -/ +theorem collected {p : Fin 6 → Word w} {N : ℕ} (reg : RowRegions p) + (h₀ : (p 0).val = N) (h₂ : (p 2).val = N) (h₄ : (p 4).val = 1) (m : Memory w) : + let out := after m (eventLog (log p 0 N)) + PreimagesAt p id out N ∧ + ∀ addr, (∀ i < N, ∀ c, addr ≠ (cell p c (Fin.ofNat _ i)).val) → out addr = m addr := by + intro out + obtain ⟨fields,keep⟩ := scan_fields reg h₀ h₂ h₄ m 0 N (by omega) + simp only [Nat.zero_add] at fields keep + refine ⟨⟨?_,?_⟩,fun addr h ↦ keep addr (fun i _ hi ↦ h i hi)⟩ + · intro i hi + have h := fields i.val (Nat.zero_le _) ((show i.val < (p 0).val from hi).trans_eq h₀) 0 + simpa [ownerAt,cell,bank,value,Fin.ofNat_eq_cast,Fin.cast_val_eq_self] using h + · intro i hi + have h := (show i.val < (p 2).val from hi).trans_eq h₂ + have hcap : p 4 = 1 := Fin.ext (h₄.trans (Nat.mod_eq_of_lt (h₄ ▸ (p 4).isLt)).symm) + have hcount := fields i.val (Nat.zero_le _) h 1 + have hrow := fields i.val (Nat.zero_le _) h 2 + simp only [Fin.ofNat_eq_cast,Fin.cast_val_eq_self] at hcount hrow + rw [preimage_singleton (h₂ ▸ (p 2).isLt.le) i h] + refine ⟨?_,?_⟩ + · change (out (cell p 1 i).val).val = 1 + change out (cell p 1 i).val = 1 at hcount + rw [hcount]; exact Nat.mod_eq_of_lt (h₄.ge.trans_lt (p 4).isLt) + · intro z + have hz : z.val = 0 := Nat.eq_zero_of_le_zero (Nat.le_of_lt_succ (show z.val < 1 from z.isLt)) + simpa [rowAt,hcap,hz,cell,bank,value] using hrow + +end CompressorRecords.RefreshPlacement + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementTrace.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementTrace.lean new file mode 100644 index 0000000000..994890f550 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPlacementTrace.lean @@ -0,0 +1,159 @@ +import OAI.Computability.VPVNP.CompressorRefreshPlacementRows +import OAI.Computability.VPVNP.CompressorLogAccess +import OAI.Computability.VPVNP.CompressorScanProgress + +/-! +# Packed placement arrays and the native degree - refresh trace + +The owner, count and singleton preimage columns occupy three consecutive arrays. +Each source report writes the three cells of its ordinal and returns the next +ordinal. Thus a complete scan writes every address in the placement arena. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshPlacement + +open BurstRAM SourceTransport +open scoped Fin.CommRing + +/-- Sizes and addresses of the three packed placement columns. -/ +def packed (w start N : ℕ) : Fin 6 → Word w := + ![N, start, N, (start + N : ℕ), 1, (start + 2 * N : ℕ)] + +private theorem packed_fields {w start N : ℕ} (fit : start + 3 * N < 2 ^ w) : + (packed w start N 0).val = N ∧ (packed w start N 1).val = start ∧ + (packed w start N 2).val = N ∧ (packed w start N 3).val = start + N ∧ + (packed w start N 4).val = 1 % (2 ^ w) ∧ (packed w start N 5).val = start + 2 * N := by + have a : start < 2 ^ w := by omega + have b : N < 2 ^ w := by omega + have c : start + N < 2 ^ w := by omega + have d : start + 2 * N < 2 ^ w := by omega + exact ⟨Nat.mod_eq_of_lt b,Nat.mod_eq_of_lt a,Nat.mod_eq_of_lt b,Nat.mod_eq_of_lt c, + rfl,Nat.mod_eq_of_lt d⟩ + +theorem packed_values {w start N : ℕ} (fit : start + 3 * N < 2 ^ w) (one : 1 < 2 ^ w) : + (packed w start N 0).val = N ∧ (packed w start N 1).val = start ∧ + (packed w start N 2).val = N ∧ (packed w start N 3).val = start + N ∧ + (packed w start N 4).val = 1 ∧ (packed w start N 5).val = start + 2 * N := by + simpa only [Nat.mod_eq_of_lt one] using packed_fields fit + +theorem packed_regions {w start N : ℕ} (fit : start + 3 * N < 2 ^ w) : + RowRegions (packed w start N) := by + obtain ⟨h₀,h₁,h₂,h₃,h₄,h₅⟩ := packed_fields fit + constructor + · rw [h₀,h₁,h₃] + · rw [h₂,h₃,h₅]; omega + · rw [h₂,h₄,h₅] + have h := Nat.mul_le_mul_left N (Nat.mod_le 1 (2 ^ w)) + omega + +theorem packed_cell_val {w start N : ℕ} (fit : start + 3 * N < 2 ^ w) + (c : Fin 3) {i : ℕ} (hi : i < N) : + (cell (packed w start N) c (Fin.ofNat _ i)).val = start + c.val * N + i := by + obtain ⟨_,h₁,_,h₃,_,h₅⟩ := packed_fields fit + have base : (bank (packed w start N) c).val = start + c.val * N := by + fin_cases c <;> simp [bank,h₁,h₃,h₅] + have room : start + c.val * N + i < 2 ^ w := by + have h := Nat.mul_le_mul_right N (show c.val ≤ 2 from by omega) + omega + rw [cell,Fin.val_add,base,Fin.val_ofNat,Nat.mod_eq_of_lt (by omega : i < 2 ^ w), + Nat.mod_eq_of_lt room] + +theorem log_scanned {w : ℕ} (p : Fin 6 → Word w) (k n : ℕ) : + StageFrame.Scanned k (k + n) (log p k n) := by + induction n generalizing k with + | zero => exact .done k + | succ n ih => + apply StageFrame.Scanned.next (by omega) + · change some ((k : Word w) + 1) = some ((k + 1 : ℕ) : Word w) + rw [Nat.cast_add_one] + · rw [show k + (n + 1) = k + 1 + n by omega] + exact ih (k + 1) + +theorem log_progress {w : ℕ} (p : Fin 6 → Word w) (k n : ℕ) (fit : k + n < 2 ^ w) : + SourceOnline.Progress ((k + n : ℕ) : Word w) (k : Word w) (log p k n) := + (log_scanned p k n).toProgress fit + +theorem log_reads {w : ℕ} (p : Fin 6 → Word w) (k n : ℕ) : + Reads (fun _ ↦ False) (eventLog (log p k n)) := by + induction n generalizing k with + | zero => intro a v h; exact List.not_mem_nil h + | succ n ih => + intro a v h + rcases List.mem_append.mp h with head | tail + · simp [report,events] at head + · exact ih (k + 1) a v tail + +private theorem write_events_iff {w : ℕ} (p : Fin 6 → Word w) (i a v : Word w) : + Event.write a v ∈ events p i ↔ ∃ c : Fin 3, a = cell p c i ∧ v = value c i := by + constructor + · intro h + simp only [events, List.mem_cons, List.not_mem_nil, or_false, reduceCtorEq, false_or, + Event.write.injEq] at h + rcases h with h | h | h + · exact ⟨0,h.1,h.2.trans (by simp [value])⟩ + · exact ⟨1,h.1,h.2.trans (by simp [value])⟩ + · exact ⟨2,h.1,h.2.trans (by simp [value])⟩ + · rintro ⟨c,rfl,rfl⟩ + fin_cases c <;> simp [events,value] + +/-- An address - value pair is written precisely when it is the cell and payload of +one of the three columns at a visited ordinal. -/ +theorem log_write_iff {w : ℕ} (p : Fin 6 → Word w) (k n : ℕ) (a v : Word w) : + Event.write a v ∈ eventLog (log p k n) ↔ + ∃ i, k ≤ i ∧ i < k + n ∧ ∃ c : Fin 3, + a = cell p c (Fin.ofNat _ i) ∧ v = value c (Fin.ofNat _ i) := by + induction n generalizing k with + | zero => + simp only [log,eventLog,List.flatMap_nil,List.not_mem_nil,Nat.add_zero,false_iff] + rintro ⟨i,hi,hj,_⟩ + omega + | succ n ih => + change Event.write a v ∈ events p (Fin.ofNat _ k) ++ eventLog (log p (k + 1) n) ↔ _ + rw [List.mem_append,write_events_iff,ih] + constructor + · rintro (h | ⟨i,h₁,h₂,h⟩) + · exact ⟨k,le_rfl,by omega,h⟩ + · exact ⟨i,by omega,by omega,h⟩ + · rintro ⟨i,h₁,h₂,h⟩ + rcases eq_or_lt_of_le h₁ with rfl | hlt + · exact Or.inl h + · exact Or.inr ⟨i,hlt,by omega,h⟩ + +theorem packed_log_access {w start N k n : ℕ} (fit : start + 3 * N < 2 ^ w) (range : k + n ≤ N) : + LogAccess (fun _ ↦ False) (fun x ↦ start ≤ x ∧ x < start + 3 * N) + (log (packed w start N) k n) := by + refine ⟨log_reads _ _ _,?_⟩ + intro a v h + obtain ⟨i,_,hi,c,rfl,_⟩ := (log_write_iff _ _ _ _ _).mp h + rw [packed_cell_val fit c (hi.trans_le range)] + have hc := Nat.mul_le_mul_right N (show c.val ≤ 2 from by omega) + omega + +/-- Every cell of the full arena occurs as a genuine native write. -/ +theorem packed_written_iff {w start N : ℕ} (fit : start + 3 * N < 2 ^ w) (a : Word w) : + (∃ v, Event.write a v ∈ eventLog (log (packed w start N) 0 N)) ↔ + start ≤ a.val ∧ a.val < start + 3 * N := by + constructor + · rintro ⟨v,h⟩ + exact (packed_log_access fit (Nat.zero_add N).le).2 a v h + · rintro ⟨ha,hb⟩ + have hit (c : Fin 3) (i : ℕ) (hi : i < N) (addr : a.val = start + c.val * N + i) : + ∃ v, Event.write a v ∈ eventLog (log (packed w start N) 0 N) := by + refine ⟨value c (Fin.ofNat _ i), (log_write_iff _ _ _ _ _).mpr + ⟨i,Nat.zero_le _,by omega,c,Fin.ext ?_,rfl⟩⟩ + exact addr.trans (packed_cell_val fit c hi).symm + by_cases h₀ : a.val < start + N + · exact hit 0 (a.val - start) (by omega) (by simp; omega) + by_cases h₁ : a.val < start + 2 * N + · exact hit 1 (a.val - (start + N)) (by omega) (by simp; omega) + · exact hit 2 (a.val - (start + 2 * N)) (by omega) (by simp; omega) + +end CompressorRecords.RefreshPlacement + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshPrepareGroup.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshPrepareGroup.lean new file mode 100644 index 0000000000..a6e9a49b31 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshPrepareGroup.lean @@ -0,0 +1,168 @@ +import OAI.Computability.VPVNP.CompressorRefreshCoreBuild +import OAI.Computability.VPVNP.CompressorRefreshBeforeSelector + +/-! +# Native refresh prefix before reading the selected term + +The gather, bundle, offset and demand scans execute from the current graph +with empty choice tapes. They produce the numerical input to the motif +worker even when the caller has not selected a term. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +set_option quotPrecheck false + +namespace CompressorRecords.RefreshPrepare + +open BurstRAM BlockPlanner Schedule DescriptorSpace Compression Compression.DegreeRefresh +open Compression.Refresh +open PortRefresh PortRefresh.Allocation PortRefresh.LevelRecipe SourceTransport SourceOnline +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {w g : ℕ} (base : BurstRAM.Word w) (positions blocks t : ℕ) +variable (X : State S.portExponent (S.portExponent + g)) + +local notation "s₀" => RefreshBlockPlan.shape B +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "cur" => Script.levelsPerBlock scr * t + S.steps +local notation "start" => arrayBase L cur +local notation "P" => plan X (S.degreeExponent 0) (s₀).dH (s₀).ties (s₀).stride start +local notation "ties" => RefreshBlockPlan.order B +local notation "hC" => (S.port_bound.connected_and_pos S.port_order).1 +local notation "hE" => Nat.two_pow_pos S.expanderExponent +local notation "N" => X.positions * 2 ^ S.portExponent +local notation "old" => packedIncidence L w cur N +local notation "Q" => Plan.scratch P w +local notation "D" => NewSlots.word (bits := w) (Plan.demand P) +local notation "I" => RefreshBlockPlan.input (BlockProgram.geometry B) S.steps (0 : Fin 6) + +/-- The deterministic refresh prefix, consisting of the gather, bundle and offset scans +followed by one demand scan for each tie. -/ +def stages : List (Stage s₀) := [.gather,.bundles,.offsets] ++ (List.finRange + (s₀).ties).map Stage.demand + +/-- Refresh stages after demand preparation, in the order of term selection, supply, expander +table rows, output slots and the base scan. -/ +def rest : List (Stage s₀) := [.term,.supply] ++ (List.finRange ((s₀).ports * + (s₀).dH)).map Stage.rom + ++ + (List.finRange (s₀).degree).map Stage.slot ++ [.base] + +theorem stages_rest : stages B ++ rest B = order s₀ := by + simp only [stages,rest,order,List.append_assoc] + +/-- The actual contiguous block interval before the selector. -/ +def window : Window scr ((stages B).map (RefreshBlockPlan.stage B I)) where + before := (BlockGroups.refresh B 1).before + after := (rest B).map (RefreshBlockPlan.stage B I) ++ (BlockGroups.refresh B 1).after + block := by + have h := (BlockGroups.refresh B 1).block + change (scr).block = (BlockGroups.refresh B 1).before ++ + (order s₀).map (RefreshBlockPlan.stage B I) ++ (BlockGroups.refresh B 1).after at h + simpa only [← stages_rest B,List.map_append,List.append_assoc] using h + +/-- The reported prefix run materializes the segment fields and the actual block demand widths +in its post-memory, writes within the planned arena, uses empty choice tapes and incurs its +stated exact charge. -/ +structure Prepared (m : Memory w) (rs : List (Report w)) : Prop where + fits : (P).segments ≤ 2 ^ w + run : PrepareRun X old Q D ties (NewSlots.word (2 ^ g)) fits m (after m (eventLog rs)) rs + segments : SegmentFields X Q fits (after m (eventLog rs)) + demands : ∀ b, DemandPreparation.demandAt ties (DemandScan.rowBase X (s₀).ties D b) (after m + (eventLog rs)) = + blockDemandWidths (splitSlots X) (bitWordFinEquiv S.portExponent) (splitWidths X) b + writes : Writes (TermDataFrame.InArena P) (eventLog rs) + quiet : branchPaths rs = List.replicate rs.length [] + charge : RAMBuckets.cost Report.probes rs = 6 * (P).sites + 12 * (P).segments + 3 * (P).blocks * + (s₀).ties + +private theorem quiet {js : List (Stage s₀)} {m : Memory w} {rs : List (Report w)} {cap : ℕ} + (walk : SourceWalk (fun j mem logs ↦ + Scheduled.PreSource X S.graph hE hC B.refresh S.degree_bounds.2 ties old start + (s₀).stride cap j mem logs ∧ + Scheduled.StageBounds (t := (s₀).ties) X S.graph hE hC B.refresh start (s₀).stride + (levelStart L 0) j mem logs) js m rs) : branchPaths rs = List.replicate rs.length [] := by + have empty {logs : List (Report w)} {n : ℕ} (h : branchPaths logs = List.replicate n []) : + branchPaths logs = List.replicate logs.length [] := by + have hn : logs.length = n := by + simpa only [branchPaths,List.length_map,List.length_replicate] using congrArg List.length h + rwa [hn] + induction walk with + | done => rfl + | @next j js u xs ys h _ ih => + have head := empty (((runSegment_iff ..).mp h.1).2.2) + simpa only [branchPaths,List.map_append,List.length_append,List.replicate_add] using congrArg₂ + (· ++ ·) head ih + +set_option maxHeartbeats 900000 in +-- The demand walk is attached at dependent global indices of the actual script. +/-- Execute the complete deterministic refresh prefix without receiving a +choice. The compiled program sees the block's dense demand coordinates at +the post - memory of these exact packets. -/ +theorem install (termCap cap : ℕ) (m : Memory w) (ht : t < blocks) (size : X.positions ≤ positions) + (fit : endAddress L < 2 ^ w) (rows : m (pt).rows.val = (directoryRows L : BurstRAM.Word w)) + (pitch : m ((pt).directory - 1).val = (levelWords L : BurstRAM.Word w)) + (clock : scanCap scr (max 64 termCap) ≤ cap) + (header : RefreshCore.Header (Fintype.card X.Base) g (levelStart L cur) start old m) + (represented : (old).Represents X m) (width : 2 ^ S.portExponent * X.maxWireWidth < 2 ^ w) + (positive : 0 < termCap) : + let win := window B + ∃ ps : List (Packet scr w), SourceOnline.Group scr L base cap + ((scr).initial.length + t * (scr).block.length + win.before.length) (directoryRows L) m ps ∧ + ps.map (fun p ↦ p.stage.phase) = win.indices ∧ Prepared B base positions blocks t X m + (ps.flatMap SourceWalk.Packet.reports) := by + intro win + have idx : cur < (L).levels := by + have bound := Nat.mul_le_mul_left (S.steps + 1) ht + rw [Nat.mul_succ] at bound + change (S.steps + 1) * t + S.steps < 1 + (S.steps + 1) * blocks + omega + let current : Fin (L).levels := ⟨cur,idx⟩ + have source := RefreshCore.source_region B base positions blocks t X current rfl size fit + have room := (BlockLevelFit.refresh B base.val positions blocks current rfl X size fit).1.word + change (plan X (S.degreeExponent 0) (s₀).dH (s₀).ties (s₀).stride (start + 0 * tableWords + L)).stop < + 2 ^ w at room + simp only [Nat.zero_mul,Nat.add_zero] at room + let alloc := prepare_layout X old (S.degreeExponent 0) (s₀).dH (s₀).ties (s₀).stride start + (fun j ↦ (source j).2) room + obtain ⟨rs,run,pr,seg,dem,_,cost⟩ := Scheduled.prepare_verified X S.graph hE hC B.refresh + S.degree_bounds.2 + ties old start (s₀).stride (levelStart L 0) termCap alloc m represented (fun j ↦ (source j).1) + (fun j ↦ (source j).2) room width + have before : levelStart L cur + 60 < start := by + change levelStart L cur + 60 < levelStart L cur + 66 + 6 * slotCapacity L + omega + have Hfit := (levelStart_mono L (Nat.zero_le _)).trans_lt fit + obtain ⟨raw,wr⟩ := RefreshCore.raw_stages B X old start termCap base positions blocks t + (fun j ↦ List.replicate (j.limit X start - j.first) []) (stages B) m rs header pitch + positive room before Hfit run + have clocks (j : Fin (scr).size) := scanCap_clocks + (p := ⟨HeaderPacket.attach scr j (pt).data 0 m (max 64 termCap) [],m,[]⟩) _ le_rfl clock + have live (j : Fin ((stages B).map (RefreshBlockPlan.stage B I)).length) : + Window.ordinal (A := scr) t (win.index j) < directoryRows L := by + rw [win.ordinal_index,BlockProgram.directory_rows,(scr).calendar_total] + have pos := (win.position j).isLt + have mul := Nat.mul_le_mul_right (scr).block.length ht + rw [Nat.succ_mul] at mul + omega + obtain ⟨ps,grp,phases,logs⟩ := win.group L base t rfl rfl Hfit cap (max 64 termCap) m rs raw + rows pitch live (fun j _ ↦ (clocks j).1) (fun j _ ↦ (clocks j).2) + refine ⟨ps,grp,phases,?_⟩ + rw [logs] + exact ⟨alloc.regions.fits,pr,seg,dem,wr,quiet B base positions blocks t X run,cost⟩ + +end CompressorRecords.RefreshPrepare + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshResidentAdvance.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshResidentAdvance.lean new file mode 100644 index 0000000000..6649dd4027 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshResidentAdvance.lean @@ -0,0 +1,130 @@ +import OAI.Computability.VPVNP.CompressorRefreshPayloadCapture +import OAI.Computability.VPVNP.CompressorCompiledResident +import OAI.Computability.VPVNP.CompressorSelectedPayloadFrames + +/-! +# Advancing the resident history through a selected refresh + +The header substep publishes the successor scalars and pointers. The native +core, copies and placement fill the graph, directory and selected payload. +Their shared output is the resident memory for the next pass. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RefreshPayloadHistory + +open BurstRAM BlockPlanner BlockHeaderRun Compression DescriptorSpace PortRefresh +open SourceOnline SelectedPayloadHistory SelectedDirectoryHistory +open PairSimulation.TraversalRoles +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable {g w : ℕ} (base : Word w) (positions blocks t : ℕ) +variable (f : B.Entry → R) (hf : B.IsSolution f) (X : State S.portExponent (S.portExponent+g)) +variable (c : Refresh.DyadicRefreshChoice (a₀ := S.degreeExponent 0) (g := g) X S.graph + (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (sel : List Bool) + +local notation "lev" => RefreshPlacement.selectedLevel B f hf X c sel +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "cur" => Script.levelsPerBlock scr*t+S.steps +local notation "nxt" => cur+1 +local notation "head" => levelStart L cur +local notation "nextHead" => levelStart L nxt +local notation "start" => arrayBase L cur +local notation "Y" => Refresh.dyadicRefreshNext X S.graph (Nat.two_pow_pos _) + (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh S.port_order (And.right S.degree_bounds) c + +set_option maxHeartbeats 1600000 in +/-- Append the selected refresh to the physical directory, current graph +and payload snapshots, using the reports from all seven groups. -/ +theorem advance {cap termCap n : ℕ} {initial : TaggedLayer} {initialFrame : Fin 8 → Word w} + {past : List (SelectedLevel B f hf)} {before m : Memory w} {core copy : List (Report w)} + {tail : List (Packet scr w)} (old new : Fin (L).levels) + (oldAt : old.val = cur) (newAt : new.val = nxt) (index : past.length = cur) + (live : t < blocks) (size : X.positions ≤ positions) (room : endAddress L < 2^w) + (stored : CompiledResident.resident B f hf base positions blocks n initial initialFrame past X before) + (sub : Substep lev L old new (by change 6 ≤ 54; decide) before) + (headerMemory : m = finalMemory lev L old new before) + (oldRep : (packedIncidence L w cur (lev).oldSlots).Represents X m) + (newBank : TraversalHeaders.HeadBank L nxt (lev).outputSlots m) + (built : RefreshCore.Built B base positions blocks t X c termCap m core) + (copied : RefreshCopyPackets.Copied B base positions blocks t X c (after m (eventLog core)) copy) + (installed : RefreshPlacement.TailResult B base positions blocks t cap f hf X c sel + (after (after m (eventLog core)) (eventLog copy)) tail) : + CompiledResident.resident B f hf base positions blocks n initial initialFrame + (past++[lev]) ((lev).pass.next (lev).term) (post (after (after m (eventLog core)) (eventLog copy)) tail) := by + let mid := after (after m (eventLog core)) (eventLog copy) + let out := post mid tail + have adj : old.val+1 = new.val := by omega + have space := Space.ofLayout B base positions blocks t X live size room + have hdr := space.header_before + have high := space.array_before + have placeEnd := space.placement_before + have nextInc : incidenceStart L nxt = nextHead+66 := rfl + have lowFirst : levelStart L 0+29 < head := by + have firstLevel : 1 ≤ cur := by have := S.steps_pos; omega + have span : levelStart L 0+29 < levelStart L 1 := by + change levelsBase L + 0*levelWords L + 29 < levelsBase L + 1*levelWords L + have width : 29 < levelWords L := by change 29 < 66 + _ + _; omega + omega + exact span.trans_le (levelStart_mono L firstLevel) + have coreFrame := core_copy_frame B base positions blocks t X c space built copied + have len : m (levelStart L 0+29) = (n : Word w) := by + rw [headerMemory,sub.firstScalarTail lev adj 29 (by decide) (by change 29 < 54; decide)] + exact (Fin.cast_val_eq_self _).symm.trans (congrArg (fun z : ℕ => (z : Word w)) stored.1.2.1.startup.length) + have midLen := (coreFrame _ (.inl (by omega : levelStart L 0+29 < start))).trans len + obtain ⟨captured,below,oldGraph⟩ := capture B base positions blocks t f hf X c sel + live size room oldRep len newBank built copied installed + have hframe : InputFrame L cur before m := by + rw [headerMemory,← oldAt] + exact InputFrame.substep sub adj + have passFrame := hframe.trans (show InputFrame L cur m out from ⟨fun x _ hi => below x hi,oldGraph⟩) + have kept (j : ℕ) (lower : 6 ≤ j) (upper : j ≤ 27) : mid (head+j) = before (head+j) := by + apply (coreFrame _ (.inl (by omega))).trans + rw [headerMemory] + apply sub.outside + · right; rw [oldAt]; omega + · left; rw [newAt]; omega + · left; rw [newAt]; change head+j < nextHead+54; omega + obtain ⟨emission,_⟩ := installed.emits + have emitted : Emission L cur lev before out := + emission.prepend (kept 14 (by decide) (by decide)) (kept 27 (by decide) (by decide)) + have currentGraph (x : ℕ) (hx : CurrentGraph.graphCell L new x ∨ CurrentGraph.startupCell L x ∨ + CurrentGraph.frameCell L x) : out x = finalMemory lev L old new before x := by + rw [← headerMemory] + rcases hx with graph | ⟨j,hj,rfl⟩ | frame + · rw [newAt] at graph + rcases graph with cell | cell + · change nextHead ≤ x ∧ x < nextHead+6 at cell + exact (installed.frame x ⟨.inr (by omega),.inr (by omega),by omega,by omega⟩ (.inr (by omega))).trans + (coreFrame x (.inr ⟨cell.1,by omega⟩)) + · change nextHead+54 ≤ x ∧ x < incidenceStart L nxt at cell + exact (installed.frame x ⟨.inr (by omega),.inr (by omega),by omega,by omega⟩ (.inr (by omega))).trans + (coreFrame x (.inr ⟨by omega,cell.2⟩)) + · simp only [List.mem_cons,List.not_mem_nil,or_false] at hj + exact below _ (by omega) + · change levelStart L 0+6 ≤ x ∧ x < levelStart L 0+14 at frame + exact below x (by omega) + have counts : IncidenceDirectory.slotCount (Y) = (Y).positions*2^(S.degreeExponent 0) := by + rw [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv g),Fintype.card_fin] + have successor := CurrentResident.append_substep (v := lev) old new (index.trans oldAt.symm) adj + stored.1 (by change 30 ≤ 54; decide) room sub (index ▸ emitted) (by + change (packedIncidence L w new (IncidenceDirectory.slotCount (Y))).Represents (Y) out + rw [newAt,counts] + exact captured.new) currentGraph (by simpa only [index] using passFrame.earlier) + apply DetailedResident.append stored successor + · rw [index] + change CompiledResident.RefreshPayload B base positions blocks n cur X c out + exact ⟨space.live,size,room,captured,installed.child n midLen⟩ + · simpa only [index] using passFrame.earlier + · simpa only [index] using passFrame.graph + +end CompressorRecords.RefreshPayloadHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshScheduledRuns.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshScheduledRuns.lean new file mode 100644 index 0000000000..4efe236032 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshScheduledRuns.lean @@ -0,0 +1,161 @@ +import OAI.Computability.VPVNP.CompressorRefreshLevelRecipe +import OAI.Computability.VPVNP.CompressorRecordRefreshBuild +import OAI.Computability.VPVNP.CompressorSourceWalk + +/-! +# Source runs of the physical degree-refresh calendar + +The external segments, internal term choice, selected supplies, expander +records and final lane-zero outputs run in order in the same memory. The +decomposition identifies every report of the complete refresh with the +corresponding finite recipe's source table, operand bank and tape. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords + +open BurstRAM Schedule Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry + +open SourceWalk (after_append) + +namespace PortRefresh.Scheduled + +open LevelRecipe NewSlots Allocation +open scoped Fin.CommRing + +variable {w a a₀ g dH t : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (c : DyadicRefreshChoice X E hdH conn F) + (ties : Fin t ≃ Tie (2^a)) (old : IncidenceDirectory w) (start stride : ℕ) + +/-- Compile the input and refreshed degree exponents, expander degree, tie count, record stride +and selector bit count into the stage recipe. -/ +abbrev shape := (⟨a,a₀,dH,t,stride,F.selectorBits⟩ : LevelRecipe.Shape) +local notation "s" => shape (t := t) E hdH conn F stride +local notation "J" => Stage s +local notation "P" => Allocation.plan X a₀ dH t stride start +local notation "term" => TermWorker.motifPass F ties (2^a*dH) +local notation "publicData" => TermWorker.motifData F ties finProdFinEquiv.symm w + +/-- Actual checked instruction budget of each worker. -/ +def fuel {shape₀ : LevelRecipe.Shape} (hd : shape₀.dH+1 ≤ shape₀.degree) (termCap : ℕ) : Stage shape₀ → ℕ + | .gather => 24 + | .bundles => 28 + | .offsets => 33 + | .demand _ => 26 + | .term => termCap + | .supply => 34 + | .rom _ => 12 + | .slot j => 1+(code (kindOf ((refreshSlots hd).symm j))).length + | .base => 29 + +/-- Actual per-block selection tapes for the term worker. Every other stage receives an empty +choice list for each cursor it scans. -/ +def tapes (j : J) : List (List Bool) := + match j with + | .term => List.ofFn (blockTapes E hdH conn F X c w) + | _ => List.replicate (j.limit X start - j.first) [] + +/-- A report sequence from this recipe's actual table, at its declared +initial cursor and using the original admitted branch. -/ +def Source (cap : ℕ) (j : J) (m : Memory w) (rs : List (Report w)) : Prop := + let data := fun z ↦ j.nativeBank hd E ties X start old publicData (Fin.cast (j.worker_params hd term) z) + let M := ((j.worker hd term).table.instantiate w data).program + runSegment M (fuel hd cap j) (some (NewSlots.word j.first)) m + (tapes (w := w) X E hdH conn F c start stride j) = some rs + +local notation "src" => Source X E hdH conn F hd c ties old start stride + +private theorem demands (cap : ℕ) {ks : List (Fin t)} {m : Memory w} {rs} + (h : DemandScan.Runs (DemandScan.words (r := 2^g) ties ((P).scratch w) (NewSlots.word (P).demand)) + (P).blocks ks m rs) : SourceWalk (src cap) (ks.map Stage.demand) m rs := by + induction h with + | nil => exact .done _ + | cons i hh ht ih => exact .next hh ih + +private theorem slots (cap : ℕ) {ks : List (Fin (2^a₀))} {m : Memory w} {rs} + (h : AllSlots.Runs (fun i ↦ kindOf ((refreshSlots hd).symm i)) + (fun i ↦ AllSlots.words (2^a) (2^g) ((P).inputs w) ((P).output w) ((refreshSlots hd).symm i)) + (P).sites ks m rs) : SourceWalk (src cap) (ks.map Stage.slot) m rs := by + induction h with + | nil => exact .done _ + | cons i hh ht ih => exact .next hh ih + +private theorem rom (cap : ℕ) (is : List (Fin (2^a*dH))) (m : Memory w) : + SourceWalk (src cap) (is.map Stage.rom) m (is.map (ExpanderROM.report E ((P).inputs w))) := by + induction is generalizing m with + | nil => exact .done _ + | cons i is ih => + change SourceWalk _ _ _ ([ExpanderROM.report E ((P).inputs w) i] ++ _) + apply SourceWalk.next _ (ih _) + change runSegment _ 12 (some (NewSlots.word i.val)) m (List.replicate (i.val+1-i.val) []) = _ + rw [show i.val+1-i.val = 1 by omega] + simp only [List.replicate_succ,List.replicate_zero,runSegment,ExpanderROM.report] + rfl + +set_option maxHeartbeats 1400000 in +/-- The complete native refresh refines the fixed ordered recipe list. -/ +theorem sources (cap : ℕ) (L : Allocation.PrepareLayout X old a₀ dH t stride start) + (m : Memory w) (rs : List (Report w)) + (h : Build.Run X E hdH conn F hD hd c ties old start stride cap L m rs) : + SourceWalk (src cap) (LevelRecipe.order s) m rs := by + obtain ⟨pre,terms,post,rfl,prep,hrTerm,finish⟩ := h + obtain ⟨rg,rd,re,ds,ext,demandsRun,_,rfl⟩ := prep + obtain ⟨hg,hb,he,_⟩ := ext + let m₀ := after (after (after m (eventLog rg)) (eventLog rd)) (eventLog re) + let m₁ := after m₀ (eventLog ds) + let m₂ := after m₁ (eventLog terms) + simp only [after_append] at finish hrTerm + obtain ⟨su,roms,os,bs,rfl,hs,hrom,ho,hbase⟩ := finish + have hw₀ : SourceWalk (src cap) [.gather,.bundles,.offsets] m (rg++rd++re) := by + rw [List.append_assoc] + exact SourceWalk.next hg (SourceWalk.next hb (SourceWalk.singleton he)) + have hw₁ := demands X E hdH conn F hd c ties old start stride cap demandsRun + have hwTerm : src cap .term m₁ terms := by + have haddr : termAddresses (NewSlots.word (bits := w) (P).demand) (NewSlots.word (bits := w) (P).term) + stride t = ![NewSlots.word (P).demand,NewSlots.word t,NewSlots.word (P).term,NewSlots.word stride] := by + funext i; fin_cases i <;> apply Fin.ext <;> simp [termAddresses,NewSlots.word] + let bank := publicData ![NewSlots.word (P).demand,NewSlots.word t,NewSlots.word (P).term,NewSlots.word stride] + have sameBank : (fun z ↦ bank (Fin.cast ((.term : J).worker_params hd term) z)) = bank := + funext fun z ↦ congrArg bank (Fin.ext rfl) + change runSegment ((term).table.instantiate w + (fun z ↦ bank (Fin.cast ((.term : J).worker_params hd term) z))).program cap (some 0) m₁ + (List.ofFn (blockTapes E hdH conn F X c w)) = some terms + have eqRun := congrArg (fun data : Fin (term).params → BurstRAM.Word w ↦ + runSegment ((term).table.instantiate w data).program cap (some 0) m₁ + (List.ofFn (blockTapes E hdH conn F X c w))) sameBank + exact eqRun.trans (by simpa only [termRun,TermWorker.program,haddr,bank] using hrTerm) + have hw₂ : SourceWalk (src cap) [.term,.supply] m₁ (terms++su) := + SourceWalk.next hwTerm (SourceWalk.singleton hs) + have hrom' := ExpanderROM.schedule_run E ((P).inputs w) 0 (after m₂ (eventLog su)) (List.finRange (2^a*dH)) + have er : roms = (List.finRange (2^a*dH)).map (ExpanderROM.report E ((P).inputs w)) := Option.some.inj (hrom.symm.trans hrom') + have hw₃ := rom X E hdH conn F hd c ties old start stride cap (List.finRange _) (after m₂ (eventLog su)) + rw [← er] at hw₃ + have hw₄ := slots X E hdH conn F hd c ties old start stride cap ho + have hsize : BaseOutput.baseCount (dyadicRefreshNext X E hdH conn F hD hd c) = + Fintype.card X.Base * 2^a * 2^a₀ := by + change Fintype.card (X.Base × Fin (2^a)) * 2^a₀ = _ + simp only [Fintype.card_prod,Fintype.card_fin] + rw [hsize] at hbase + have hw₅ : SourceWalk (src cap) [.base] _ bs := SourceWalk.singleton hbase + have htail := hw₃.append (hw₄.append hw₅) + have hmiddle := hw₂.append (by simpa only [after_append] using htail) + have hdem := hw₁.append hmiddle + have whole := hw₀.append (by simpa only [after_append] using hdem) + simpa only [LevelRecipe.order,List.append_assoc] using whole + +end PortRefresh.Scheduled +end CompressorRecords + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshSelectorInput.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshSelectorInput.lean new file mode 100644 index 0000000000..60698637b9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshSelectorInput.lean @@ -0,0 +1,78 @@ +import OAI.Computability.VPVNP.CompressorRefreshBeforeSelector +import OAI.Computability.VPVNP.CompressorRefreshBlockPlan +import OAI.Computability.VPVNP.CompressorSelectedTermWorker + +/-! +# The actual term-worker input at a refresh boundary + +The native preparation fills one demand row for each old base and residual lane. +Its physical order and term addresses give the input of the local-history +selector before any of its term bits are read. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.RefreshSelector + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PairSimulation.LocalHistory +open PortRefresh PortRefresh.LevelRecipe SelectedTerms NewSlots +open scoped Fin.CommRing +open private termInputs from OAI.Computability.VPVNP.CompressorRecordRefreshAdmitted + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f) +variable {g w : ℕ} (X : State S.portExponent (S.portExponent+g)) +local notation "O" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "sh" => RefreshBlockPlan.shape B +local notation "ord" => RefreshBlockPlan.order B +local notation "n" => Fintype.card X.Base * 2^g +local notation "d" => Shape.ties sh +local notation "stride" => Shape.stride sh +local notation "e" => (Shape.ports sh)*(Shape.dH sh) +local notation "demand" => blockDemandWidths (splitSlots X) (bitWordFinEquiv S.portExponent) (splitWidths X) + +private theorem demand_order (i : Fin n) : (PairSimulation.LocalHistory.termRows O).demand i = demand ((DemandScan.blocks X).symm i) := rfl + +/-- The two allocations and the dense demand readback generated by `prepare_verified` +supply all machine inputs of the physical selector. The instruction budget may +be any supplied cap at least as large as the motif worker's checked budget. -/ +def workerInput (source dest : BurstRAM.Word w) (sep : source.val+n*d ≤ dest.val) (room : dest.val+n*stride < 2^w) + (width : SelectedTermWorker.fitConstant B+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (cap : ℕ) (clock : TermWorker.budget B.refresh d e w X.maxWireWidth ≤ cap) (m : Memory w) + (data : ∀ s, DemandPreparation.demandAt ord (DemandScan.rowBase X d source s) m = demand s) : + WorkerInput O w := by + let layout := PortRefresh.termRows X source dest stride le_rfl sep room + let addr := PortRefresh.termAddresses source dest stride d + have hin := termInputs ord X source dest stride le_rfl sep room m data + have hi : TermRecordScan.Inputs (grid O).demandOrder.entries layout (PairSimulation.LocalHistory.termRows O).demand m := by + intro i + exact (hin i).trans (demand_order B f hf X i).symm + let W := SelectedTermWorker.input O width layout addr + (TermWorker.addresses_strided source.val dest.val d stride le_rfl le_rfl sep room) m hi + exact {W with fuel := cap, clock := clock} + +/-- Both the physical input and output of every block live above the current +controller area, even when the rows have different strides. -/ +theorem workerRows {source dest : BurstRAM.Word w} (sep : source.val+n*d ≤ dest.val) (room : dest.val+n*stride < 2^w) + (width : SelectedTermWorker.fitConstant B+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (cap : ℕ) (clock : TermWorker.budget B.refresh d e w X.maxWireWidth ≤ cap) (m : Memory w) + (data : ∀ s, DemandPreparation.demandAt ord (DemandScan.rowBase X d source s) m = demand s) : + let W := workerInput B f hf X source dest sep room width cap clock m data + ∀ i : Fin n, source.val ≤ (W.layout.source i).val ∧ dest.val ≤ (W.layout.base i).val := by + intro W i + have a := Nat.mul_le_mul_right d (Nat.le_of_lt i.isLt) + have b := Nat.mul_le_mul_right stride (Nat.le_of_lt i.isLt) + change source.val ≤ (source.val+i.val*d)%(2^w) ∧ dest.val ≤ (dest.val+i.val*stride)%(2^w) + rw [Nat.mod_eq_of_lt (by omega : source.val+i.val*d<2^w),Nat.mod_eq_of_lt (by omega : dest.val+i.val*stride<2^w)] + exact ⟨Nat.le_add_right ..,Nat.le_add_right ..⟩ + +end CompressorRecords.RefreshSelector + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshSelectorLogs.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshSelectorLogs.lean new file mode 100644 index 0000000000..83b20095ed --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshSelectorLogs.lean @@ -0,0 +1,145 @@ +import OAI.Computability.VPVNP.CompressorRefreshCoreBuild +import OAI.Computability.VPVNP.CompressorRefreshPrepareGroup +import OAI.Computability.VPVNP.CompressorCanonicalNativeTapes +import OAI.Computability.VPVNP.CompressorSourceObservableFrame + +/-! +# Exact preparation, selector and suffix reports of the refresh calendar + +Split the actual native source at its term ordinal. The prefix is the +preparation reported by the graph builder. The selector consumes the +canonical worker tapes. Every other stage reads an empty choice tape. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +set_option quotPrecheck false + +namespace CompressorRecords.RefreshCore + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PhaseRecipe BlockPlanner Schedule +open DescriptorSpace PortRefresh PortRefresh.LevelRecipe PortRefresh.Allocation SourceTransport +open scoped Fin.CommRing + +variable {w : ℕ} + +private theorem split_walk {J : Type*} {src : J → Memory w → List (Report w) → Prop} + (a b : List J) {m : Memory w} {rs : List (Report w)} (walk : SourceWalk src (a++b) m rs) : + ∃ left right, rs=left++right ∧ SourceWalk src a m left ∧ SourceWalk src b (after m (eventLog left)) right := by + induction a generalizing m rs with + | nil => exact ⟨[],rs,rfl,.done _,walk⟩ + | cons j js ih => + cases walk with + | @next _ _ _ head tail current more => + obtain ⟨pre,post,eqn,hp,hs⟩ := ih more + refine ⟨head++pre,post,by rw [eqn,List.append_assoc],.next current hp,?_⟩ + rw [SourceWalk.after_append]; exact hs + +private theorem weaken {J : Type*} {src dst : J → Memory w → List (Report w) → Prop} + (imp : ∀ j m rs, src j m rs → dst j m rs) {js : List J} {m : Memory w} {rs : List (Report w)} + (h : SourceWalk src js m rs) : SourceWalk dst js m rs := by + induction h with + | done => exact .done _ + | next h _ ih => exact .next (imp _ _ _ h) ih + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +local notation "sh" => RefreshBlockPlan.shape B +local notation "hd" => S.degree_bounds.2 +local notation "hc" => (S.port_bound.connected_and_pos S.port_order).1 +local notation "he" => Nat.two_pow_pos S.expanderExponent +local notation "ties" => RefreshBlockPlan.order B + +/-- Native stages strictly following the chosen refresh term. -/ +def afterTerm : List (Stage sh) := [.supply] ++ (List.finRange ((sh).ports*(sh).dH)).map .rom ++ + (List.finRange (sh).degree).map .slot ++ [.base] + +theorem stage_split : LevelRecipe.order sh = RefreshPrepare.stages B ++ .term :: afterTerm B := by + simp only [RefreshPrepare.stages,afterTerm,LevelRecipe.order,List.append_assoc,List.cons_append,List.nil_append] + +variable {g : ℕ} (X : State S.portExponent (S.portExponent+g)) +variable (c : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1 B.refresh) +variable (old : IncidenceDirectory w) (start termCap low : ℕ) + +local notation "P" => plan X (sh).a₀ (sh).dH (sh).ties (sh).stride start +local notation "native" => Scheduled.Source X S.graph he hc B.refresh hd c ties old start (sh).stride termCap +local notation "bounds" => Scheduled.StageBounds (t := (sh).ties) X S.graph he hc B.refresh start (sh).stride low +local notation "checked" => fun j m rs => native j m rs ∧ bounds j m rs +local notation "Q" => Plan.scratch P w +local notation "D" => NewSlots.word (bits := w) (Plan.demand P) +local notation "recordBase" => NewSlots.word (bits := w) (Plan.term P) +local notation "frame" => PrepareLayout X old (sh).a₀ (sh).dH (sh).ties (sh).stride start + +open private demands from OAI.Computability.VPVNP.CompressorRefreshScheduledRuns + +private theorem prepare_walk {L : frame} {m : Memory w} {rs : List (Report w)} + (h : PrepareRun X old Q D ties (NewSlots.word (2^g)) L.regions.fits m (after m (eventLog rs)) rs) : + SourceWalk native (RefreshPrepare.stages B) m rs := by + obtain ⟨rg,rb,ro,ds,⟨hg,hb,ho,_⟩,rows,_,rfl⟩ := h + have front : SourceWalk native [.gather,.bundles,.offsets] m (rg++rb++ro) := by + rw [List.append_assoc]; exact .next hg (.next hb (.singleton ho)) + apply front.append + rw [SourceWalk.after_append,SourceWalk.after_append] + exact demands X S.graph he hc B.refresh hd c ties old start (sh).stride termCap rows + +/-- All chronological calls of either side of the selector are deterministic. -/ +theorem side_quiet {js : List (Stage sh)} {m : Memory w} {rs : List (Report w)} + (quiet : ∀ j ∈ js, j ≠ .term) (run : SourceWalk checked js m rs) : + branchPaths rs = List.replicate rs.length [] := by + induction run with + | done => rfl + | @next j js m pre post one _ ih => + have eqn := ((runSegment_iff ..).mp one.1).2.2 + have ne := quiet j List.mem_cons_self + have h : branchPaths pre = List.replicate pre.length [] := by + have h' : branchPaths pre = List.replicate (j.limit X start-j.first) [] := by + cases j <;> first | exact eqn | exact (ne rfl).elim + have len := congrArg List.length h' + simp only [branchPaths,List.length_map,List.length_replicate] at len + rwa [len] + have rest := ih (fun j hj => quiet j (List.mem_cons_of_mem _ hj)) + rw [branchPaths,List.map_append,List.length_append,List.replicate_add] + change branchPaths pre ++ branchPaths post = _ + rw [h,rest] + +/-- The exact split of the reports simultaneously retains the real native +stage proofs and the graph builder's preparation/term/suffix memory interfaces. -/ +theorem split_logs {m : Memory w} {rs : List (Report w)} (L : frame) + (build : Build.Run X S.graph he hc B.refresh S.port_order hd c ties old start (sh).stride termCap L m rs) + (actual : SourceWalk checked (LevelRecipe.order sh) m rs) : + ∃ pre terms tail, rs=pre++terms++tail ∧ + (let m₁ := after m (eventLog pre) + let m₂ := after m₁ (eventLog terms) + SourceWalk checked (RefreshPrepare.stages B) m pre ∧ checked .term m₁ terms ∧ + SourceWalk checked (afterTerm B) m₂ tail ∧ + PrepareRun X old Q D ties (NewSlots.word (2^g)) L.regions.fits m m₁ pre ∧ + termRun S.graph he hc B.refresh ties X D recordBase (sh).stride termCap (blockTapes S.graph he hc B.refresh X c w) m₁ = some terms ∧ + Finish.Run X S.graph he hc B.refresh S.port_order hd c recordBase (sh).stride ((P).inputs w) ((P).output w) m₂ tail) := by + obtain ⟨prep,ts,suf,eqn,hp,ht,hs⟩ := build + rw [stage_split] at actual + obtain ⟨pre,rest,all,hpre,hrest⟩ := split_walk (RefreshPrepare.stages B) (.term::afterTerm B) actual + cases hrest with + | @next _ _ _ termLog tail chosen last => + have same : pre=prep := walk_deterministic (src := native) (fun _ _ _ _ a b => Option.some.inj (a.symm.trans b)) + (weaken (dst := native) (fun _ _ _ h => h.1) hpre) (prepare_walk B X c old start termCap (L := L) hp) + subst prep + have lengthEq : termLog.length=ts.length := by + have ln := congrArg List.length (((runSegment_iff ..).mp chosen.1).2.2) + have lt := congrArg List.length (((runSegment_iff ..).mp ht).2.2) + simpa only [branchPaths,List.length_map] using ln.trans lt.symm + have ab : pre++(termLog++tail) = pre++(ts++suf) := (all.symm.trans eqn).trans (List.append_assoc ..) + have ss := List.append_cancel_left ab + obtain ⟨rfl,rfl⟩ := List.append_inj ss lengthEq + refine ⟨pre,termLog,tail,?_,hpre,chosen,last,hp,ht,hs⟩ + exact all.trans (List.append_assoc ..).symm + +end CompressorRecords.RefreshCore + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshSelectorMount.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshSelectorMount.lean new file mode 100644 index 0000000000..fd0794caca --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshSelectorMount.lean @@ -0,0 +1,138 @@ +import OAI.Computability.VPVNP.CompressorRefreshSourceWorker +import OAI.Computability.VPVNP.CompressorRefreshBeforeGroup + +/-! # Mounting a refresh selector from its deterministic preparation + +Every live scheduler boundary agreeing with the generated data suffix can +install the actual term selector. Its level header and planner pitch are +retained by the same refresh prefix that produces its demand coordinates. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.RefreshSelector + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PairSimulation.LocalHistory +open PortRefresh PortRefresh.LevelRecipe PortRefresh.Allocation SelectedTerms NewSlots BlockPlanner DescriptorSpace +open Schedule PhaseRecipe SourceTransport ScheduledTrace SourceOnline +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) +variable {g w : ℕ} (pub : Fin 11 → BurstRAM.Word w) (positions blocks t : ℕ) +variable (X : State S.portExponent (S.portExponent+g)) +local notation "O" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "sh" => RefreshBlockPlan.shape B +local notation "d" => LevelRecipe.Shape.ties sh +local notation "stride" => LevelRecipe.Shape.stride sh +local notation "e" => (LevelRecipe.Shape.ports sh)*(LevelRecipe.Shape.dH sh) +local notation "scr" => BlockProgram.script B +local notation "base" => pub 2 +local notation "layout" => BlockProgram.layout B (Fin.val base) positions blocks +local notation "firstLevel" => Script.levelsPerBlock scr*t +local notation "cur" => firstLevel+S.steps +local notation "start" => arrayBase layout cur +local notation "old" => packedIncidence layout w cur ((State.positions X)*2^S.portExponent) +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "atRow" => List.length (Script.initial scr)+t*List.length (Script.block scr)+Fin.val (Window.position (selectorWindow B) 0) +local notation "H" => levelStart layout 0 +local notation "tag" => LiveStageLink.tagWord w (Online.calendarIndex (Script.size scr) (Script.size scr)) +local notation "inp" => RefreshBlockPlan.input (BlockProgram.geometry B) S.steps (0 : Fin 6) + +/-- The prepared post-memory contains the selector's physical inputs. Any +matching live calendar at this ordinal installs that selector, before any +term tape or any succeeding level is chosen. -/ +private theorem mount (termCap small cap : ℕ) (m : Memory w) (rs : List (Report w)) + (pre : RefreshPrepare.Prepared B base positions blocks t X m rs) + (ht : t PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "sh" => RefreshBlockPlan.shape B +local notation "ord" => RefreshBlockPlan.order B +local notation "n" => Fintype.card X.Base * 2^g +local notation "d" => LevelRecipe.Shape.ties sh +local notation "stride" => LevelRecipe.Shape.stride sh +local notation "e" => (LevelRecipe.Shape.ports sh)*(LevelRecipe.Shape.dH sh) +local notation "scr" => BlockProgram.script B +local notation "inp" => RefreshBlockPlan.input (BlockProgram.geometry B) S.steps (0 : Fin 6) +local notation "V" => BlockIndex.refreshSelector B +local notation "demand" => blockDemandWidths (splitSlots X) (bitWordFinEquiv S.portExponent) (splitWidths X) + +/-- The occurrence immediately after the last demand scan, inside the complete script. -/ +def selectorWindow : Window scr [V] := + let foc := BlockIndex.blockRefresh B + ⟨foc.before,foc.after,foc.split.trans (by simp only [List.append_assoc,List.cons_append,List.nil_append]; rfl)⟩ + +/-- The fixed-script visit index of the refresh motif selector immediately after the +deterministic demand prefix. -/ +def selectorIndex := (selectorWindow B).index 0 + +theorem selector_visit : (scr).visit (selectorIndex B) = V := (selectorWindow B).visit 0 + +theorem selector_position : Fin.val (Window.position (selectorWindow B) 0) = (BlockIndex.blockRefresh B).index.val := Nat.add_zero _ + +/-- The packet uses the published header evaluated before the selector. It +may be mounted with any prospective tape, including an empty one. -/ +def packet (C : Context w) (fuel : ℕ) (tapes : List (List Bool)) (rs : List (Report w)) : SourceOnline.Packet scr w := + ⟨HeaderPacket.attach scr (selectorIndex B) C.pub C.state C.memory fuel tapes,C.memory,rs⟩ + +private theorem params_at {v v' : BlockPlanner.Visit} (h : v=v') (i : Fin v.worker.params) : + v.params i = v'.params (Fin.cast (congrArg (fun q : BlockPlanner.Visit ↦ q.worker.params) h) i) := by subst v'; rfl + +variable (old : IncidenceDirectory w) (start : ℕ) +local notation "p" => Allocation.plan X (LevelRecipe.Shape.a₀ sh) (LevelRecipe.Shape.dH sh) d stride start +local notation "source" => NewSlots.word (bits := w) (Allocation.Plan.demand p) +local notation "dest" => NewSlots.word (bits := w) (Allocation.Plan.term p) + +private theorem selectorHeads : PortRefresh.termAddresses source dest stride d = + ![source, NewSlots.word d, dest, NewSlots.word stride] := by + funext i; fin_cases i <;> apply Fin.ext <;> simp [PortRefresh.termAddresses,NewSlots.word] + +theorem termParams (C : Context w) (h : Describes (s := sh) inp C X start old) + (i : Fin ((scr).catalog (selectorIndex B)).params) : + let code : (scr).catalog (selectorIndex B) = TermWorker.motifPass (grid O).block (grid O).demandOrder.entries (grid O).e := + congrArg BlockPlanner.Visit.worker (selector_visit B) + (((scr).visit (selectorIndex B)).params i).eval C.pub C.state C.memory = + TermWorker.catalogWords (grid O).block (grid O).demandOrder.entries (grid O).supplyOrder.entries + (scr).catalog (selectorIndex B) (PortRefresh.termAddresses source dest stride d) code i := by + intro code + have hv := selector_visit B + let i' := Fin.cast (congrArg (fun q : BlockPlanner.Visit ↦ q.worker.params) hv) i + have hi := params_at hv i + let slot : Fin (RefreshBlockPlan.term B).params := i' + have banks : C.eval ((V).params i') = _ := motif_workerBank_eq (s := sh) (w := w) (g := g) inp S.degree_bounds.2 S.graph ord C X start old (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh h (.term : Stage sh) slot + rw [hi] + change C.eval ((V).params i') = _ + refine banks.trans ?_ + have orderEq : (grid O).supplyOrder.entries = finProdFinEquiv.symm := by ext j; rfl + rw [TermWorker.catalogWords,orderEq,selectorHeads B X start] + rfl + +variable (L : DescriptorSpace.Layout) (base : BurstRAM.Word w) (t : ℕ) +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Ports.data pt +local notation "firstLevel" => Script.levelsPerBlock scr*t +local notation "state" => (levelStart L firstLevel : BurstRAM.Word w) +local notation "H" => levelStart L 0 +local notation "idx" => selectorIndex B +local notation "pos" => Fin.val (Window.position (selectorWindow B) 0) +local notation "atRow" => List.length (Script.initial scr) + t*List.length (Script.block scr) + pos + +/-- The actual calendar launches this packet from every scheduler memory +agreeing with the prepared post-memory. No term selection enters this proof. -/ +theorem prepared (m : Memory w) (fuel : ℕ) (tapes : List (List Bool)) (rs : List (Report w)) + (arityEq : arity (scr).catalog = L.shape.arity) (baseEq : base.val=L.base) (fit : H<2^w) + (rows : m (pt).rows.val = (directoryRows L : BurstRAM.Word w)) + (pitch : m ((pt).directory-1).val = (levelWords L : BurstRAM.Word w)) + (live : atRow < directoryRows L) + (head : RefreshCore.Header (Fintype.card X.Base) g (levelStart L (firstLevel+S.steps)) start old m) : + SourceOnline.Prepared scr L base atRow (directoryRows L) (packet B ⟨pub,state,m⟩ fuel tapes rs) := by + let C : Context w := ⟨pub,state,m⟩ + let D := Window.operandRegion scr L base + have ent : LevelFields.Entry L firstLevel C.pub C.state C.memory := ⟨rfl,pitch⟩ + have supp : InputReads D C.pub C.state C.memory inp := RefreshCore.Header.reads (F := BlockProgram.geometry B) + (step := S.steps) rfl (0 : Fin 6) rfl ent head (.inr (.inl rfl)) + (fun z _ ↦ .inr (.inr ((levelStart_mono L (Nat.zero_le _)).trans (Nat.le_add_right ..)))) + have stage := stage_supported D C.pub C.state C.memory B supp (.term : Stage sh) + have h : HeaderOperands.Supported D C.pub C.state C.memory ((scr).visit idx) := (selector_visit B).symm ▸ stage + exact (selectorWindow B).prepared L base arityEq baseEq fit 0 t (packet B C fuel tapes rs) m (fun _ _ ↦ rfl) rows pitch live + ⟨rfl,rfl,rfl,fun _ ↦ rfl,h.initial,h.stop,h.params⟩ + +end CompressorRecords.RefreshSelector + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshSourceWorker.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshSourceWorker.lean new file mode 100644 index 0000000000..7bedd6b3c0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshSourceWorker.lean @@ -0,0 +1,76 @@ +import OAI.Computability.VPVNP.CompressorRefreshSelectorPacket +import OAI.Computability.VPVNP.CompressorSelectorSitePacket + +/-! # Installing the refresh term worker at its actual calendar cut + +Its demand rows are the output of the deterministic pre-selector workers. The +installed instruction table and the semantic decoder share the same finite +order, source and destination rows, field addresses and instruction budget. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.RefreshSelector + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PairSimulation.LocalHistory +open PortRefresh PortRefresh.LevelRecipe SelectedTerms NewSlots BlockPlanner DescriptorSpace +open Schedule PhaseRecipe SourceTransport ScheduledTrace +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) +variable {g w : ℕ} (X : State S.portExponent (S.portExponent+g)) (old : IncidenceDirectory w) (start : ℕ) +local notation "O" => PassOrigin.refresh (B := B) (f := f) (hf := hf) X +local notation "sh" => RefreshBlockPlan.shape B +local notation "ord" => RefreshBlockPlan.order B +local notation "d" => LevelRecipe.Shape.ties sh +local notation "stride" => LevelRecipe.Shape.stride sh +local notation "e" => (LevelRecipe.Shape.ports sh)*(LevelRecipe.Shape.dH sh) +local notation "scr" => BlockProgram.script B +local notation "inp" => RefreshBlockPlan.input (BlockProgram.geometry B) S.steps (0 : Fin 6) +local notation "demand" => blockDemandWidths (splitSlots X) (bitWordFinEquiv S.portExponent) (splitWidths X) +local notation "p" => Allocation.plan X (LevelRecipe.Shape.a₀ sh) (LevelRecipe.Shape.dH sh) d stride start +local notation "source" => NewSlots.word (bits := w) (Allocation.Plan.demand p) +local notation "dest" => NewSlots.word (bits := w) (Allocation.Plan.term p) +local notation "ready" => Allocation.PrepareLayout X old (LevelRecipe.Shape.a₀ sh) (LevelRecipe.Shape.dH sh) d stride start + +/-- The actual input and the explicit packet at the global selector index +satisfy every field needed for installation in the online controller. -/ +theorem sourceWorker (L : DescriptorSpace.Layout) (C : Context w) (described : Describes (s := sh) inp C X start old) + (r : ready) (low : levelStart L 0 ≤ start) (room : (p).stop < 2^w) + (width : SelectedTermWorker.fitConstant B+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (cap : ℕ) (clock : TermWorker.budget B.refresh d e w X.maxWireWidth ≤ cap) + (data : ∀ s, DemandPreparation.demandAt ord (DemandScan.rowBase X d source s) C.memory = demand s) + (tapes : List (List Bool)) (rs : List (Report w)) : + let W := workerInput B f hf X source dest r.demandTerm r.termRoom width cap clock C.memory data + SelectorSite.SourceWorker W L (packet B C cap tapes rs) := by + intro W + have hc := counters (s := sh) inp C X start old described (.term : Stage sh) + have hv := selector_visit B + have code := congrArg BlockPlanner.Visit.worker hv + have fit := limit_fits (s := sh) (w := w) (g := g) S.degree_bounds.2 X start room.le (.term : Stage sh) + have row := workerRows B f hf X r.demandTerm r.termRoom width cap clock C.memory data + have natural : (source).val = (p).demand := Nat.mod_eq_of_lt (by + dsimp only [Allocation.Plan.stop,Allocation.Plan.next,Allocation.Plan.reverseSlot,Allocation.Plan.targetPort, + Allocation.Plan.supply,Allocation.Plan.term] at room + omega) + have hsrc : levelStart L 0 ≤ (source).val := by + rw [natural]; exact low.trans (Nat.le_add_right start _) + refine ⟨code,?_,?_,termParams B f hf X old start C described,rfl,width,fun i ↦ hsrc.trans (row i).1, + fun i ↦ ?_,fun _ _ ↦ rfl⟩ + · change ((scr).visit (selectorIndex B)).initial.eval C.pub C.state C.memory = 0 + rw [hv]; exact hc.1 + · change (((scr).visit (selectorIndex B)).stop.eval C.pub C.state C.memory).val = (O).motifCount + rw [hv]; exact (congrArg Fin.val hc.2).trans (Nat.mod_eq_of_lt fit) + · exact (hsrc.trans ((Nat.le_add_right ..).trans r.demandTerm)).trans (row i).2 + +end CompressorRecords.RefreshSelector + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshSplitWindows.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshSplitWindows.lean new file mode 100644 index 0000000000..2863bd59e3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshSplitWindows.lean @@ -0,0 +1,132 @@ +import OAI.Computability.VPVNP.CompressorRefreshSelectorLogs +import OAI.Computability.VPVNP.CompressorDeterministicGroup +import OAI.Computability.VPVNP.CompressorSourceGroupSplit + +/-! # Three consecutive online windows around the refresh selector + +Each native subwalk retains its reports while the dispatcher computes its +own rows. The earlier physical columns and the level header survive all +three subwalks, since every worker writes only to its refresh workspace. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +set_option quotPrecheck false + +namespace CompressorRecords.RefreshCore + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PhaseRecipe BlockPlanner Schedule +open DescriptorSpace PortRefresh PortRefresh.LevelRecipe PortRefresh.Allocation SourceTransport SourceOnline +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +local notation "scr" => BlockProgram.script B +local notation "sh" => RefreshBlockPlan.shape B +local notation "I" => RefreshCore.input B +local notation "W" => BlockGroups.refresh B 1 + +private def lists : List (List (BlockPlanner.Visit)) := + [(RefreshPrepare.stages B).map (RefreshBlockPlan.stage B I),[RefreshBlockPlan.stage B I .term], + (afterTerm B).map (RefreshBlockPlan.stage B I)] + +private theorem flattened : (lists B).flatten = entries B := by + change _ = (LevelRecipe.order sh).map (RefreshBlockPlan.stage B I) + rw [stage_split] + simp only [lists,List.flatten_cons,List.flatten_nil,List.append_nil,List.map_append,List.map_cons, + List.cons_append,List.nil_append] + +/-- The one-stage window for selecting a refresh term, immediately after the refresh +preparation stages. -/ +def selectWindow : Window scr [RefreshBlockPlan.stage B I .term] := + BlockGroups.within W (lists B) (flattened B) ⟨1,show 1 < 3 by decide⟩ + +/-- The window for the remaining refresh stages after the selected term. -/ +def finishWindow : Window scr ((afterTerm B).map (RefreshBlockPlan.stage B I)) := + BlockGroups.within W (lists B) (flattened B) ⟨2,show 2 < 3 by decide⟩ + +theorem select_before : (selectWindow B).before.length = (W).before.length+(RefreshPrepare.stages B).length := by + change ((W).before ++ _).length = _ + rw [List.length_append]; congr 1 + simp [lists,List.length_map] + +theorem finish_before : (finishWindow B).before.length = + (W).before.length+(RefreshPrepare.stages B).length+1 := by + change ((W).before ++ _).length = _ + rw [List.length_append] + simp [lists,List.length_map,Nat.add_assoc] + +theorem select_index : (selectWindow B).index 0 = RefreshCore.index B (CanonicalWorker.refreshTermIndex B) := by + have len : (RefreshPrepare.stages B).length = 3+(sh).ties := by simp [RefreshPrepare.stages]; omega + apply Fin.ext + rw [Window.index_val,select_before,RefreshCore.index,Window.index_val,Fin.val_cast,CanonicalWorker.refreshTermIndex_val,len] + change (scr).initial.length+((W).before.length+(3+(sh).ties))+0 = + (scr).initial.length+(W).before.length+(3+(sh).ties) + omega + +variable {w g : ℕ} (base : BurstRAM.Word w) (positions blocks t : ℕ) +variable (X : State S.portExponent (S.portExponent+g)) +variable (c : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1 B.refresh) +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "cur" => Script.levelsPerBlock scr*t+S.steps +local notation "head" => levelStart L cur +local notation "H" => levelStart L 0 +local notation "start" => arrayBase L cur +local notation "old" => packedIncidence L w cur (X.positions*2^S.portExponent) +local notation "P" => plan X (sh).a₀ (sh).dH (sh).ties (sh).stride start +local notation "hc" => (S.port_bound.connected_and_pos S.port_order).1 +local notation "he" => Nat.two_pow_pos S.expanderExponent +local notation "hd" => S.degree_bounds.2 +local notation "ties" => RefreshBlockPlan.order B + +/-- The three incoming memory facts needed by all refresh subwindows. -/ +structure EntryState (m : Memory w) : Prop where + header : Header (Fintype.card X.Base) g head start old m + rows : m (pt).rows.val = (directoryRows L : BurstRAM.Word w) + pitch : m ((pt).directory-1).val = (levelWords L : BurstRAM.Word w) + +variable (termCap : ℕ) +local notation "src" => Scheduled.Source X S.graph he hc B.refresh hd c ties old start (sh).stride termCap +local notation "bounded" => Scheduled.StageBounds (t := (sh).ties) X S.graph he hc B.refresh start (sh).stride H + +/-- Attach one contiguous subwalk and retain its exact report list and +the state of the header needed by the next subwalk. -/ +theorem attach_part (js : List (Stage sh)) (win : Window scr (js.map (RefreshBlockPlan.stage B I))) + {m : Memory w} {rs : List (Report w)} (entry : EntryState B base positions blocks t X m) + (ht : t < blocks) (fit : H < 2^w) (room : (P).stop < 2^w) (before : head+60 < start) + (positive : 0 < termCap) (cap : ℕ) (clock : SourceOnline.scanCap scr (max 64 termCap) ≤ cap) + (walk : SourceWalk (fun j m rs => src j m rs ∧ bounded j m rs) js m rs) : + ∃ ps : List (SourceOnline.Packet scr w), + Group scr L base cap ((scr).initial.length+t*(scr).block.length+win.before.length) (directoryRows L) m ps ∧ + ps.map (fun p => p.stage.phase) = win.indices ∧ ps.flatMap SourceWalk.Packet.reports = rs ∧ + EntryState B base positions blocks t X (after m (eventLog rs)) := by + obtain ⟨raw,wr⟩ := raw_stages B X old start termCap base positions blocks t + (Scheduled.tapes (t := (sh).ties) (w := w) X S.graph he hc B.refresh c start (sh).stride) + js m rs entry.header entry.pitch positive room before fit walk + have live (j : Fin (js.map (RefreshBlockPlan.stage B I)).length) : Window.ordinal (A:=scr) t (win.index j) < directoryRows L := by + rw [win.ordinal_index,BlockProgram.directory_rows,(scr).calendar_total] + have mul := Nat.mul_le_mul_right (scr).block.length ht + rw [Nat.succ_mul] at mul + have loc := (win.position j).isLt + omega + have clocks (j : Fin (scr).size) := scanCap_clocks + (p := ⟨HeaderPacket.attach scr j (pt).data 0 m (max 64 termCap) [],m,[]⟩) _ le_rfl clock + obtain ⟨ps,grp,labels,reports⟩ := win.group L base t rfl rfl fit cap (max 64 termCap) m rs raw + entry.rows entry.pitch live (fun j _ => (clocks j).1) (fun j _ => (clocks j).2) + have keep (x : ℕ) (lt : x < start) : after m (eventLog rs) x = m x := + after_outside m wr (fun h => (Nat.not_le_of_lt lt) h.1) + have lo := levelStart_mono L (Nat.zero_le cur) + have gap := Window.lowCells (A := scr) L base rfl rfl fit + exact ⟨ps,grp,labels,reports,entry.header.keep (fun j hj => keep _ (by omega)), + (keep _ (gap.1.trans (by omega))).trans entry.rows,(keep _ (gap.2.trans (by omega))).trans entry.pitch⟩ + +end CompressorRecords.RefreshCore + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshStageFrame.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshStageFrame.lean new file mode 100644 index 0000000000..f639a5bce6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshStageFrame.lean @@ -0,0 +1,121 @@ +import OAI.Computability.VPVNP.CompressorRecordsOrdinalFootprint + +/-! +# Guarded deterministic compressor scans + +The source call at ordinal `j` emits a concrete list of events and returns +`j+1`. Bounds on the read and write addresses of those events preserve the +scheduler's frame and control words throughout the scan. The resulting +trace can be replayed after the scheduler changes its own cells. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.StageFrame + +open BurstRAM Schedule OrdinalRun SourceTransport +open scoped Fin.CommRing + +variable {w d : ℕ} {Q : Type*} + +/-- The exact returned cursor in each source report, including the terminal ordinal. -/ +inductive Scanned : ℕ → ℕ → List (Report w) → Prop where + | done (N : ℕ) : Scanned N N [] + | next {j N : ℕ} {r : Report w} {rs : List (Report w)} (live : j < N) + (cursor : r.result = some ((j+1 : ℕ) : Word w)) (tail : Scanned (j+1) N rs) : + Scanned j N (r :: rs) + +/-- Establish ordinal order, terminal invariant and all accessed addresses before the +scheduler installs any worker frame. -/ +theorem scan (P : BurstRAM.Program w Q) (fuel : ℕ) (first N : ℕ) + (I : ℕ → Memory w → Prop) (events : Memory w → Word w → List (Event w)) + (readable writable : ℕ → Prop) + (native : ∀ j, first ≤ j → j < N → ∀ m, execute P fuel (P.start (j : Word w)) m [] = + some ⟨events m (j : Word w), some ((j : Word w)+1)⟩) + (step : ∀ j, first ≤ j → j < N → ∀ m, I j m → + I (j+1) (after m (events m (j : Word w))) ∧ Reads readable (events m (j : Word w)) ∧ + Writes writable (events m (j : Word w))) + (first_le : first ≤ N) (m : Memory w) (rs : List (Report w)) (inv : I first m) + (run : runSegment P fuel (some (first : Word w)) m (List.replicate (N-first) []) = some rs) : + Scanned first N rs ∧ I N (after m (eventLog rs)) ∧ + Reads readable (eventLog rs) ∧ Writes writable (eventLog rs) := by + have visit (count j : ℕ) (hj : first ≤ j) (size : j + count = N) (m : Memory w) + (inv : I j m) (rs : List (Report w)) + (run : runSegment P fuel (some (j : Word w)) m (List.replicate count []) = some rs) : + Scanned j N rs ∧ I N (after m (eventLog rs)) ∧ + Reads readable (eventLog rs) ∧ Writes writable (eventLog rs) := by + induction count generalizing j m rs with + | zero => + change some [] = some rs at run + cases Option.some.inj run + have h : j = N := by omega + subst j + exact ⟨.done _,inv,fun _ _ h ↦ (List.not_mem_nil h).elim,fun _ _ h ↦ (List.not_mem_nil h).elim⟩ + | succ count ih => + have hlt : j < N := by omega + obtain ⟨next,rd,wr⟩ := step j hj hlt m inv + rw [List.replicate_succ, runSegment, native j hj hlt m] at run + simp only [← Nat.cast_add_one, Option.map_eq_some_iff] at run + obtain ⟨tail, ht, rfl⟩ := run + let rep : Report w := ⟨events m (j : Word w), some ((j+1 : ℕ) : Word w)⟩ + obtain ⟨vt,vi,vr,vw⟩ := ih (j+1) (by omega) (by omega) (after m rep.events) next tail ht + refine ⟨.next hlt rfl vt, ?_, ?_, ?_⟩ + · change I N ((rep.events ++ eventLog tail).foldl update m) + rwa [List.foldl_append] + · intro a v ha + exact (List.mem_append.mp ha).elim (rd a v) (vr a v) + · intro a v ha + exact (List.mem_append.mp ha).elim (wr a v) (vw a v) + exact visit (N-first) first le_rfl (by omega) m inv rs run + +/-- Ordinal order and write separation validate a guard in any prepared replay memory. -/ +theorem Scanned.guarded (C : Catalog d) (worker : Fin d) (ports : Ports w) + (pub : Fin (C worker).params → Word w) {first N : ℕ} {rs : List (Report w)} + (shape : Scanned first N rs) (fit : N < 2^w) (writable : ℕ → Prop) + (wr : Writes writable (eventLog rs)) (separate : ∀ x, ControlCell (C worker).params ports x → ¬ writable x) + (m : Memory w) (ready : Ready C worker ports pub (N : Word w) m) : + ValidTrace C worker ports pub (N : Word w) (first : Word w) m rs ∧ + Preserved (C worker).params ports m (after m (eventLog rs)) := by + constructor + · induction shape generalizing m with + | done => exact ⟨ready,le_rfl⟩ + | @next j N r rs live cursor _ ih => + have hword : (j : Word w) < (N : Word w) := by + change j%(2^w) < N%(2^w) + rwa [Nat.mod_eq_of_lt (live.trans fit), Nat.mod_eq_of_lt fit] + have keep : Preserved (C worker).params ports m (after m r.events) := + fun x hx ↦ after_outside m (fun a v ha ↦ wr a v (List.mem_append_left _ ha)) (separate x hx) + exact ⟨ready,hword,_,cursor,ih fit (fun a v ha ↦ wr a v (List.mem_append_right _ ha)) _ + (ready_of_preserved C worker ports ready keep)⟩ + · exact fun x hx ↦ after_outside m wr (separate x hx) + +/-- Prove guard validity and the footprint of the same genuine deterministic +source run. The source-specific invariant may track partial descriptor data. -/ +theorem validScan (C : Catalog d) (worker : Fin d) (ports : Ports w) (P : BurstRAM.Program w Q) + (fuel : ℕ) (pub : Fin (C worker).params → Word w) (first N : ℕ) + (I : ℕ → Memory w → Prop) (events : Memory w → Word w → List (Event w)) + (readable writable : ℕ → Prop) + (native : ∀ j, first ≤ j → j < N → ∀ m, execute P fuel (P.start (j : Word w)) m [] = + some ⟨events m (j : Word w), some ((j : Word w)+1)⟩) + (step : ∀ j, first ≤ j → j < N → ∀ m, I j m → + I (j+1) (after m (events m (j : Word w))) ∧ Reads readable (events m (j : Word w)) ∧ + Writes writable (events m (j : Word w))) + (separate : ∀ x, ControlCell (C worker).params ports x → ¬ writable x) + (first_le : first ≤ N) (fit : N < 2^w) + (m : Memory w) (rs : List (Report w)) (inv : I first m) + (ready : Ready C worker ports pub (N : Word w) m) + (run : runSegment P fuel (some (first : Word w)) m (List.replicate (N-first) []) = some rs) : + ValidTrace C worker ports pub (N : Word w) (first : Word w) m rs ∧ + I N (after m (eventLog rs)) ∧ Reads readable (eventLog rs) ∧ Writes writable (eventLog rs) ∧ + Preserved (C worker).params ports m (after m (eventLog rs)) := by + obtain ⟨shape,inv',rd,wr⟩ := scan P fuel first N I events readable writable native step first_le m rs inv run + obtain ⟨valid,keep⟩ := shape.guarded C worker ports pub fit writable wr separate m ready + exact ⟨valid,inv',rd,wr,keep⟩ + +end CompressorRecords.StageFrame + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshStageSupport.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshStageSupport.lean new file mode 100644 index 0000000000..766315b556 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshStageSupport.lean @@ -0,0 +1,133 @@ +import OAI.Computability.VPVNP.CompressorRefreshBlockPlan +import OAI.Computability.VPVNP.CompressorHeaderOperands + +/-! +# Memory operands of the installed expander-refresh workers + +The worker recipes only read the six inputs from the current level. The +admission grid and supply weights in the selected motif are fixed literals. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords + +open BurstRAM PhaseRecipe + +namespace TermWorker + +open MotifGrid MotifBlocks MotifConversion MotifSelector +open private demandLiterals gridLiterals from OAI.Computability.VPVNP.CompressorTermWorkerRecipe + +variable {k : Type*} [_root_.Field k] {J D S : Type} [Fintype J] [Fintype D] [Fintype S] +variable {a b : D → J} {P : Supply J S} {p : D → ℚ} {q : S → ℚ} {H H' : ℝ} +variable (B : FixedBlock k a b P (realWidths p) (realWidths q) H H') + +theorem motifExprs_reads {d n w : ℕ} (order : Fin d ≃ D) (supply : Fin n ≃ S) + (head : Fin 4 → Expr) (region : ℕ → Prop) (pub : Fin 5 → BurstRAM.Word w) + (s : BurstRAM.Word w) (m : Memory w) (ok : ∀ i, (head i).ReadsFrom region pub s m) + (i : Fin (motifPass B order n).params) : + (motifExprs B order supply head i).ReadsFrom region pub s m := by + have demand (scale : ℕ) (j : Fin (d+1)) : + (demandLiterals order p scale j).ReadsFrom region pub s m := by + cases j using Fin.lastCases <;> simp [demandLiterals,Expr.ReadsFrom] + unfold motifExprs + cases i using Fin.addCases with + | left i => simpa only [Fin.append_left] using ok i + | right i => + rw [Fin.append_right] + cases i using Fin.addCases with + | left i => + rw [Fin.append_left] + cases i using Fin.addCases <;> simp only [Fin.append_left,Fin.append_right] <;> + first | exact demand _ _ | trivial + | right i => + rw [Fin.append_right] + cases i using Fin.addCases <;> simp only [Fin.append_left,Fin.append_right] <;> + first | exact demand _ _ | trivial + +end TermWorker + +namespace PortRefresh.LevelRecipe + +variable {w : ℕ} (D : ℕ → Prop) (pub : Fin 5 → BurstRAM.Word w) (state : Word w) (m : Memory w) + +/-- At the given public words, state and memory, evaluating the six refresh level inputs reads +only addresses satisfying the supplied predicate. -/ +structure InputReads (I : Input) : Prop where + start : I.start.ReadsFrom D pub state m + vertices : I.vertices.ReadsFrom D pub state m + lanes : I.lanes.ReadsFrom D pub state m + oldOut : I.oldOut.ReadsFrom D pub state m + oldShift : I.oldShift.ReadsFrom D pub state m + oldWidth : I.oldWidth.ReadsFrom D pub state m + +open Compression +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {I : Input} (h : InputReads D pub state m I) +local notation "R" => Expr.ReadsFrom D pub state m +local notation "s" => RefreshBlockPlan.shape B + +include h in +theorem stage_supported (j : Stage s) : + HeaderOperands.Supported D pub state m (RefreshBlockPlan.stage B I j) := by + have ps : R (sites s I) := ⟨⟨h.vertices,trivial⟩,h.lanes⟩ + have bl : R (blocks I) := ⟨h.vertices,h.lanes⟩ + have sg : R (segments s I) := ⟨ps,trivial⟩ + have ca : R (capacity s I) := ⟨ps,trivial⟩ + have dm : R (demandStart s I) := ⟨h.start,trivial,sg⟩ + have tm : R (termStart s I) := ⟨dm,bl,trivial⟩ + have sp : R (supplyStart s I) := ⟨tm,bl,trivial⟩ + have tg : R (targetPort s I) := ⟨sp,ps,trivial⟩ + have rv : R (reverseSlot s I) := ⟨tg,trivial,trivial⟩ + have out : R (outputStart s I) := ⟨rv,trivial,trivial⟩ + have col (i : Fin 6) : R (column s I i) := ⟨out,trivial,ca⟩ + have sc (i : Fin 8) : R (scratch s I i) := by + unfold scratch + split + · trivial + · exact ⟨h.start,trivial,sg⟩ + have initial : R j.initial := by cases j <;> trivial + have stop : R (j.stop I) := by + cases j <;> first | exact sg | exact ps | exact bl | exact ⟨ps,trivial⟩ + | exact ⟨⟨h.vertices,trivial⟩,trivial⟩ | trivial + let bank := TermWorker.motifExprs B.refresh (RefreshBlockPlan.order B) finProdFinEquiv.symm + have banks (k : Stage s) (z : Fin (k.arity (RefreshBlockPlan.term B).params)) : + R (k.bank I S.degree_bounds.2 S.graph (RefreshBlockPlan.order B) bank z) := by + cases k with + | gather => fin_cases z; exacts [sc 0,h.lanes,h.oldWidth,sc 1] + | bundles => + fin_cases z + exacts [h.lanes,h.oldOut,sc 2,sc 3,sc 4,h.oldShift,True.intro,True.intro] + | offsets => exact sc _ + | demand k => + have choose : R (if (RefreshBlockPlan.order B k).1 then scratch s I 1 + else scratch s I 7) := by + split <;> exact sc _ + fin_cases z <;> first | exact h.lanes | exact choose | exact dm | trivial + | term => + apply TermWorker.motifExprs_reads + intro n + fin_cases n <;> first | exact dm | exact tm | trivial + | supply => fin_cases z <;> first | exact h.lanes | exact tm | exact sp | trivial + | rom k => fin_cases z <;> first | exact tg | exact rv | trivial + | slot k => + fin_cases z + exacts [True.intro,True.intro,True.intro,h.lanes,True.intro,sc 2,sc 4, + tg,rv,sp,col 3,col 4,col 5] + | base => fin_cases z <;> first | exact h.lanes | exact col _ | trivial + exact ⟨initial,stop,fun i ↦ + banks j (Fin.cast (j.worker_params S.degree_bounds.2 (RefreshBlockPlan.term B)) i)⟩ + +end PortRefresh.LevelRecipe +end CompressorRecords + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshStageVisits.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshStageVisits.lean new file mode 100644 index 0000000000..9ee6bed57f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshStageVisits.lean @@ -0,0 +1,90 @@ +import OAI.Computability.VPVNP.CompressorRefreshScheduledRuns +import OAI.Computability.VPVNP.CompressorPhaseVisits + +/-! +# Multiplicities of the actual degree-refresh recipes + +The flat scan of each recipe has exactly its interval's number of calls. +The expander ROM has one call per hardwired edge. The final base scan +visits only lane zero. These counts match the charged visit scopes in +the online directory budget. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.Scheduled + +open BurstRAM Schedule Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry +open LevelRecipe NewSlots Allocation PhaseVisits +open scoped Fin.CommRing + +variable {w a a₀ g dH t : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (c : DyadicRefreshChoice X E hdH conn F) + (ties : Fin t ≃ Tie (2^a)) (old : IncidenceDirectory w) (start stride : ℕ) + +local notation "sh" => shape (t := t) E hdH conn F stride +local notation "J" => Stage sh + +/-- The integral cursor difference; only the ROM starts from a nonzero edge ordinal. -/ +def visits (j : J) := j.limit X start - j.first + +/-- One worker row in the flat refresh calendar. -/ +def phase {s : LevelRecipe.Shape} : Stage s → PhaseVisits.Phase + | .gather | .offsets => ⟨.oldSlots,1⟩ + | .bundles | .slot _ => ⟨.oldSites,1⟩ + | .demand _ | .term => ⟨.motifs,1⟩ + | .supply => ⟨.oldSites,s.dH⟩ + | .rom _ => ⟨.once,1⟩ + | .base => ⟨.oldBase,s.ports*s.degree⟩ + +theorem tapes_length (j : J) : (tapes (w := w) X E hdH conn F c start stride j).length = + visits X E hdH conn F start stride j := by + cases j <;> simp [tapes,visits,Stage.limit,Stage.first,Allocation.plan] + +theorem source_calls {cap : ℕ} {j : J} {m : Memory w} {rs : List (Report w)} + (run : Source X E hdH conn F hd c ties old start stride cap j m rs) : + rs.length = visits X E hdH conn F start stride j := + (by simpa [branchPaths] using congrArg List.length ((runSegment_iff ..).mp run).2.2 : + rs.length = (tapes (w := w) X E hdH conn F c start stride j).length).trans + (tapes_length X E hdH conn F c start stride j) + +theorem source_packets (cap : ℕ) (L : Allocation.PrepareLayout X old a₀ dH t stride start) + {m : Memory w} {rs : List (Report w)} (run : Build.Run X E hdH conn F hD hd c ties old start stride cap L m rs) : + ∃ ps : List (SourceWalk.Packet J w), ps.map SourceWalk.Packet.stage = LevelRecipe.order sh ∧ + ps.flatMap SourceWalk.Packet.reports = rs ∧ + SourceWalk.Chronological (Source X E hdH conn F hd c ties old start stride cap) m ps ∧ + rs.length = ((LevelRecipe.order sh).map (visits X E hdH conn F start stride)).sum := by + have walk := sources X E hdH conn F hD hd c ties old start stride cap L m rs run + obtain ⟨ps,stages,data,chron⟩ := walk.packets + exact ⟨ps,stages,data,chron,walk.report_count _ (fun _ _ _ h ↦ source_calls X E hdH conn F hd c ties old start stride h)⟩ + +variable {S : BlockSchedule k} {B : S.Templates} {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f} + +/-- The certificate attaches an actual refresh-state source row to its object +kind and visit multiplicity, using the original pass's selected term. -/ +theorem visits_eq_scope {g : ℕ} (X : State S.portExponent (S.portExponent+g)) + (c : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1 B.refresh) + (sel : List Bool) (capacity start stride : ℕ) {ties : ℕ} + (j : Stage (shape (t := ties) S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh stride)) : + let origin := PassOrigin.refresh (B := B) (f := f) (hf := hf) X + let v : SelectedLevel B f hf := ⟨_,_,_,_,X,_,origin,c,sel⟩ + visits X S.graph (Nat.two_pow_pos _) (S.port_bound.connected_and_pos S.port_order).1 B.refresh start stride j = + (phase j).scope.count capacity v * (phase j).perObject := by + intro origin v + have hp := PortRefresh.bundleCount_positions X (IncidenceDirectory.baseOrder X) + cases j <;> simp only [visits,Stage.limit,Stage.first,phase,Scope.count,SelectedLevel.oldSlots, + PassOrigin.motifCount,origin,v,Nat.sub_zero,Nat.mul_one,Nat.add_sub_cancel_left, + Allocation.plan,Allocation.Plan.segments,shape,LevelRecipe.Shape.ports,LevelRecipe.Shape.degree] + all_goals first | exact hp | rw [← hp] | ring + +end CompressorRecords.PortRefresh.Scheduled + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshTermDataFrame.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshTermDataFrame.lean new file mode 100644 index 0000000000..7c55278bcb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshTermDataFrame.lean @@ -0,0 +1,334 @@ +import OAI.Computability.VPVNP.CompressorRefreshStageFrame +import OAI.Computability.VPVNP.CompressorRecordRefreshPrepareAllocation + +/-! +# Scheduler frames for the refresh demand, supply and expander-ROM workers + +These three passes read and write inside the packed refresh allocation. +A single tie pass preserves every previously completed demand cell. Supply +visits preserve the term records and advance the supply prefix. Each fixed +ROM row starts at its own edge ordinal and fills the two reverse-edge cells. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.TermDataFrame + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.Refresh +open Compression.DegreeRefresh SpectralGeometry SourceTransport NewSlots Allocation +open scoped Fin.CommRing + +open private src_eq dst_val halfSlot layout one_step saved_congr pack_lt + from OAI.Computability.VPVNP.CompressorRecordRefreshDemandScan +open private physical_addresses finPair_val step from OAI.Computability.VPVNP.CompressorRecordRefreshSupplyScan +open private address value written from OAI.Computability.VPVNP.CompressorRecordRefreshExpanderROM +open private Plan.address_val from OAI.Computability.VPVNP.CompressorRecordRefreshAllocation + +/-- Addresses from the refresh allocation's start inclusive to its stop exclusive. -/ +def InArena (P : Plan) (addr : ℕ) := P.start ≤ addr ∧ addr < P.stop + +/-- The two premises a concrete deterministic source supplies to the guarded +scheduler scan. Native entry is required only at the actual active ordinals. -/ +structure Scan {w : ℕ} {Q : Type*} (P : Plan) (program : BurstRAM.Program w Q) + (fuel first N : ℕ) (inv : ℕ → Memory w → Prop) (events : Memory w → W w → List (Event w)) : Prop where + native : ∀ j, first ≤ j → j < N → ∀ m, execute program fuel (program.start (j : W w)) m [] = + some ⟨events m (j : W w), some ((j : W w)+1)⟩ + step : ∀ j, first ≤ j → j < N → ∀ m, inv j m → + inv (j+1) (after m (events m (j : W w))) ∧ + Reads (InArena P) (events m (j : W w)) ∧ Writes (InArena P) (events m (j : W w)) + +theorem Scan.run {w fuel first N : ℕ} {Q : Type*} {P : Plan} {program : BurstRAM.Program w Q} + {inv : ℕ → Memory w → Prop} {events : Memory w → W w → List (Event w)} + (scan : Scan P program fuel first N inv events) (first_le : first ≤ N) (m : Memory w) + (rs : List (Report w)) (initial : inv first m) + (run : runSegment program fuel (some (first : W w)) m (List.replicate (N-first) []) = some rs) : + StageFrame.Scanned first N rs ∧ inv N (after m (eventLog rs)) ∧ + Reads (InArena P) (eventLog rs) ∧ Writes (InArena P) (eventLog rs) := + StageFrame.scan program fuel first N inv events _ _ scan.native scan.step first_le m rs initial run + +private theorem ranges (P : Plan) : P.start ≤ P.demand ∧ P.demand ≤ P.term ∧ P.term ≤ P.supply ∧ + P.supply ≤ P.targetPort ∧ P.targetPort ≤ P.reverseSlot ∧ P.reverseSlot ≤ P.next ∧ P.next ≤ P.stop := + ⟨Nat.le_add_right .., Nat.le_add_right .., Nat.le_add_right .., Nat.le_add_right .., + Nat.le_add_right .., Nat.le_add_right .., Nat.le_add_right ..⟩ + +variable {a g t w : ℕ} (X : State a (a+g)) (a₀ dH stride start : ℕ) +local notation "P" => plan X a₀ dH t stride start +local notation "B" => Fintype.card X.Base * 2^g +local notation "sitesN" => Fintype.card X.Base * 2^a * 2^g +local notation "Q" => Plan.scratch P w + +section Demand + +variable (ties : Fin t ≃ Tie (2^a)) +local notation "dBank" => DemandScan.words (r := 2^g) ties Q (word (Plan.demand P)) + +private theorem demand_ranges (room : (P).stop < 2^w) (k : Fin t) (j : Fin B) : + start ≤ (DemandScan.src dBank k j).val ∧ (DemandScan.src dBank k j).val < (P).demand ∧ + (P).demand ≤ (DemandScan.dst dBank k j).val ∧ (DemandScan.dst dBank k j).val < (P).term := by + obtain ⟨h₁,h₂,h₃,h₄,h₅,h₆,h₇⟩ := ranges P + have segments : (P).segments ≤ (P).demand := by dsimp only [Plan.demand]; omega + have fit : sitesN*2^a ≤ 2^w := by change (P).segments ≤ _; omega + have lanes : 2^g < 2^w := by + have h₁ : 2^g ≤ sitesN := Nat.le_mul_of_pos_left _ (Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos _)) + have h₂ : sitesN ≤ (P).segments := Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _) + omega + let s := (DemandScan.blocks X).symm j + have hs := src_eq X ties Q (word (P).demand) fit lanes k s + rw [(DemandScan.blocks X).apply_symm_apply j] at hs + let z := idWord (sites (D := 2^a) X.baseIndex (bitWordFinEquiv g)) fit (halfSlot X s (ties k)) + have hz : z.val < (P).segments := (numbered (sites (D := 2^a) X.baseIndex (bitWordFinEquiv g)) _).isLt + have src : start ≤ (DemandScan.src dBank k j).val ∧ (DemandScan.src dBank k j).val < (P).demand := by + rw [hs] + split <;> first | exact (P).scratch_interval (by omega) 1 (by decide) z hz | + exact (P).scratch_interval (by omega) 7 (by decide) z hz + have hv : (word (bits := w) (P).demand).val = (P).demand := Nat.mod_eq_of_lt (by omega) + have hterm : (P).term = (P).demand+B*t := rfl + have dst := dst_val X ties Q (word (P).demand) (by rw [hv]; omega) j k + rw [hv] at dst + have hkey := pack_lt j.isLt k.isLt + exact ⟨src.1,src.2,by omega,by omega⟩ + +/-- One tie's native scan and the exact prefix invariant for all earlier +ties and blocks. Its only read is from a segment column and its only store +lies in the dense demand array. -/ +theorem demandScan (room : (P).stop < 2^w) (k : Fin t) (ref : Memory w) + (done : Fin t → Fin B → Prop) : + Scan P ((template DemandScan.visit 0).instantiate w (dBank k)).program 26 0 B + (fun j m ↦ DemandScan.Saved dBank ref m (fun u i ↦ done u i ∨ u=k ∧ i.val SupplyScan.params (bits := w) (2^a) (2^g) dH (word (Plan.term P)) stride F.selectorBits + (word (Plan.supply P)) +local notation "O" => sites (D := 2^a) X.baseIndex (bitWordFinEquiv g) + +private theorem supply_ranges (room : (P).stop < 2^w) (rowSize : 2+2^a*dH ≤ stride) + (i : W w) (hi : i.val < sitesN*dH) : + (P).term ≤ (SupplyScan.header sBank i+1).val ∧ (SupplyScan.header sBank i+1).val < (P).supply ∧ + (P).term ≤ (SupplyScan.payload sBank i).val ∧ (SupplyScan.payload sBank i).val < (P).supply ∧ + (P).supply ≤ (sBank 6+i).val ∧ (sBank 6+i).val < (P).targetPort := by + obtain ⟨h₁,h₂,h₃,h₄,h₅,h₆,h₇⟩ := ranges P + have upto : (P).targetPort = (P).supply + sitesN*dH := rfl + have endTerm : (P).supply = (P).term + B*stride := rfl + have hsites : 0 < sitesN := by positivity + have siteFit : sitesN < 2^w := (Nat.le_mul_of_pos_right _ hdH).trans_lt (by omega) + have vpos : 0 < Fintype.card X.Base := Fintype.card_pos + have portsFit : 2^a < 2^w := ((Nat.le_mul_of_pos_left _ vpos).trans + (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos g))).trans_lt siteFit + have laneFit : 2^g < 2^w := (Nat.le_mul_of_pos_left _ (Nat.mul_pos vpos (Nat.two_pow_pos a))).trans_lt siteFit + have dims : SupplyScan.Fits (dH := dH) X w := + ⟨portsFit, laneFit, (Nat.le_mul_of_pos_left _ hsites).trans_lt (by omega), by omega⟩ + let pos := (finProdFinEquiv (m := sitesN) (n := dH)).symm ⟨i.val,hi⟩ + let s := (O).symm pos.1 + let k := pos.2 + let key := (DemandScan.blocks X s.1).val + have hk : key < B := (DemandScan.blocks X s.1).isLt + have endRow := Nat.mul_le_mul_right stride (Nat.succ_le_of_lt hk) + rw [Nat.succ_mul] at endRow + have bval : (SupplyScan.recordBase X (word (bits := w) (P).term) stride s.1).val = + (P).term+key*stride := by + dsimp only [key] + rw [DemandScan.blocks_val] + change (((P).term % 2^w + (((_ : ℕ) % 2^w)*(stride % 2^w)) % 2^w) % 2^w) = _ + rw [Nat.mod_mul_mod,Nat.mul_mod_mod,Nat.add_mod_mod,Nat.mod_add_mod] + apply Nat.mod_eq_of_lt + rw [← DemandScan.blocks_val] + change (P).term+key*stride < 2^w + omega + have index : (O s).val*dH+k.val = i.val := by + have h := congrArg Fin.val (finProdFinEquiv.apply_symm_apply (⟨i.val,hi⟩ : Fin (sitesN*dH))) + rw [show (finProdFinEquiv pos).val = pos.1.val*dH+pos.2.val from finPair_val ..] at h + simpa only [s,k,Equiv.apply_symm_apply] using h + have eqw : word ((O s).val*dH+k.val) = i := by rw [index]; exact Fin.ext (Nat.mod_eq_of_lt i.isLt) + have hrow : (SupplyScan.recordBase X (word (bits := w) (P).term) stride s.1).val+2+2^a*dH < 2^w := by + rw [bval]; omega + obtain ⟨hh,hp⟩ := physical_addresses X E hdH conn F (word (P).term) stride (word (P).supply) dims s k hrow + rw [eqw,bval] at hh hp + have hc := pack_lt s.2.isLt k.isLt + have ho : (sBank 6+i).val = (P).supply+i.val := + Plan.address_val (len := sitesN*dH) (by omega) i hi + rw [hh,hp,ho] + constructor <;> omega + +/-- The actual term-operand reads stay below the selected supply column. +Therefore later visits retain their source values while earlier output +rows stay intact. -/ +theorem supplyScan (room : (P).stop < 2^w) (rowSize : 2+2^a*dH ≤ stride) (ref : Memory w) : + Scan P ((template SupplyScan.visit 0).instantiate w sBank).program 34 0 (sitesN*dH) + (fun j m ↦ SupplyScan.Prefix sBank ref m j) (SupplyScan.events sBank) := by + have bounds := supply_ranges (t := t) X a₀ dH stride start E hdH conn F room rowSize + have apart : SupplyScan.Apart sBank (sitesN*dH) := by + intro i j hi hj + have x := bounds i hi + have y := bounds j hj + constructor <;> omega + refine ⟨fun j _ _ m ↦ SupplyScan.visit_native sBank m (j : W w), ?_⟩ + intro j _ hj m current + let i := (j : W w) + have upto : (P).targetPort = (P).supply+sitesN*dH := rfl + have h := ranges P + have hv : i.val = j := Nat.mod_eq_of_lt (by omega) + have hi : i.val < sitesN*dH := hv ▸ hj + obtain ⟨hh,hh',hp,hp',ho,ho'⟩ := bounds i hi + have readH : InArena P (SupplyScan.header sBank i+1).val := ⟨by omega,by omega⟩ + have readP : InArena P (SupplyScan.payload sBank i).val := ⟨by omega,by omega⟩ + have writeO : InArena P (sBank 6+i).val := ⟨by omega,by omega⟩ + refine ⟨?_,?_,?_⟩ + · rw [SupplyScan.events_after] + have next := step sBank ref m apart i hi (by rwa [hv]) + rwa [hv] at next + · intro addr val read + simp only [SupplyScan.events,List.mem_cons,List.not_mem_nil,Event.read.injEq, + reduceCtorEq, false_or, or_false] at read + rcases read with ⟨ha,_⟩ | ⟨ha,_⟩ + · exact ha ▸ readH + · exact ha ▸ readP + · intro addr val wr + simp [SupplyScan.events] at wr + exact wr.1 ▸ writeO + +/-- Replay evidence for the whole dense supply column. -/ +theorem supply_trace (room : (P).stop < 2^w) (rowSize : 2+2^a*dH ≤ stride) + (m : Memory w) (rs : List (Report w)) + (run : runSegment ((template SupplyScan.visit 0).instantiate w sBank).program 34 + (some 0) m (List.replicate (sitesN*dH) []) = some rs) : + StageFrame.Scanned 0 (sitesN*dH) rs ∧ Reads (InArena P) (eventLog rs) ∧ Writes (InArena P) (eventLog rs) := by + have h := supplyScan (t := t) X a₀ dH stride start E hdH conn F room rowSize m + have initial : SupplyScan.Prefix sBank m m 0 := ⟨fun _ hi ↦ False.elim (Nat.not_lt_zero _ hi),fun _ _ ↦ rfl⟩ + obtain ⟨shape,_,rd,wr⟩ := h.run (Nat.zero_le _) m rs initial (by simpa only [Nat.sub_zero,Nat.cast_zero] using run) + exact ⟨shape,rd,wr⟩ + +end Supply + +section ROM + +variable (E : RegularArcGraph (Fin (2^a)) dH) +local notation "I" => Plan.inputs P w + +/-- Publication of the two reverse-edge cells for one fixed ROM row. -/ +theorem romScan (room : (P).stop < 2^w) (i : Fin (2^a*dH)) : + let words := ExpanderROM.words E I i + Scan P ((template ExpanderROM.put 0).instantiate w words).program 12 i.val (i.val+1) + (fun j m ↦ j=i.val ∨ m ((P).targetPort+i.val) = word (E.reverse (finProdFinEquiv.symm i)).1.val ∧ + m ((P).reverseSlot+i.val) = word (E.reverse (finProdFinEquiv.symm i)).2.val) + (fun _ _ ↦ ExpanderROM.events words) := by + intro words + obtain ⟨h₁,h₂,h₃,h₄,h₅,h₆,h₇⟩ := ranges P + have headR : (P).targetPort+2^a*dH = (P).reverseSlot := rfl + have headN : (P).reverseSlot+2^a*dH = (P).next := rfl + have hp : (I).targetPort.val = (P).targetPort := Nat.mod_eq_of_lt (by omega) + have hs : (I).reverseSlot.val = (P).reverseSlot := Nat.mod_eq_of_lt (by omega) + have reg : ExpanderROM.Regions I (2^a*dH) := by + constructor + · rw [hp]; omega + · rw [hs]; omega + · exact Or.inl (by rw [hp,hs,headR]) + have hi : (word (bits := w) i.val).val = i.val := Nat.mod_eq_of_lt (by have := i.isLt; omega) + have portVal : (words 3+words 0).val = (P).targetPort+i.val := + (Plan.address_val (len := 2^a*dH) (by omega) _ (hi ▸ i.isLt)).trans (congrArg (_+·) hi) + have slotVal : (words 4+words 0).val = (P).reverseSlot+i.val := + (Plan.address_val (len := 2^a*dH) (by omega) _ (hi ▸ i.isLt)).trans (congrArg (_+·) hi) + have hp' : InArena P (words 3+words 0).val := ⟨by rw [portVal]; omega,by rw [portVal]; have := i.isLt; omega⟩ + have hs' : InArena P (words 4+words 0).val := ⟨by rw [slotVal]; omega,by rw [slotVal]; have := i.isLt; omega⟩ + refine ⟨?_,?_⟩ + · intro j hlo hhi m + have : j = i.val := by omega + subst j + exact ExpanderROM.native words _ m + · intro j _ _ m _ + have hport := written E I reg i m true + have hslot := written E I reg i m false + change after m (ExpanderROM.events words) (words 3+words 0).val = _ at hport + change after m (ExpanderROM.events words) (words 4+words 0).val = _ at hslot + rw [portVal] at hport + rw [slotVal] at hslot + refine ⟨.inr ⟨hport,hslot⟩,?_,?_⟩ + · intro addr val read + simp [ExpanderROM.events] at read + · intro addr val wr + simp [ExpanderROM.events] at wr + rcases wr with ⟨ha,_⟩ | ⟨ha,_⟩ + · exact ha ▸ hp' + · exact ha ▸ hs' + +/-- The hardwired ROM stage has exactly one source report, even when its +initial edge ordinal is positive. -/ +theorem rom_trace (room : (P).stop < 2^w) (i : Fin (2^a*dH)) (m : Memory w) : + let rep := ExpanderROM.report E I i + StageFrame.Scanned i.val (i.val+1) [rep] ∧ Reads (InArena P) (eventLog [rep]) ∧ + Writes (InArena P) (eventLog [rep]) := by + intro rep + let pub := ExpanderROM.words E I i + let M := (template ExpanderROM.put 0).instantiate w pub + have run : runSegment M.program 12 (some (i.val : W w)) m [[]] = some [rep] := by + rw [runSegment,ExpanderROM.native] + rfl + obtain ⟨shape,_,rd,wr⟩ := (romScan (t := t) X a₀ dH stride start E room i).run + (Nat.le_succ _) m [rep] (.inl rfl) (by rw [Nat.add_sub_cancel_left]; exact run) + exact ⟨shape,rd,wr⟩ + +end ROM +end CompressorRecords.PortRefresh.TermDataFrame + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalChild.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalChild.lean new file mode 100644 index 0000000000..36b25f3a92 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalChild.lean @@ -0,0 +1,136 @@ +import OAI.Computability.VPVNP.CompressorRefreshLevelDirectory +import OAI.Computability.VPVNP.PairTraversalRoles + +/-! +# Singleton child rows of a selected refresh + +Promotion retains the preceding site's numerical identifier. In the physical +DFS arena the corresponding child address is obtained from the preceding layer +base and the same identifier as the popped parent. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.RefreshPlacement + +open PairSimulation BurstRAM Compression Compression.Refresh Compression.DegreeRefresh + PairSimulation.LocalHistory PairSimulation.TraversalRows +open scoped Fin.CommRing + +open private placementLayer from OAI.Computability.VPVNP.PairTraversalStageSize +open private preimage_singleton from OAI.Computability.VPVNP.CompressorRefreshPlacementRows +open private actualPass from OAI.Computability.VPVNP.CompressorRefreshLevelDirectory + +variable {g : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {A : Type*} [CommRing A] (f : B.Entry → A) (hf : B.IsSolution f) + (X : State S.portExponent (S.portExponent + g)) + (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (bits : List Bool) + +/-- The selected refresh pass packaged with its input state, promoted output, refresh origin, +term choice and branch bits for DFS traversal. -/ +abbrev traversalLevel : SelectedLevel B f hf := + ⟨_, _, _, _, X, actualPass f hf X, .refresh X, choice, bits⟩ + +/-- This site has exactly its own ordinal as its child, including at nonzero +residual - lane offsets. The proof identifies the stored order using the native +identity preimage list. -/ +theorem layer_singleton (i : Fin (levelLayer B f hf (traversalLevel f hf X choice bits)).count) : + (levelLayer B f hf (traversalLevel f hf X choice bits)).ids i = [i.val] := by + classical + let prev := siteOrder X + let next := siteOrder ((actualPass f hf X).next choice) + let t := (actualPass f hf X).step.term choice + let place := t.place + let width := X.positions + have counts := site_counts f hf X choice + have oldRoom : prev.length ≤ 2 ^ width := counts.1.trans_le (Nat.le_of_lt Nat.lt_two_pow_self) + have newRoom : next.length ≤ 2 ^ width := counts.2.trans_le (Nat.le_of_lt Nat.lt_two_pow_self) + have fit : i.val < prev.length := i.isLt.trans_eq (counts.2.trans counts.1.symm) + have hi : i.val < 2 ^ width := fit.trans_le oldRoom + let j : Fin next.length := i + let v := next.entries j + have code : siteWord width next v = (i.val : BurstRAM.Word width) := by + change Fin.ofNat (2 ^ width) (next.entries.symm (next.entries j)).val = Fin.ofNat + (2 ^ width) j.val + rw [Equiv.symm_apply_apply] + have ordered := preimagePrefix_eq_orderedIds prev next place id + (placement_identity (w := width) f hf X choice) oldRoom newRoom v + have single := preimage_singleton oldRoom (siteWord width next v) (by + rw [code, Fin.val_natCast, Nat.mod_eq_of_lt hi]; exact fit) + have numeric := congrArg (List.map Fin.val) (ordered.symm.trans single) + rw [code] at numeric + have value (u : X.network.Site) : (siteWord width prev u).val = (prev.entries.symm u).val := + Nat.mod_eq_of_lt ((prev.entries.symm u).isLt.trans_le oldRoom) + simp only [orderedIds, List.map_ofFn, Function.comp_def, value, List.map_cons, List.map_nil, + Fin.val_natCast, Nat.mod_eq_of_lt hi] at numeric + exact numeric + +/-- A row returned by the native traversal arena points directly to the matching +node in the preceding layer at the actual exclusive row stride. -/ +theorem singleton_row {w cap prev base : ℕ} {m : Memory w} + (rows : (levelLayer B f hf (traversalLevel f hf X choice bits)).Rows w m cap prev base) + (i : Fin (levelLayer B f hf (traversalLevel f hf X choice bits)).count) : + DFS.Row m (address cap base i.val) (address cap base i.val + 2) + [(address cap prev i.val : BurstRAM.Word w)] := by + simpa only [childWords, layer_singleton f hf X choice bits i, List.map_cons, List.map_nil] using + (rows i).2 + +open TraversalRoles + +private theorem successor_rows {w cap previous base : ℕ} {m : Memory w} {layers : List TaggedLayer} + (rows : AllRows w m cap previous base (layers.map TaggedLayer.layer)) (i : ℕ) + (hi : i + 1 < layers.length) : + layers[i + 1].layer.Rows w m cap (layerBase cap base layers i) (layerBase cap base layers + (i + 1)) := by + induction layers generalizing previous base i with + | nil => simp at hi + | cons L layers ih => + change L.layer.Rows w m cap previous base ∧ AllRows w m cap base (endPos cap base L.layer) + (layers.map TaggedLayer.layer) at rows + cases i with + | zero => + cases layers with + | nil => simp at hi + | cons H tail => + simpa only [List.getElem_cons_succ, List.getElem_cons_zero, layerBase_cons, + layerBase_zero] using rows.2.1 + | succ i => + simpa only [List.getElem_cons_succ, layerBase_cons] using + ih rows.2 i (by simpa only [List.length_cons, Nat.add_lt_add_iff_right] using hi) + +/-- Extract the singleton row directly from the all-level memory guarantee of the +native arena, at the two layer bases used by the popped-node locator. -/ +theorem selected_row {n w base : ℕ} {m : Memory w} (T : ℕ) (hT : T * S.laneBits ≤ n) + (initial : State (S.degreeExponent 0) n) (z : (B.execute f hf T hT initial).Choices) + (rows : AllRows w m B.recordLimit base base (selectedLayers B f hf T hT initial z)) + (stage : Fin (executeLevels B f hf T hT initial z).length) + (refresh : (executeLevels B f hf T hT initial z)[stage] = traversalLevel f hf X choice bits) + (i : Fin (levelLayer B f hf (traversalLevel f hf X choice bits)).count) : + let tags := selected B f hf T hT initial z + let parent := address B.recordLimit (layerBase B.recordLimit base tags (stage.val + 1)) i.val + let child := address B.recordLimit (layerBase B.recordLimit base tags stage.val) i.val + DFS.Row m parent (parent + 2) [(child : BurstRAM.Word w)] := by + let tags := selected B f hf T hT initial z + have all : AllRows w m B.recordLimit base base (tags.map TaggedLayer.layer) := by + rwa [selected_layers] + have bound : stage.val + 1 < tags.length := by simp [tags, selected] + have layer : tags[stage.val + 1].layer = levelLayer B f hf + (traversalLevel f hf X choice bits) := by + simp only [tags, selected, List.getElem_cons_succ, List.getElem_map] + exact congrArg (levelLayer B f hf) refresh + have row := successor_rows all stage.val bound + rw [layer] at row + exact singleton_row f hf X choice bits row i + +end CompressorRecords.RefreshPlacement + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalHeadReads.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalHeadReads.lean new file mode 100644 index 0000000000..f4fc7c1a4f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalHeadReads.lean @@ -0,0 +1,79 @@ +import OAI.Computability.VPVNP.CompressorRefreshArgumentReads +import OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders + +/-! +# Header and singleton-row reads of the refresh role + +The expressions that compute incidence and scratch heads read the published old and +new level headers. The child-node pointer uses exactly two cells of the preimage row. +All subsequent offset arithmetic on the level-plan operands introduces no probes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.TraversalHeaders + +open BurstRAM PhaseRecipe Compression PairSimulation NewSlots +open scoped Fin.CommRing + +variable {w : ℕ} (pub : Fin 5 → W w) (state : W w) (m : Memory w) (limit : ℕ) + +/-- The child and parent argument addresses are readable, and the lane count, segment heads and +demand and term bases read only below the stated memory limit. -/ +structure InputReads (I : OperandInputs.Input) : Prop where + child : ArgumentAddress.Readable I.child limit pub state m + parent : ArgumentAddress.Readable I.parent limit pub state m + lanes : I.lanes.ReadsFrom (· < limit) pub state m + offOut : I.offOut.ReadsFrom (· < limit) pub state m + offIn : I.offIn.ReadsFrom (· < limit) pub state m + widthOut : I.widthOut.ReadsFrom (· < limit) pub state m + widthIn : I.widthIn.ReadsFrom (· < limit) pub state m + demand : I.demandBase.ReadsFrom (· < limit) pub state m + term : I.termBase.ReadsFrom (· < limit) pub state m + +local notation "ok" => Expr.ReadsFrom (· < limit) pub state m + +theorem input_reads (s : LevelRecipe.Shape) {oldHead newHead parent listHead child : ℕ} + (stateWord : state.val = oldHead) (newWord : (pub 2).val = newHead) + (parentWord : (pub 1).val = parent) + (row : DFS.Row m parent listHead [word (bits := w) child]) + (oldBefore : oldHead + 60 < limit) (newBefore : newHead + 59 < limit) + (parentBefore : parent < limit) (listBefore : listHead < limit) : + InputReads pub state m limit (input s) := by + have addBound (x : W w) (v : ℕ) : (x + (v : W w)).val ≤ x.val + v := + (Nat.mod_le ..).trans (Nat.add_le_add_left (Nat.mod_le ..) _) + have old (j : ℕ) (hj : j ≤ 60) : ok (.header j) := by + refine ⟨⟨trivial, trivial⟩, ?_⟩ + change (state + (j : W w)).val < limit + apply (addBound ..).trans_lt; omega + have curr (j : ℕ) (hj : j ≤ 59) : ok (current j) := by + refine ⟨⟨trivial, trivial⟩, ?_⟩ + change (pub 2 + (j : W w)).val < limit + apply (addBound ..).trans_lt; omega + have childAt : ok traversal.child := by + refine ⟨⟨trivial, parentWord ▸ parentBefore⟩, ?_⟩ + change (m (pub 1).val).val < limit + rw [parentWord, row.2.2.1] + exact (Nat.mod_le ..).trans_lt listBefore + have ls : ok level.lanes := old 3 (by decide) + have vs : ok level.vertices := old 0 (by decide) + have st : ok level.start := old 60 le_rfl + have seg : ok (LevelRecipe.segments s level) := ⟨⟨⟨vs, trivial⟩, ls⟩, trivial⟩ + have sc (j : Fin 8) : ok (LevelRecipe.scratch s level j) := by + unfold LevelRecipe.scratch; split + · trivial + · exact ⟨st, trivial, seg⟩ + have dm : ok (LevelRecipe.demandStart s level) := ⟨st, trivial, seg⟩ + have tr : ok (LevelRecipe.termStart s level) := ⟨dm, ⟨vs, ls⟩, trivial⟩ + exact ⟨⟨old 17 (by decide), old 18 (by decide), childAt, trivial, old 58 (by decide), old 59 + (by decide)⟩, + ⟨old 17 (by decide), old 18 (by decide), trivial, trivial, curr 58 (by decide), curr 59 le_rfl⟩, + ls, sc 5, sc 6, sc 1, sc 7, dm, tr⟩ + +end CompressorRecords.PortRefresh.TraversalHeaders + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalHeaders.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalHeaders.lean new file mode 100644 index 0000000000..aa945fa4a5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalHeaders.lean @@ -0,0 +1,310 @@ +import OAI.Computability.VPVNP.CompressorRefreshArgumentPlan +import OAI.Computability.VPVNP.CompressorBlockMetadata +import OAI.Computability.VPVNP.PairTraversalArena + +/-! +# Refresh operands at a completed DFS node + +The persistent state names the input level header. Public operands zero, one and two +name the owner site, popped parent node, and current level header. The sole child is +read through the parent row pointer. The parent node uses the canonical inverse-slot +and width columns named by the current header. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.TraversalHeaders + +open BurstRAM PhaseRecipe Compression Compression.Refresh Compression.DegreeRefresh NewSlots +open OperandInputs RefreshMapOperands PairSimulation PairSimulation.NodeArguments DescriptorSpace +open scoped Fin.CommRing + +/-- Read the six level-plan operands from the old header. The first table pointer +starts the packed refresh scratch region. -/ +def level : LevelRecipe.Input := + ⟨.header 60, .header 0, .header 3, .header 54, .header 56, .header 59⟩ + +/-- Refresh traversal expressions for the saved arena start and stride, the sole child's +address read through the parent pointer, the parent and owner operands, and the old +incoming-slot head. -/ +def traversal : OperandInputs.Traversal := + ⟨.header 17, .header 18, .load (.load (.publicWord 1)), .publicWord 1, .publicWord 0, .header 58⟩ + +/-- Load the field at the given offset in the successor level header whose base is public +operand two. -/ +def current (offset : ℕ) : Expr := .load ((Expr.publicWord 2).add (.lit offset)) + +/-- Retain the old level's segment and term addresses, while sourcing the new incidence +columns from the successor's canonical header. -/ +def input (s : LevelRecipe.Shape) : OperandInputs.Input := + let I := fromLevel s level traversal + { I with parent := { I.parent with actualIn := current 58, width := current 59 } } + +variable {w : ℕ} + +/-- Typed values in the persisted level headers used by the actual refresh expression +bank. The two canonical incidence arrays may occupy separate physical regions. -/ +structure Geometry (V g oldHead newHead start : ℕ) (A : Arena) (T U : IncidenceDirectory w) + (m : Memory w) : Prop where + oldRoom : oldHead + 60 < 2 ^ w + newRoom : newHead + 59 < 2 ^ w + vertices : m (oldHead + 0) = word V + residual : m (oldHead + 3) = word (2 ^ g) + arena : m (oldHead + 17) = word A.start + stride : m (oldHead + 18) = word A.stride + oldIncidence : ∀ c : Fin 6, m (oldHead + 54 + c.val) = T.column c + newIncidence : ∀ c : Fin 6, m (newHead + 54 + c.val) = U.column c + scratch : m (oldHead + 60) = word start + +/-- Transfer retained header facts through later planner and traversal writes. -/ +theorem Geometry.keep {V g oldHead newHead start : ℕ} {A : Arena} {T U : IncidenceDirectory w} + {m m' : Memory w} + (data : Geometry V g oldHead newHead start A T U m) + (old : ∀ n ≤ 60, m' (oldHead + n) = m (oldHead + n)) + (new : ∀ n ≤ 59, m' (newHead + n) = m (newHead + n)) : + Geometry V g oldHead newHead start A T U m' := by + refine ⟨data.oldRoom, data.newRoom, (old 0 (by decide)).trans data.vertices, + (old 3 (by decide)).trans data.residual, (old 17 (by decide)).trans data.arena, + (old 18 (by decide)).trans data.stride, ?_, ?_, (old 60 le_rfl).trans data.scratch⟩ + · intro c + rw [Nat.add_assoc, old _ (by have := c.isLt; omega), ← Nat.add_assoc] + exact data.oldIncidence c + · intro c + rw [Nat.add_assoc, new _ (by have := c.isLt; omega), ← Nat.add_assoc] + exact data.newIncidence c + +private theorem addr_val {x : W w} {base offset : ℕ} (h : x.val = base) + (room : base + offset < 2 ^ w) : + (x + word offset).val = base + offset := by + rw [Fin.val_add, h, Fin.val_ofNat, Nat.mod_eq_of_lt (show offset < 2 ^ w by omega), + Nat.mod_eq_of_lt room] + +/-- The two external loads at the popped parent read its first and unique child. -/ +theorem child_read {pub : Fin 5 → W w} {state : W w} {m : Memory w} {parent child listHead : ℕ} + (hp : (pub 1).val = parent) (row : DFS.Row m parent listHead [word child]) : + traversal.child.eval pub state m = word child := by + obtain ⟨_, room, head, _, kids⟩ := row + have hl : (m parent).val = listHead := by + rw [head] + exact Nat.mod_eq_of_lt (by + simpa using (Nat.lt_of_le_of_lt (Nat.le_add_right listHead _) room)) + change m (m (pub 1).val).val = _ + rw [hp, hl] + exact kids ⟨0, by simp⟩ + +variable (s : LevelRecipe.Shape) {g : ℕ} (X : State s.a (s.a + g)) + (p : (X.Base × BitWord g) × Fin (2 ^ s.a)) (P : SlotGraph (Fin (2 ^ s.a)) s.dH) + (hD : 1 < 2 ^ s.a) (hd : s.dH + 1 ≤ 2 ^ s.a₀) + (internal : X.Base × BitWord g → Fin (2 ^ s.a) × Fin s.dH → ℕ) + (A : Arena) (T U : IncidenceDirectory w) (C : LevelRecipe.Context w) + +local notation "O" => sites (D := 2 ^ s.a) X.baseIndex (bitWordFinEquiv g) + +/-- The fixed header expressions evaluate to all typed operands of the chosen map. +The old and current headers, saved site, and popped parent are the four live DFS words. -/ +theorem describes {oldHead newHead start parent child listHead : ℕ} + (geometry : Geometry (Fintype.card X.Base) g oldHead newHead start A T U C.memory) + (state : C.state.val = oldHead) (newHeadWord : (C.pub 2).val = newHead) + (site : (C.pub 0).val = (O p).val) (parentWord : (C.pub 1).val = parent) + (row : DFS.Row C.memory parent listHead [word child]) (lanesFit : 2 ^ g < 2 ^ w) : + Describes (input s) C.pub C.state C.memory X p P hD hd internal A child parent T U + ((Allocation.plan X s.a₀ s.dH s.ties s.stride start).scratch w) + (word (Allocation.plan X s.a₀ s.dH s.ties s.stride start).demand) + (word (Allocation.plan X s.a₀ s.dH s.ties s.stride start).term) := by + have oldRead (i : ℕ) (hi : i ≤ 60) : C.eval (.header i) = C.memory (oldHead + i) := + congrArg C.memory (addr_val state ((Nat.add_le_add_left hi _).trans_lt geometry.oldRoom)) + have newRead (i : ℕ) (hi : i ≤ 59) : C.eval (current i) = C.memory (newHead + i) := + congrArg C.memory (addr_val newHeadWord ((Nat.add_le_add_left hi _).trans_lt geometry.newRoom)) + have levelData : LevelRecipe.Describes (s := s) level C X start T := + ⟨(oldRead 60 le_rfl).trans geometry.scratch, (oldRead 0 (by decide)).trans geometry.vertices, + (oldRead 3 (by decide)).trans geometry.residual, + (oldRead 54 (by decide)).trans (geometry.oldIncidence 0), + (oldRead 56 (by decide)).trans (geometry.oldIncidence 2), + (oldRead 59 (by decide)).trans (geometry.oldIncidence 5)⟩ + have prev := describes_fromLevel s level traversal C X p P hD hd internal A child parent start T + levelData + ((oldRead 17 (by decide)).trans geometry.arena) ((oldRead 18 (by decide)).trans geometry.stride) + (child_read (state := C.state) parentWord row) + (Fin.ext (parentWord.trans (Nat.mod_eq_of_lt (parentWord ▸ (C.pub 1).isLt)).symm)) site + ((oldRead 58 (by decide)).trans (geometry.oldIncidence 4)) lanesFit + refine ⟨prev.childRep, ?_, prev.site, prev.lanes, prev.offOut, prev.offIn, + prev.widthOut, prev.widthIn, + prev.demandBase, prev.termBase⟩ + exact ⟨prev.parentRep.arena, prev.parentRep.stride, prev.parentRep.node, prev.parentRep.site, + (newRead 58 (by decide)).trans (geometry.newIncidence 4), + (newRead 59 le_rfl).trans (geometry.newIncidence 5)⟩ + +/-- Both pointer banks as emitted by the native incidence/table-head publisher. -/ +structure HeadBank (L : Layout) (i rows : ℕ) (m : Memory w) : Prop where + incidence : ∀ c : Fin 6, m (incidenceHead L i c) = word (incidenceBase L i rows c) + tables : ∀ c : Fin L.shape.tables, m (tableHead L i c) = word (tableBase L i c) + +theorem HeadBank.ofNative {L : Layout} {i : Fin L.levels} {rows : ℕ} {m : Memory w} + (run : BlockHeaderRun.HeadsRun L i rows m) : + HeadBank L i rows (after m (eventLog [BlockHeaderRun.headReport L i m])) := by + simpa only [eventLog, List.flatMap_cons, List.flatMap_nil, List.append_nil] using + (show HeadBank L i rows (after m (BlockHeaderRun.headReport L i m).events) from + ⟨run.incidence, run.tables⟩) + +theorem HeadBank.keep {L : Layout} {i rows : ℕ} {m m' : Memory w} (data : HeadBank L i rows m) + (same : ∀ n < levelHeaderWords L, m' (levelStart L i + n) = m (levelStart L i + n)) : + HeadBank L i rows m' := by + constructor + · intro c + rw [incidenceHead, Nat.add_assoc, same _ (by unfold levelHeaderWords; have := c.isLt; omega), + ← Nat.add_assoc] + exact data.incidence c + · intro c + change m' (levelStart L i + L.shape.scalarFields + 6 + c.val) = _ + rw [Nat.add_assoc, Nat.add_assoc, same _ (by unfold levelHeaderWords; have := c.isLt; omega)] + simpa only [tableHead, Nat.add_assoc] using data.tables c + +private theorem header_before {L : Layout} {i j : ℕ} (order : i < j) : + levelStart L i + levelHeaderWords L ≤ levelStart L j := by + refine le_trans ?_ (levelStart_mono L order) + unfold levelStart; rw [Nat.succ_mul]; unfold levelWords; omega + +private theorem HeadBank.keep_pointers {L : Layout} {i rows : ℕ} {m m' : Memory w} + (data : HeadBank L i rows m) + (same : ∀ n, L.shape.scalarFields ≤ n → n < levelHeaderWords L → + m' (levelStart L i + n) = m (levelStart L i + n)) : HeadBank L i rows m' := by + constructor + · intro c + rw [incidenceHead, Nat.add_assoc, same _ (by omega) + (by unfold levelHeaderWords; have := c.isLt; omega)] + simpa only [incidenceHead, Nat.add_assoc] using data.incidence c + · intro c + change m' (levelStart L i + L.shape.scalarFields + 6 + c.val) = _ + rw [Nat.add_assoc, Nat.add_assoc, same _ (by omega) + (by unfold levelHeaderWords; have := c.isLt; omega)] + simpa only [tableHead, Nat.add_assoc] using data.tables c + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} {v : SelectedLevel B f hf} + +/-- The scalar relabel and successor publisher retain the old pointers and produce +the new incidence/table heads in the same memory. -/ +theorem headBanks_of_substep {L : Layout} {i j : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} + {rows : ℕ} {m : Memory w} (run : BlockHeaderRun.Substep v L i j six m) + (order : i.val < j.val) (old : HeadBank L i rows m) : + HeadBank L i rows (BlockHeaderRun.finalMemory v L i j m) ∧ + HeadBank L j v.outputSlots (BlockHeaderRun.finalMemory v L i j m) := by + refine ⟨old.keep_pointers ?_, ⟨run.heads.incidence, run.heads.tables⟩⟩ + have span := header_before (L := L) order + intro n lower upper + apply run.outside + all_goals omega + +/-- Read the private frame origin and stride from the twelve published metadata words. +These are positions two and three of the packet starting at header offset fifteen. -/ +theorem arena_of_packet {m : Memory w} {head limit degree slots n ain width sites : ℕ} + (placement : BlockMetadata.Placement) + (packet : ∀ j : Fin 12, m (head + 15 + j.val) = + word (BlockMetadata.payload limit slots degree n ain width sites placement j)) : + m (head + 17) = word n ∧ m (head + 18) = word (frameStride slots n) := by + constructor + · have h := packet 2 + change m (head + 15 + 2) = word n at h + rw [Nat.add_assoc] at h; exact h + · have h := packet 3 + change m (head + 15 + 3) = word (frameStride slots n) at h + rw [Nat.add_assoc] at h; exact h + +/-- The actual scalar publisher, old and current incidence head banks, table zero, +and the published metadata packet provide the traversal geometry. -/ +theorem Geometry.ofPublished {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} {v : SelectedLevel B f hf} + {dH : ℕ} + {L : Layout} {i j : Fin L.levels} {oldRows newRows : ℕ} {m : Memory w} + (oldScalars : LevelFields.Published L i v dH m) (old : HeadBank L i oldRows m) + (new : HeadBank L j newRows m) + (scalarCount : L.shape.scalarFields = 54) (hasTables : 0 < L.shape.tables) + (room : endAddress L < 2 ^ w) + (A : Arena) (arena : m (levelStart L i + 17) = word A.start) + (stride : m (levelStart L i + 18) = word A.stride) : + Geometry (Fintype.card v.input.Base) v.outputLanes (levelStart L i) (levelStart L j) + (arrayBase L i) + A (packedIncidence L w i oldRows) (packedIncidence L w j newRows) m := by + have span (l : Fin L.levels) : levelStart L l + 61 ≤ levelStart L (l.val + 1) := by + have hw : 61 ≤ levelWords L := by unfold levelWords levelHeaderWords; omega + unfold levelStart; rw [Nat.succ_mul]; omega + have bank (l : Fin L.levels) (rows : ℕ) (h : HeadBank L l rows m) (c : Fin 6) : + m (levelStart L l + 54 + c.val) = (packedIncidence L w l rows).column c := by + rw [packed_column] + simpa only [incidenceHead, scalarCount] using h.incidence c + refine ⟨(Nat.add_le_add_left (by decide : 60 ≤ 61) _).trans_lt + ((span i).trans_lt (level_room L room i)), + (Nat.add_le_add_left (by decide : 59 ≤ 61) _).trans_lt + ((span j).trans_lt (level_room L room j)), + oldScalars.vertices, oldScalars.residual, arena, stride, bank i oldRows old, + bank j newRows new, ?_⟩ + let c : Fin L.shape.tables := ⟨0, hasTables⟩ + simpa [tableHead, tableBase, c, scalarCount, Nat.add_assoc] using old.tables c + +/-- Run the native metadata visits over the emitted scalar and pointer banks. +Only the input-length cell of the initial header is needed to calculate the +private argument frame. The result supplies its actual readback at the old header. -/ +theorem run_metadata {L : Layout} {first step : ℕ} {pub : Fin 5 → W w} {state : W w} (m : Memory w) + (entry : LevelFields.Entry L first pub state m) (limit slots : ℕ) + (placement : BlockMetadata.Fields) + {oldSites n oldRows newRows dH : ℕ} + (sitesEq : (LevelFields.sites step).eval pub state m = word oldSites) + (firstHeader : BlockHeaderPlan.firstHeader.eval pub state m = word (levelStart L 0)) + (nCell : m (levelStart L 0 + 29) = word n) + (oldScalars : LevelFields.Published L (first + step) v dH m) + (old : HeadBank L (first + step) oldRows m) (new : HeadBank L (first + (step + 1)) newRows m) + (scalarCount : L.shape.scalarFields = 54) (hasTables : 0 < L.shape.tables) + (nextLevel : first + (step + 1) < L.levels) (room : endAddress L < 2 ^ w) + (pitchBefore : (pub 1 - 1).val < levelStart L (first + step)) : + ∃ rs, SourceWalk (BlockMetadata.Source pub state) + (BlockMetadata.visits L.shape step limit slots .refresh placement) m rs ∧ + Geometry (Fintype.card v.input.Base) v.outputLanes (levelStart L (first + step)) + (levelStart L (first + (step + 1))) (arrayBase L (first + step)) ⟨n, frameStride slots n⟩ + (packedIncidence L w (first + step) oldRows) + (packedIncidence L w (first + (step + 1)) newRows) + (after m (eventLog rs)) := by + obtain ⟨rs, walk, packet, _, _, keep, _⟩ := BlockMetadata.publish_metadata m entry limit slots + .refresh placement oldSites sitesEq (by omega) nextLevel room pitchBefore + let i : Fin L.levels := ⟨first + step, by omega⟩ + let j : Fin L.levels := ⟨first + (step + 1), nextLevel⟩ + have span := header_before (L := L) (show first + step < first + (step + 1) by omega) + have headerLen : 60 ≤ levelHeaderWords L := by unfold levelHeaderWords; omega + let out := after m (eventLog rs) + have low (a : ℕ) (ha : a < 15) : out (levelStart L i + a) = m (levelStart L i + a) := by + change out (levelStart L (first + step) + a) = _ + apply keep <;> omega + have prev : LevelFields.Published L i v dH out := + ⟨oldScalars.room, (low 0 (by decide)).trans oldScalars.vertices, + (low 1 (by decide)).trans oldScalars.degree, + (low 2 (by decide)).trans oldScalars.lanes, (low 3 (by decide)).trans oldScalars.residual, + (low 4 (by decide)).trans oldScalars.nextDegree, (low 5 (by decide)).trans oldScalars.expander⟩ + have oldBank : HeadBank L i oldRows out := old.keep_pointers (by + intro a lower upper; apply keep <;> omega) + have newBank : HeadBank L j newRows out := new.keep_pointers (by + intro a lower upper; apply keep <;> omega) + have firstSpan := header_before (L := L) (show 0 < L.levels by omega) + change levelStart L 0 + levelHeaderWords L ≤ endAddress L at firstSpan + have len : BlockMetadata.lengthWord.eval pub state m = word n := by + change m (BlockHeaderPlan.firstHeader.eval pub state m + word 29).val = _ + rw [firstHeader, addr_val (base := levelStart L 0) (Nat.mod_eq_of_lt (by omega)) (by omega), + nCell] + refine ⟨rs, walk, Geometry.ofPublished prev oldBank newBank scalarCount hasTables room _ ?_ ?_⟩ + · have h := packet 2 + change out (levelStart L i + 15 + 2) = BlockMetadata.lengthWord.eval pub state m at h + rw [Nat.add_assoc, len] at h + exact h + · have h := packet 3 + change out (levelStart L i + 15 + 3) = + (word (2 * slots)) * BlockMetadata.lengthWord.eval pub state m + 1 at h + rw [Nat.add_assoc, len] at h + change out (levelStart L i + 18) = ((2 * slots * n + 1 : ℕ) : W w) + change out (levelStart L i + 18) = ((2 * slots : ℕ) : W w) * (n : W w) + 1 at h + simpa only [Nat.cast_add, Nat.cast_mul, Nat.cast_one] using h + +end CompressorRecords.PortRefresh.TraversalHeaders + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalRecipeReads.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalRecipeReads.lean new file mode 100644 index 0000000000..1e9a7cf9bd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshTraversalRecipeReads.lean @@ -0,0 +1,182 @@ +import OAI.Computability.VPVNP.CompressorRefreshTraversalHeadReads +import OAI.Computability.VPVNP.CompressorRefreshMapCall +import OAI.Computability.VPVNP.CompressorRefreshDiagonalFrame +import OAI.Computability.VPVNP.CompressorRefreshMapRoute + +/-! +# Addresses read by the refresh diagonal, dispatch and motif map recipes + +The diagonal reads two widths and two segment offsets at the selected arc. Every motif +read is in an actual incidence column, a segment column, a demand row or the admitted +term row. The bound applies even to map operands whose endpoint has zero width. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.PortRefresh.TraversalRecipeReads + +open BurstRAM Compression Compression.Refresh Compression.DegreeRefresh PhaseRecipe +open OperandInputs PairSimulation.NodeArguments RefreshMapOperands NewSlots +open scoped Fin.CommRing +open private scratch_addr from OAI.Computability.VPVNP.CompressorRecordRefreshAllocation + +variable {bits g t : ℕ} {k : Type} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + (X : State S.portExponent (S.portExponent + g)) + (choice : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (And.left (S.port_bound.connected_and_pos S.port_order)) B.refresh) + (v : (X.Base × BitWord g) × Fin (2 ^ S.portExponent)) (A : Arena) (child parent : ℕ) + (U V : IncidenceDirectory bits) (ties : Fin t ≃ Tie (2 ^ S.portExponent)) (start stride limit : ℕ) + (pub : Fin 5 → W bits) (state : W bits) (m : Memory bits) (I : Input) +local notation "D" => 2 ^ S.portExponent +local notation "H" => 2 ^ S.expanderExponent +local notation "hc" => And.left (S.port_bound.connected_and_pos S.port_order) +local notation "hd" => And.right S.degree_bounds +local notation "P" => S.graph.toSlotGraph +local notation "supply" => + blockSupplyWidths (splitSlots X) (bitWordFinEquiv _) (splitWidths X) S.graph + (Nat.two_pow_pos _) hc B.refresh choice +local notation "Y" => + dyadicRefreshNext X S.graph (Nat.two_pow_pos _) hc B.refresh S.port_order hd choice +local notation "Pl" => Allocation.plan X (S.degreeExponent 0) H t stride start +local notation "N" => Fintype.card X.Base * 2 ^ (S.portExponent + g) * 2 ^ S.portExponent +local notation "NN" => Fintype.card (State.Base Y) * 2 ^ g * 2 ^ (S.degreeExponent 0) +local notation "ok" => Expr.ReadsFrom (· < limit) pub state m +local notation "ev" => Expr.eval pub state m + +private theorem indexed_lt {w : ℕ} (h i j : ℕ) (k : W w) (v : ℕ) (eqn : k = word v) (hk : v < i) + (hj : j < h) : + (k * word h + word j).val < i * h := by + rw [eqn, Fin.val_add, Fin.val_mul] + have x : (word (bits := w) v).val ≤ v := Nat.mod_le .. + have y : (word (bits := w) h).val ≤ h := Nat.mod_le .. + have z : (word (bits := w) j).val ≤ j := Nat.mod_le .. + have b := (Nat.mod_le ((word (bits := w) v).val * (word (bits := + w) h).val) (2 ^ w)).trans (Nat.mul_le_mul x y) + have c := Nat.mul_le_mul_right h (Nat.succ_le_of_lt hk) + rw [Nat.succ_mul] at c + exact (Nat.mod_le ..).trans_lt (by omega) + +private theorem row_lt {w : ℕ} (base count stride j v : ℕ) (hw : v < count) (hj : j < stride) : + (word (bits := w) base + word v * word stride + word j).val < base + count * stride := by + have bound := indexed_lt stride count j (word (bits := w) v) v rfl hw hj + rw [add_assoc, Fin.val_add] + exact (Nat.mod_le ..).trans_lt (Nat.add_lt_add_of_le_of_lt (Nat.mod_le ..) bound) + +set_option maxHeartbeats 1600000 in +-- The proof unfolds the recipes for each old and new port and for each map field. +/-- Simultaneous address bound for all selected refresh recipes. The extent conditions +are the sizes of the retained native columns and of the packed refresh allocation. -/ +theorem fields {fit : Fintype.card X.Base * D * 2 ^ g * D ≤ 2 ^ bits} (directory histogram : Expr) + (data : Describes I pub state m X v P S.port_order hd supply A child parent U V + ((Pl).scratch bits) (word (Pl).demand) (word (Pl).term)) + (heads : TraversalHeaders.InputReads pub state m limit I) (old : U.ActualColumns X m) + (new : V.ActualColumns Y m) + (oi : U.actualIn.val + N ≤ limit) (ow : U.width.val + N ≤ limit) + (ni : V.actualIn.val + NN ≤ limit) (nw : V.width.val + NN ≤ limit) + (area : (Pl).supply ≤ limit) (fitLimit : limit ≤ 2 ^ bits) + (wide : D < 2 ^ bits) (enough : 2 + D * H ≤ stride) (dirRead : ok directory) + (histRead : ok histogram) : + (∀ j, ok (DiagonalFrame.fields D (refreshSlots hd (Sum.inl 0)) I j)) ∧ + (∀ j, ok (MapRoute.fields D stride I j)) ∧ + ∀ a, ok (MapCallWords.fields P hd ties stride I + (MapCallWords.plannedHeads D H stride I directory histogram) a) := by + let slot := ArgumentSite.portIndex D I.parent.siteOrd I.lanes + let block := ArgumentSite.blockIndex D I.parent.siteOrd I.lanes + have slotR : ok slot := ⟨⟨heads.parent.site, heads.lanes⟩, trivial⟩ + have blockR : ok block := + ⟨⟨⟨⟨heads.parent.site, heads.lanes⟩, trivial⟩, heads.lanes⟩, heads.parent.site, heads.lanes⟩ + have bv : ev block = word (DemandScan.blocks X v.1).val := + ArgumentSite.blockIndex_eval X v pub state m _ _ data.site data.lanes wide + have blockLt : (DemandScan.blocks X v.1).val < (Pl).blocks := (DemandScan.blocks X v.1).isLt + have oldAt := ArgumentAddress.field_reads_below heads.child data.childRep old oi ow + have oldStatic := ArgumentAddress.fieldStatic_reads_below heads.child data.childRep old oi ow + have newStatic := ArgumentAddress.fieldStatic_reads_below heads.parent data.parentRep new ni nw + have dmBefore : (Pl).demand ≤ (Pl).supply := + by unfold Allocation.Plan.supply Allocation.Plan.term; omega + have readSegment (head : Expr) (c : Fin 8) (hne : c ≠ 0) (hr : ok head) + (value : ev head = (Pl).scratch bits c) + (j : Fin D) (idx : Expr) (index : ok idx) + (hi : ev idx = idWord (sites X.baseIndex (bitWordFinEquiv g)) fit (v, j)) : + ok (.load (head.add idx)) := by + refine ⟨⟨hr, index⟩, ?_⟩ + change (ev head + ev idx).val < limit + rw [value, hi] + exact (scratch_addr Pl (dmBefore.trans (area.trans fitLimit)) c hne _ (numbered _ (v, + j)).isLt).trans_le (dmBefore.trans area) + let diagonal := ArgumentSite.diagonal D I.parent.siteOrd I.lanes + have dR : ok diagonal := ⟨⟨heads.parent.site, trivial⟩, slotR⟩ + have dv := ArgumentSite.diagonal_eval X v pub state m I.parent.siteOrd I.lanes data.site + data.lanes wide fit + have termAt (j : ℕ) (hj : j < stride) : + ok (.load ((I.termBase.add (block.mul (.lit stride))).add (.lit j))) := by + refine ⟨⟨⟨heads.term, blockR, trivial⟩, trivial⟩, ?_⟩ + change (ev I.termBase + ev block * word stride + word j).val < limit + rw [data.termBase, bv] + exact (row_lt _ _ _ _ _ blockLt hj).trans_le area + have termHead : ok (.load (I.termBase.add (block.mul (.lit stride)))) := by + refine ⟨⟨heads.term, blockR, trivial⟩, ?_⟩ + change (ev I.termBase + ev block * word stride).val < limit + rw [data.termBase, bv] + simpa only [show word (bits := bits) 0 = 0 from rfl, add_zero] using + ((row_lt (w := bits) (Pl).term (Pl).blocks stride 0 _ blockLt (by omega)).trans_le area) + have demandAt (e : Tie D) : ok (MapFrameFields.storedWidth (dH := + H) ties stride I (.inl (false, e))) := by + refine ⟨⟨⟨heads.demand, blockR, trivial⟩, trivial⟩, ?_⟩ + change (ev I.demandBase + ev block * word t + word (ties.symm e).val).val < limit + rw [data.demandBase, bv] + exact (row_lt _ _ _ _ _ blockLt (ties.symm e).isLt).trans_le + (by unfold Allocation.Plan.supply at area; exact (Nat.le_add_right ..).trans area) + have copies : ok (MapCallWords.copies D stride I) := termAt 1 (by omega) + have external (dir : Bool) (j : Fin D) : + ok (.load ((if dir then I.offIn else I.offOut).add (ArgumentSite.segment D I.parent.siteOrd + (.lit j.val)))) := by + have idx : ok (ArgumentSite.segment D I.parent.siteOrd (.lit j.val)) := + ⟨⟨heads.parent.site, trivial⟩, trivial⟩ + have pos := ArgumentSite.segment_eval X v pub state m I.parent.siteOrd data.site (.lit j.val) j + (Nat.mod_eq_of_lt (j.isLt.trans wide)) fit + cases dir with + | false => exact readSegment _ 5 (by decide) heads.offOut data.offOut j _ idx pos + | true => exact readSegment _ 6 (by decide) heads.offIn data.offIn j _ idx pos + refine ⟨?_, ?_, ?_⟩ + · intro j; fin_cases j + · exact oldAt false slot slotR + · exact ⟨oldAt false slot slotR, readSegment _ 1 + (by decide) heads.widthOut data.widthOut _ _ dR dv⟩ + · exact ⟨newStatic false _, readSegment _ 5 (by decide) heads.offOut data.offOut _ _ dR dv⟩ + · exact oldAt true slot slotR + · exact ⟨oldAt true slot slotR, readSegment _ 7 + (by decide) heads.widthIn data.widthIn _ _ dR dv⟩ + · exact ⟨newStatic true _, readSegment _ 6 (by decide) heads.offIn data.offIn _ _ dR dv⟩ + · intro j; fin_cases j + · exact termHead + · exact slotR + · trivial + · trivial + · intro a + cases a with + | base f => + rcases f with ⟨dir, e⟩ | ⟨dir, e⟩ + · cases dir with + | false => exact oldStatic _ _ + | true => exact ⟨newStatic _ _, external (!e.1) (tieSource e)⟩ + · cases dir <;> exact newStatic _ _ + | demand e => exact demandAt e + | payload e => + have hi := (finProdFinEquiv e).isLt + have bound : e.1.val * H + e.2.val < D * H := by + change e.2.val + H * e.1.val < D * H at hi + rwa [Nat.mul_comm, Nat.add_comm] + exact termAt _ (by omega) + | copies => exact copies + | directory => exact dirRead + | source => exact ⟨dirRead, trivial⟩ + | target => exact ⟨⟨dirRead, trivial⟩, copies⟩ + | hist => exact histRead + +end CompressorRecords.PortRefresh.TraversalRecipeReads + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshVerifiedStages.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshVerifiedStages.lean new file mode 100644 index 0000000000..207dc21567 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshVerifiedStages.lean @@ -0,0 +1,202 @@ +import OAI.Computability.VPVNP.CompressorRefreshMiddleRecords +import OAI.Computability.VPVNP.CompressorRefreshExternalReplay +import OAI.Computability.VPVNP.CompressorRefreshTermDataFrame +import OAI.Computability.VPVNP.CompressorRefreshIncidenceWorkerSafety +import OAI.Computability.VPVNP.CompressorRefreshStageVisits +import OAI.Computability.VPVNP.CompressorTermWorkerFootprint +import OAI.Computability.VPVNP.CompressorSourceZip + +/-! +# Cursor and address checks for the complete native refresh schedule + +The certified walk follows the actual selected term tape through the external +scans, demands, term row, supplies, fixed expander, slot scans and final base rows. +Old columns supply the first two scans. Every remaining access stays inside the +packed level. The resulting checks can be attached to the global online calendar. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.PortRefresh.Scheduled + +open BurstRAM PrimedStackRAM Compression Compression.Refresh Compression.DegreeRefresh SpectralGeometry +open LevelRecipe NewSlots Allocation StageFrame SourceTransport +open scoped Fin.CommRing +open private bounds from OAI.Computability.VPVNP.CompressorRecordRefreshBuild + +variable {w a a₀ g dH t : ℕ} {k : Type*} [_root_.Field k] {K K' : ℝ} +variable (X : State a (a+g)) (E : RegularArcGraph (Fin (2^a)) dH) (hdH : 0 < dH) + (conn : (arcSupportGraph E.multiplicity).Connected) + (F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K') + (hD : 1 < 2^a) (hd : dH+1 ≤ 2^a₀) (c : DyadicRefreshChoice X E hdH conn F) + (ties : Fin t ≃ Tie (2^a)) (old : IncidenceDirectory w) (start stride : ℕ) +local notation "P" => plan X a₀ dH t stride start +local notation "I" => Plan.inputs P w +local notation "T" => Plan.output P w +local notation "Q" => Plan.scratch P w +local notation "S₀" => shape (t := t) E hdH conn F stride +local notation "J" => Stage S₀ +local notation "D" => word (bits := w) (Plan.demand P) +local notation "M" => word (bits := w) (Plan.term P) +local notation "Y" => dyadicRefreshNext X E hdH conn F hD hd c +local notation "src" => Source X E hdH conn F hd c ties old start stride +local notation "area" => TermDataFrame.InArena P + +/-- The reports span the selected stage's cursor interval, read only at or above the lower +address bound and write only within the refresh allocation. -/ +def StageBounds (low : ℕ) (j : J) (_ : Memory w) (rs : List (Report w)) : Prop := + Scanned j.first (j.limit X start) rs ∧ Reads (low ≤ ·) (eventLog rs) ∧ Writes area (eventLog rs) + +local notation "checked" => StageBounds (t := t) X E hdH conn F start stride + +private theorem lift_bounds {first N low : ℕ} {rs : List (Report w)} {r s write : ℕ → Prop} + (x : Scanned first N rs ∧ Reads r (eventLog rs) ∧ Writes s (eventLog rs)) + (rd : ∀ a, r a → low ≤ a) (wr : ∀ a, s a → write a) : + Scanned first N rs ∧ Reads (low ≤ ·) (eventLog rs) ∧ Writes write (eventLog rs) := + ⟨x.1,fun a v h ↦ rd _ (x.2.1 a v h),fun a v h ↦ wr _ (x.2.2 a v h)⟩ + +private theorem term_bounds (L : PrepareLayout X old a₀ dH t stride start) (low cap : ℕ) + (low_le : low ≤ start) (wide : 2+2^a*dH ≤ stride) (room : (P).stop < 2^w) + (m : Memory w) (rs : List (Report w)) + (run : termRun E hdH conn F ties X D M stride cap (blockTapes E hdH conn F X c w) m = some rs) : + checked low .term m rs := by + let B := (P).blocks + let n := 2^a*dH + let b := termAddresses D M stride t + let ord := (finProdFinEquiv (m := 2^a) (n := dH)).symm + let L₀ := termRows X D M stride wide L.demandTerm L.termRoom + let prog := TermWorker.program F ties ord b + let tape := List.ofFn (blockTapes E hdH conn F X c w) + have rt : runSegment prog cap (some (0 : W w)) m tape = some rs := run + have has := TermWorker.addresses_strided (m := B) (d := t) (n := n) (D).val (M).val t stride le_rfl wide L.demandTerm L.termRoom + have len : 0+tape.length=B := by simp [tape,B,plan] + have shape := scanned_tapes prog cap B (fun j hj mem bs rep hr ↦ by + let i : Fin B := ⟨j,hj⟩ + obtain ⟨s,u⟩ := has i + have sourceFits : (TermWorker.source b (word j)).val+t ≤ 2^w := s.symm ▸ L₀.sourceFits i + have destFits : (TermWorker.base b (word j)).val+2+n < 2^w := u.symm ▸ L₀.termFits i + simpa only [Nat.cast_add_one,word,Fin.ofNat_eq_cast] using (TermWorker.Footprint.call F ties ord b (word j) mem cap bs rep sourceFits destFits hr).1) + 0 m tape rs len rt + have fp := TermWorker.Footprint.strided_segment F ties ord (D).val (M).val t stride le_rfl wide + L.demandTerm L.termRoom 0 cap m tape rs len.le rt + have ht : (P).term ≤ (P).stop := by dsimp only [Plan.stop,Plan.next,Plan.reverseSlot,Plan.targetPort,Plan.supply]; omega + have hd : (P).demand ≤ (P).term := Nat.le_add_right .. + have ds : (D).val = (P).demand := Nat.mod_eq_of_lt (hd.trans_lt (ht.trans_lt room)) + have ms : (M).val = (P).term := Nat.mod_eq_of_lt (ht.trans_lt room) + have lower : start ≤ (P).demand := Nat.le_add_right .. + have top : (M).val+B*stride ≤ (P).stop := by + rw [ms] + change (P).supply ≤ (P).stop + dsimp only [Plan.stop,Plan.next,Plan.reverseSlot,Plan.targetPort]; omega + exact lift_bounds ⟨shape,fp⟩ (fun x hx ↦ low_le.trans (lower.trans (ds ▸ hx.1))) + (fun x hx ↦ ⟨lower.trans (hd.trans (ms ▸ hx.1)),hx.2.trans_le top⟩) + +private theorem demand_bounds (low : ℕ) (low_le : low ≤ start) (room : (P).stop < 2^w) + {ks : List (Fin t)} {m : Memory w} {rs : List (Report w)} + (run : DemandScan.Runs (DemandScan.words (r := 2^g) ties Q D) (P).blocks ks m rs) : + SourceWalk (checked low) (ks.map Stage.demand) m rs := by + induction run with + | nil => exact .done _ + | cons j h _ ih => + have scan := TermDataFrame.demand_trace X a₀ dH stride start ties room j _ _ h + exact .next (lift_bounds scan (fun _ h ↦ low_le.trans h.1) (fun _ h ↦ h)) ih + +private theorem rom_bounds (low : ℕ) (low_le : low ≤ start) (room : (P).stop < 2^w) + (js : List (Fin (2^a*dH))) (m : Memory w) : + SourceWalk (checked low) (js.map Stage.rom) m (js.map (ExpanderROM.report E I)) := by + induction js generalizing m with + | nil => exact .done _ + | cons j js ih => + have scan := TermDataFrame.rom_trace (t := t) X a₀ dH stride start E room j m + change SourceWalk _ _ _ ([ExpanderROM.report E I j] ++ _) + exact .next (lift_bounds scan (fun _ h ↦ low_le.trans h.1) (fun _ h ↦ h)) (ih _) + +private theorem slot_bounds (low : ℕ) (low_le : low ≤ start) (room : (P).stop < 2^w) + (fit : AllSlots.Fits (a₀ := a₀) X w) (ref : Memory w) (sourceTables : AllSlots.SourceTables X E hdH conn F c I ref) + {ks : List (Fin (2^a₀))} {m : Memory w} {rs : List (Report w)} + (agree : IncidenceWorkerSafety.SlotInvariant P ref m) + (run : AllSlots.Runs (fun j ↦ kindOf ((refreshSlots hd).symm j)) + (fun j ↦ AllSlots.words (2^a) (2^g) I T ((refreshSlots hd).symm j)) (P).sites ks m rs) : + SourceWalk (checked low) (ks.map Stage.slot) m rs := by + induction run with + | nil => exact .done _ + | cons j h _ ih => + obtain ⟨shape,ag,fp⟩ := IncidenceWorkerSafety.slot_scan (t := t) (stride := stride) (start := start) + X E hdH conn F hd c ((refreshSlots hd).symm j) fit room.le ref _ sourceTables agree _ h + exact .next (lift_bounds ⟨shape,fp⟩ (fun _ h ↦ low_le.trans h.1) (fun _ h ↦ h)) (ih ag) + +/-- All raw stages of the selected physical execution, together with their +scheduler guards and concrete data read/write bounds. -/ +theorem verified_sources (low cap : ℕ) (L : PrepareLayout X old a₀ dH t stride start) + (m : Memory w) (rs : List (Report w)) (rep : old.Represents X m) + (oldAbove : ∀ j, low ≤ (old.column j).val) + (before : ∀ j, (old.column j).val+(P).segments ≤ start) + (wide : 2+2^a*dH ≤ stride) (room : (P).stop < 2^w) + (termBits : termConstant E hdH conn F ties + 4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (nextWidth : (Y).maxWireWidth < 2^w) (capFit : TermWorker.budget F t (2^a*dH) w X.maxWireWidth ≤ cap) + (run : Build.Run X E hdH conn F hD hd c ties old start stride cap L m rs) : + SourceWalk (fun j mem logs ↦ src cap j mem logs ∧ checked low j mem logs) (order S₀) m rs := by + have raw := sources X E hdH conn F hD hd c ties old start stride cap L m rs run + apply raw.zip _ rfl (fun j mem xs ys h₁ h₂ ↦ (source_calls X E hdH conn F hd c ties old start stride h₁).trans + (StageFrame.Scanned.length h₂.1).symm) + obtain ⟨pre,terms,post,rfl,hpre,hterm,hpost⟩ := run + let m₁ := after m (eventLog pre) + let m₂ := after m₁ (eventLog terms) + have mid := Build.middle_records X E hdH conn F hD hd c ties old start stride L m m₁ rep pre terms hpre wide room + termBits nextWidth cap capFit hterm + obtain ⟨su,roms,os,bs,rfl,hs,hr,ho,hb⟩ := hpost + have afterTerm := Build.output_records (t := t) X E hdH conn F hD hd c start stride m₂ su roms os wide room nextWidth + L.regions.fits mid.2.1 mid.2.2 hs hr ho + have low_le : low ≤ start := (oldAbove 0).trans ((Nat.le_add_right ..).trans (before 0)) + have lowOld (x) (hx : FrontFrame.OldCell old (P).segments x) : low ≤ x := by + obtain ⟨j,hj,_⟩ := hx + exact (oldAbove j).trans hj + have lowArena (x) (hx : area x) : low ≤ x := low_le.trans hx.1 + have next := finish_layout X E hdH conn F hD hd c t stride start wide room.le + have hterm' := term_bounds X E hdH conn F c ties old start stride L low cap low_le wide room m₁ terms hterm + have hsup := TermDataFrame.supply_trace (t := t) X a₀ dH stride start E hdH conn F room wide m₂ su hs + have htermSu : SourceWalk (checked low) [.term,.supply] m₁ (terms++su) := + .next hterm' (.singleton (lift_bounds hsup lowArena (fun _ h ↦ h))) + let m₃ := after m₂ (eventLog su) + have he' := ExpanderROM.schedule_run E I 0 m₃ (List.finRange (2^a*dH)) + have same := Option.some.inj (hr.symm.trans he') + have hw₃ := rom_bounds (t := t) X E hdH conn F start stride low low_le room (List.finRange _) m₃ + rw [← same] at hw₃ + let m₄ := after m₃ (eventLog roms) + have hw₄ := slot_bounds X E hdH conn F hd c start stride low low_le room next.dims m₄ afterTerm.1 (fun _ _ ↦ rfl) ho + have cap_eq : BaseOutput.actualCount (Y) = (P).capacity := by + change Fintype.card (X.Base × Fin (2^a)) * 2^g * 2^a₀ = _ + simp only [Fintype.card_prod,Fintype.card_fin]; rfl + obtain ⟨baseShape,_,baseFp⟩ := IncidenceWorkerSafety.base_scan (P) (Y) cap_eq room.le next.incidence + (after m₄ (eventLog os)) afterTerm.2 bs hb + have hsize : BaseOutput.baseCount (Y) = Fintype.card X.Base*2^a*2^a₀ := by + change Fintype.card (X.Base × Fin (2^a))*2^a₀ = _ + simp only [Fintype.card_prod,Fintype.card_fin] + rw [hsize] at baseShape + have hw₅ : SourceWalk (checked low) [.base] (after m₄ (eventLog os)) bs := + .singleton (lift_bounds ⟨baseShape,baseFp⟩ lowArena (fun _ h ↦ h)) + have tail := hw₃.append (hw₄.append hw₅) + have rest := htermSu.append (by simpa only [SourceWalk.after_append] using tail) + obtain ⟨rg,rd,re,ds,ext,dem,_,rfl⟩ := hpre + have extFit := FrontFrame.external_scans X old a₀ dH t stride start before room + (bounds X E hdH conn F hD hd c nextWidth).1 m rep rg rd re L.regions.fits ext + let m₀ := after (after (after m (eventLog rg)) (eventLog rd)) (eventLog re) + have hfirst : SourceWalk (checked low) [.gather,.bundles,.offsets] m (rg++rd++re) := by + rw [List.append_assoc] + exact .next (lift_bounds extFit.1 lowOld (fun _ h ↦ h)) (.next (lift_bounds extFit.2.1 lowOld (fun _ h ↦ h)) + (.singleton (lift_bounds extFit.2.2 lowArena (fun _ h ↦ h)))) + have hdem := demand_bounds X E hdH conn F ties start stride low low_le room dem + have hdemRest := hdem.append (by simpa only [m₁,SourceWalk.after_append] using rest) + have full := hfirst.append (by simpa only [SourceWalk.after_append] using hdemRest) + simpa only [order,List.append_assoc] using full + +end CompressorRecords.PortRefresh.Scheduled + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRefreshWindowRun.lean b/lean/OAI/Computability/VPVNP/CompressorRefreshWindowRun.lean new file mode 100644 index 0000000000..44455fa79c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRefreshWindowRun.lean @@ -0,0 +1,176 @@ +import OAI.Computability.VPVNP.CompressorRefreshCoreHeader +import OAI.Computability.VPVNP.CompressorRefreshVerifiedStages +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorWindowPackets +import OAI.Computability.VPVNP.CompressorSourceScanned + +/-! +# Selected native reports for the full expander-refresh window + +At each chronological worker, the six input formulas read the previously +published counts and pointer bank. Its source program uses the same words +as the expander - refresh construction. Its stores are confined to the new +arrays, retaining the header for the next worker in the window. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +set_option quotPrecheck false + +namespace CompressorRecords.RefreshCore + +open BurstRAM Compression Compression.DegreeRefresh Compression.Refresh +open PortRefresh PortRefresh.LevelRecipe PhaseRecipe BlockPlanner Schedule +open DescriptorSpace SourceTransport NewSlots +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {w g : ℕ} (X : State S.portExponent (S.portExponent + g)) +local notation "hd" => S.degree_bounds.2 +private abbrev portConnected := (S.port_bound.connected_and_pos S.port_order).1 +local notation "hc" => portConnected (S := S) +local notation "sh" => RefreshBlockPlan.shape B +local notation "ties" => RefreshBlockPlan.order B +local notation "I" => RefreshBlockPlan.input (BlockProgram.geometry B) S.steps (0 : Fin 6) +local notation "scr" => BlockProgram.script B + +private theorem fuel_bounds {s : LevelRecipe.Shape} (d : s.dH + 1 ≤ s.degree) {cap : ℕ} + (pos : 0 < cap) + (j : Stage s) : 0 < Scheduled.fuel d cap j ∧ Scheduled.fuel d cap j ≤ max 64 cap := by + cases j with + | term => exact ⟨pos,Nat.le_max_right ..⟩ + | slot k => + change 0 < 1 + (code (kindOf ((refreshSlots d).symm k))).length ∧ + 1 + (code (kindOf ((refreshSlots d).symm k))).length ≤ max 64 cap + exact ⟨by omega,(by cases kindOf ((refreshSlots d).symm k) <;> decide : + 1 + (code (kindOf ((refreshSlots d).symm k))).length ≤ 64).trans (Nat.le_max_left ..)⟩ + | _ => simp only [Scheduled.fuel]; omega + +variable (c : DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) +variable (old : IncidenceDirectory w) (start cap : ℕ) +local notation "p" => Allocation.plan X (sh).a₀ (sh).dH (sh).ties (sh).stride start +local notation "native" => Scheduled.Source X S.graph (Nat.two_pow_pos _) hc B.refresh hd c ties + old start (sh).stride cap +local notation "region" => TermDataFrame.InArena p +local notation "bounds" => Scheduled.StageBounds (t := (sh).ties) X S.graph + (Nat.two_pow_pos _) hc B.refresh start (sh).stride + +/-- An actual worker run with the tape supplied for this calendar stage. -/ +def StageRun (j : Stage sh) (bits : List (List Bool)) (m : Memory w) (rs : List + (Report w)) : Prop := + let term := RefreshBlockPlan.term B + let data := fun i ↦ j.nativeBank hd S.graph ties X start old + (TermWorker.motifData B.refresh ties finProdFinEquiv.symm w) (Fin.cast + (j.worker_params hd term) i) + runSegment ((j.worker hd term).table.instantiate w data).program (Scheduled.fuel hd cap j) + (some (word j.first)) m bits = some rs + +variable (base : BurstRAM.Word w) (positions blocks t : ℕ) +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog scr)) base +local notation "pub" => Schedule.Ports.data pt +local notation "firstLevel" => Script.levelsPerBlock scr * t +local notation "st" => (levelStart L firstLevel : BurstRAM.Word w) +local notation "head" => levelStart L (firstLevel + S.steps) +local notation "H" => levelStart L 0 +local notation "D" => Window.operandRegion scr L base +local notation "R" => Window.Raw (A := scr) L base t (max 64 cap) + +set_option maxHeartbeats 800000 in +-- The native bank and compiled bank have dependent arities in each of the nine cases. +private theorem stage_raw (bits : List (List Bool)) (m : Memory w) (rs : List (Report w)) + (j : Stage sh) + (h : Header (Fintype.card X.Base) g head start old m) + (pitch : m ((pt).directory - 1).val = (levelWords L : BurstRAM.Word w)) + (pos : 0 < cap) (room : (p).stop < 2 ^ w) (low : H ≤ start) + (r : StageRun B X old start cap j bits m rs) (b : bounds H j m rs) : R + (RefreshBlockPlan.stage B I j) m rs := by + let C : Context w := ⟨pub,st,m⟩ + have entry : LevelFields.Entry L firstLevel C.pub C.state C.memory := ⟨rfl,pitch⟩ + have describes : Describes (s := sh) I C X start old := Header.describes + (F := BlockProgram.geometry B) (s := sh) (X := X) (step := S.steps) rfl (0 : Fin 6) rfl entry h + have support : InputReads D C.pub C.state C.memory I := Header.reads (F := BlockProgram.geometry + B) (step := S.steps) rfl (0 : Fin 6) rfl entry h + (.inr (.inl rfl)) (fun n _ ↦ .inr (.inr ((levelStart_mono L (Nat.zero_le _)).trans + (Nat.le_add_right ..)))) + have ec := counters I C X start old describes j + have eb := motif_workerBank_eq I hd S.graph ties C X start old (Nat.two_pow_pos _) hc B.refresh + describes j + let data := fun i ↦ j.nativeBank hd S.graph ties X start old + (TermWorker.motifData B.refresh ties finProdFinEquiv.symm w) (Fin.cast (j.worker_params hd + (RefreshBlockPlan.term B)) i) + have bank : (fun i ↦ C.eval ((RefreshBlockPlan.stage B I j).params i)) = data := funext eb + have fuel := fuel_bounds hd pos j + refine ⟨Scheduled.fuel hd cap j,bits,fuel.2,⟨fuel.1,?_,?_,b.2.1,?_⟩,stage_supported D pub st m B + support j⟩ + · change runSegment (((RefreshBlockPlan.stage B I j).worker.table.instantiate w + (fun i ↦ C.eval ((RefreshBlockPlan.stage B I j).params i))).program) _ (some + (C.eval j.initial)) m bits = some rs + rw [bank,ec.1] + exact r + · change SourceOnline.Progress (C.eval (j.stop I)) (C.eval j.initial) rs + rw [ec.1,ec.2] + have fit := limit_fits (s := sh) (w := w) (g := g) hd X start room.le j + exact b.1.toProgress fit + · exact fun a v ha ↦ low.trans (b.2.2 a v ha).1 + +set_option maxHeartbeats 800000 in +-- The induction threads the full typed layout and the worker index through each stage. +/-- Transform the verified chronological native execution into the actual +worker recipes. The entire interval writes only the allocated refresh arena. -/ +theorem raw_stages (bits : Stage sh → List (List Bool)) (js : List (Stage sh)) (m : Memory w) + (rs : List (Report w)) + (header : Header (Fintype.card X.Base) g head start old m) + (pitch : m ((pt).directory - 1).val = (levelWords L : BurstRAM.Word w)) (pos : 0 < cap) + (room : (p).stop < 2 ^ w) (before : head + 60 < start) (fit : H < 2 ^ w) + (run : SourceWalk (fun j mem logs ↦ StageRun B X old start cap j (bits j) mem logs + ∧ bounds H j mem logs) js m rs) : + SourceWalk R (js.map (RefreshBlockPlan.stage B I)) m rs ∧ Writes region (eventLog rs) := by + have below := Window.lowCells (A := scr) L base rfl rfl fit + have hhead := levelStart_mono L (show 0 ≤ firstLevel + S.steps from Nat.zero_le _) + have low : H ≤ start := by omega + have loop (js : List (Stage sh)) (mem : Memory w) (logs : List (Report w)) + (walk : SourceWalk (fun j u ls ↦ StageRun B X old start cap j (bits j) u ls + ∧ bounds H j u ls) js mem logs) + (hh : Header (Fintype.card X.Base) g head start old mem) + (hp : mem ((pt).directory - 1).val = (levelWords L : BurstRAM.Word w)) : + SourceWalk R (js.map (RefreshBlockPlan.stage B I)) mem logs ∧ Writes region + (eventLog logs) := by + induction walk with + | done => exact ⟨.done _,fun _ _ h ↦ by cases h⟩ + | @next j js u xs ys h _ ih => + have w₀ := h.2.2.2 + have keep (addr : ℕ) (lt : addr < start) : after u (eventLog xs) addr = u addr := + after_outside u w₀ (fun inside ↦ (Nat.not_le_of_lt lt) inside.1) + have next := ih (hh.keep (fun i hi ↦ keep _ (by omega))) ((keep _ + (below.2.trans_le low)).trans hp) + refine ⟨.next (stage_raw B X old start cap base positions blocks t + (bits j) u xs j hh hp pos room low h.1 h.2) next.1,?_⟩ + intro a v h + simp only [eventLog,List.flatMap_append,List.mem_append] at h + exact h.elim (w₀ a v) (next.2 a v) + exact loop _ _ _ run header pitch + +theorem raw_window (m : Memory w) (rs : List (Report w)) + (header : Header (Fintype.card X.Base) g head start old m) + (pitch : m ((pt).directory - 1).val = (levelWords L : BurstRAM.Word w)) (pos : 0 < cap) + (room : (p).stop < 2 ^ w) (before : head + 60 < start) (fit : H < 2 ^ w) + (run : SourceWalk (fun j mem logs ↦ native j mem logs ∧ bounds H j mem logs) (order sh) m rs) : + SourceWalk R ((order sh).map (RefreshBlockPlan.stage B I)) m rs ∧ Writes region (eventLog rs) := + raw_stages B X old start cap base positions blocks t + (Scheduled.tapes (t := (sh).ties) (w := w) X S.graph (Nat.two_pow_pos _) hc B.refresh c start + (sh).stride) + (order sh) m rs header pitch pos room before fit run + +end CompressorRecords.RefreshCore + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRegisterSetupClock.lean b/lean/OAI/Computability/VPVNP/CompressorRegisterSetupClock.lean new file mode 100644 index 0000000000..329efcd186 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRegisterSetupClock.lean @@ -0,0 +1,101 @@ +import OAI.Computability.VPVNP.CompressorRecordRegisterSetup + +/-! +# The event log of register setup + +Every external address used by the expression compiler is computed from +the public operands, the state word and the current memory. The scratch +registers can therefore start with arbitrary words. Even nested loads and +repeated loads of the same address have the same complete event log. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RegisterSetup + +open BurstRAM BurstRAM.PrivateRAM PhaseRecipe RowRecipe +open PrimedStackRAM (Regs) +open scoped Fin.CommRing +open private run compile_value from OAI.Computability.VPVNP.CompressorRecordsPhaseRecipe +open private scratch_val room from OAI.Computability.VPVNP.CompressorRecordRegisterSetup + +variable {w r n : ℕ} (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) + +private theorem events_append (xs ys : List (Assign r 5)) (rs : Regs w r) : + (evaluate pub state m (xs ++ ys) rs).1 = (evaluate pub state m xs rs).1 ++ + (evaluate pub state m ys (run pub state m xs rs)).1 := by + induction xs generalizing rs with + | nil => rfl + | cons a xs ih => exact congrArg (List.cons (a.rhs.event m rs)) (ih _) + +private theorem no_read_events (xs : List (Assign r 5)) (rs ts : Regs w r) + (noReads : (xs.map fun a => a.rhs.reads).sum = 0) : + (evaluate pub state m xs rs).1 = (evaluate pub state m xs ts).1 := by + induction xs generalizing rs ts with + | nil => rfl + | cons a xs ih => + simp only [List.map_cons, List.sum_cons, Nat.add_eq_zero_iff] at noReads + have step : a.rhs.event m rs = a.rhs.event m ts := by + have h := noReads.1 + cases he : a.rhs <;> first | rfl | simp [he, RHS.reads] at h + exact congrArg₂ List.cons step (ih _ _ noReads.2) + +private theorem compile_events (e : Expr) (slot : ℕ → Fin r) (cap start : ℕ) (rs ts : Regs w r) + (fits : start + e.slots ≤ cap) (inj : ∀ i < cap, ∀ j < cap, slot i = slot j → i = j) : + (evaluate pub state m (e.compile slot start) rs).1 = + (evaluate pub state m (e.compile slot start) ts).1 := by + induction e generalizing start rs ts with + | lit n => + apply no_read_events + exact Expr.compile_reads (.lit n) slot start + | publicWord _ | state => rfl + | load a ih => + have hv (s : Regs w r) := compile_value pub state m a slot cap start s fits inj + simp only [Expr.compile, events_append] + change _ ++ [Event.read (run pub state m (a.compile slot start) rs (slot start)) _] = + _ ++ [Event.read (run pub state m (a.compile slot start) ts (slot start)) _] + rw [ih start rs ts fits, hv rs, hv ts] + | binary op a b ha hb => + change start + max a.slots (1 + b.slots) ≤ cap at fits + have hL := ha start rs ts (by omega) + have hR := hb (start+1) (run pub state m (a.compile slot start) rs) + (run pub state m (a.compile slot start) ts) (by omega) + simp only [Expr.compile, events_append] + change _ ++ _ ++ [(Event.tick : Event w)] = _ ++ _ ++ [(Event.tick : Event w)] + rw [hL,hR] + +variable (f : Fin n → Expr) + +private theorem emit_events (i : Fin n) (rs ts : Regs w (regCount f)) : + (evaluate pub state m (emit f i) rs).1 = (evaluate pub state m (emit f i) ts).1 := by + have hf : 0 + (f i).slots ≤ scratchCount f := by simpa only [Nat.zero_add] using room f i + have inj (u : ℕ) (hu : u < scratchCount f) (v : ℕ) (hv : v < scratchCount f) + (eq : scratch f u = scratch f v) : u = v := by + have nums := congrArg Fin.val eq + rw [scratch_val f hu, scratch_val f hv] at nums + omega + simp only [emit, events_append] + change _ ++ [(Event.tick : Event w)] = _ ++ [(Event.tick : Event w)] + rw [compile_events pub state m (f i) (scratch f) (scratchCount f) 0 rs ts hf inj] + +/-- Evaluating all setup lines produces the same events as a zeroed +compiler bank, including the address and return value of every read. -/ +theorem events_eq (f : Fin n → Expr) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) + (rs : Regs w (regCount f)) : + (evaluate pub state m (lines f) rs).1 = (evaluate pub state m (lines f) (fun _ ↦ 0)).1 := by + have go (is : List (Fin n)) (xs ys : Regs w (regCount f)) : + (evaluate pub state m (is.flatMap (emit f)) xs).1 = (evaluate pub state m (is.flatMap (emit f)) ys).1 := by + induction is generalizing xs ys with + | nil => rfl + | cons i is ih => + simp only [List.flatMap_cons, events_append] + rw [emit_events pub state m f i xs ys, ih] + exact go (List.finRange n) rs (fun _ ↦ 0) + +end CompressorRecords.RegisterSetup + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorRegisterSetupTrace.lean b/lean/OAI/Computability/VPVNP/CompressorRegisterSetupTrace.lean new file mode 100644 index 0000000000..de77b99d40 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorRegisterSetupTrace.lean @@ -0,0 +1,85 @@ +import OAI.Computability.VPVNP.CompressorRecordRegisterSetup +import OAI.Computability.VPVNP.CompressorFormulaFootprint + +/-! +# Chronological trace of the native register setup + +The actual straight-line interpreter emits the events of its compiled +assignment list, in order, including the address and word of each read. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.RegisterSetup + +open BurstRAM BurstRAM.PrivateRAM PhaseRecipe RowRecipe +open private eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe +open private execute_lines emit_list lines_probes no_choices + from OAI.Computability.VPVNP.CompressorRecordRegisterSetup +open private ReadPrefix.execute from OAI.Computability.VPVNP.PairSimulationPrivateSlices + +open SourceTransport PrimedStackRAM +open private compile_safe log_append reads_append + from OAI.Computability.VPVNP.CompressorFormulaFootprint +open private room scratch_val from OAI.Computability.VPVNP.CompressorRecordRegisterSetup + +/-- Every read of the native register setup occurs in an operand expression. -/ +theorem lines_reads {n w : ℕ} (f : Fin n → Expr) (data : ℕ → Prop) + (pub : Fin 5 → Word w) (s : Word w) (m : Memory w) + (safe : ∀ i, (f i).ReadsFrom data pub s m) (rs : Regs w (regCount f)) : + Reads data (evaluate pub s m (lines f) rs).1 := by + suffices h : ∀ (js : List (Fin n)) (regs : Regs w (regCount f)), + Reads data (evaluate pub s m (js.flatMap (emit f)) regs).1 from h _ rs + intro js + induction js with + | nil => simp [evaluate, Reads] + | cons i js ih => + intro regs + rw [List.flatMap_cons, log_append] + apply reads_append _ (ih _) + rw [emit, log_append] + refine reads_append ?_ ?_ + · apply compile_safe data pub s m _ (safe i) (scratch f) (scratchCount f) 0 + (by simpa only [Nat.zero_add] using room f i) + intro j hj k hk eqn + have he := congrArg Fin.val eqn + rw [scratch_val f hj, scratch_val f hk] at he + omega + · simp [evaluate, RHS.event, Reads] + +variable {n w p r k : ℕ} (f : Fin n → Expr) (inputs : Fin 6 → Fin r) + (vm : Fin (regCount f) ↪ Fin r) + +/-- Execute the setup with the exact event list of the assignment interpreter. -/ +theorem execute_setup_raw (M : Machine w p r k) (m : Memory w) (pc : ℕ → Fin p) + (link : Linked vm inputs M pc (lines f)) (safe : ∀ i j, vm i ≠ inputs j) + (c : Config w p r) (hpc : c.pc = pc 0) : + let pub := fun i : Fin 5 => c.reg (inputs i.castSucc) + let state := c.reg (inputs (Fin.last 5)) + let events := (evaluate pub state m (lines f) (fun i ↦ c.reg (vm i))).1 + ∃ d, events.length = (lines f).length ∧ countProbes events = ∑ i, (f i).loads ∧ + choiceBits events = [] ∧ + d.pc = pc (lines f).length ∧ + d.privateMem = c.privateMem ∧ d.persistent = c.persistent ∧ + (∀ i, d.reg (vm (output f i)) = (f i).eval pub state m) ∧ + (∀ j, (∀ i, j ≠ vm i) → d.reg j = c.reg j) ∧ + ∀ fuel bs, execute M.program (fuel+events.length) c m bs = + (execute M.program fuel d m bs).map (fun rep => ⟨events++rep.events,rep.result⟩) := by + let pub := fun i : Fin 5 => c.reg (inputs i.castSucc) + let state := c.reg (inputs (Fin.last 5)) + let rs := fun i => c.reg (vm i) + obtain ⟨d,hd,endPC,mem,pers,vals,frame⟩ := + execute_lines vm inputs M m (lines f) safe pub state rs pc link c hpc + (fun _ => rfl) rfl (fun _ => rfl) + refine ⟨d,(eval_cost pub state m (lines f) rs).1,lines_probes f ..,no_choices ..,endPC,mem,pers, + fun i => ?_,frame,ReadPrefix.execute hd⟩ + exact (vals _).trans ((emit_list f pub state m (List.finRange n) rs i).trans + (ite_eq_left (List.mem_finRange i))) + +end CompressorRecords.RegisterSetup + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorResidentGeometry.lean b/lean/OAI/Computability/VPVNP/CompressorResidentGeometry.lean new file mode 100644 index 0000000000..ffb78e9834 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorResidentGeometry.lean @@ -0,0 +1,130 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentRun +import OAI.Computability.VPVNP.CompressorBlockCapacity + +/-! # Physical table capacity for the shrinking resident group + +The old absolute and role arrays are bounded by table zero and the two +resident directories are bounded by table five. A fitted block workspace +therefore supplies the required disjoint ranges and represents the selected +score cell without word truncation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkResidentPackets + +open Compression BurstRAM BlockPlanner PhaseRecipe DescriptorSpace +open ShrinkResidentRun ShrinkResidentLayout +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) + {g w : ℕ} (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) +variable (base : Word w) (positions blocks : ℕ) +local notation "A" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "H" => levelStart L 0 + +/-- Word address of the old absolute-identifier array immediately following the gathered motif +words. -/ +abbrev absoluteWord {a g w : ℕ} (Y : State a (packingLaneBits a g)) (start : ℕ) : Word w := + let Z := ShrinkInput.plan Y start + ((Z.gathered + Z.B*Z.Q : ℕ) : Word w) + +/-- Word address of the old role array for the selected shrinking terms with ten-word records. -/ +abbrev roleWord {a g w : ℕ} (Y : State a (packingLaneBits a g)) (start : ℕ) : Word w := + (SelectedArena.roleBase Y (ShrinkInput.termHead (w := w) Y start) (10 : Word w) : Word w) + +/-- Natural address of the selected layout score cell at offset two in the shrinking term +arena. -/ +abbrev scoreAddr {a g w : ℕ} (Y : State a (packingLaneBits a g)) (start : ℕ) := + SelectedArena.origin Y (ShrinkInput.termHead (w := w) Y start) (10 : Word w)+2 + +private theorem prefix_order {a g : ℕ} (Y : State a (packingLaneBits a g)) (start : ℕ) : + let Z := ShrinkInput.plan Y start + start ≤ Z.gathered+Z.B*Z.Q ∧ Z.gathered+Z.B*Z.Q+ShrinkTermInputs.motifCount Y ≤ ShrinkInput.stop Y start := by + intro Z + have motif : ShrinkTermInputs.motifCount Y = Z.B*Z.Q := ShrinkTermSelection.motifCount_eq Y + have first : start ≤ Z.origin := by + change start ≤ ShrinkInput.placementBase Y start + _ + rw [ShrinkInput.placementBase,GreedyArena.greedyStop_eq] + omega + change start ≤ Z.gathered+Z.B*Z.Q ∧ Z.gathered+Z.B*Z.Q+ShrinkTermInputs.motifCount Y ≤ + (Z.gathered+Z.rectangleSize+Z.A)+6*(Z.B*Z.Q)+2*Z.B + have mid : Z.origin ≤ Z.gathered := by + change Z.origin ≤ (Z.origin+2*Z.A+2*Z.B)+Z.rectangleSize + omega + omega + +theorem geometry (old : Fin (L).levels) (size : X.positions ≤ positions) (room : endAddress L < 2^w) : + let start := tableBase L old (0 : Fin 6) + let arena := tableBase L old (5 : Fin 6) + let abs : Word w := absoluteWord X start + let roles : Word w := roleWord X start + Areas X arena abs roles ∧ H ≤ abs.val ∧ H ≤ roles.val ∧ + levelStart L old+36 ≤ scoreAddr (w := w) X start ∧ scoreAddr (w := w) X start < arena ∧ + ShrinkInput.termEnd X start 10 < 2^w ∧ 10 < 2^w ∧ levelStart L old+66 ≤ 2^w ∧ + roles.val = SelectedArena.roleBase X (ShrinkInput.termHead (w := w) X start) (10 : Word w) := by + intro start arena abs roles + let Z := ShrinkInput.plan X start + let N := Z.B*Z.Q + let term : Word w := ShrinkInput.termHead X start + let stride : Word w := 10 + let end0 := start+tableWords L + have budget : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords L := by + change X.positions*ShrinkLevelSpace.tableFactor S ≤ positions*(BlockProgram.allocationShape B).slots*(BlockProgram.allocationShape B).fields + rw [Nat.mul_assoc] + exact Nat.mul_le_mul size (BlockProgram.field_rates B base.val positions blocks).1 + have ptr := (ShrinkLevelSpace.packed_ends S i X start 0 0 0 w) + have res := (ShrinkLevelSpace.resident_table S i X start arena w).2 + have endFit : end0 < 2^w := tableStop_lt L old (0 : Fin 6) le_rfl room + have arenaFit : (layout X arena).endAddr < 2^w := res.trans_lt (tableStop_lt L old (5 : Fin 6) budget room) + have before : end0 ≤ arena := tableEnd_le_tableBase L old (a := (0 : Fin 6)) (b := (5 : Fin 6)) (by decide : (0 : Fin 6)<5) + have src : ShrinkInput.stop X start ≤ end0 := ptr.1.trans (Nat.add_le_add_left budget _) + have termCap : ShrinkInput.termEnd X start 10 ≤ end0 := ptr.2.1.trans (Nat.add_le_add_left budget _) + have selected : SelectedFinish.stop X term stride ≤ end0 := ptr.2.2.1.trans (Nat.add_le_add_left budget _) + have low := levelStart_mono L (Nat.zero_le old.val) + have hbase : levelStart L old+66 ≤ start := by + change levelStart L old+66 ≤ (levelStart L old+66)+6*slotCapacity L+0*tableWords L + omega + have hstart : start ≤ end0 := Nat.le_add_right .. + have hrange := prefix_order X start + change start ≤ Z.gathered+N ∧ Z.gathered+N+ShrinkTermInputs.motifCount X ≤ ShrinkInput.stop X start at hrange + have absVal : abs.val=Z.gathered+N := Nat.mod_eq_of_lt (show Z.gathered+N < 2^w by omega) + have termVal : term.val = ShrinkInput.stop X start+2*N := by + apply Nat.mod_eq_of_lt + change ShrinkInput.stop X start+2*N < 2^w + change ShrinkInput.stop X start+2*N+N*10 ≤ end0 at termCap + omega + have upto : SelectedArena.roleBase X term stride+4*DemandRAM.absoluteCount X ≤ end0 := by + apply le_trans _ selected + change SelectedArena.endAddr X term stride ≤ SelectedArena.endAddr X term stride + _ + _ + omega + have roleVal : roles.val = SelectedArena.roleBase X term stride := Nat.mod_eq_of_lt (show SelectedArena.roleBase X term stride < 2^w by omega) + have lower : term.val ≤ SelectedArena.origin X term stride := Nat.le_add_right .. + have split : SelectedArena.origin X term stride+2 < SelectedArena.roleBase X term stride := by + change SelectedArena.origin X term stride+2 < SelectedArena.origin X term stride+3+4*_ + omega + have length : (PairSimulation.LocalHistory.shrinkMotifOrder X).length = ShrinkTermInputs.motifCount X := rfl + have all : Areas X arena abs roles := by + refine ⟨arenaFit,?_,?_,.inl ?_,.inl ?_,by omega⟩ + · rw [absVal,length]; omega + · rw [roleVal]; omega + · rw [absVal,length]; omega + · rw [roleVal]; omega + change Areas X arena abs roles ∧ H ≤ abs.val ∧ H ≤ roles.val ∧ + levelStart L old+36 ≤ SelectedArena.origin X term stride+2 ∧ SelectedArena.origin X term stride+2 < arena ∧ + ShrinkInput.termEnd X start 10 < 2^w ∧ 10 < 2^w ∧ levelStart L old+66 ≤ 2^w ∧ roles.val=_ + rw [absVal,roleVal] + exact ⟨all,by omega,by omega,by omega,by omega,termCap.trans_lt endFit,by omega,by omega,rfl⟩ + +end CompressorRecords.ShrinkResidentPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorResidentNativeWalk.lean b/lean/OAI/Computability/VPVNP/CompressorResidentNativeWalk.lean new file mode 100644 index 0000000000..e9fb39c98b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorResidentNativeWalk.lean @@ -0,0 +1,123 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentPackets +import OAI.Computability.VPVNP.CompressorResidentPacketScans +import OAI.Computability.VPVNP.CompressorShrinkResidentFootprint + +/-! # Chronological native source walk of the resident directories -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkResidentPackets + +open Compression BurstRAM BlockPlanner PhaseRecipe SourceTransport SourceOnline +open ShrinkResidentRun ShrinkResidentLayout +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Addresses the resident group may write, comprising its allocated array interval and header +offsets 30 through 35. -/ +def Mutable (D : Values w) (x : ℕ) : Prop := + (D.layout.first ≤ x ∧ x < D.layout.endAddr) ∨ (D.level+30 ≤ x ∧ x < D.level+36) + +/-- The chosen resident stage runs from cursor zero, reaches its limit, reads above the lower +bound, and writes only within its mutable region. -/ +structure Native (P : Plan) (D : Values w) (low : ℕ) (j : Stage) (m : Memory w) (rs : List (Report w)) : Prop where + run : let M := ((j.visit P).worker.table.instantiate w (j.bank P D)).program + runSegment M j.fuel (some 0) m (List.replicate (j.limit D) []) = some rs + progress : Progress (j.limit D : Word w) 0 rs + read : Reads (low ≤ ·) (eventLog rs) + write : Writes (Mutable D) (eventLog rs) + +variable (P : Plan) {g : ℕ} (X : State P.exponent (packingLaneBits P.exponent g)) +variable (first level : ℕ) (absolute role : Word w) (side : Bool) + +/-- Assemble the resident-stage operands from the state layout, level header, absolute and role +array heads, and selected side. -/ +def values : Values w := ⟨layout X first,level,absolute,role,side⟩ + +local notation "D" => values P X first level absolute role side + +theorem scan_walk (maps : Bool) {m : Memory w} {r : Passes w} + (built : Built X first absolute role side maps m r) + (space : Areas X first absolute role) (dir : ShrinkResidentDirectory.Absolute X absolute m) + (low : ℕ) (dataStart : low ≤ first) (absStart : low ≤ absolute.val) (roleStart : low ≤ role.val) : + SourceWalk (Native P D low) (scans maps) m r.all := by + let L := layout X first + let p := ownerBank X first absolute role side maps + obtain ⟨shape,rd,wr⟩ := built.owners.scanned X maps p rfl (space.owner side maps) dir + obtain ⟨_,h0,h1,_,_,_,_⟩ := frame X first maps space.fit + change (p 3).val = L.owner maps at h1 + have nfit : L.size maps < 2^w := h0 ▸ ((layout X first).params P.exponent maps w 0).isLt + obtain ⟨owner,counts,rows,last⟩ := L.ranges maps + change first ≤ L.owner maps at owner + have owners : Native P D low (.owners maps) m r.owners := by + refine ⟨built.owners.native,shape.toProgress nfit,?_,?_⟩ + · intro a v ha + rcases rd a v ha with h|h + · exact absStart.trans h.1 + · exact roleStart.trans h.1 + · intro a v ha + have h := wr a v ha + change (p 3).val ≤ a.val ∧ a.val < (p 3).val+L.size maps at h + rw [h1] at h + exact .inl ⟨owner.trans h.1,by change a.val < L.endAddr; omega⟩ + obtain ⟨cp,cr,cw⟩ := counter_scan X first absolute role side maps built space.fit + have clear : Native P D low (.clear maps) (r.mid m) r.clear := by + refine ⟨built.clear,cp,fun a v hv => False.elim (cr a v hv),?_⟩ + intro a v hv + have ha := cw a v hv + change L.counts maps ≤ a.val ∧ a.val < L.rows maps at ha + exact .inl ⟨by change first ≤ a.val; omega,by change a.val < L.endAddr; omega⟩ + obtain ⟨ap,ar,aw⟩ := preimage_scan X first absolute role side maps built space.fit + have append : Native P D low (.append maps) (r.cleared m) r.collect := + ⟨built.collect,ap,fun a v h => dataStart.trans (ar a v h).1,fun a v h => .inl (aw a v h)⟩ + have path := SourceWalk.next owners (SourceWalk.next clear (SourceWalk.singleton append)) + simpa only [scans,Passes.all,List.append_assoc] using path + +theorem publish_walk (low : ℕ) (fit : level+36 ≤ 2^w) (m : Memory w) : + SourceWalk (Native P D low) ((List.finRange 6).map Stage.header) m + (List.ofFn (ShrinkResidentsPlan.headerReport level (layout X first) w)) := by + let L := layout X first + have go (is : List (Fin 6)) (mem : Memory w) : + SourceWalk (Native P D low) (is.map Stage.header) mem (is.map (ShrinkResidentsPlan.headerReport level L w)) := by + induction is generalizing mem with + | nil => exact .done _ + | cons i is ih => + have shape := header_scan (w := w) level L i fit + refine SourceWalk.next (rs := [ShrinkResidentsPlan.headerReport level L w i]) ?_ (ih _) + refine ⟨ShrinkResidentsPlan.header_source P.chosen P.first P.oldLevel level L i mem,shape.1, + fun a v ha => False.elim (shape.2.1 a v ha),?_⟩ + intro a v ha + have h := shape.2.2 a v ha + change (first ≤ a.val ∧ a.val < L.endAddr) ∨ (level+30 ≤ a.val ∧ a.val < level+36) + exact .inr (by have := i.isLt; omega) + simpa only [List.ofFn_eq_map] using go (List.finRange 6) m + +/-- Both tables and the six headers execute against the post-memory of the +preceding stage. All modified cells lie in the declared two intervals. -/ +theorem native_walk (space : Areas X first absolute role) (m : Memory w) + (dir : ShrinkResidentDirectory.Absolute X absolute m) (roles : DemandRAM.RoleColumns X side role.val m) + (low : ℕ) (dataStart : low ≤ first) (absStart : low ≤ absolute.val) (roleStart : low ≤ role.val) + (hdrFit : level+36 ≤ 2^w) : + ∃ h r : Passes w, Built X first absolute role side false m h ∧ + Built X first absolute role side true (h.final m) r ∧ + SourceWalk (Native P D low) order m + ((h.all++r.all)++List.ofFn (ShrinkResidentsPlan.headerReport level (layout X first) w)) := by + obtain ⟨h,r,hh,hr,_,_⟩ := both X first absolute role side space m dir roles + have dir' := (hh.inputs X first absolute role side false dir roles space).1 + have hw := scan_walk P X first level absolute role side false hh space dir low dataStart absStart roleStart + have rw := scan_walk P X first level absolute role side true hr space dir' low dataStart absStart roleStart + rw [← h.after_all m] at rw + exact ⟨h,r,hh,hr,(hw.append rw).append (publish_walk P X first level absolute role side low hdrFit _)⟩ + +end CompressorRecords.ShrinkResidentPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorResidentPacketGroup.lean b/lean/OAI/Computability/VPVNP/CompressorResidentPacketGroup.lean new file mode 100644 index 0000000000..7214325531 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorResidentPacketGroup.lean @@ -0,0 +1,252 @@ +import OAI.Computability.VPVNP.CompressorResidentNativeWalk +import OAI.Computability.VPVNP.CompressorShrinkResidentFinal +import OAI.Computability.VPVNP.CompressorShrinkSelectedReadback +import OAI.Computability.VPVNP.CompressorShrinkSlotPacketGroup +import OAI.Computability.VPVNP.CompressorShrinkSlotOperandTransport +import OAI.Computability.VPVNP.CompressorWindowPackets +import OAI.Computability.VPVNP.CompressorBlockHeadReads +import OAI.Computability.VPVNP.CompressorSourceScanned + +/-! # Launching the resident directory group in the repeated block + +The planner rereads its size, address and layout inputs before every native +stage. The current group writes only the fresh table and the six designated +header cells. The inputs therefore keep their physical values through all +twelve stages, even though each stage sees the preceding report log. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkResidentPackets + +open Compression BurstRAM BlockPlanner PhaseRecipe SourceTransport SourceOnline DescriptorSpace +open ShrinkResidentRun ShrinkResidentLayout +open scoped Classical Fin.CommRing + +private theorem map_walk {J K : Type*} {w : ℕ} {source : J → Memory w → List (Report w) → Prop} + {dest : K → Memory w → List (Report w) → Prop} (f : J → K) + (convert : ∀ j m rs, source j m rs → dest (f j) m rs) {js : List J} {m : Memory w} {rs : List (Report w)} + (walk : SourceWalk source js m rs) : SourceWalk dest (js.map f) m rs := by + induction walk with + | done => exact .done _ + | next head _ ih => exact .next (convert _ _ _ head) ih + +theorem raw_walk {w : ℕ} {P : Plan} (D : Values w) {A : Script} (L : DescriptorSpace.Layout) + (base : Word w) (t : ℕ) (m : Memory w) (rs : List (Report w)) + (values : OperandValues P D (Workspace.ports (Schedule.arity A.catalog) base).data (levelStart L (A.levelsPerBlock*t)) m) + (roots : OperandReads P (fun x => Window.operandRegion A L base x ∧ ¬ Mutable D x) + (Workspace.ports (Schedule.arity A.catalog) base).data (levelStart L (A.levelsPerBlock*t)) m) + (lowArena : levelStart L 0 ≤ D.layout.first) (lowHeader : levelStart L 0 ≤ D.level) + (walk : SourceWalk (Native P D (levelStart L 0)) order m rs) : + SourceWalk (Window.Raw («A» := A) L base t 40) P.visits m rs := by + let region := Window.operandRegion A L base + let keep := fun x => region x ∧ ¬ Mutable D x + let pub := (Workspace.ports (Schedule.arity A.catalog) base).data + let state : Word w := levelStart L (A.levelsPerBlock*t) + have stay (j : Stage) (mem : Memory w) (logs : List (Report w)) (native : Native P D (levelStart L 0) j mem logs) + (same : Agree keep m mem) : Agree keep m (after mem (eventLog logs)) := + fun x hx => (same x hx).trans (after_outside mem native.write hx.2).symm + have h := (walk.with_invariant (I := Agree keep m) (fun _ _ => rfl) stay).1 + rw [← P.ordered] + apply map_walk (Stage.visit P) _ h + intro j mem logs info + obtain ⟨native,same⟩ := info + let v := j.visit P + have support := roots.supported j + obtain ⟨first,stop,bank⟩ := values.words j + have start : v.initial.eval pub state mem = 0 := (v.initial.eval_eq_of_reads support.initial same).symm.trans first + have limit : v.stop.eval pub state mem = (j.limit D : Word w) := (v.stop.eval_eq_of_reads support.stop same).symm.trans stop + have args : (fun k => (v.params k).eval pub state mem) = j.bank P D := + funext fun k => ((v.params k).eval_eq_of_reads (support.params k) same).symm.trans (congrFun bank k) + refine ⟨j.fuel,List.replicate (j.limit D) [],j.clock.2,?_,?_⟩ + · refine ⟨j.clock.1,?_,?_,native.read,?_⟩ + · change runSegment ((v.worker.table.instantiate w (fun k => (v.params k).eval pub state mem)).program) + j.fuel (some (v.initial.eval pub state mem)) mem _ = _ + rw [args,start]; exact native.run + · change Progress (v.stop.eval pub state mem) (v.initial.eval pub state mem) logs + rw [limit,start]; exact native.progress + · intro a y hv + rcases native.write a y hv with hit | hit + · exact lowArena.trans hit.1 + · exact lowHeader.trans ((Nat.le_add_right ..).trans hit.1) + · have widen : ∀ x, keep x → region x := fun _ hx => hx.1 + exact ⟨v.initial.reads_transport support.initial same widen,v.stop.reads_transport support.stop same widen, + fun j => (v.params j).reads_transport (support.params j) same widen⟩ + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) + {g w : ℕ} (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) +variable (base : Word w) (positions blocks t : ℕ) +local notation "A" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "H" => levelStart L 0 +local notation "W" => window B i +local notation "pt" => Workspace.ports (Schedule.arity (BlockPlanner.Script.catalog (BlockProgram.script B))) base +local notation "pub" => Schedule.Ports.data pt +local notation "blockFirst" => BlockPlanner.Script.levelsPerBlock (BlockProgram.script B)*t +local notation "st" => (levelStart L blockFirst : Word w) +local notation "stepLevel" => blockFirst+i.val +local notation "oldHead" => levelStart L stepLevel +local notation "first" => tableBase L stepLevel (5 : Fin 6) +local notation "P" => plan B i + +/-- Uniform clock bound for resident packet scans obtained from the block script with worker +fuel 40. -/ +def clock := scanCap (BlockProgram.script B) 40 + +/-- The physical read bank survives the publications at offsets 30–35 and +all resident-array writes. Only the genuine selected score is loaded from +an address outside the immutable header words. -/ +theorem root_reads (m : Memory w) (absolute role : Word w) (side : Bool) + (entry : LevelFields.Entry L blockFirst pub st m) (levelFit : oldHead+66 ≤ 2^w) + (pitchLow : ((pt).directory-1).val < H) + (scoreLo : oldHead+36 ≤ ((SelectedPlan.layoutCell (P).chosen).eval pub st m).val) + (scoreHi : ((SelectedPlan.layoutCell (P).chosen).eval pub st m).val < first) : + OperandReads P (fun x => Window.operandRegion A L base x ∧ ¬ Mutable (values P X first oldHead absolute role side) x) + pub st m := by + let D := values P X first oldHead absolute role side + let R := fun x => Window.operandRegion A L base x ∧ ¬ Mutable D x + have oldLow : H ≤ oldHead := levelStart_mono L (Nat.zero_le stepLevel) + have dataAfter : oldHead+66 ≤ first := by + change oldHead+66 ≤ ((oldHead+66)+6*slotCapacity L)+5*tableWords L + omega + have outside (x : ℕ) (below : x True) trivial (fun _ _ => trivial)).1 + have bundle := ShrinkBundlePlan.head_values X (fields.reads B entry) + exact operand_values B i X base positions blocks t m _ _ inc start side entry room head selected bundle chosen + +/-- Native, consecutive checked and prepared rows from the actual header +and selected role data. The width and the prior choice enter through RAM. -/ +theorem group (m : Memory w) (absolute role : Word w) (side : Bool) + (space : Areas X first absolute role) (dir : ShrinkResidentDirectory.Absolute X absolute m) + (roles : DemandRAM.RoleColumns X side role.val m) (absLow : H ≤ absolute.val) (roleLow : H ≤ role.val) + (vals : OperandValues P (values P X first oldHead absolute role side) pub st m) + (scoreLo : oldHead+36 ≤ ((SelectedPlan.layoutCell (P).chosen).eval pub st m).val) + (scoreHi : ((SelectedPlan.layoutCell (P).chosen).eval pub st m).val < first) + (rows : m (pt).rows.val = (directoryRows L : Word w)) (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (ht : t < blocks) (cap : ℕ) (clockFits : clock B ≤ cap) : + ∃ h r : Passes w, ∃ ps : List (SourceOnline.Packet A w), + Built X first absolute role side false m h ∧ Built X first absolute role side true (h.final m) r ∧ + Group A L base cap ((A).initial.length+t*(A).block.length+(BlockIndex.earlier B i).length+36) + (directoryRows L) m ps ∧ ps.map (fun p => p.stage.phase) = (W).indices ∧ + ps.flatMap SourceWalk.Packet.reports = (h.all++r.all)++List.ofFn (ShrinkResidentsPlan.headerReport oldHead (layout X first) w) ∧ + (∀ j : Fin 6, post m ps (oldHead+(30+j.val)) = (ShrinkResidentsPlan.headValues (layout X first) j : Word w)) ∧ + (∀ x, x < oldHead+30 ∨ oldHead+36 ≤ x → post m ps x = r.final (h.final m) x) ∧ + (∀ maps : Bool, ShrinkHistoryRows.Directory (ShrinkResidentDirectory.oldOrder X maps) (ShrinkHistoryRows.packedOrder X) + (ShrinkResidentDirectory.place X maps side) (outputBank X first maps) (post m ps)) ∧ + RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) = (layout X first).charge := by + let D := values P X first oldHead absolute role side + have headerLow := levelStart_mono L (Nat.zero_le stepLevel) + have dataAfter : oldHead+66 ≤ first := by + change oldHead+66 ≤ ((oldHead+66)+6*slotCapacity L)+5*tableWords L + omega + have arenaFit : first < 2^w := by + have ranges := (layout X first).ranges false + have bound := space.fit + obtain ⟨a,b,c,d⟩ := ranges + change first ≤ (layout X first).owner false at a + omega + have floor : H ≤ first := headerLow.trans ((Nat.le_add_right ..).trans dataAfter) + have hfit := floor.trans_lt arenaFit + have entry : LevelFields.Entry L blockFirst pub st m := ⟨rfl,pitch⟩ + have arity := (BlockProgram.layout_arity B base.val positions blocks).symm + have low := Window.lowCells («A» := A) L base arity rfl hfit + have roots := root_reads B i X base positions blocks t m absolute role side entry (by omega) low.2 scoreLo scoreHi + obtain ⟨h,r,hh,hr,walk⟩ := native_walk P X first oldHead absolute role side space m dir roles H floor + absLow roleLow (by omega) + have raw := raw_walk D L base t m _ vals roots floor headerLow walk + have live (j : Fin (P).visits.length) : Window.ordinal («A» := A) t ((W).index j) < directoryRows L := by + rw [(W).ordinal_index,BlockProgram.directory_rows,(A).calendar_total] + have pos := ((W).position j).isLt + have before := Nat.mul_le_mul_right (A).block.length ht + rw [Nat.succ_mul] at before + omega + let recTime (j : Fin (A).size) := ((A).plan.recipes j).2.code.length+1+2*Schedule.Online.N (A).size (A).size+5 + have rc (j : Fin (A).size) (_ : j ∈ (W).indices) : recTime j ≤ cap := + (Finset.le_sup (f := recTime) (Finset.mem_univ j)).trans ((le_max_left ..).trans clockFits) + have dc (j : Fin (A).size) (_ : j ∈ (W).indices) : + 40+3+4*(((A).catalog j).params+1)+2*Schedule.Online.N (A).size (A).size+5 ≤ cap := by + have h := Schedule.params_le_arity (A).catalog j + have bound : 40+3+4*(Schedule.arity (A).catalog+1)+2*Schedule.Online.N (A).size (A).size+5 ≤ cap := + (le_max_right ..).trans clockFits + omega + obtain ⟨ps,cert,stages,logs⟩ := (W).group L base t arity rfl hfit cap 40 m _ raw rows pitch live rc dc + rw [window_offset] at cert + have effect : post m ps = after (r.final (h.final m)) (eventLog (List.ofFn (ShrinkResidentsPlan.headerReport oldHead (layout X first) w))) := by + unfold post + rw [logs,SourceWalk.after_append,SourceWalk.after_append,h.after_all,r.after_all] + rfl + have headerData := ShrinkResidentsPlan.published oldHead (layout X first) (w := w) (by omega) (r.final (h.final m)) + have finalHeads := effect.symm ▸ headerData + refine ⟨h,r,ps,hh,hr,by simpa only [Nat.add_assoc] using cert,stages,logs,finalHeads.1,finalHeads.2,?_,?_⟩ + · intro maps + apply transfer X first side maps (m := r.final (h.final m)) _ space.fit + (fun x hx _ => finalHeads.2 x (.inr (by omega))) + cases maps + · exact retained_hidden X first absolute role side hh hr space.fit + · exact hr.directory + · rw [logs,RAMBuckets.cost_append,RAMBuckets.cost_append,hh.charge,hr.charge] + change 9*((layout X first).motifs*4)+2*(layout X first).sites+ + (9*((layout X first).motifs*6)+2*(layout X first).sites)+12 = + 90*(layout X first).motifs+4*(layout X first).sites+12 + omega + +end CompressorRecords.ShrinkResidentPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorResidentPacketScans.lean b/lean/OAI/Computability/VPVNP/CompressorResidentPacketScans.lean new file mode 100644 index 0000000000..203bb1f646 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorResidentPacketScans.lean @@ -0,0 +1,107 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentRun +import OAI.Computability.VPVNP.CompressorShrinkResidentHeaders +import OAI.Computability.VPVNP.CompressorShrinkSelectedScans + +/-! # Cursors and probe addresses in the resident counter, append, and publication scans -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkResidentPackets + +open Compression BurstRAM PrimedStackRAM SourceTransport SourceOnline ShrinkResidentLayout ShrinkResidentRun +open scoped Fin.CommRing + +variable {w : ℕ} + +theorem clear_bounds {base : Word w} {n : ℕ} (fit : base.val+n < 2^w) {m : Memory w} {rs : List (Report w)} + (run : runSegment ((template SliceRAM.clearOps 0).instantiate w (fun _ => base)).program 8 (some 0) m + (List.replicate n []) = some rs) : + Progress (n : Word w) 0 rs ∧ Reads (fun _ => False) (eventLog rs) ∧ + Writes (fun x => base.val ≤ x ∧ x < base.val+n) (eventLog rs) := by + obtain ⟨order,read,write⟩ := ShrinkHistoryTrace.clear_scanned base n fit.le m rs run + exact ⟨order.toProgress (by omega),read,write⟩ + +theorem append_bounds {p : Fin 6 → Word w} (regions : RowRegions p) {m : Memory w} {rs : List (Report w)} + (run : runSegment ((template collectPreimage 3).instantiate w p).program 23 (some 0) m + (List.replicate (p 0).val []) = some rs) : + Progress (p 0) 0 rs ∧ Reads (SlotFillFootprint.AppendReads p) (eventLog rs) ∧ + Writes (SlotFillFootprint.AppendWrites p) (eventLog rs) := by + have order := ShrinkHistoryTrace.append_scanned p (p 0).val m rs run + have prog := order.toProgress (p 0).isLt + have word : ((p 0).val : Word w) = p 0 := Fin.ext (Nat.mod_eq_of_lt (p 0).isLt) + rw [word] at prog + exact ⟨prog,SlotFillFootprint.append_run regions run⟩ + +variable {a g : ℕ} (X : State a (packingLaneBits a g)) (first : ℕ) (absolute roles : Word w) (side maps : Bool) +variable {m : Memory w} {r : Passes w} (h : Built X first absolute roles side maps m r) + +include h in +theorem counter_scan (fit : (layout X first).endAddr < 2^w) : + Progress ((layout X first).sites : Word w) 0 r.clear ∧ Reads (fun _ => False) (eventLog r.clear) ∧ + Writes (fun x => (layout X first).counts maps ≤ x ∧ x < (layout X first).rows maps) (eventLog r.clear) := by + obtain ⟨_,_,_,_,hc,_,_⟩ := frame X first maps fit + obtain ⟨_,_,next,stop⟩ := (layout X first).ranges maps + let p := outputBank (w := w) X first maps + change (p 3).val = _ at hc + have bound : (p 3).val+(layout X first).sites < 2^w := by omega + obtain ⟨prog,rd,wr⟩ := clear_bounds bound h.clear + rw [hc,next] at wr + exact ⟨prog,rd,wr⟩ + +include h in +theorem preimage_scan (fit : (layout X first).endAddr < 2^w) : + Progress ((layout X first).size maps : Word w) 0 r.collect ∧ + Reads (fun x => first ≤ x ∧ x < (layout X first).endAddr) (eventLog r.collect) ∧ + Writes (fun x => first ≤ x ∧ x < (layout X first).endAddr) (eventLog r.collect) := by + let L := layout X first + let p := outputBank (w := w) X first maps + obtain ⟨reg,h0,h1,h2,h3,h4,h5⟩ := frame X first maps fit + have h0p : (p 0).val = L.size maps := h0 + have run := h.collect + change runSegment _ 23 _ _ (List.replicate (L.size maps) []) = some r.collect at run + rw [← h0p] at run + obtain ⟨prog,rd,wr⟩ := append_bounds reg run + obtain ⟨owner,counts,rows,last⟩ := L.ranges maps + have size := size_eq_rows X first maps + refine ⟨prog,?_,?_⟩ + · intro a v hit + have ha := rd a v hit + simp only [SlotFillFootprint.AppendReads,SlotFillFootprint.InColumn,h0,h1,h3,h2] at ha + change first ≤ a.val ∧ a.val < L.endAddr + change (L.owner maps ≤ a.val ∧ a.val < L.owner maps+L.size maps) ∨ + (L.counts maps ≤ a.val ∧ a.val < L.counts maps+L.sites) at ha + change first ≤ L.owner maps at owner + omega + · intro a v hit + have ha := wr a v hit + simp only [SlotFillFootprint.AppendWrites,SlotFillFootprint.InColumn,h3,h2,h5,h4] at ha + change first ≤ a.val ∧ a.val < L.endAddr + change (L.counts maps ≤ a.val ∧ a.val < L.counts maps+L.sites) ∨ + (L.rows maps ≤ a.val ∧ a.val < L.rows maps+L.sites*rowCapacity _ maps) at ha + change L.size maps = L.sites*rowCapacity _ maps at size + change first ≤ L.owner maps at owner + omega + +theorem header_scan (level : ℕ) (L : Layout) (j : Fin 6) (fit : level+36 ≤ 2^w) : + let rs := [ShrinkResidentsPlan.headerReport level L w j] + Progress (1 : Word w) 0 rs ∧ Reads (fun _ => False) (eventLog rs) ∧ + Writes (fun x => x = level+(30+j.val)) (eventLog rs) := by + refine ⟨.next ?_ rfl (.done le_rfl),?_,?_⟩ + · change 0 % (2^w) < 1 % (2^w) + rw [Nat.zero_mod,Nat.mod_eq_of_lt (by omega : 1 < 2^w)] + decide + · intro a v hv + simp [eventLog,ShrinkResidentsPlan.headerReport] at hv + · intro a v hv + simp only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil,ShrinkResidentsPlan.headerReport, + List.mem_cons,List.not_mem_nil,or_false,false_or,reduceCtorEq,Event.write.injEq] at hv + obtain ⟨rfl,_⟩ := hv + exact Nat.mod_eq_of_lt (by have := j.isLt; omega) + +end CompressorRecords.ShrinkResidentPackets + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorResidentPhysicalFrame.lean b/lean/OAI/Computability/VPVNP/CompressorResidentPhysicalFrame.lean new file mode 100644 index 0000000000..0c2b580436 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorResidentPhysicalFrame.lean @@ -0,0 +1,102 @@ +import OAI.Computability.VPVNP.CompressorResidentNativeWalk +import OAI.Computability.VPVNP.CompressorBlockCapacity +import OAI.Computability.VPVNP.CompressorWindowPackets + +/-! # Persistent inputs and succeeding level fields after the resident group + +The six publications target offsets 30 through 35. The data workers +target only table five. The current scalar inputs, both sets of incidence +heads, all six old table heads, and all of table zero retain their values. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkResidentPackets + +open Compression BurstRAM BlockPlanner DescriptorSpace SourceTransport +open ShrinkResidentLayout +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) + {g w : ℕ} (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) +variable (base : Word w) (positions blocks : ℕ) +local notation "A" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (Schedule.arity (BlockPlanner.Script.catalog A)) base + +/-- The resident group preserves the row and pitch words, old header fields outside its six +publications, incidence and table heads, table zero, and all addresses from the next level +onward. -/ +structure PhysicalFrame (old : Fin (L).levels) (m out : Memory w) : Prop where + rows : out (pt).rows.val = m (pt).rows.val + pitch : out ((pt).directory-1).val = m ((pt).directory-1).val + scalar (j : ℕ) (low : j < 30) : out (levelStart L old+j) = m (levelStart L old+j) + higher (j : ℕ) (lo : 36 ≤ j) (hi : j < 66) : out (levelStart L old+j) = m (levelStart L old+j) + incidence (c : Fin 6) : out (incidenceHead L old c) = m (incidenceHead L old c) + tables (a : Fin 6) : out (tableHead L old a) = m (tableHead L old a) + tableZero (x : ℕ) (lo : tableBase L old (0 : Fin 6) ≤ x) + (hi : x < tableBase L old (0 : Fin 6)+tableWords L) : out x = m x + next (x : ℕ) (lo : levelStart L (old.val+1) ≤ x) : out x = m x + +/-- The finite header and table readbacks follow from the exact footprint of +the physical group and the capacity of table five. -/ +theorem physical_frame (old : Fin (L).levels) (size : X.positions ≤ positions) (room : endAddress L < 2^w) + (abs role : Word w) (side : Bool) (m out : Memory w) + (keep : ∀ x, ¬ Mutable (values (plan B i) X (tableBase L old (5 : Fin 6)) (levelStart L old) abs role side) x → + out x = m x) : PhysicalFrame B base positions blocks old m out := by + let header := levelStart L old + let start := tableBase L old (0 : Fin 6) + let first := tableBase L old (5 : Fin 6) + let D := values (plan B i) X first header abs role side + have cap : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords L := by + change _ ≤ positions*(BlockProgram.allocationShape B).slots*(BlockProgram.allocationShape B).fields + rw [Nat.mul_assoc] + exact Nat.mul_le_mul size (BlockProgram.field_rates B base.val positions blocks).1 + have endData : (layout X first).endAddr ≤ levelStart L (old.val+1) := + (ShrinkLevelSpace.resident_table S i X start first w).2.trans + ((Nat.add_le_add_left cap _).trans (tableEnd_le_nextLevel L old (5 : Fin 6))) + have headLow : levelStart L 0 ≤ header := levelStart_mono L (Nat.zero_le _) + have firstArray : header+66 ≤ start := by + change header+66 ≤ header+66+6*slotCapacity L+0*tableWords L + omega + have order : start+tableWords L ≤ first := tableEnd_le_tableBase L old (a := (0 : Fin 6)) (b := (5 : Fin 6)) (by decide : (0 : Fin 6)<5) + have dataNext := (layout X first).ranges false + obtain ⟨b,c,r,e⟩ := dataNext + change first ≤ (layout X first).owner false at b + have cells := Window.lowCells («A» := BlockProgram.script B) L base (BlockProgram.layout_arity B ..).symm rfl + ((levelStart_mono L (Nat.zero_le (L).levels)).trans_lt room) + have early (x : ℕ) (h : x < first) (d : x < header+30 ∨ header+36 ≤ x) : out x = m x := by + apply keep + rintro (hw|hh) + · exact (Nat.not_le_of_gt h) hw.1 + · change header+30 ≤ x ∧ x < header+36 at hh + omega + refine ⟨early _ (by have := cells.1; omega) (.inl (by have := cells.1; omega)), + early _ (by have := cells.2; omega) (.inl (by have := cells.2; omega)), + fun j hj => early _ (by omega) (.inl (by omega)),fun j lo hi => early _ (by omega) (.inr (by omega)), + ?_,?_,fun x lo hi => early x (hi.trans_le order) (.inr (by omega)),?_⟩ + · intro c + change out (header+54+c.val) = m (header+54+c.val) + exact early _ (by have := c.isLt; omega) (.inr (by omega)) + · intro a + change out (header+54+6+a.val) = m (header+54+6+a.val) + exact early _ (by have := a.isLt; omega) (.inr (by omega)) + · intro x lo + apply keep + rintro (hw|hh) + · change first ≤ x ∧ x < (layout X first).endAddr at hw + omega + · change header+30 ≤ x ∧ x < header+36 at hh + omega + +end CompressorRecords.ShrinkResidentPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorResidentPhysicalGroup.lean b/lean/OAI/Computability/VPVNP/CompressorResidentPhysicalGroup.lean new file mode 100644 index 0000000000..fe609b5f6a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorResidentPhysicalGroup.lean @@ -0,0 +1,144 @@ +import OAI.Computability.VPVNP.CompressorResidentGeometry +import OAI.Computability.VPVNP.CompressorResidentPacketGroup +import OAI.Computability.VPVNP.CompressorPublishedHeadWindows + +/-! # Resident rows at an actual selected shrinking level + +A fitted descriptor allocation and the published old header are sufficient +to locate both input tables, the selected score, and the six output heads. +The next phase receives the same old graph and selected term data outside +these two resident rectangles. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkResidentPackets + +open Compression BurstRAM BlockPlanner PhaseRecipe SourceTransport SourceOnline DescriptorSpace +open ShrinkResidentRun ShrinkResidentLayout +open scoped Classical Fin.CommRing + + +private theorem pass_bits {a g w : ℕ} {Y : State a (packingLaneBits a g)} {arena : ℕ} {abs role : Word w} + {side maps : Bool} {m : Memory w} {r : Passes w} (h : Built Y arena abs role side maps m r) : + branchPaths r.all = List.replicate (2*(layout Y arena).size maps+(layout Y arena).sites) [] := by + have x := ((runSegment_iff ..).mp h.owners.native).2.2 + have y := ((runSegment_iff ..).mp h.clear).2.2 + have z := ((runSegment_iff ..).mp h.collect).2.2 + change branchPaths r.owners = List.replicate ((layout Y arena).size maps) [] at x + change branchPaths ((r.owners++r.clear)++r.collect) = _ + rw [show branchPaths ((r.owners++r.clear)++r.collect) = + (branchPaths r.owners++branchPaths r.clear)++branchPaths r.collect by simp only [branchPaths,List.map_append]] + rw [x,y,z,← List.replicate_add,← List.replicate_add] + congr 1 + omega + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) + {g w : ℕ} (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) +variable (base : Word w) (positions blocks t : ℕ) +local notation "A" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "H" => levelStart L 0 +local notation "W" => window B i +local notation "pt" => Workspace.ports (Schedule.arity (BlockPlanner.Script.catalog A)) base +local notation "pub" => Schedule.Ports.data pt +local notation "blockFirst" => BlockPlanner.Script.levelsPerBlock A*t +local notation "st" => (levelStart L blockFirst : Word w) +local notation "stepLevel" => blockFirst+i.val +local notation "oldHead" => levelStart L stepLevel +local notation "first" => tableBase L stepLevel (5 : Fin 6) +local notation "start" => tableBase L stepLevel (0 : Fin 6) +local notation "P" => plan B i +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "D" => values P X first oldHead (absoluteWord (w := w) X start) (roleWord (w := w) X start) + +theorem physical_group (m : Memory w) (inc : IncidenceDirectory w) (side : Bool) + (fields : ShrinkHeaderReads.Header i X inc start L blockFirst m) + (head : m (tableHead L stepLevel (5 : Fin 6)) = (first : Word w)) + (chosen : m (scoreAddr (w := w) X start) = (side.toNat : Word w)) + (dir : ShrinkResidentDirectory.Absolute X (absoluteWord X start) m) + (roles : DemandRAM.RoleColumns X side (SelectedArena.roleBase X term (10 : Word w)) m) + (size : X.positions ≤ positions) (fits : endAddress L < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (ht : t < blocks) (cap : ℕ) (hc : clock B ≤ cap) : + ∃ ps : List (SourceOnline.Packet A w), + Group A L base cap ((A).initial.length+t*(A).block.length+(BlockIndex.earlier B i).length+36) + (directoryRows L) m ps ∧ ps.map (fun p => p.stage.phase) = (W).indices ∧ + (∀ j : Fin 6, post m ps (oldHead+(30+j.val)) = (ShrinkResidentsPlan.headValues (layout X first) j : Word w)) ∧ + (∀ x, ¬ Mutable (D side) x → post m ps x = m x) ∧ + (∀ maps : Bool, ShrinkHistoryRows.Directory (ShrinkResidentDirectory.oldOrder X maps) (ShrinkHistoryRows.packedOrder X) + (ShrinkResidentDirectory.place X maps side) (outputBank X first maps) (post m ps)) ∧ + RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) = (layout X first).charge ∧ + ps.length=12 ∧ ps.flatMap (fun p => p.stage.choices) = List.replicate (layout X first).calls [] := by + have within : stepLevel < (L).levels := by + change (S.steps+1)*t+i.val < 1+(S.steps+1)*blocks + have h := Nat.mul_le_mul_left (S.steps+1) ht + rw [Nat.mul_succ] at h + have := i.isLt + omega + let old : Fin (L).levels := ⟨stepLevel,within⟩ + obtain ⟨space,absLow,roleLow,scoreLow,scoreHigh,termFit,ten,headerFit,roleValue⟩ := + geometry B i X base positions blocks old size fits + have entry : LevelFields.Entry L blockFirst pub st m := ⟨rfl,pitch⟩ + have selected := (SelectedTailPackets.header_values B i X inc start pub st m fields entry termFit ten + (fun _ => True) trivial (fun _ _ => trivial)).1 + have score := SelectedPlan.score_head (P).chosen X (ShrinkInput.placementBank X inc start) inc term pub st m selected + have arenaFit : first < 2^w := by + have bound := (layout X first).ranges false + obtain ⟨o,c,r,stop⟩ := bound + change first ≤ (layout X first).owner false at o + have top : (layout X first).endAddr < 2^w := space.fit + omega + have cell : ((SelectedPlan.layoutCell (P).chosen).eval pub st m).val = scoreAddr (w := w) X start := by + have eq : (SelectedPlan.layoutCell (P).chosen).eval pub st m = (scoreAddr (w := w) X start : Word w) := by + change (SelectedPlan.scoreBase (P).chosen).eval pub st m+2 = + ((SelectedArena.origin X term (10 : Word w)+2 : ℕ) : Word w) + rw [score,Nat.cast_add] + rfl + exact (congrArg Fin.val eq).trans (Nat.mod_eq_of_lt (scoreHigh.trans arenaFit)) + have values := header_values B i X base positions blocks t m inc start side entry headerFit fields termFit ten + head (by rw [cell]; exact chosen) + obtain ⟨h,r,ps,hh,hr,checked,stages,logs,heads,keep,dirs,cost⟩ := group B i X base positions blocks t m + (absoluteWord (w := w) X start) (roleWord (w := w) X start) side space dir (roleValue.symm ▸ roles) + absLow roleLow values (by rw [cell]; exact scoreLow) (by rw [cell]; exact scoreHigh) rows pitch ht cap hc + have num : ps.length = 12 := by + have len := congrArg List.length stages + simp only [Window.indices,List.length_map,List.length_ofFn] at len + exact len.trans (ShrinkResidentsPlan.visits_length ..) + have quiet : ps.flatMap (fun p => p.stage.choices) = List.replicate (layout X first).calls [] := by + rw [PublishedHeads.chronological_tapes m ps checked.chronological,logs] + have headBits : branchPaths (List.ofFn (ShrinkResidentsPlan.headerReport oldHead (layout X first) w)) = + List.replicate 6 [] := rfl + rw [show branchPaths (h.all++r.all++List.ofFn (ShrinkResidentsPlan.headerReport oldHead (layout X first) w)) = + (branchPaths h.all++branchPaths r.all)++branchPaths (List.ofFn (ShrinkResidentsPlan.headerReport oldHead (layout X first) w)) + by simp only [branchPaths,List.map_append]] + rw [pass_bits hh,pass_bits hr,headBits,← List.replicate_add,← List.replicate_add] + congr 1 + change 2*((layout X first).motifs*4)+(layout X first).sites+(2*((layout X first).motifs*6)+(layout X first).sites)+6 = + 20*(layout X first).motifs+2*(layout X first).sites+6 + omega + refine ⟨ps,checked,stages,heads,?_,dirs,cost,num,quiet⟩ + intro x outside + have apart (maps : Bool) : x < (layout X first).owner maps ∨ + (layout X first).rows maps+(layout X first).size maps ≤ x := by + obtain ⟨lo,_,_,hi⟩ := (layout X first).ranges maps + by_cases h : x < (layout X first).owner maps + · exact .inl h + · exact .inr (le_of_not_gt fun hx => outside (.inl ⟨lo.trans (Nat.le_of_not_gt h),hx.trans_le hi⟩)) + have header : x outside (.inr ⟨Nat.le_of_not_gt before,h⟩)) + exact (keep x header).trans ((hr.frame x (apart true)).trans (hh.frame x (apart false))) + +end CompressorRecords.ShrinkResidentPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScanProgress.lean b/lean/OAI/Computability/VPVNP/CompressorScanProgress.lean new file mode 100644 index 0000000000..cecd058068 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScanProgress.lean @@ -0,0 +1,35 @@ +import OAI.Computability.VPVNP.CompressorRefreshStageFrame +import OAI.Computability.VPVNP.CompressorSourceOnline + +/-! +# Scheduler guard progress of a finite ordinal scan + +When the exclusive stop fits in a word, every natural strict inequality +in the source trace is the same inequality tested by the scheduler. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM +open scoped Fin.CommRing + +theorem StageFrame.Scanned.toProgress {w first N : ℕ} {rs : List (Report w)} + (shape : StageFrame.Scanned first N rs) (fit : N < 2^w) : + SourceOnline.Progress (N : Word w) (first : Word w) rs := by + induction shape with + | done => exact .done le_rfl + | @next j N rep tail live returned scanned ih => + have active : (j : Word w) < (N : Word w) := by + change j % 2^w < N % 2^w + rwa [Nat.mod_eq_of_lt (live.trans fit), Nat.mod_eq_of_lt fit] + exact .next active returned (ih fit) + +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScatterCall.lean b/lean/OAI/Computability/VPVNP/CompressorScatterCall.lean new file mode 100644 index 0000000000..de419fb569 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScatterCall.lean @@ -0,0 +1,141 @@ +import OAI.Computability.VPVNP.CompressorRecordsRowRecipe + +/-! +# A native call with a bank of scattered stores + +A finite list of assignments snapshots every operand from the entry memory. +The call then stores selected registers to computed addresses and returns +one designated register. The exact external effect is a fold of these stores. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScatterCall + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM RowRecipe +open private eval_cost from OAI.Computability.VPVNP.CompressorRecordsRowRecipe + +variable {w r k : ℕ} + +/-- Translate a row-recipe register assignment to its corresponding burst operation. -/ +def op (a : Assign r k) : Op r k := match a.rhs with + | .literal v => .constant a.dst v + | .publicWord i => .publicWord a.dst i + | .state => .stateWord a.dst + | .copy i => .copy a.dst i + | .binary f i j => .binary f a.dst i j + | .read i => .read a.dst i + +/-- Run all register assignments, then emit the ordered external writes from the selected +register pairs. -/ +def ops (code : List (Assign r k)) (writes : List (Fin r × Fin r)) : List (Op r k) := + code.map op ++ writes.map (fun (i,j) => .write i j) + +/-- Resolve address and value register pairs to a list of word-addressed stores. -/ +def stores (rs : Regs w r) (writes : List (Fin r × Fin r)) := + writes.map (fun (i,j) => (rs i,rs j)) + +/-- Encode the ordered address-value pairs as external write events. -/ +def storeLog (xs : List (Word w × Word w)) : List (Event w) := xs.map (fun (a,v) => .write a v) + +/-- Apply the ordered stores to memory, with later writes taking precedence at a repeated +address. -/ +def applyStores (mem : Memory w) (xs : List (Word w × Word w)) := + xs.foldl (fun m av => writeMemory m av.1 av.2) mem + +private theorem assignments (xs : List (Assign r k)) (pub : Fin k → Word w) (st : Word w) + (m : Memory w) (rs : Regs w r) : + let out := evaluate pub st m xs rs + trace pub st (xs.map op) rs m = some (out.1,out.2,m) := by + induction xs generalizing rs with + | nil => rfl + | cons a as ih => + have effect : (op a).effect pub st rs m = some (a.rhs.event m rs, + Function.update rs a.dst (a.rhs.value pub st m rs),m) := by + cases a with | mk dst rhs => cases rhs <;> rfl + simp only [List.map_cons,trace,effect,bind,Option.bind_some,ih,evaluate]; rfl + +private theorem writing (xs : List (Fin r × Fin r)) (pub : Fin k → Word w) (st : Word w) + (m : Memory w) (rs : Regs w r) : + trace pub st (xs.map (fun (i,j) => .write i j)) rs m = + some (storeLog (stores rs xs),rs,applyStores m (stores rs xs)) := by + induction xs generalizing m with + | nil => rfl + | cons av xs ih => + cases av + simp [trace,Op.effect,ih,stores,storeLog,applyStores] + +/-- Evaluate the assignments from zero registers, append the selected stores to the event log, +and return the designated register's value. -/ +def report (xs : List (Assign r k)) (writes : List (Fin r × Fin r)) (ret : Fin r) (pub : Fin k → Word w) + (st : Word w) (m : Memory w) : Report w := + let out := evaluate pub st m xs (fun _ => 0) + ⟨out.1 ++ storeLog (stores out.2 writes),some (out.2 ret)⟩ + +private theorem trace_call (xs : List (Assign r k)) (writes : List (Fin r × Fin r)) (ret : Fin r) + (pub : Fin k → Word w) (st : Word w) (m : Memory w) : + let out := evaluate pub st m xs (fun _ => 0) + trace pub st (ops xs writes) (fun _ => 0) m = some + ((report xs writes ret pub st m).events,out.2,applyStores m (stores out.2 writes)) := by + rw [ops,trace_append,assignments]; simp only [Option.bind_some,writing]; rfl + +theorem native (xs : List (Assign r k)) (writes : List (Fin r × Fin r)) (ret : Fin r) + (pub : Fin k → Word w) (st : Word w) (m : Memory w) : + let T := ((template (ops xs writes) ret).instantiate w pub).program + execute T (1+(ops xs writes).length) (T.start st) m [] = some (report xs writes ret pub st m) := by + let T := (template (ops xs writes) ret).instantiate w pub + change execute T.program (1+(ops xs writes).length) ⟨T.entry,st,fun _ => 0,fun _ => 0⟩ m [] = _ + rw [execute_template,run_eq_trace,trace_call xs writes ret]; simp [report] + +theorem effect (xs : List (Assign r k)) (writes : List (Fin r × Fin r)) (ret : Fin r) + (pub : Fin k → Word w) (st : Word w) (m : Memory w) : + after m (report xs writes ret pub st m).events = + applyStores m (stores (evaluate pub st m xs (fun _ => 0)).2 writes) := + Greedy.trace_after (trace_call xs writes ret pub st m) + +theorem cost (xs : List (Assign r k)) (writes : List (Fin r × Fin r)) (ret : Fin r) + (pub : Fin k → Word w) (st : Word w) (m : Memory w) : + let rep := report xs writes ret pub st m + rep.events.length = xs.length+writes.length ∧ rep.probes = (xs.map fun a => a.rhs.reads).sum + writes.length ∧ + choiceBits rep.events = [] := by + dsimp only + have e := eval_cost pub st m xs (fun _ => 0) + have sl (vs : List (Word w × Word w)) : countProbes (storeLog vs) = vs.length := by + induction vs with | nil => rfl | cons x xs ih => simpa only [storeLog,List.map_cons,countProbes,List.length_cons,Nat.add_comm 1] using congrArg Nat.succ ih + refine ⟨by simp [report,storeLog,stores,e.1],?_,(execute_spec (native xs writes ret pub st m)).2.2⟩ + change countProbes (_ ++ storeLog _) = _ + rw [Greedy.probes_append,e.2,sl]; simp [stores] + +theorem outside (xs : List (Word w × Word w)) (m : Memory w) (x : ℕ) + (h : ∀ av ∈ xs, av.1.val ≠ x) : applyStores m xs x = m x := by + induction xs generalizing m with + | nil => rfl + | cons av xs ih => + change applyStores (writeMemory m av.1 av.2) xs x = _ + rw [ih _ (fun b hb => h b (List.mem_cons_of_mem _ hb))] + exact ite_eq_right (h av List.mem_cons_self).symm + +theorem stored (xs : List (Word w × Word w)) (m : Memory w) {x : ℕ} {v : Word w} + (live : ∃ av ∈ xs, av.1.val = x) (agree : ∀ av ∈ xs, av.1.val = x → av.2 = v) : + applyStores m xs x = v := by + induction xs generalizing m with + | nil => simp at live + | cons av xs ih => + change applyStores (writeMemory m av.1 av.2) xs x = _ + by_cases h : ∃ u ∈ xs, u.1.val = x + · exact ih _ h (fun u hu => agree u (List.mem_cons_of_mem _ hu)) + · rw [outside _ _ _ (fun u hu he => h ⟨u,hu,he⟩)] + have ha : av.1.val = x := by + obtain ⟨u,hu,he⟩ := live + rcases List.mem_cons.mp hu with rfl | hu + · exact he + · exact (h ⟨u,hu,he⟩).elim + simp [writeMemory,ha,agree av List.mem_cons_self ha] + +end CompressorRecords.ScatterCall + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScheduledExecution.lean b/lean/OAI/Computability/VPVNP/CompressorScheduledExecution.lean new file mode 100644 index 0000000000..a9b4ce58ba --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScheduledExecution.lean @@ -0,0 +1,106 @@ +import OAI.Computability.VPVNP.CompressorScheduledTrace +import OAI.Computability.VPVNP.CompressorTimelineDepth +import OAI.Computability.VPVNP.CompressorPrefixLevelScale + +/-! # Applying the descriptor induction to the paper's iterated compressor + +The actual compression tree and its native table share their chronological +block and pass indices. Partial branches use the proved size bounds on +their current graph, and the completed path gives the native source log +and the retained mathematical levels at the same terminal memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace + +open BurstRAM Compression BranchSegments PassTimeline PairSimulation.LocalHistory +attribute [local irreducible] BlockProgram.script + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} +variable {w cap small rate total T P M : ℕ} {pub : Fin 11 → Word w} {pitch : Word w} +variable {resident : Resident B f hf w} +local notation "A" => BlockProgram.script B + +/-- The native per-pass constructor is needed only in its true block and +substep and only for graph sizes permitted by the initial allocation. -/ +abbrev LocatedRuns (resident : Resident B f hf w) (pub : Fin 11 → Word w) (pitch : Word w) + (total cap small rate T P M : ℕ) := + ∀ {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} (o : PassOrigin B f hf p) + (encode : p.step.Choice → List Bool) (loc : Located S.steps) (past : List (SelectedLevel B f hf)) + (m : Memory w), ExecutionCalendar.kind o = loc.phase → loc.block < T → past.length = loc.depth → + X.positions ≤ P → X.maxWireWidth ≤ M → + (∀ i, (p.next i).positions ≤ P ∧ (p.next i).maxWireWidth ≤ M) → Boundary resident pub pitch total (loc.first B) past X m → + Nonempty (PassRun resident pub pitch total cap small rate loc o encode past m) + +private theorem runTree_of_located {a g b n : ℕ} {X : State a g} + (build : LocatedRuns resident pub pitch total cap small rate T P M) + (E : StateExecution R b n X) (o : PassOrigins B f hf E) (W : E.MapWitnesses f) (r : ExecutionReaders E W) + (xs : List (Located S.steps)) (past : List (SelectedLevel B f hf)) + (depth : Numbered past.length xs) (inside : ∀ loc ∈ xs, loc.block < T) + (order : ExecutionCalendar.Follows E o (xs.map Located.phase)) (size : PrefixLevelScale.Within P M E) : + RunTree resident pub pitch total cap small rate E o W r xs past := by + induction E generalizing xs past with + | done => trivial + | more p tail ih => + cases xs with + | nil => exact order.elim + | cons loc rest => + refine ⟨fun phase m ready => build o.1 r.1.select.encode loc past m phase (inside loc List.mem_cons_self) + depth.head.symm size.1 size.2.1 (fun i => (size.2.2 i).current) ready,?_⟩ + intro i + apply ih i (o := o.2 i) (W := W.2 i) (r := r.2 i) (xs := rest) + · simpa only [List.length_append,List.length_singleton] using depth.tail + · exact fun loc hl => inside loc (List.mem_cons_of_mem _ hl) + · exact order.2 i + · exact size.2.2 i + +variable {lanes : ℕ} (h : T*S.laneBits ≤ lanes) (X : State (S.degreeExponent 0) lanes) + +/-- The term readers for the scheduled execution obtained by repeating the block readers across +all selected blocks. -/ +noncomputable abbrev nativeReaders := + repeatReaders (blockReaders B f hf) _ T lanes (Nat.add_sub_of_le h).symm X + +local notation "sel" => B.execute f hf T h X +local notation "origins" => executeOrigins B f hf T h X +local notation "stages" => timeline S.steps T +local notation "lastRow" => Schedule.LevelCalendar.Calendar.total (Schedule.Online.calendar (BlockPlanner.Script.plan A)) T + +/-- Recursion on the actual chosen compression execution, beginning just +after its four deterministic cursor initialization rows. -/ +theorem execute (m : Memory w) + (bounds : Schedule.Online.Run.ControlBounds (BlockPlanner.Script.plan A) cap (w := w)) + (smallBounds : Schedule.Online.Run.ControlBounds (BlockPlanner.Script.plan A) small (w := w)) + (passes : RunTree resident pub pitch lastRow cap small rate sel origins _ + (nativeReaders (B := B) (f := f) (hf := hf) h X) stages []) + (ready : Boundary resident pub pitch lastRow (BlockPlanner.Script.initial A).length [] X m) : + Nonempty (Result resident pub pitch lastRow cap small (T*(S.steps+1)*rate+4) + sel origins _ (nativeReaders (B := B) (f := f) (hf := hf) h X) [] (some 0) m) := by + rw [← timeline_length S.steps T] + exact iterate bounds smallBounds sel origins _ _ [] _ _ m rfl stages (execute_follows_timeline B f hf T h X) + (timeline_consecutive B T) passes ready + +theorem execute_of_local (m : Memory w) + (bounds : Schedule.Online.Run.ControlBounds (BlockPlanner.Script.plan A) cap (w := w)) + (smallBounds : Schedule.Online.Run.ControlBounds (BlockPlanner.Script.plan A) small (w := w)) + (build : LocatedRuns resident pub pitch lastRow cap small rate T P M) + (size : PrefixLevelScale.Within P M sel) + (ready : Boundary resident pub pitch lastRow (BlockPlanner.Script.initial A).length [] X m) : + Nonempty (Result resident pub pitch lastRow cap small (T*(S.steps+1)*rate+4) + sel origins _ (nativeReaders (B := B) (f := f) (hf := hf) h X) [] (some 0) m) := by + apply execute h X m bounds smallBounds _ ready + exact runTree_of_located build sel origins _ _ stages [] (timeline_numbered S.steps T) + (fun _ hl => block_lt_of_mem hl) (execute_follows_timeline B f hf T h X) size + +end CompressorRecords.ScheduledTrace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScheduledGreedyRates.lean b/lean/OAI/Computability/VPVNP/CompressorScheduledGreedyRates.lean new file mode 100644 index 0000000000..a1788ea30e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScheduledGreedyRates.lean @@ -0,0 +1,140 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy +import OAI.Computability.VPVNP.CompressorBlockHeaderPlan +import OAI.Computability.VPVNP.CompressorCatalogRates + +/-! +# Uniform traffic of the shrinking assignment and level publishers + +The greedy run contains all six native projection, preparation and read visits. +At each substep two scalar rows and one array-head row are published. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledRates + +open Compression BurstRAM Greedy Greedy.WalkLayout +open PhaseRecipe DescriptorSpace + +variable {w : ℕ} + +/-- Uniform coefficient for the relocated six-visit color and tag directory. -/ +def greedyRate (d : ℕ) := 18+7*d+8*d^2+5*tagCount d+8*(tagCount d)^2 + +private theorem assignmentCap {V A : Type*} {N d width arity tests : ℕ} + {L : WalkLayout w N width} {T : PortTables w} {G : SlotGraph V d} + {order : V ≃ Fin N} {rows : OperandRows d} {src : Memory w} {encode : A → Word w} {f : V → A} + (h : GreedyArena.Assignment L T G order rows arity tests src encode f) : + ∀ r ∈ h.prep++h.reads, r.events.length+1 ≤ CatalogRates.greedyCap rows.length width arity + tests := by + intro r hr + rcases List.mem_append.mp hr with hp|hq + · apply le_trans _ (le_max_left ..) + have := (h.prepWork r hp).1; omega + · rw [(h.readWork r hq).1] + exact le_trans (by omega) (le_max_right ..) + +/-- The six fixed rows in `GreedyLevelPlan.visits` run on the incoming state. +Projection, both relocated preparers, and both readers have degree-only clocks. -/ +theorem greedyProgram {a g : ℕ} (X : GreedyArena.ShrinkingState a g) + (T : IncidenceDirectory w) (origin : ℕ) (m : Memory w) (r : GreedyArena.Run X T origin m) : + r.reports.length = Fintype.card X.Base*(2^a+4)+1 ∧ + RAMBuckets.cost Report.probes r.reports ≤ X.positions*greedyRate (2^a) ∧ + ∀ rep ∈ r.reports, rep.events.length+1 ≤ max 14 (CatalogRates.greedyShrinkCap (2^a)) := by + have hc := r.reports_cost + let d := 2^a + let K := 16+7*d+8*d^2+5*tagCount d+8*(tagCount d)^2 + have hn : Fintype.card X.Base ≤ X.positions := by + rw [State.positions,Fintype.card_prod]; exact Nat.le_mul_of_pos_right _ Fintype.card_pos + have hc' : RAMBuckets.cost Report.probes r.reports = 2+Fintype.card X.Base*K := hc + refine ⟨r.reports_length,?_,?_⟩ + · rw [hc',show greedyRate (2^a) = 2+K from by dsimp [greedyRate,K,d]; ring] + exact (Nat.add_le_add (by have := X.positions_pos; omega : 2 ≤ X.positions*2) + (Nat.mul_le_mul_right K hn)).trans_eq (Nat.mul_add ..).symm + · intro rep hr + have color := assignmentCap r.color rep + have off := assignmentCap r.offsets rep + have csz : (colorOperandRows (2^a)).length = 2*2^a := by simp [colorOperandRows] + have tsz : (tagOperandRows (2^a)).length = tagCount (2^a) := by simp [tagOperandRows,tagCount] + rw [csz] at color; rw [tsz] at off + simp only [GreedyArena.Run.reports,List.mem_append] at hr + rcases hr with (((hp|cp)|cr)|tp)|tr + · apply le_trans _ (le_max_left ..) + have := (r.projection.work rep hp).1; omega + · exact (color (List.mem_append_left _ cp)).trans ((le_max_left ..).trans (le_max_right ..)) + · exact (color (List.mem_append_right _ cr)).trans ((le_max_left ..).trans (le_max_right ..)) + · exact (off (List.mem_append_left _ tp)).trans ((le_max_right ..).trans (le_max_right ..)) + · exact (off (List.mem_append_right _ tr)).trans ((le_max_right ..).trans (le_max_right ..)) + +/-- Charge of one generated field-publisher row, including the call itself. -/ +def publisherRate {g : ℕ} (R : FormulaRow g) := 1+R.recipe.reads+(g+3) + +/-- Fuel for a formula-row publisher, equal to its instruction count plus one. -/ +def publisherCap {g : ℕ} (R : FormulaRow g) := R.recipe.code.length+1 + +private theorem publisherCounts {g : ℕ} (R : FormulaRow g) (p : Fin 5 → Word w) + (s : Word w) (m : Memory w) : + let r := R.recipe.report p s m + execute (R.recipe.table.instantiate w p).program (publisherCap R) + ((R.recipe.table.instantiate w p).program.start s) m [] = some r ∧ + 1+r.probes = publisherRate R ∧ r.events.length+1 = publisherCap R := by + intro r + obtain ⟨hl,hp,_⟩ := RowRecipe.report_cost R.recipe p s m + refine ⟨RowRecipe.execute_row R.recipe p s m [] _ (Nat.lt_succ_self _),?_,?_⟩ + · change 1+(R.recipe.report p s m).probes = _ + rw [hp]; unfold publisherRate; omega + · change (R.recipe.report p s m).events.length+1 = _ + rw [hl,publisherCap,RowRecipe.code_length] + +/-- Sum the traffic rates of the two scalar publishers and the successor incidence and +table-head publisher for one substep. -/ +def headerRate {a b : ℕ} (F : Shape) (p : Scalars.Pass a b) := + publisherRate (Scalars.advanceRow (.terminal a) p) + publisherRate (Scalars.advanceRow p + (.terminal b)) + + publisherRate (DescriptorHeads.publisher F) + +/-- Maximum fuel needed by any of the three header publishers at a substep. -/ +def headerCap {a b : ℕ} (F : Shape) (p : Scalars.Pass a b) := + max (publisherCap (Scalars.advanceRow (.terminal a) p)) + (max (publisherCap (Scalars.advanceRow p (.terminal b))) + (publisherCap (DescriptorHeads.publisher F))) + +/-- Three actual publisher reports, in chronological order and with a clock fixed by +the compiled formulas. The incoming memories may include scheduler frame writes. -/ +theorem substepHeaderCounts {a b : ℕ} (F : Shape) (p : Scalars.Pass a b) (pub : Fin 3 → Fin 5 → + Word w) + (state : Fin 3 → Word w) (m : Fin 3 → Memory w) : + let first := Scalars.advanceRow (.terminal a) p + let next := Scalars.advanceRow p (.terminal b) + let heads := DescriptorHeads.publisher F + let r₀ := first.recipe.report (pub 0) (state 0) (m 0) + let r₁ := next.recipe.report (pub 1) (state 1) (m 1) + let r₂ := heads.recipe.report (pub 2) (state 2) (m 2) + let run (g : ℕ) (R : FormulaRow g) (j : Fin 3) (rep : Report w) := + let M := (R.recipe.table.instantiate w (pub j)).program + execute M (publisherCap R) (M.start (state j)) (m j) [] = some rep + run 3 first 0 r₀ ∧ run 3 next 1 r₁ ∧ run (F.tables+3) heads 2 r₂ ∧ + RAMBuckets.cost Report.probes [r₀,r₁,r₂] = headerRate F p ∧ + ∀ rep ∈ [r₀,r₁,r₂], rep.events.length+1 ≤ headerCap F p := by + intro first next heads r₀ r₁ r₂ run + obtain ⟨ha,ca,ta⟩ := publisherCounts first (pub 0) (state 0) (m 0) + obtain ⟨hb,cb,tb⟩ := publisherCounts next (pub 1) (state 1) (m 1) + obtain ⟨hc,cc,tc⟩ := publisherCounts heads (pub 2) (state 2) (m 2) + change 1+r₀.probes = _ at ca; change 1+r₁.probes = _ at cb; change 1+r₂.probes = _ at cc + refine ⟨ha,hb,hc,?_,?_⟩ + · change _ + (_ + (_ + 0)) = publisherRate first + publisherRate next + publisherRate heads + rw [ca,cb,cc]; omega + · intro rep h + simp only [List.mem_cons,List.mem_nil_iff,or_false] at h + rcases h with rfl|rfl|rfl + · exact ta.le.trans (le_max_left ..) + · exact tb.le.trans ((le_max_left ..).trans (le_max_right ..)) + · exact tc.le.trans ((le_max_right ..).trans (le_max_right ..)) + +end CompressorRecords.ScheduledRates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScheduledPassCases.lean b/lean/OAI/Computability/VPVNP/CompressorScheduledPassCases.lean new file mode 100644 index 0000000000..8395e24e98 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScheduledPassCases.lean @@ -0,0 +1,64 @@ +import OAI.Computability.VPVNP.CompressorScheduledExecution + +/-! # The two concrete source constructors of the descriptor calendar + +The semantic origin fixes the input graph and the precise shrinking index +or refresh pass. Equality with the physical window index identifies the +native worker in the finite script. The remaining bounds are available for +the input graph and every immediate selected successor. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace +open Compression PassTimeline +attribute [local irreducible] BlockProgram.script + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} +variable {w cap small rate total T P M : ℕ} {pub : Fin 11 → BurstRAM.Word w} {pitch : BurstRAM.Word w} +variable {resident : Resident B f hf w} + +/-- A native execution for one pass origin at its specified block and substep, from every ready memory. -/ +abbrev EmitAt (resident : Resident B f hf w) (pub : Fin 11 → BurstRAM.Word w) (pitch : BurstRAM.Word w) + (total cap small rate T P M : ℕ) {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} + (o : PassOrigin B f hf p) (loc : Located S.steps) := + ∀ (encode : p.step.Choice → List Bool) (past : List (SelectedLevel B f hf)) (m : BurstRAM.Memory w), + loc.block < T → past.length = loc.depth → X.positions ≤ P → X.maxWireWidth ≤ M → + (∀ i, (p.next i).positions ≤ P ∧ (p.next i).maxWireWidth ≤ M) → + Boundary resident pub pitch total (loc.first B) past X m → + Nonempty (PassRun resident pub pitch total cap small rate loc o encode past m) + +/-- These two local constructors suffice for the actual iterated program. +Only valid shrinking indices occur, and the identity cast of the lane count +makes the shrinking input exactly the packing state expected by its worker. -/ +theorem locatedRuns_of_passes + (shrink : ∀ (i : Fin S.steps) (g t : ℕ) (X : State (S.degreeExponent i.castSucc) + (packingLaneBits (S.degreeExponent i.castSucc) g)), + EmitAt resident pub pitch total cap small rate T P M (PassOrigin.shrink i rfl X) ⟨t,.shrink i⟩) + (refresh : ∀ (g t : ℕ) (X : State S.portExponent (S.portExponent+g)), + EmitAt resident pub pitch total cap small rate T P M (PassOrigin.refresh X) ⟨t,.refresh⟩) : + LocatedRuns resident pub pitch total cap small rate T P M := by + intro a g b n X p o encode loc past m hphase + obtain ⟨t,s⟩ := loc + cases o with + | shrink i h Y => + subst h + cases s with + | shrink j => + have eq : i = j := Fin.ext (ExecutionCalendar.Phase.shrink.inj hphase) + subst j + exact shrink i _ t _ encode past m + | refresh => contradiction + | refresh Y => + cases s with + | shrink i => contradiction + | refresh => exact refresh _ t Y encode past m + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScheduledSliceRates.lean b/lean/OAI/Computability/VPVNP/CompressorScheduledSliceRates.lean new file mode 100644 index 0000000000..5361eb9d74 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScheduledSliceRates.lean @@ -0,0 +1,272 @@ +import OAI.Computability.VPVNP.CompressorSlotPhaseCosts +import OAI.Computability.VPVNP.CompressorFlatRowWorker +import OAI.Computability.VPVNP.CompressorShrinkABSliceVisits +import OAI.Computability.VPVNP.CompressorSurvivingNative +import OAI.Computability.VPVNP.CompressorSourceWalk + +/-! +# Traffic of the flattened slice workers + +All AB operands are affine functions of the global bundle ordinal. The +flattening prologue uses registers for these operands. Each surviving-role +worker reads the selected term and writes the thirteen cells of a piece. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledRates + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ShrinkABSliceRecipe SliceRAM +open PhaseCosts ShrinkSliceSweep + +variable {w : ℕ} + +private theorem affineProbes {k : ℕ} (pub : FlatRows.Public k w) (s : Word w) (m : Memory w) : + countProbes (FlatRows.events (fun _ => false) pub s m) = 0 := by + have h (is : List (Fin (k+1))) : + countProbes (is.flatMap (FlatRows.operandEvents (fun _ => false) pub s m)) = 0 := by + induction is with + | nil => rfl + | cons i is ih => rw [List.flatMap_cons,Greedy.probes_append,ih,Nat.add_zero]; rfl + rw [FlatRows.events,Greedy.probes_append,Greedy.probes_append,h]; rfl + +open private execute_reads execute_stores wordStores reads from + OAI.Computability.VPVNP.CompressorSlicePairVisit + +/-- A pair visit charges four input probes and at most three writes, including +successful executions at the machine's arithmetic boundary. -/ +private theorem pairProbes (p : Fin 6 → Word w) (s : Word w) (m : Memory w) (r : Report w) + (hr : execute (IndexedPair.table.instantiate w p).program 38 + ((IndexedPair.table.instantiate w p).program.start s) + m [] = some r) : r.probes ≤ 7 := by + rw [execute_reads p s m 14,execute_stores p s m _ rfl rfl] at hr + obtain rfl := Option.some.inj hr + change countProbes (reads p s m ++ wordStores _ _ _ _ _) ≤ 7 + rw [Greedy.probes_append,show countProbes (reads p s m) = 4 from rfl] + have bound (a s t lo hi : Word w) : countProbes (wordStores a s t lo hi) ≤ 3 := by + unfold wordStores; split <;> first | exact (le_refl 3) | exact (by decide : 1 ≤ 3) + exact Nat.add_le_add_left (bound ..) 4 + +/-- Probe count is unchanged when direct affine operands prepare the flattened +call. Its instruction overhead is already included in the execution budget. -/ +private theorem flatProbes {r p k : ℕ} (core : Template p r k) (fuel limit : ℕ) + (one : ∀ (u : Fin k → Word w) x mem rep, execute (core.instantiate w u).program fuel + ((core.instantiate w u).program.start x) mem [] = some rep → rep.probes ≤ limit) + (bank : FlatRows.Public k w) (m : Memory w) (st : Word w) (rep : Report w) : + let P := ((FlatRows.compile core (fun _ => false)).instantiate w bank).program + execute P (fuel+(3+7*(k+1))) (P.start st) m [] = some rep → rep.probes ≤ limit := by + intro P run + rw [FlatRows.execute_flat] at run + obtain ⟨localReport,hl,rfl⟩ := Option.map_eq_some_iff.mp run + change countProbes (_++localReport.events) ≤ limit + rw [Greedy.probes_append,affineProbes,Nat.zero_add]; exact one _ _ _ _ hl + +/-- The three different AB row workers have their own input arities. -/ +def abFuel {m n : ℕ} : Stage m n → ℕ + | .clear _ => 25 + | .pair _ => 90 + | .refs _ => 95 + +/-- Maximum probes for one AB slice visit, one to clear a count and seven to test a pair or +update its references. -/ +def abProbeCap {m n : ℕ} : Stage m n → ℕ + | .clear _ => 1 + | .pair _ | .refs _ => 7 + +private theorem abOne {m n : ℕ} (I : Inputs) (j : Stage m n) + (bank : Fin (stage I j).worker.params → Word w) (mem : Memory w) (st : Word w) + (rep : Report w) : + let P := ((stage I j).worker.table.instantiate w bank).program + execute P (abFuel j) (P.start st) mem [] = some rep → rep.probes ≤ abProbeCap j := by + cases j with + | clear i => + apply flatProbes (template clearOps 0) 8 1 _ bank mem st rep + intro u x m r hr + have he := clearVisit_native (u 0) x m + have single : (fun _ : Fin 1 => u 0) = u := funext (fun i => by fin_cases i; rfl) + rw [single] at he + rw [he] at hr; cases hr; exact le_rfl + | pair i => exact flatProbes IndexedPair.table 38 7 pairProbes bank mem st rep + | refs i => + apply flatProbes adjTemplate 36 7 _ bank mem st rep + intro u x m r hr + rw [adjVisit_native u m x] at hr + cases hr + change countProbes _ ≤ 7 + rw [(adjEvents_work u m x).1]; split <;> decide + +private theorem boundedScan {C : Type*} {P : BurstRAM.Program w C} {fuel limit calls : ℕ} + (s : Option (Word w)) + (one : ∀ mem st rep, execute P fuel (P.start st) mem [] = some rep → rep.probes ≤ limit) + (mem : Memory w) (rs : List (Report w)) (run : runSegment P fuel s mem + (List.replicate calls []) = some rs) : + RAMBuckets.cost Report.probes rs ≤ (1+limit)*calls := by + induction calls generalizing s mem rs with + | zero => have h : rs = [] := (Option.some.inj run).symm; simp [h] + | succ n ih => + cases s with + | none => simp [List.replicate_succ,runSegment] at run + | some st => + rw [List.replicate_succ,runSegment] at run + cases he : execute P fuel (P.start st) mem [] with + | none => simp [he] at run + | some r => + rw [he] at run + obtain ⟨more,hm,rfl⟩ := Option.map_eq_some_iff.mp run + have hp := one mem st r he + have ht := ih _ _ more hm + rw [RAMBuckets.cost,Nat.mul_succ]; omega + +/-- The actual AB stage table runs once over all global bundle ordinals. This +accepts the physical operands installed by the scheduled recipe. -/ +def ABSource {m n : ℕ} (I : Inputs) (rows : ℕ) (j : Stage m n) (mem : Memory w) + (rs : List (Report w)) : Prop := + ∃ bank : Fin (stage I j).worker.params → Word w, + runSegment ((stage I j).worker.table.instantiate w bank).program (abFuel j) + (some 0) mem (List.replicate rows []) = some rs + +private theorem abWalk {m n rows : ℕ} (I : Inputs) {js : List (Stage m n)} {mem : Memory w} + {rs : List (Report w)} + (h : SourceWalk (ABSource I rows) js mem rs) : + rs.length = rows*js.length ∧ + RAMBuckets.cost Report.probes rs ≤ rows*(js.map (fun j ↦ 1+abProbeCap j)).sum ∧ + ∀ r ∈ rs, r.events.length+1 ≤ 95 := by + induction h with + | done => simp + | @next j js mem rs more src _ ih => + obtain ⟨bank,run⟩ := src + have n := (run_length run).trans (List.length_replicate ..) + have c := boundedScan _ (abOne I j bank) _ _ run + refine ⟨?_,?_,?_⟩ + · rw [List.length_append,n,ih.1,List.length_cons,Nat.mul_succ,Nat.add_comm] + · rw [RAMBuckets.cost_append,List.map_cons,List.sum_cons,Nat.mul_add] + exact Nat.add_le_add (c.trans_eq (Nat.mul_comm ..)) ih.2.1 + · intro rep hr + rcases List.mem_append.mp hr with ha|hb + · exact (run_cap run rep ha).trans (by cases j <;> simp only [abFuel] <;> decide) + · exact ih.2.2 _ hb + +/-- Whole-level AB table, with a fixed number of scheduler visits independent of the +number of bundles and of their selected widths. -/ +theorem flatABCounts {m n rows : ℕ} (I : Inputs) {mem : Memory w} {rs : List (Report w)} + (h : SourceWalk (ABSource I rows) (phases m n) mem rs) : + rs.length = rows*(m+n+2*(m*n)) ∧ + RAMBuckets.cost Report.probes rs ≤ rows*(2*(m+n)+16*(m*n)) ∧ + ∀ r ∈ rs, r.events.length+1 ≤ 95 := by + obtain ⟨len,work,cap⟩ := abWalk I h + have hl := visits_length I m n + rw [visits,List.length_map] at hl + rw [hl] at len + have weight : ((phases m n).map (fun j => 1+abProbeCap j)).sum = 2*(m+n)+16*(m*n) := by + simp only [phases,List.map_append,List.sum_append,List.map_map] + change ((List.finRange (m+n)).map (fun _ => 2)).sum + + ((List.finRange (m*n)).map (fun _ => 8)).sum + + ((List.finRange (m*n)).map (fun _ => 8)).sum = _ + simp [List.map_const']; ring + rw [weight] at work + exact ⟨len,work,cap⟩ + +private theorem flatTotal {r p k : ℕ} (core : Template p r k) (fuel : ℕ) + (one : ∀ (u : Fin k → Word w) st mem, ∃ rep, execute (core.instantiate w u).program fuel + ((core.instantiate w u).program.start st) mem [] = some rep) + (bank : FlatRows.Public k w) (mem : Memory w) (st : Word w) : + let P := ((FlatRows.compile core (fun _ => false)).instantiate w bank).program + ∃ rep, execute P (fuel+(3+7*(k+1))) (P.start st) mem [] = some rep := by + intro P + let v := FlatRows.value (fun _ => false) bank st mem + obtain ⟨r,h⟩ := one (fun j => v j.castSucc) (v (Fin.last k)) mem + rw [FlatRows.execute_flat,h]; exact ⟨_,rfl⟩ + +private theorem abTotal {m n : ℕ} (I : Inputs) (j : Stage m n) + (bank : Fin (stage I j).worker.params → Word w) + (mem : Memory w) (st : Word w) : + let P := ((stage I j).worker.table.instantiate w bank).program + ∃ rep, execute P (abFuel j) (P.start st) mem [] = some rep := by + cases j with + | clear i => + apply flatTotal (template clearOps 0) 8 _ bank mem st + intro u x m + have h := clearVisit_native (u 0) x m + rw [show (fun _ : Fin 1 => u 0) = u from funext fun j => by fin_cases j; rfl] at h + exact ⟨_,h⟩ + | pair i => + apply flatTotal IndexedPair.table 38 _ bank mem st + intro u x m + rw [execute_reads u x m 14,execute_stores u x m _ rfl rfl]; exact ⟨_,rfl⟩ + | refs i => + apply flatTotal adjTemplate 36 _ bank mem st + intro u x m; exact ⟨_,adjVisit_native u m x⟩ + +private theorem useFixedFuel {C : Type*} (P : BurstRAM.Program w C) {fixed cap n : ℕ} + (total : ∀ m s, ∃ r, execute P fixed (P.start s) m [] = some r) + {s : Option (Word w)} {m : Memory w} {rs : List (Report w)} + (run : runSegment P cap s m (List.replicate n []) = some rs) : + runSegment P fixed s m (List.replicate n []) = some rs := by + induction n generalizing s m rs with + | zero => exact run + | succ n ih => + cases s with + | none => simp [List.replicate_succ,runSegment] at run + | some st => + rw [List.replicate_succ,runSegment] at run ⊢ + cases hc : execute P cap (P.start st) m [] with + | none => simp [hc] at run + | some r => + rw [hc] at run + obtain ⟨t,ht,rfl⟩ := Option.map_eq_some_iff.mp run + obtain ⟨s,hs⟩ := total m st + have eqn : s = r := (execute_prefix_unique hs (suffix := []) hc).2 + rw [hs,eqn] + change (runSegment P fixed r.result (after m r.events) (List.replicate n [])).map + (r :: ·) = _ + rw [ih ht]; rfl + +/-- Each successful planner row can be replayed at its fixed worker-specific fuel, +including when the external scheduler supplied a larger uniform allowance. -/ +theorem abSourceOfScheduled {m n rows cap : ℕ} (I : Inputs) (pub : Fin 5 → Word w) (state : Word w) + (ref : Memory w) {j : Stage m n} {mem : Memory w} {rs : List (Report w)} + (source : ShrinkABSliceRecipe.Source I pub state ref rows cap j mem rs) : ABSource I rows j + mem rs := + ⟨fun i => ((stage I j).params i).eval pub state ref,useFixedFuel _ (abTotal I j _) source⟩ + +/-- Resource count on the exact full AB calendar walk generated by its planner. -/ +theorem scheduledABCounts {m n rows cap : ℕ} (I : Inputs) (pub : Fin 5 → Word w) (state : Word w) + (ref : Memory w) {mem : Memory w} {rs : List (Report w)} + (h : SourceWalk (ShrinkABSliceRecipe.Source I pub state ref rows cap) (phases m n) mem rs) : + rs.length = rows*(m+n+2*(m*n)) ∧ RAMBuckets.cost Report.probes rs ≤ rows*(2*(m+n)+16*(m*n)) ∧ + ∀ r ∈ rs, r.events.length+1 ≤ 95 := by + apply flatABCounts (mem := mem) I + generalize phases m n = js at h ⊢ + induction h with + | done => exact .done _ + | next head _ tail => exact .next (abSourceOfScheduled I pub state ref head) tail + +/-- The selected supply worker uses four reads and thirteen writes for every +physical motif piece. Its event count is independent of payload width. -/ +theorem survivingCounts {M : ℕ} (subdiv : Fin 4 → ℕ) (banks : Fin 4 → SurvivingNative.Public w) + (mem : Fin 4 → Memory w) (rs : Fin 4 → List (Report w)) + (run : ∀ t, runSegment ((SurvivingNative.pass.table.instantiate w (banks t)).program) + (1 + SurvivingNative.ops.length) (some 0) (mem t) (List.replicate (M * subdiv t) []) = some + (rs t)) : + (∑ t, (rs t).length) = M*(∑ t, subdiv t) ∧ + (∑ t, RAMBuckets.cost Report.probes (rs t)) = 18*M*(∑ t, subdiv t) ∧ + ∀ t, ∀ r ∈ rs t, r.events.length+1 = 1+SurvivingNative.ops.length := by + have count (t : Fin 4) := fixedScanCounts (fun m s ↦ (SurvivingNative.report + (banks t) s m).events) + (fun m s ↦ by + obtain ⟨he,ret,_⟩ := SurvivingNative.native (banks t) s m + rw [he,← ret]) (fun m s ↦ + let h := SurvivingNative.native (banks t) s m + ⟨h.2.2.2.2.1,h.2.2.2.1⟩) (run t) + refine ⟨?_,?_,?_⟩ + · simp only [(count _).1,Finset.mul_sum] + · simp only [(count _).2.1,Nat.mul_assoc,Finset.mul_sum] + · intro t r hr; rw [(count t).2.2.2 r hr,Nat.add_comm] + +end CompressorRecords.ScheduledRates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScheduledSlotRates.lean b/lean/OAI/Computability/VPVNP/CompressorScheduledSlotRates.lean new file mode 100644 index 0000000000..35a4f2bd44 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScheduledSlotRates.lean @@ -0,0 +1,168 @@ +import OAI.Computability.VPVNP.CompressorCatalogRates +import OAI.Computability.VPVNP.CompressorSlotBuild +import OAI.Computability.VPVNP.CompressorRecordsCopyIncidence + +/-! +# Charged work of the complete shrinking slot program + +The seven preparation segments, nine slot and incidence segments, and six +canonical copy segments form the 22 visits of the fixed slot plan. +The copy also applies to the output of a port refresh. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledRates + +open Compression BurstRAM PhaseCosts SlotLevel ShrinkSlots + +variable {w : ℕ} + +open private full_count from OAI.Computability.VPVNP.CompressorRecordsCopyIncidence + +/-- Six canonical transfer passes for any selected output state. The first three +columns have one cell per base port and the remaining three one per actual port. -/ +theorem copyColumns {a l : ℕ} (X : State a l) (T U : IncidenceDirectory w) (m : Memory w) : + let rs := CopyIncidence.reports X T U CopyIncidence.allColumns m + CopyIncidence.Runs X T U CopyIncidence.allColumns m rs ∧ + rs.length = 3*(Fintype.card X.Base*2^a)+3*(X.positions*2^a) ∧ + RAMBuckets.cost Report.probes rs = 9*(Fintype.card X.Base*2^a)+9*(X.positions*2^a) ∧ + RAMBuckets.cost Report.probes rs ≤ X.positions*(18*2^a) ∧ + ∀ r ∈ rs, r.events.length+1 = 12 := by + intro rs + obtain ⟨n,c,h⟩ := CopyIncidence.reports_work X T U CopyIncidence.allColumns m + have eqn : (CopyIncidence.allColumns.map (CopyIncidence.rows X)).sum = + 3*(Fintype.card X.Base*2^a)+3*(X.positions*2^a) := full_count X + have b : Fintype.card X.Base*2^a ≤ X.positions*2^a := CopyIncidence.rows_le_slots X 0 + rw [eqn] at n c + refine ⟨CopyIncidence.reports_run ..,n,c.trans (by ring),?_,fun r hr ↦ congrArg (·+1) (h r hr).1⟩ + exact c.le.trans (by linarith only [b]) + +private theorem outputResources {s : Shape} {h : Heads} {m : Memory w} {split : ℕ} + {r : Build.Passes w} + (native : r.Native s h split m) : + RAMBuckets.cost Report.probes (r.mates.all++r.widths) = 3*baseArcs s+12*actualCount s ∧ + ∀ rep ∈ r.mates.all++r.widths, rep.events.length+1 ≤ 43 := by + obtain ⟨_,⟨inv,out,inc⟩,widths⟩ := native + let ip := inverseBank s h w + have ib := fixedScanCounts (probes := 2) (ticks := 9) + (fun mem x ↦ SlotScatter.events ip x (mem (ip 0+x).val)) (SlotScatter.visit_native ip) + (fun _ _ ↦ ⟨rfl,rfl⟩) inv + have ob := fixedScanCounts _ (SlotIncidencePass.native _ false) + (fun mem x ↦ SlotIncidencePass.events_work _ false mem x) out + have rb := fixedScanCounts _ (SlotIncidencePass.native _ true) + (fun mem x ↦ SlotIncidencePass.events_work _ true mem x) inc + have wb := fixedScanCounts _ (SlotWidthScan.native _) + (fun mem x ↦ SlotWidthScan.events_work _ mem x) widths + refine ⟨?_,?_⟩ + · simp only [MateReports.all,RAMBuckets.cost_append,ib.2.1,ob.2.1,rb.2.1,wb.2.1]; ring + · intro rep hr + simp only [MateReports.all,List.mem_append] at hr + rcases hr with ((hx|hx)|hx)|hx + · exact (run_cap inv _ hx).trans (by decide) + · exact (run_cap out _ hx).trans (by decide) + · exact (run_cap inc _ hx).trans (by decide) + · exact run_cap widths _ hx + +/-- Coefficient per packed site, including the temporary owner holes, zeroed +counters, lane-lifted incidence columns and the six transfers. -/ +def slotRate (s : Shape) := + let U := 4*s.oldDegree*(2^s.colors*s.oldDegree)*(∑ t, s.subdivisions t) + 30+26*U+20*pad s+44*s.newDegree + +/-- The 22 physical passes with their native reports. The two count equalities +are supplied by `ShrinkSlots.next_counts` for the actual selected output. -/ +theorem slotProgram {a l : ℕ} (Y : State a l) (s : Shape) (h : Heads) (split : ℕ) + (U : IncidenceDirectory w) (layout : Bool) (m : Memory w) (r : Build.Construction w) + (native : r.Native s h split layout m) (lanes : 1 ≤ s.lanes) (positive : 0 < sites s) + (base : Fintype.card Y.Base * 2 ^ a = baseArcs s) + (actual : Y.positions * 2 ^ a = actualCount s) : + let cp := CopyIncidence.reports Y (directory s h w) U CopyIncidence.allColumns (r.final m) + let all := r.all++cp + CopyIncidence.Runs Y (directory s h w) U CopyIncidence.allColumns (r.final m) cp ∧ + RAMBuckets.cost Report.probes all = + 24+2*sites s+2*(owners s+fields s)+6*genuineCount s+3*dummyCount s+5*fields s+ + 3*(owners s*s.newDegree)+17*baseArcs s+21*actualCount s ∧ + RAMBuckets.cost Report.probes all ≤ sites s*slotRate s ∧ + ∀ rep ∈ all, rep.events.length+1 ≤ 49 := by + intro cp all + obtain ⟨prep,pass⟩ := native + obtain ⟨_,wp,_,capP⟩ := ShrinkSlots.Preparation.Reports.Native.resources prep + have ws := slotLevelExactCost pass.1 + obtain ⟨_,bs,capS,_⟩ := slotLevelBounds s h _ r.passes.slots pass.1 lanes ws + obtain ⟨wo,capO⟩ := outputResources pass + obtain ⟨copy,_,wc,_,capC⟩ := copyColumns Y (directory s h w) U (r.final m) + rw [base,actual] at wc + have wt : RAMBuckets.cost Report.probes all = + RAMBuckets.cost Report.probes r.prepare.all + RAMBuckets.cost Report.probes + r.passes.slots.all + + RAMBuckets.cost Report.probes (r.passes.mates.all++r.passes.widths) + + RAMBuckets.cost Report.probes cp := by + simp only [all,Build.Construction.all,Build.Passes.all,RAMBuckets.cost_append]; ring + have base_le : baseArcs s ≤ actualCount s := by + change s.bases*s.tags*s.newDegree ≤ s.bases*(s.tags*s.lanes)*s.newDegree + rw [← Nat.mul_assoc]; exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ lanes) + let K := 4*s.oldDegree*(2^s.colors*s.oldDegree)*(∑ t,s.subdivisions t) + have hg : genuineCount s = sites s*(2*K) := by dsimp [genuineCount,sites,Slots.keyCount,K]; ring + have hd : dummyCount s = sites s*(2*pad s) := by dsimp [dummyCount,sites]; ring + have hf : fields s = sites s*(2*(K+pad s)) := by rw [← counts_add,hg,hd]; ring + have ho : owners s = 2*sites s := Nat.mul_comm .. + refine ⟨copy,?_,?_,?_⟩ + · rw [wt,wp,ws,wo,wc]; ring + · rw [wt,wp,wo,wc,ho,hf] + change _ ≤ sites s*(30+26*K+20*pad s+44*s.newDegree) + change _ ≤ sites s*s.newDegree at base_le + change _ ≤ sites s*(22*K+16*pad s+11*s.newDegree) at bs + change _ + (3*baseArcs s+12*(sites s*s.newDegree)) + (9*baseArcs s+9*(sites s*s.newDegree)) ≤ _ + linarith only [bs,base_le,positive] + · intro rep hr + simp only [all,Build.Construction.all,Build.Passes.all,List.mem_append] at hr + rcases hr with (hp|((hs|hm)|hw))|hc + · exact (capP _ hp).trans (by decide) + · exact capS _ hs + · exact (capO _ (List.mem_append_left _ hm)).trans (by decide) + · exact (capO _ (List.mem_append_right _ hw)).trans (by decide) + · rw [capC _ hc]; decide + +open Compression.State Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy +open MotifBlocks MotifGrid MotifConversion + +/-- The 22 visits on the selected dyadic branch, including the transfer of its actual +width column into the next level. The incoming position count pays for the whole run. -/ +theorem selectedSlotProgram {a b g : ℕ} {δ factor : ℝ} {k : Type*} [_root_.Field k] + (X : State a (packingLaneBits a g)) + (B : FixedBlock k demandSource demandTarget supply (realWidths demandMass) + (realWidths supplyMass) (31 / 16) factor) + (ready : Ready (2 ^ a) (2 * 2 ^ a + 1) (2 ^ b) δ) (sel : X.ShrinkSelection B) + (h : Heads) (split : ℕ) (U : IncidenceDirectory w) (m : Memory w) (r : Build.Construction w) : + let s := levelShape (b := b) X + let Y := X.shrinkNext B ready sel + let cp := CopyIncidence.reports Y (directory s h w) U CopyIncidence.allColumns (r.final m) + let all := r.all++cp + r.Native s h split (selectedLayout X B sel) m → + CopyIncidence.Runs Y (directory s h w) U CopyIncidence.allColumns (r.final m) cp ∧ + RAMBuckets.cost Report.probes all ≤ X.positions*slotRate s ∧ + ∀ rep ∈ all, rep.events.length+1 ≤ 49 := by + intro s Y cp all native + obtain ⟨hb,ha⟩ := ShrinkSlots.next_counts X B ready sel + have ha' : Y.positions*2^b = actualCount s := by + simpa only [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv g), + Fintype.card_fin] + using ha + have hl : 1 ≤ s.lanes := Nat.two_pow_pos g + have hp : 0 < sites s := Nat.mul_pos Fintype.card_pos (Nat.mul_pos (Nat.two_pow_pos _) + (Nat.two_pow_pos _)) + have eqn := CatalogRates.shrinkShape_positions X s.subdivisions (2^b) + change sites s*(2^s.colors*s.oldDegree) = X.positions at eqn + have le : sites s ≤ X.positions := (Nat.le_mul_of_pos_right _ + (Nat.mul_pos (Nat.two_pow_pos _) (Nat.two_pow_pos _))).trans_eq eqn + obtain ⟨rc,_,c,hc⟩ := slotProgram Y s h split U _ m r native hl hp hb ha' + exact ⟨rc,c.trans (Nat.mul_le_mul_right _ le),hc⟩ + +end CompressorRecords.ScheduledRates + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScheduledTrace.lean b/lean/OAI/Computability/VPVNP/CompressorScheduledTrace.lean new file mode 100644 index 0000000000..ddff43065b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScheduledTrace.lean @@ -0,0 +1,91 @@ +import OAI.Computability.VPVNP.CompressorScheduledTraceData + +/-! # Native execution in chronological block order -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace +open BurstRAM Compression BranchSegments PassTimeline PairSimulation.LocalHistory +open scoped Fin.CommRing +attribute [local irreducible] BlockProgram.script +open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} +variable {w cap small rate total : ℕ} {pub : Fin 11 → Word w} {pitch : Word w} + +local notation "script" => BlockProgram.script B +local notation "pt" => Workspace.ports (Schedule.arity (BlockPlanner.Script.catalog (BlockProgram.script B))) (pub 2) +local notation "outer" => OnlineWorkspace.program (BlockPlanner.Script.plan (BlockProgram.script B)) pub +local notation "lo" => Fin.val (pub 2)+6 + +variable {resident : Resident B f hf w} {a g b n : ℕ} {X : State a g} + +theorem iterate + (bounds : Schedule.Online.Run.ControlBounds (BlockPlanner.Script.plan script) cap (w := w)) + (smallBounds : Schedule.Online.Run.ControlBounds (BlockPlanner.Script.plan script) small (w := w)) + (E : StateExecution R b n X) (o : PassOrigins B f hf E) (W : E.MapWitnesses f) (r : ExecutionReaders E W) + (past : List (SelectedLevel B f hf)) (ord : ℕ) (st : Option (Word w)) (m : Memory w) (hs : st = some 0) + (xs : List (Located S.steps)) (order : ExecutionCalendar.Follows E o (xs.map Located.phase)) + (calendar : Consecutive B ord xs total) (pass : RunTree resident pub pitch total cap small rate E o W r xs past) + (ready : Boundary resident pub pitch total ord past X m) : + Nonempty (Result resident pub pitch total cap small (xs.length*rate+4) E o W r past st m) := by + induction E generalizing past ord xs st m with + | done X => + cases xs with + | cons x xs => contradiction + | nil => + subst st + change ord = total at calendar + subst ord + have stop : m (pt).rows.val ≤ m (pt).ordinal.val := Fin.le_def.mpr (ready.totalValue.trans ready.ordinalValue.symm).le + let seg := OnlineWorkspace.terminalSegment script pub bounds ready.tag ready.bank stop + have halt : seg.state = none := OnlineWorkspace.terminalSegment_state .. + let t : ExecutionTrace outer (cap+24) (.done X : StateExecution R _ _ X) (some 0) m := .done seg 1 rfl halt + let core := OnlineWorkspace.terminalCore (A := script) (pub := pub) bounds smallBounds ready.tag ready.bank stop + refine ⟨⟨t,?_,fun _ => core,fun _ => ?_,fun _ => ?_⟩⟩ + · exact OnlineWorkspace.terminalSegment_stable script pub bounds ready.tag ready.bank stop lo + · simpa only [core,List.length_nil,Nat.zero_mul,Nat.zero_add] using + (OnlineWorkspace.terminal_cost bounds smallBounds ready.tag ready.bank stop).le + · change Boundary resident pub pitch total total (past++[]) X seg.memory + rw [List.append_nil,OnlineWorkspace.terminalSegment_memory]; exact ready + | more p tail ih => + cases xs with + | nil => exact order.elim + | cons loc rest => + subst st + obtain ⟨hphase,phases⟩ := order + obtain ⟨first,remaining⟩ := calendar + let encode := r.1.select.encode + let here := (pass.1 hphase m (first ▸ ready)).some + let child (i : p.step.Choice) := + (ih i (o := o.2 i) (W := W.2 i) (r := r.2 i) (past := past++[level o.1 encode i]) + (ord := loc.finish B) (st := (here.cut.part i).state) (m := (here.cut.part i).memory) + (hs := here.state i) (xs := rest) (order := phases i) (calendar := remaining) (pass := pass.2 i) (ready := here.next i)).some + let t : ExecutionTrace outer (cap+24) (.more p tail) (some 0) m := .more here.cut fun i => (child i).trace + refine ⟨⟨t,⟨here.frame,fun i => (child i).frame⟩, + fun z => (here.source z.1).append ((child z.1).source z.2),?_,?_⟩⟩ + · intro z + obtain ⟨i,u⟩ := z + rw [OnlineWorkspace.Core.cost_append] + have step := here.cost i + have later := (child i).cost u + simp only [List.length_cons,Nat.succ_mul] + omega + · intro z + obtain ⟨i,u⟩ := z + change Boundary resident pub pitch total total (past++level o.1 encode i :: collectLevels B f hf (tail i) _ _ _ u) + _ (((here.cut.part i).append ((child i).trace.cut.part u)).memory) + rw [Segment.append_memory] + simpa only [List.append_assoc,List.singleton_append,StateExecution.finalState] using (child i).final u + +end CompressorRecords.ScheduledTrace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScheduledTraceData.lean b/lean/OAI/Computability/VPVNP/CompressorScheduledTraceData.lean new file mode 100644 index 0000000000..7058cba8f6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScheduledTraceData.lean @@ -0,0 +1,115 @@ +import OAI.Computability.VPVNP.CompressorPassTimeline +import OAI.Computability.VPVNP.CompressorPrefixFrames +import OAI.Computability.VPVNP.CompressorWorkspaceCore + +/-! # Threading the physical descriptor program through the selected execution + +The fixed finite table uses the calendar of the compiled block program. +At each shrinking or refresh pass the next interval starts at its proved +absolute ordinal, in the memory returned on that choice. The final call +uses the true exclusive bound. The construction retains the full selected +history, the source reports at their private clock, and the low-address +frame even on successful partial streams which cannot extend to acceptance. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section +namespace CompressorRecords.ScheduledTrace +open BurstRAM Compression BranchSegments PassTimeline PairSimulation.LocalHistory +open scoped Fin.CommRing +attribute [local irreducible] BlockProgram.script +open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} +variable {w cap small rate total : ℕ} {pub : Fin 11 → Word w} {pitch : Word w} + +local notation "script" => BlockProgram.script B +local notation "pt" => Workspace.ports (Schedule.arity (BlockPlanner.Script.catalog (BlockProgram.script B))) (pub 2) +local notation "outer" => OnlineWorkspace.program (BlockPlanner.Script.plan (BlockProgram.script B)) pub +local notation "lo" => Fin.val (pub 2)+6 + +/-- The application-specific stored graph and the records of all previously +selected levels. The controller fields are tracked separately. -/ +abbrev Resident (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (w : ℕ) := + List (SelectedLevel B f hf) → {a g : ℕ} → State a g → Memory w → Prop + +variable {resident : Resident B f hf w} + +/-- Physical state shared by the preceding pass, the next recipe and the +eventual terminal traversal. -/ +structure Boundary (resident : Resident B f hf w) (pub : Fin 11 → Word w) (pitch : Word w) + (total ordinal : ℕ) (past : List (SelectedLevel B f hf)) {a g : ℕ} (X : State a g) (m : Memory w) : Prop where + bank : Workspace.Installed (Schedule.arity (BlockProgram.script B).catalog) (pub 2) m + tag : m (Workspace.ports (Schedule.arity (BlockProgram.script B).catalog) (pub 2)).tag.val = + LiveStageLink.tagWord w (Schedule.Online.calendarIndex (BlockProgram.script B).size (BlockProgram.script B).size) + ordinalValue : (m (Workspace.ports (Schedule.arity (BlockProgram.script B).catalog) (pub 2)).ordinal.val).val = ordinal + totalValue : (m (Workspace.ports (Schedule.arity (BlockProgram.script B).catalog) (pub 2)).rows.val).val = total + stride : m ((Workspace.ports (Schedule.arity (BlockProgram.script B).catalog) (pub 2)).directory-1).val = pitch + stored : resident past X m + +/-- Package a pass, its origin, the selected term, and that term's encoded tape as one history +level. -/ +def level {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} + (o : PassOrigin B f hf p) (encode : p.step.Choice → List Bool) (i : p.step.Choice) : SelectedLevel B f hf := + ⟨a,g,b,n,X,p,o,i,encode i⟩ + +/-- Evidence for one physical interval of the repeating calendar. The +reports and memory of each branch are those of the concrete cut. -/ +structure PassRun (resident : Resident B f hf w) (pub : Fin 11 → Word w) (pitch : Word w) + (total cap small rate : ℕ) (loc : Located S.steps) {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} + (o : PassOrigin B f hf p) (encode : p.step.Choice → List Bool) (past : List (SelectedLevel B f hf)) (m : Memory w) where + /-- Native pass segments indexed by term choice, with disjoint tape prefixes covering every + halting run. -/ + cut : Cut (OnlineWorkspace.program (BlockProgram.script B).plan pub) (cap+24) (some 0) m p.step.Choice + frame : cut.PrefixFrame ((pub 2).val+6) + state : ∀ i, (cut.part i).state = some 0 + /-- Source reports recovered from the native segment for each choice of the current pass. -/ + source : ∀ i, OnlineWorkspace.Core (clock := cap+24) (BlockProgram.script B) pub (cut.part i) small + cost : ∀ i, RAMBuckets.cost Report.probes (source i).logs ≤ rate + next : ∀ i, Boundary resident pub pitch total (loc.finish B) (past++[level o encode i]) (p.next i) (cut.part i).memory + +/-- Local constructors are needed only on the actual mathematical tree, +with the concrete reader, earlier selected history and physical window. +No extension of a prefix to a complete accepting branch is required. -/ +def RunTree (resident : Resident B f hf w) (pub : Fin 11 → Word w) (pitch : Word w) + (total cap small rate : ℕ) {a g b n : ℕ} {X : State a g} : + (E : StateExecution R b n X) → PassOrigins B f hf E → (W : E.MapWitnesses f) → + ExecutionReaders E W → List (Located S.steps) → List (SelectedLevel B f hf) → Prop + | .done _, _, _, _, _, _ => True + | .more _ _, _, _, _, [], _ => False + | @StateExecution.more _ _ _ _ _ _ _ _ X _ tail, o, W, r, loc::rest, past => + (ExecutionCalendar.kind o.1 = loc.phase → ∀ m, + Boundary resident pub pitch total (loc.first B) past X m → + Nonempty (PassRun resident pub pitch total cap small rate loc o.1 r.1.select.encode past m)) ∧ + ∀ i, RunTree resident pub pitch total cap small rate (tail i) (o.2 i) (W.2 i) (r.2 i) rest + (past++[level o.1 r.1.select.encode i]) + +variable {a g b n : ℕ} {X : State a g} {E : StateExecution R b n X} + +/-- All selected mathematical histories are retained in their real final +memories. Work counts visits with multiplicity, including repeated states. -/ +structure Result (resident : Resident B f hf w) (pub : Fin 11 → Word w) (pitch : Word w) + (total cap small budget : ℕ) (E : StateExecution R b n X) (o : PassOrigins B f hf E) + (W : E.MapWitnesses f) (r : ExecutionReaders E W) (past : List (SelectedLevel B f hf)) + (st : Option (Word w)) (m : Memory w) where + /-- Native execution trace for the scheduled descriptor program, indexed by branches of the + compression execution. -/ + trace : ExecutionTrace (OnlineWorkspace.program (BlockProgram.script B).plan pub) (cap+24) E st m + frame : trace.Framed ((pub 2).val+6) + /-- Source reports underlying the native trace segment for each complete branch. -/ + source : ∀ z, OnlineWorkspace.Core (clock := cap+24) (BlockProgram.script B) pub (trace.cut.part z) small + cost : ∀ z, RAMBuckets.cost Report.probes (source z).logs ≤ budget + final : ∀ z, Boundary resident pub pitch total total (past++collectLevels B f hf E W r o z) + (E.finalState z) (trace.cut.part z).memory + +end CompressorRecords.ScheduledTrace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScriptSnapshot.lean b/lean/OAI/Computability/VPVNP/CompressorScriptSnapshot.lean new file mode 100644 index 0000000000..50f64f4e26 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScriptSnapshot.lean @@ -0,0 +1,121 @@ +import OAI.Computability.VPVNP.CompressorOnlineFootprint + +/-! # The operands loaded by each actual compressor-script visit + +The calendar and recipe compute an address and all public worker operands in +the current memory. The launcher copies these operands to the active frame, +increments the ordinal and preserves the row count. All addresses are derived +from the declared workspace layout. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.BlockPlanner.Script + +open BurstRAM DescriptorSpace Schedule +open scoped Fin.CommRing + +variable {w : ℕ} (A : Script) (L : Layout) (base : Word w) +local notation "g₀" => arity A.catalog +local notation "P₀" => Workspace.ports g₀ base + +private theorem field_addresses (g : ℕ) (base : Word w) (fit : base.val + (11+g) < 2^w) : + let p := Workspace.ports g base + p.tag.val = base.val+6 ∧ p.ordinal.val = base.val+7 ∧ p.rows.val = base.val+8 ∧ + p.directory.val = base.val+(11+g) ∧ + ∀ i : Fin (g+1), (p.activeFrame+(i.val : Word w)).val = base.val+(9+i.val) := by + intro p + have addAt (j : ℕ) (hj : j ≤ 11+g) : (base+(j : Word w)).val = base.val+j := by + rw [Fin.val_add,Fin.val_natCast,Nat.mod_eq_of_lt (by omega : j < 2^w),Nat.mod_eq_of_lt (by omega)] + refine ⟨addAt 6 (by omega),addAt 7 (by omega),addAt 8 (by omega),addAt _ le_rfl,fun i => ?_⟩ + change (base+9+(i.val : Word w)).val = _ + rw [show base+9+(i.val : Word w) = base+((9+i.val : ℕ) : Word w) by simp [Nat.cast_add,add_assoc]] + exact addAt _ (by have := i.isLt; omega) + +/-- Compute the level header used by the script recipe from the calendar and the current +memory. -/ +def recipeState (m : Memory w) := LevelCalendar.header (Online.calendar A.plan) (P₀).data m + +/-- Evaluate a recipe expression at a script occurrence using its level header and calendar +memory. -/ +def operand (m : Memory w) (j : Fin A.size) (x : PhaseRecipe.Expr) : Word w := + x.eval (P₀).data (recipeState A base m) (Online.calendarMemory (d := A.size) P₀ m j) + +/-- The row directory, active frame, and controller counter properties all +hold on the actual output of the calendar and its selected recipe. -/ +theorem snapshot (hg : arity A.catalog = L.shape.arity) (hb : base.val = L.base) + (fit : levelStart L 0 < 2^w) (m : Memory w) (j : Fin A.size) + (room : (m (P₀).ordinal.val).val < directoryRows L) (live : m (P₀).ordinal.val < m (P₀).rows.val) : + let entry := Online.rowInput A.plan P₀ m j + let prepared := Directory.prepared A.catalog P₀ entry + let visit := A.visit j + entry (P₀).ordinal.val = m (P₀).ordinal.val ∧ entry (P₀).rows.val = m (P₀).rows.val ∧ + entry (P₀).tag.val = 0 ∧ + Directory.start A.catalog P₀ entry = operand A base m j visit.initial ∧ + Directory.bound A.catalog P₀ entry = operand A base m j visit.stop ∧ + Directory.words A.catalog P₀ j entry = (fun i => operand A base m j (visit.params i)) ∧ + Ready A.catalog j P₀ (fun i => operand A base m j (visit.params i)) (operand A base m j visit.stop) prepared ∧ + (prepared (P₀).ordinal.val).val = (m (P₀).ordinal.val).val+1 ∧ + prepared (P₀).rows.val = m (P₀).rows.val := by + intro entry prepared visit + have hdir : directoryBase L = base.val+(11+g₀) := by + rw [hg,hb] + simp only [directoryBase,plannerTag,frameBase] + omega + have hend : levelStart L 0 = directoryBase L + directoryRows L*(g₀+3) := by + simp [levelStart,levelsBase,hg] + have hfit : base.val + (11+g₀) < 2^w := by rw [← hdir]; omega + obtain ⟨tag,ord,total,dir,bank⟩ := field_addresses g₀ base hfit + have ot : (P₀).ordinal ≠ (P₀).tag := fun h => by have := congrArg Fin.val h; omega + have tt : (P₀).rows ≠ (P₀).tag := fun h => by have := congrArg Fin.val h; omega + have frame : Directory.FrameFits A.catalog P₀ := by + refine ⟨by omega,fun i => ?_⟩ + have h := bank i + constructor <;> intro he <;> have hh := congrArg Fin.val he <;> omega + have high := OnlineFootprint.row_bound A L base hg hb fit m room + have addrFit : (P₀).directory.val + (m (P₀).ordinal.val).val*(g₀+3) < 2^w := by + have h := Nat.mul_le_mul_right (g₀+3) room + rw [Nat.succ_mul] at h + omega + have addr := Directory.rowBase_val A.catalog P₀ m addrFit + have away (k : Word w) (h : k ∈ [(P₀).tag,(P₀).ordinal,(P₀).rows]) : + k.val < (Directory.rowBase A.catalog P₀ m).val ∨ (Directory.rowBase A.catalog P₀ m).val+(g₀+3) ≤ k.val := by + simp only [List.mem_cons,List.not_mem_nil,or_false] at h + rcases h with rfl | rfl | rfl <;> exact Or.inl (by omega) + let st := operand A base m j visit.initial + let stop := operand A base m j visit.stop + let params := fun i => operand A base m j ((A.phase j).params i) + have src := Online.computed_ready A.plan P₀ m j j st stop params frame ot tt + (PhaseRecipe.recipe_address (A.phase j) ..) (PhaseRecipe.recipe_words (A.phase j) ..) (high.trans fit.le) away + obtain ⟨eo,er,es,ready⟩ := src + have eqParams : (fun u => params (Fin.castLE (params_le_arity A.catalog j) u)) = + (fun i => operand A base m j (visit.params i)) := by + funext i + exact congrArg (operand A base m j) (A.phase_param j i) + rw [eqParams] at ready + have rt : entry (Directory.rowBase A.catalog P₀ entry).val = LiveStageLink.tagWord w j.succ := + (Controller.after_row_tag g₀ (P₀).data entry).symm.trans ready.1 + have actual := Directory.ready A.catalog P₀ entry j frame rt + have entryLive : entry (P₀).ordinal.val < entry (P₀).rows.val := by + rw [show entry (P₀).ordinal.val = _ from eo, show entry (P₀).rows.val = _ from er] + exact live + refine ⟨eo,er,by simp [entry,Online.rowInput,writeMemory],es, + actual.2.1.symm.trans ready.2.1,actual.2.2.symm.trans ready.2.2,ready,?_,?_⟩ + · exact (Controller.after_row_ordinal_val g₀ (P₀).data entry ot entryLive).trans + (congrArg (fun x : Word w => x.val+1) eo) + · apply Eq.trans _ er + apply Controller.after_row_outside g₀ (P₀).data entry + · change (P₀).rows.val ≠ (P₀).ordinal.val; omega + · exact Fin.val_ne_of_ne tt + · intro i + have h := bank i + change (P₀).rows.val ≠ ((P₀).activeFrame+(i.val : Word w)).val + omega + +end CompressorRecords.BlockPlanner.Script + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorScriptWindow.lean b/lean/OAI/Computability/VPVNP/CompressorScriptWindow.lean new file mode 100644 index 0000000000..7b33ebac35 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorScriptWindow.lean @@ -0,0 +1,87 @@ +import OAI.Computability.VPVNP.CompressorSourceOnline + +/-! +# Embedding a contiguous native substep in the fixed block program + +A window identifies each occurrence by its ordinal inside the complete +static block. Equal worker tables can occur many times. An indexed map +of a chronological source walk retains this distinction while keeping +the original input memories, tapes and reports. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords + +open BurstRAM Schedule + +namespace BlockPlanner + +/-- A decomposition of the script block around a specified contiguous list of visits. -/ +structure Window (A : Script) (visits : List Visit) where + /-- Visits in the block preceding the first occurrence in the window. -/ + before : List Visit + /-- Visits in the block following the window. -/ + after : List Visit + block : A.block = before ++ visits ++ after + +namespace Window + +variable {A : Script} {visits : List Visit} (W : Window A visits) + +/-- Index of a window occurrence in the block, obtained by skipping its preceding visits. -/ +def position (i : Fin visits.length) : Fin A.block.length := + ⟨W.before.length+i.val,by rw [W.block]; simp only [List.length_append]; have := i.isLt; omega⟩ + +/-- Index of a window occurrence in the whole script, including the initialization prefix. -/ +def index (i : Fin visits.length) : Fin A.size := (W.position i).natAdd A.initial.length + +theorem index_val (i : Fin visits.length) : (W.index i).val = A.initial.length + W.before.length + i.val := by + change A.initial.length+(W.before.length+i.val) = _; omega + +theorem visit (i : Fin visits.length) : A.visit (W.index i) = visits[i.val] := by + rw [index,A.block_visit] + change A.block[W.before.length+i.val]'_ = _ + erw [List.getElem_of_eq W.block] + rw [List.getElem_append_left (by simp only [List.length_append]; have := i.isLt; omega)] + rw [List.getElem_append_right (by omega)] + simp + +end Window +end BlockPlanner + +theorem SourceWalk.mapAt {J K : Type*} {w : ℕ} {source : J → Memory w → List (Report w) → Prop} + {dest : K → Memory w → List (Report w) → Prop} {js : List J} {m : Memory w} {rs : List (Report w)} + (h : SourceWalk source js m rs) (labels : Fin js.length → K) + (convert : ∀ i mem log, source js[i.val] mem log → dest (labels i) mem log) : + SourceWalk dest (List.ofFn labels) m rs := by + induction h with + | done => simp only [List.length_nil,List.ofFn_zero]; exact .done _ + | @next j js m rs ts hhead _ ih => + rw [@List.ofFn_succ K js.length labels] + exact .next (convert 0 m rs hhead) (ih _ (fun i mem log hs ↦ convert i.succ mem log hs)) + +namespace SourceOnline.Visit + +variable {A : BlockPlanner.Script} {w : ℕ} + +/-- Form a script visit from a native worker, transporting its operands to the matching catalog +entry. -/ +def ofWorker (j : Fin A.size) (W : Pass) (hw : A.catalog j = W) (fuel : ℕ) (start stop : Word w) + (params : Fin W.params → Word w) (choices : List (List Bool)) : SourceOnline.Visit A w := + ⟨j,fuel,start,stop,fun i ↦ params (Fin.cast (congrArg Pass.params hw) i),choices⟩ + +theorem ofWorker_runs (j : Fin A.size) (W : Pass) (hw : A.catalog j = W) (fuel : ℕ) (start stop : Word w) + (params : Fin W.params → Word w) (choices : List (List Bool)) (m : Memory w) (rs : List (Report w)) : + (ofWorker j W hw fuel start stop params choices).Runs m rs ↔ + runSegment (W.table.instantiate w params).program fuel (some start) m choices = some rs := by + subst W; rfl + +end SourceOnline.Visit +end CompressorRecords + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectedChildDirectory.lean b/lean/OAI/Computability/VPVNP/CompressorSelectedChildDirectory.lean new file mode 100644 index 0000000000..4723d56412 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectedChildDirectory.lean @@ -0,0 +1,141 @@ +import OAI.Computability.VPVNP.PairNodeChildPublishedDirectory +import OAI.Computability.VPVNP.CompressorShrinkScheduledTail +import OAI.Computability.VPVNP.CompressorSelectedPayloadHistory + +/-! +# The seven child-scan operands at a selected level + +The child decoder reads its old-level directory in one contiguous block +at scalar 14. The following six scalar words come from the pass metadata +packet. Its first word is the carried DFS base, supplied at traversal by +the chronological directory history. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SelectedChildDirectory + +open BurstRAM Compression DescriptorSpace PairSimulation.NodeArguments PairSimulation.NodeArguments.ChildScan +open BlockPlanner Schedule +open scoped Fin.CommRing + +variable {w a g : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable (L : Layout) (i n : ℕ) (X : State a g) (m : Memory w) + +local notation "head" => levelStart L i +local notation "T" => packedIncidence L w i (X.positions*2^a) +local notation "arena" => Arena.mk n (frameStride (slotDegree S) n) + +/-- All seven words at the actual header pointer. The first word may be +given as any natural representative of the stored DFS row base. -/ +structure Stored : Prop where + room : head+20 < 2^w + wide : 20 < levelWords L + bank : ∀ older : ℕ, m (head+14) = (older : Word w) → + (directory a older B.recordLimit arena T).Stored m ((head : Word w)+14) + +variable {B L i n X m} {out : Memory w} + +open private field_address from OAI.Computability.VPVNP.PairNodeChildPublishedDirectory + +theorem Stored.stride (d : Stored B L i n X m) : m (head+15) = ((B.recordLimit+2 : ℕ) : Word w) := by + have h := d.bank (m (head+14)).val (Fin.cast_val_eq_self _).symm 1 + rw [field_address head d.room 1] at h + exact h + +/-- Term, map, and later live scheduler writes preserve the child operands +when they preserve these seven actual cells. -/ +theorem Stored.keep (d : Stored B L i n X m) + (same : ∀ x, head+14 ≤ x → x ≤ head+20 → out x = m x) : Stored B L i n X out := + ⟨d.room,d.wide,fun older base => directory_retain + (d.bank older ((same _ le_rfl (by omega)).symm.trans base)) d.room same⟩ + +theorem Stored.transfer (d : Stored B L i n X m) + (same : SourceTransport.Agree (SelectedPayloadHistory.Cells L i) m out) : Stored B L i n X out := by + apply d.keep + intro x lo hi + have edge : levelStart L (i+1) = head+levelWords L := by + simp only [levelStart,Nat.succ_mul,Nat.add_assoc] + exact (same x (Or.inl ⟨by omega,by have := d.wide; omega⟩)).symm + +variable {workspace : Word w} {positions blocks t : ℕ} +local notation "prog" => BlockProgram.script B +local notation "layout" => BlockProgram.layout B workspace.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog prog)) workspace +local notation "pub" => Ports.data pt +local notation "first" => Script.levelsPerBlock prog*t +local notation "st" => (levelStart layout first : Word w) + +private theorem layout_width : 20 < levelWords layout := by + change 20 < 66+_+_ + omega + +open private BlockMetadata.Published.keeps_row_base from OAI.Computability.VPVNP.PairNodeChildPublishedDirectory + +section Shrink + +variable {j : Fin S.steps} {r : ℕ} {Y : State (ShrinkBlockInputs.a j) (packingLaneBits (ShrinkBlockInputs.a j) r)} +local notation "cur" => first+j.val +local notation "old" => packedIncidence layout w cur (Y.positions*2^(ShrinkBlockInputs.a j)) + +/-- The actual shrinking metadata writer publishes the old child directory. -/ +theorem Stored.of_shrink {start : ℕ} {rs : List (Report w)} + (p : BlockMetadata.Published B workspace positions blocks t j.val .shrink (BlockMetadata.shrinkFields B j) + m (ShrinkPreimages.oldCount Y) rs) + (header : ShrinkHeaderReads.Header j Y old start layout first m) + (entry : LevelFields.Entry layout first pub st m) (termFits : ShrinkInput.termEnd Y start 10 < 2^w) + (rows : m (pt).rows.val = (directoryRows layout : Word w)) + (nCell : m (levelStart layout 0+29) = (n : Word w)) : + Stored B layout cur n Y (after m (eventLog rs)) := by + refine ⟨by have := header.room; omega,layout_width,fun older rowBase => ?_⟩ + apply p.shrink_child_directory B j Y old start workspace positions blocks t header entry termFits rows n older nCell + exact (BlockMetadata.Published.keeps_row_base B workspace positions blocks t p).symm.trans rowBase + +/-- The shrinking term and data publishers follow the metadata writer in +the same pass and preserve all seven child-scan operands. -/ +theorem Stored.of_shrink_tail {cap start : ℕ} {ms ps : List (SourceOnline.Packet prog w)} + (tail : ShrinkScheduledTail.Result B workspace positions blocks t cap j Y m ms ps) + (header : ShrinkHeaderReads.Header j Y (packedIncidence layout w cur (DemandRAM.oldCount Y)) start layout first m) + (pitch : m (pub 1-1).val = (levelWords layout : Word w)) (termFits : ShrinkInput.termEnd Y start 10 < 2^w) + (rows : m (pt).rows.val = (directoryRows layout : Word w)) + (nCell : m (levelStart layout 0+29) = (n : Word w)) : + Stored B layout cur n Y (SourceOnline.post m ps) := by + have count : DemandRAM.oldCount Y = Y.positions*2^(ShrinkBlockInputs.a j) := by + rw [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv _),Fintype.card_fin] + have metadata := Stored.of_shrink tail.baseFields (count ▸ header) ⟨rfl,pitch⟩ termFits rows nCell + exact metadata.keep (fun x _ hi => tail.metaCell x (Or.inl (by omega))) + +end Shrink + +section Refresh + +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) +variable {r : ℕ} (Y : State S.portExponent (S.portExponent+r)) +variable (c : Refresh.DyadicRefreshChoice Y S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (bits : List Bool) +local notation "lev" => RefreshPlacement.selectedLevel B f hf Y c bits +local notation "cur" => first+S.steps + +/-- The selected refresh metadata writer publishes the same child operand +bank for its singleton placement. -/ +theorem Stored.of_refresh {rs : List (Report w)} {dH : ℕ} + (p : BlockMetadata.Published B workspace positions blocks t S.steps .refresh (BlockMetadata.refreshFields B) + m Y.positions rs) + (entry : LevelFields.Entry layout first pub st m) + (header : LevelFields.Published layout cur lev dH m) + (pointers : PortRefresh.TraversalHeaders.HeadBank layout cur (lev).oldSlots m) + (room : levelStart layout cur+66 ≤ 2^w) (rows : m (pt).rows.val = (directoryRows layout : Word w)) + (nCell : m (levelStart layout 0+29) = (n : Word w)) : + Stored B layout cur n Y (after m (eventLog rs)) := by + refine ⟨by omega,layout_width,fun older rowBase => ?_⟩ + apply p.refresh_child_directory B workspace positions blocks t f hf Y c bits entry header pointers room rows n older nCell + exact (BlockMetadata.Published.keeps_row_base B workspace positions blocks t p).symm.trans rowBase + +end Refresh +end CompressorRecords.SelectedChildDirectory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectedDirectoryEmission.lean b/lean/OAI/Computability/VPVNP/CompressorSelectedDirectoryEmission.lean new file mode 100644 index 0000000000..6668b9a66c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectedDirectoryEmission.lean @@ -0,0 +1,121 @@ +import OAI.Computability.VPVNP.CompressorSelectedDirectoryHistory +import OAI.Computability.VPVNP.CompressorBlockMetadataPackets + +/-! +# Native metadata publications for selected directory histories + +The preimage worker supplies the arrays in the incoming memory. The +metadata worker leaves these arrays intact and installs the five directory +operands and the next state's DFS header. Later term-head publishers can +extend the emission by preserving precisely those cells. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SelectedDirectoryHistory + +open BurstRAM Compression DescriptorSpace PairSimulation.TraversalRows +open BlockPlanner PhaseRecipe Schedule +open scoped Fin.CommRing + +variable {w : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k} +variable {B : S.Templates} {f : B.Entry → A} {hf : B.IsSolution f} {v : SelectedLevel B f hf} +variable {L : Layout} {i : ℕ} {m m₀ out out' : Memory w} + +/-- The five packet fields read by the traversal controller, in the +metadata writer's twelve-word order. -/ +def PlacementWords (values : Fin 12 → Word w) (pub : Fin 6 → Word w) : Prop := + values 6 = pub 0 ∧ values 7 = pub 2 ∧ values 9 = pub 3 ∧ values 10 = pub 5 ∧ values 11 = pub 4 + +/-- Recover the pre-pass input after preliminary work on placement and incidence +arrays which leaves the DFS base and role of the active state intact. -/ +noncomputable def Emission.prepend (e : Emission L i v m out) + (base : m (levelStart L i+14) = m₀ (levelStart L i+14)) + (role : m (levelStart L i+27) = m₀ (levelStart L i+27)) : Emission L i v m₀ out := + { e with + keepBase := e.keepBase.trans base + keepRole := e.keepRole.trans role + nextBase := by rw [e.nextBase,base] } + +/-- Term pointers and scheduler writes can follow the packet in the same +pass. They only need to frame its placement arrays and these header offsets. -/ +noncomputable def Emission.transfer (e : Emission L i v m out) + (arrays : SourceTransport.Agree (Directory.cells e.dir.pub) out out') + (active : ∀ o ∈ [14,21,22,24,25,26,27], out' (levelStart L i+o) = out (levelStart L i+o)) + (successor : ∀ o ∈ [14,27], out' (levelStart L (i+1)+o) = out (levelStart L (i+1)+o)) : + Emission L i v m out' := by + exact ⟨e.dir.transport arrays,e.lower,(active 14 (by decide)).trans e.keepBase, + (active 27 (by decide)).trans e.keepRole,(successor 14 (by decide)).trans e.nextBase, + (successor 27 (by decide)).trans e.nextRole,(active 21 (by decide)).trans e.old, + (active 22 (by decide)).trans e.directory.1,(active 24 (by decide)).trans e.directory.2.1, + (active 25 (by decide)).trans e.directory.2.2.1,(active 26 (by decide)).trans e.directory.2.2.2⟩ + +@[simp] theorem Emission.prepend_pub (e : Emission L i v m out) (base role) : + (e.prepend (m₀ := m₀) base role).dir.pub = e.dir.pub := rfl + +@[simp] theorem Emission.transfer_pub (e : Emission L i v m out) (arrays active successor) : + (e.transfer (out' := out') arrays active successor).dir.pub = e.dir.pub := rfl + +variable {workspace : Word w} {positions blocks t step : ℕ} {fields : BlockMetadata.Fields} +variable {rs : List (Report w)} +local notation "plan" => BlockProgram.script B +local notation "layout" => BlockProgram.layout B workspace.val positions blocks +local notation "first" => Script.levelsPerBlock plan*t +local notation "cur" => first+step +local notation "head" => levelStart layout cur +local notation "next" => levelStart layout (cur+1) +local notation "pub" => Ports.data (Workspace.ports (arity (Script.catalog plan)) workspace) +local notation "state" => (levelStart layout first : Word w) + +/-- The native writer evaluates the field bank in the metadata input memory +and publishes all five traversal operands with their exact word values. -/ +theorem placement_words {bank : Fin 6 → Word w} {oldSites : ℕ} {role : BlockMetadata.Role} + (p : BlockMetadata.Published B workspace positions blocks t step role fields m oldSites rs) + (values : PlacementWords (fun j => + (BlockMetadata.fieldExprs (layout).shape step B.recordLimit (slotDegree S) fields j).eval pub state m) bank) : + PlacementWords (fun j => after m (eventLog rs) (head+15+j.val)) bank := by + obtain ⟨a,b,c,d,e⟩ := values + exact ⟨(p.payload 6).trans a,(p.payload 7).trans b,(p.payload 9).trans c, + (p.payload 10).trans d,(p.payload 11).trans e⟩ + +/-- Construct the pass emission from the actual three metadata visits and +the completed native preimage rows. The owner column starts past the scalar +packet, and the entire directory ends before the successor header. -/ +noncomputable def Emission.ofPublished + (p : BlockMetadata.Published B workspace positions blocks t step (BlockMetadata.producingRole v.origin) + fields m v.input.positions rs) + (d : LevelDirectory v m next) (lower : head+28 ≤ (d.pub 1).val) + (values : PlacementWords (fun j => after m (eventLog rs) (head+15+j.val)) d.pub) : + Emission layout cur v m (after m (eventLog rs)) := by + have stepEq : first+(step+1) = cur+1 := Nat.add_assoc .. |>.symm + have wide : 28 ≤ levelWords layout := by + change 28 ≤ 54+6+6+6*slotCapacity layout+6*tableWords layout + omega + have span : head+28 ≤ next := by + have advance (j : ℕ) : levelStart layout (j+1) = levelStart layout j+levelWords layout := by + simp only [levelStart,Nat.succ_mul,Nat.add_assoc] + rw [advance] + exact Nat.add_le_add_left wide head + have arrays : SourceTransport.Agree (Directory.cells d.pub) m (after m (eventLog rs)) := by + intro x hx + obtain ⟨lo,hi⟩ := Directory.cells_interval d hx + exact (p.outside x (by omega) (by rw [stepEq]; omega) (by rw [stepEq]; omega)).symm + have keep (o : ℕ) (ho : o = 14 ∨ o = 27) : after m (eventLog rs) (head+o) = m (head+o) := by + apply p.outside <;> first | omega | rw [stepEq]; omega + have low : levelsBase layout ≤ head := Nat.le_add_right .. + exact ⟨d.transport arrays,show levelsBase layout ≤ (d.pub 1).val by omega,keep 14 (Or.inl rfl),keep 27 (Or.inr rfl), + stepEq ▸ p.successor,stepEq ▸ p.tag,values.1,values.2.1,values.2.2.1,values.2.2.2.1,values.2.2.2.2⟩ + +@[simp] theorem Emission.ofPublished_pub + (p : BlockMetadata.Published B workspace positions blocks t step (BlockMetadata.producingRole v.origin) + fields m v.input.positions rs) + (d : LevelDirectory v m next) (lower values) : + (Emission.ofPublished p d lower values).dir.pub = d.pub := rfl + +end CompressorRecords.SelectedDirectoryHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectedDirectoryHistory.lean b/lean/OAI/Computability/VPVNP/CompressorSelectedDirectoryHistory.lean new file mode 100644 index 0000000000..a933e71d0f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectedDirectoryHistory.lean @@ -0,0 +1,351 @@ +import OAI.Computability.VPVNP.CompressorPlacementPersistence +import OAI.Computability.VPVNP.CompressorBlockMetadata +import OAI.Computability.VPVNP.PairTraversalControllerInputs + +/-! +# Placement directories in the final memory of a selected branch + +A pass publishes its preimage arrays and input-header fields in its own +level and advances the successor's DFS base and role. Replaying subsequent +passes preserves the completed levels, including the occurrence-specific +directory of each selected term. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SelectedDirectoryHistory + +open BurstRAM Compression DescriptorSpace PairSimulation.LocalHistory +open PairSimulation.TraversalRows PairSimulation.TraversalRoles +open scoped Fin.CommRing + +variable {w : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) +/-- The input layer followed by the actual output layers in the accumulated branch. -/ +noncomputable def layers (initial : TaggedLayer) (past : List (SelectedLevel B f hf)) : List TaggedLayer := + initial :: past.map fun v => ⟨levelLayer B f hf v,tagLevel B f hf v⟩ + +/-- The directory arrays and their native header words in one memory. +The upper bound for each array is the next level, even though the common +traversal limit is the start of the DFS arena. -/ +structure Past (initial : TaggedLayer) (L : Layout) (base : ℕ) (past : List (SelectedLevel B f hf)) + (raw : Memory w) where + /-- Placement directory of each previously selected level, as represented in the current raw + memory. -/ + dirs : (i : Fin past.length) → LevelDirectory past[i] raw base + within : ∀ i : Fin past.length, ((dirs i).pub 5).val + ((dirs i).pub 2).val*((dirs i).pub 4).val ≤ + levelStart L (i.val+1) + lower : ∀ i : Fin past.length, levelsBase L ≤ ((dirs i).pub 1).val + current : ∀ j ≤ past.length, raw (levelStart L j+14) = (layerBase B.recordLimit base (layers B f hf initial past) j : Word w) + role : ∀ j : Fin (layers B f hf initial past).length, raw (levelStart L j.val+27) = ((layers B f hf initial past)[j].role.code : Word w) + old : ∀ i : Fin past.length, raw (levelStart L i.val+21) = (dirs i).pub 0 + directory : ∀ i : Fin past.length, raw (levelStart L i.val+22) = (dirs i).pub 2 ∧ + raw (levelStart L i.val+24) = (dirs i).pub 3 ∧ raw (levelStart L i.val+25) = (dirs i).pub 5 ∧ + raw (levelStart L i.val+26) = (dirs i).pub 4 + +/-- Cardinality of the state where the next physical pass starts. -/ +noncomputable def currentCount (initial : TaggedLayer) (past : List (SelectedLevel B f hf)) : ℕ := + ((layers B f hf initial past)[past.length]'(by simp [layers])).layer.count + +/-- Past portion of the scheduled branch boundary. -/ +def Prefix (initial : TaggedLayer) (L : Layout) (base : ℕ) (past : List (SelectedLevel B f hf)) + {a g : ℕ} (Y : State a g) (raw : Memory w) : Prop := + Nonempty (Past B f hf initial L base past raw) ∧ currentCount B f hf initial past = Y.positions + +variable {B f hf} {L : Layout} {base : ℕ} {raw raw' : Memory w} + +/-- The terminal prefix may write its own table and header after the +completed directory region. Only the first 28 words of the final level are +needed to retain the selected DFS headers. -/ +noncomputable def Past.transport {initial : TaggedLayer} {past : List (SelectedLevel B f hf)} + (D : Past B f hf initial L base past raw) + (agree : ∀ x, levelsBase L ≤ x → x < levelStart L past.length + 28 → raw' x = raw x) : + Past B f hf initial L base past raw' := by + let ds (i : Fin past.length) := (D.dirs i).transport (m' := raw') (by + intro x hx + have ⟨hc,hr,_⟩ := (D.dirs i).regions + have lower := D.lower i + have upper := (D.within i).trans (levelStart_mono L i.isLt) + rcases hx with hx|hx|hx <;> exact (agree x (by omega) (by omega)).symm) + have read (j o : ℕ) (hj : j ≤ past.length) (ho : o < 28) : + raw' (levelStart L j+o) = raw (levelStart L j+o) := by + have lo : levelsBase L ≤ levelStart L j := Nat.le_add_right .. + have hi := levelStart_mono L hj + exact agree _ (by omega) (by omega) + refine ⟨ds,D.within,D.lower,fun j hj => (read j 14 hj (by decide)).trans (D.current j hj),?_, + fun i => (read i.val 21 i.isLt.le (by decide)).trans (D.old i),?_⟩ + · intro j + have bound : j.val ≤ past.length := by + simpa only [layers,List.length_cons,List.length_map,Nat.lt_succ_iff] using j.isLt + exact (read j.val 27 bound (by decide)).trans (D.role j) + · intro i + obtain ⟨hn,hc,hr,hk⟩ := D.directory i + exact ⟨(read i.val 22 i.isLt.le (by decide)).trans hn,(read i.val 24 i.isLt.le (by decide)).trans hc, + (read i.val 25 i.isLt.le (by decide)).trans hr,(read i.val 26 i.isLt.le (by decide)).trans hk⟩ + + +/-- Live scheduler and row-launcher writes below the level arena leave the +past-directory portion of the branch boundary intact. -/ +theorem Prefix.transfer {a g : ℕ} {Y : State a g} {initial : TaggedLayer} + {past : List (SelectedLevel B f hf)} (h : Prefix B f hf initial L base past Y raw) + (agree : SourceTransport.Agree (levelStart L 0 ≤ ·) raw raw') : Prefix B f hf initial L base past Y raw' := by + obtain ⟨⟨P⟩,count⟩ := h + exact ⟨⟨P.transport fun x lo _ => (agree x (by simpa [levelStart] using lo)).symm⟩,count⟩ + +/-- The readback required at the completion of one native substep. +Its DFS prefix is advanced by the size of this input state; both words +written to the successor belong to the next pass's input header. -/ +structure Emission (L : Layout) (i : ℕ) (v : SelectedLevel B f hf) (m out : Memory w) where + /-- Placement directory published by the selected pass in its output memory, bounded by the + next level's start. -/ + dir : LevelDirectory v out (levelStart L (i+1)) + lower : levelsBase L ≤ (dir.pub 1).val + keepBase : out (levelStart L i+14) = m (levelStart L i+14) + keepRole : out (levelStart L i+27) = m (levelStart L i+27) + nextBase : out (levelStart L (i+1)+14) = + m (levelStart L i+14) + ((B.recordLimit+2 : ℕ) : Word w)*(v.input.positions : Word w) + nextRole : out (levelStart L (i+1)+27) = ((BlockMetadata.producingRole v.origin).code : Word w) + old : out (levelStart L i+21) = dir.pub 0 + directory : out (levelStart L i+22) = dir.pub 2 ∧ out (levelStart L i+24) = dir.pub 3 ∧ + out (levelStart L i+25) = dir.pub 5 ∧ out (levelStart L i+26) = dir.pub 4 + +variable {initial : TaggedLayer} {past : List (SelectedLevel B f hf)} {v : SelectedLevel B f hf} + +private structure Stored (L : Layout) (base i : ℕ) (v : SelectedLevel B f hf) (m : Memory w) where + dir : LevelDirectory v m base + within : (dir.pub 5).val+(dir.pub 2).val*(dir.pub 4).val ≤ levelStart L (i+1) + lower : levelsBase L ≤ (dir.pub 1).val + old : m (levelStart L i+21) = dir.pub 0 + directory : m (levelStart L i+22) = dir.pub 2 ∧ m (levelStart L i+24) = dir.pub 3 ∧ + m (levelStart L i+25) = dir.pub 5 ∧ m (levelStart L i+26) = dir.pub 4 + +/-- Initialize the DFS history from the published base and cursor role. -/ +theorem Prefix.empty {a g : ℕ} {Y : State a g} + (baseCell : raw (levelStart L 0+14) = (base : Word w)) + (roleCell : raw (levelStart L 0+27) = 0) : + Prefix B f hf ⟨leafLayer (siteOrder Y),.cursor⟩ L base [] Y raw := by + refine ⟨⟨⟨fun i => Fin.elim0 i,fun i => Fin.elim0 i,fun i => Fin.elim0 i,?_,?_, + fun i => Fin.elim0 i,fun i => Fin.elim0 i⟩⟩,?_⟩ + · intro j hj + obtain rfl : j = 0 := Nat.eq_zero_of_le_zero hj + simpa only [layerBase_zero] using baseCell + · intro j + change Fin 1 at j + obtain rfl : j = 0 := Subsingleton.elim _ _ + exact roleCell + · change (siteOrder Y).length = Fintype.card Y.network.Site + simpa only [Fintype.card_fin] using Fintype.card_congr (siteOrder Y).entries + +private theorem layers_append (v : SelectedLevel B f hf) : + layers B f hf initial (past++[v]) = layers B f hf initial past ++ [⟨levelLayer B f hf v,tagLevel B f hf v⟩] := by + simp [layers] + +/-- Extend the selected history by its actual pass. The new level can also +write the scheduler and the successor state. The proof only uses equality +on strictly earlier levels and the two carried words of its input header. -/ +theorem Prefix.append (h : Prefix B f hf initial L base past v.input raw) + (p : Emission L past.length v raw raw') (wide : 28 ≤ levelWords L) + (room : levelStart L (past.length+1) ≤ base) + (agree : ∀ x, levelsBase L ≤ x → x < levelStart L past.length → raw' x = raw x) : + Prefix B f hf initial L base (past++[v]) (v.pass.next v.term) raw' := by + obtain ⟨⟨P⟩,count⟩ := h + let ls := layers B f hf initial past + let newTag : TaggedLayer := ⟨levelLayer B f hf v,tagLevel B f hf v⟩ + have length : ls.length = past.length+1 := by simp [ls,layers] + have here (j o : ℕ) (hj : j < past.length) (ho : o < 28) : + raw' (levelStart L j+o) = raw (levelStart L j+o) := by + have next := levelStart_mono L (show j+1 ≤ past.length from hj) + have span : levelStart L j+levelWords L = levelStart L (j+1) := by + simp only [levelStart,Nat.succ_mul,Nat.add_assoc] + exact agree _ (by unfold levelStart; omega) (by omega) + have oldStored (j : Fin past.length) : Stored L base j.val past[j] raw' := by + let d := (P.dirs j).transport (m' := raw') (by + intro x hx + have ⟨hc,hr,_⟩ := (P.dirs j).regions + have lower := P.lower j + have upper := (P.within j).trans (levelStart_mono L j.isLt) + rcases hx with hx|hx|hx <;> exact (agree x (by omega) (by omega)).symm) + obtain ⟨hn,hc,hr,hk⟩ := P.directory j + exact ⟨d,P.within j,P.lower j,(here j.val 21 j.isLt (by decide)).trans (P.old j), + (here j.val 22 j.isLt (by decide)).trans hn,(here j.val 24 j.isLt (by decide)).trans hc, + (here j.val 25 j.isLt (by decide)).trans hr,(here j.val 26 j.isLt (by decide)).trans hk⟩ + let ds (j : Fin (past++[v]).length) : Stored L base j.val (past++[v])[j] raw' := by + by_cases old : j.val < past.length + · simp only [Fin.getElem_fin,List.getElem_append_left old] + exact oldStored ⟨j.val,old⟩ + · have hi : j.val < past.length+1 := by simpa using j.isLt + have eqn : j.val = past.length := by omega + simp only [Fin.getElem_fin] + rw [List.getElem_concat_length eqn j.isLt,eqn] + exact ⟨{ p.dir with inputEnd := p.dir.inputEnd.trans room },p.dir.inputEnd,p.lower,p.old,p.directory⟩ + refine ⟨⟨⟨fun j => (ds j).dir,fun j => (ds j).within,fun j => (ds j).lower,?_,?_, + fun j => (ds j).old,fun j => (ds j).directory⟩⟩,?_⟩ + · intro j hj + have bound : j ≤ ls.length := by simpa only [length,List.length_append,List.length_singleton] using hj + rw [layers_append] + change _ = (layerBase B.recordLimit base (ls++[newTag]) j : Word w) + rw [layerBase,List.take_append_of_le_length bound] + change _ = (layerBase B.recordLimit base ls j : Word w) + rcases lt_trichotomy j past.length with hj|rfl|hj + · exact (here j 14 hj (by decide)).trans (P.current j hj.le) + · exact p.keepBase.trans (P.current _ le_rfl) + · have hj' : j = past.length+1 := by omega + subst j + let i : Fin ls.length := ⟨past.length,by omega⟩ + change ls[i].layer.count = v.input.positions at count + exact p.nextBase.trans (by rw [P.current _ le_rfl,← count]; exact BlockMetadata.next_layerBase _ _ ls i) + · intro j + have jfit : j.val < (ls++[newTag]).length := by simpa only [layers_append] using j.isLt + have index : (layers B f hf initial (past++[v]))[j] = (ls++[newTag])[j.val]'jfit := + by simp only [Fin.getElem_fin,layers_append]; rfl + rw [index] + by_cases old : j.val < ls.length + · rw [List.getElem_append_left old] + let i : Fin ls.length := ⟨j.val,old⟩ + rcases lt_or_eq_of_le (show j.val ≤ past.length by omega) with hj|hj + · exact (here j.val 27 hj (by decide)).trans (P.role i) + · exact (hj ▸ p.keepRole : raw' (levelStart L j.val+27) = raw (levelStart L j.val+27)).trans (P.role i) + · have jle : j.val < ls.length+1 := by simpa using jfit + have jeq : j.val = ls.length := by omega + rw [List.getElem_concat_length jeq jfit,jeq,length,p.nextRole,BlockMetadata.producingRole_code] + · simp only [currentCount,layers_append,List.length_append,List.length_singleton] + rw [List.getElem_concat_length (by simp [layers])] + exact levelLayer_count B f hf v + +/-- A native report stream which writes only below the level arena or at +and above its own input level preserves every previously collected row. -/ +theorem Prefix.append_reports (h : Prefix B f hf initial L base past v.input raw) (rs : List (Report w)) + (p : Emission L past.length v raw (after raw (eventLog rs))) (wide : 28 ≤ levelWords L) + (room : levelStart L (past.length+1) ≤ base) + (writes : SourceTransport.Writes (fun x => x < levelsBase L ∨ levelStart L past.length ≤ x) (eventLog rs)) : + Prefix B f hf initial L base (past++[v]) (v.pass.next v.term) (after raw (eventLog rs)) := + h.append p wide room fun _ lo hi => SourceTransport.after_outside raw writes (by omega) + +/-- Replay the first `j` packets, keeping their source boundaries. -/ +private def snapshot {J : Type*} (m : Memory w) (ps : List (SourceWalk.Packet J w)) (j : ℕ) : Memory w := + after m (eventLog ((ps.take j).flatMap SourceWalk.Packet.reports)) + +private theorem chronological_at {J : Type*} {source : J → Memory w → List (Report w) → Prop} + {m : Memory w} {ps : List (SourceWalk.Packet J w)} (h : SourceWalk.Chronological source m ps) + (i : Fin ps.length) : + ps[i].input = snapshot m ps i.val ∧ source ps[i].stage ps[i].input ps[i].reports ∧ + ps[i].output = snapshot m ps (i.val+1) := by + induction ps generalizing m with + | nil => exact Fin.elim0 i + | cons p ps ih => + obtain ⟨rfl,src,tail⟩ := h + cases i using Fin.cases with + | zero => exact ⟨rfl,src,by simp [snapshot,SourceWalk.Packet.output]⟩ + | succ i => + have h := ih tail i + simpa only [Fin.getElem_fin,Fin.val_succ,List.getElem_cons_succ,snapshot,List.take_succ_cons, + List.flatMap_cons,SourceWalk.after_append,SourceWalk.Packet.output] using h + + +variable (B f hf) +variable {n : ℕ} (T : ℕ) (hT : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) +variable (z : (B.execute f hf T hT X).Choices) + +local notation "vs" => executeLevels B f hf T hT X z +local notation "tags" => selected B f hf T hT X z + +/-- The accumulated directories of the actual selected execution. -/ +abbrev Retained (L : Layout) (base : ℕ) (raw : Memory w) := + Past B f hf ⟨leafLayer (siteOrder X),.cursor⟩ L base vs raw + +variable {B f hf T hT X z} + +/-- Transport the full selected execution through the terminal prefix. -/ +noncomputable def Retained.transport (D : Retained B f hf T hT X z L base raw) + (agree : ∀ x, levelsBase L ≤ x → x < levelStart L (vs).length + 28 → raw' x = raw x) : + Retained B f hf T hT X z L base raw' := Past.transport D agree + +open private collectLevels from OAI.Computability.VPVNP.CompressorExecutionLevels + +private theorem input_counts {a g b l : ℕ} {Y : State a g} + (E : StateExecution A b l Y) (W : E.MapWitnesses f) (r : ExecutionReaders E W) + (o : PassOrigins B f hf E) (c : E.Choices) : + let ls := collectLevels B f hf E W r o c + ls.map (fun v => v.input.positions) ++ [(E.finalState c).positions] = + Y.positions :: ls.map SelectedLevel.outputSites := by + induction E with + | done => rfl + | more p tail ih => + exact congrArg (List.cons _) (ih c.1 (W.2 c.1) (r.2 c.1) (o.2 c.1) c.2) + +private theorem tag_count (i : Fin (vs).length) : + (tags[i.val]'(by simp only [selected,List.length_cons,List.length_map]; omega)).layer.count = + vs[i].input.positions := by + have e : (vs).map (fun v => v.input.positions) ++ [((B.execute f hf T hT X).finalState z).positions] = + X.positions :: (vs).map SelectedLevel.outputSites := input_counts (B.execute f hf T hT X) _ _ _ z + have h : (tags).map (fun l => l.layer.count) = + X.positions :: (vs).map SelectedLevel.outputSites := by + rw [← selected_layer_counts B f hf T hT X z,← selected_layers B f hf T hT X z,List.map_map] + rfl + have eq := congrArg (fun l : List ℕ => l[i.val]?) (h.trans e.symm) + have hi : i.val < ((vs).map (fun v => v.input.positions)).length := by simp + simpa only [List.getElem?_map,List.getElem?_append_left hi,List.getElem?_eq_getElem i.isLt, + List.getElem?_eq_getElem (show i.val < (tags).length by simp [selected]), + Option.map_some,Option.some.injEq,Fin.getElem_fin] using eq + +private theorem current_take (i : Fin (vs).length) : + currentCount B f hf ⟨leafLayer (siteOrder X),.cursor⟩ ((vs).take i.val) = vs[i].input.positions := by + have len := List.length_take_of_le i.isLt.le + have pre : layers B f hf ⟨leafLayer (siteOrder X),.cursor⟩ ((vs).take i.val) = (tags).take (i.val+1) := by + simp only [layers,selected,List.take_succ_cons,List.map_take] + simpa only [currentCount,len,pre,List.getElem_take] using tag_count (B := B) (f := f) (hf := hf) (z := z) i + +/-- A batch of native reports which emits the selected occurrence and frames +all earlier levels, including when it also updates the low scheduler words. -/ +def Source (L : Layout) (i : Fin (vs).length) (m : Memory w) (rs : List (Report w)) : Prop := + Nonempty (Emission L i.val vs[i] m (after m (eventLog rs))) ∧ + SourceTransport.Writes (fun x => x < levelsBase L ∨ levelStart L i.val ≤ x) (eventLog rs) + +/-- Extract every occurrence's directory at the final memory of the actual +report walk. Empty walks retain the cursor header. -/ +noncomputable def ofWalk {rs : List (Report w)} + (walk : SourceWalk (Source (B := B) (f := f) (hf := hf) (z := z) L) (List.finRange (vs).length) raw rs) + (baseCell : raw (levelStart L 0+14) = (base : Word w)) + (roleCell : raw (levelStart L 0+27) = 0) + (wide : 28 ≤ levelWords L) (room : levelStart L (vs).length ≤ base) : + Retained B f hf T hT X z L base (after raw (eventLog rs)) := by + apply Classical.choice + obtain ⟨ps,stages,logs,chron⟩ := walk.packets + let image := snapshot raw ps + let initial : TaggedLayer := ⟨leafLayer (siteOrder X),.cursor⟩ + have size : ps.length = (vs).length := by + simpa only [List.length_map,List.length_finRange] using congrArg List.length stages + have accum (j : ℕ) (hj : j ≤ (vs).length) : Nonempty (Past B f hf initial L base ((vs).take j) (image j)) := by + induction j with + | zero => exact (Prefix.empty (B := B) (f := f) (hf := hf) (Y := X) baseCell roleCell).1 + | succ j ih => + let i : Fin (vs).length := ⟨j,hj⟩ + let q : Fin ps.length := ⟨j,size.symm ▸ hj⟩ + have stage : ps[q].stage = i := by + have eqn := getElem_congr_coll (i := j) (w := by rw [List.length_map]; exact q.isLt) stages + simp only [List.getElem_map,List.getElem_finRange] at eqn + exact Fin.ext (congrArg Fin.val eqn) + obtain ⟨start,src,finish⟩ := chronological_at chron q + rw [stage,start] at src + obtain ⟨⟨p⟩,writes⟩ := src + have len : ((vs).take j).length = j := List.length_take_of_le (Nat.le_of_lt hj) + have before : Prefix B f hf initial L base ((vs).take j) vs[i].input (image j) := + ⟨ih (Nat.le_of_lt hj),current_take i⟩ + have out := before.append_reports ps[q].reports (by rw [len]; exact p) wide + (by rw [len]; exact (levelStart_mono L hj).trans room) (by rw [len]; exact writes) + change after ps[q].input (eventLog ps[q].reports) = image (j+1) at finish + rw [start] at finish + change after (image j) (eventLog ps[q].reports) = image (j+1) at finish + rw [List.take_succ_eq_append_getElem hj,← finish] + exact out.1 + have finalMem : image (vs).length = after raw (eventLog rs) := by + simp only [image,snapshot,← size,List.take_length,logs] + simpa only [List.take_length,finalMem] using accum (vs).length le_rfl + +end CompressorRecords.SelectedDirectoryHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectedPayloadFrames.lean b/lean/OAI/Computability/VPVNP/CompressorSelectedPayloadFrames.lean new file mode 100644 index 0000000000..6f2f48b6c8 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectedPayloadFrames.lean @@ -0,0 +1,131 @@ +import OAI.Computability.VPVNP.CompressorSelectedPayloadHistory +import OAI.Computability.VPVNP.CompressorShrinkScheduledTail +import OAI.Computability.VPVNP.CompressorRefreshCoreBuild +import OAI.Computability.VPVNP.CompressorRefreshCopyGroup +import OAI.Computability.VPVNP.CompressorRefreshPlacementTrace + +/-! +# Frames of the native groups used by the selected payload history + +The old incidence bank remains readable during scalar publication, +scratch-array scans, and the final term/data header writes. Consecutive +group frames compose in the actual intermediate memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SelectedPayloadHistory + +open BurstRAM Compression DescriptorSpace SourceTransport +open scoped Fin.CommRing + +variable {w : ℕ} {L : Layout} {i : ℕ} {m n out : Memory w} + +/-- The two regions shared with all previously emitted parser data. -/ +structure InputFrame (L : Layout) (i : ℕ) (m out : Memory w) : Prop where + earlier : ∀ x, levelsBase L ≤ x → x < levelStart L i → out x = m x + graph : Agree (GraphCells L i) m out + +theorem InputFrame.trans (h : InputFrame L i m n) (h' : InputFrame L i n out) : + InputFrame L i m out := + ⟨fun x lo hi => (h'.earlier x lo hi).trans (h.earlier x lo hi), + fun x hx => (h.graph x hx).trans (h'.graph x hx)⟩ + +/-- Readback below the scratch allocation, as supplied by the shrink slot +group and its successor copies, suffices for both history regions. -/ +theorem InputFrame.below_array (same : ∀ x, levelsBase L ≤ x → x < arrayBase L i → out x = m x) : + InputFrame L i m out := by + have low : levelsBase L ≤ levelStart L i := Nat.le_add_right .. + have high : levelStart L i ≤ arrayBase L i := by unfold arrayBase incidenceStart; omega + exact ⟨fun x lo hi => same x lo (hi.trans_le high), + fun x hx => (same x (low.trans ((Nat.le_add_right ..).trans hx.1)) hx.2).symm⟩ + +/-- Workers can also publish scalar fields of their own input level. +The pointer words and old incidence still agree in the two images. -/ +theorem InputFrame.of_writes {es : List (Event w)} + (writes : Writes (fun x => x < levelsBase L ∨ + (levelStart L i ≤ x ∧ x < levelStart L i+L.shape.scalarFields) ∨ arrayBase L i ≤ x) es) : + InputFrame L i m (after m es) := by + have low : levelsBase L ≤ levelStart L i := Nat.le_add_right .. + have head : levelStart L i ≤ arrayBase L i := by unfold arrayBase incidenceStart; omega + refine ⟨fun x lo hi => after_outside m writes (by omega),?_⟩ + intro x hx + obtain ⟨a,b⟩ := hx + exact (after_outside m writes (by omega)).symm + +/-- A scratch worker can write any word starting at the input's array base. +Its scheduler may also update the low control area. -/ +theorem InputFrame.of_array {es : List (Event w)} + (writes : Writes (fun x => x < levelsBase L ∨ arrayBase L i ≤ x) es) : InputFrame L i m (after m es) := + of_writes fun a v hv => (writes a v hv).elim Or.inl (fun h => Or.inr (Or.inr h)) + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} {B : S.Templates} +variable {f : B.Entry → R} {hf : B.IsSolution f} {v : SelectedLevel B f hf} + +open private array_before from OAI.Computability.VPVNP.CompressorSelectedPayloadHistory + +theorem InputFrame.substep {i j : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} + (p : BlockHeaderRun.Substep v L i j six m) (next : i.val+1 = j.val) : + InputFrame L i.val m (BlockHeaderRun.finalMemory v L i j m) := by + refine ⟨fun x _ hi => p.before v next x hi,?_⟩ + have bound := array_before L i + rw [next] at bound + intro x hx + obtain ⟨lo,hi⟩ := hx + exact (p.outside x (.inr (by omega)) (.inl (by omega)) (.inl (by omega))).symm + +variable {base : Word w} {positions blocks t step : ℕ} +local notation "plan" => BlockProgram.script B +local notation "layout" => BlockProgram.layout B base.val positions blocks +local notation "first" => BlockPlanner.Script.levelsPerBlock plan*t + +/-- The old metadata packet and the two successor scalar writes preserve +the input pointer bank and canonical incidence, as well as earlier levels. -/ +theorem InputFrame.metadata {role : BlockMetadata.Role} {fields : BlockMetadata.Fields} {oldSites : ℕ} + {rs : List (Report w)} (p : BlockMetadata.Published B base positions blocks t step role fields m oldSites rs) : + InputFrame layout (first+step) m (after m (eventLog rs)) := by + have bound := array_before layout (first+step) + rw [Nat.add_assoc] at bound + have old : levelStart layout (first+step) ≤ levelStart layout (first+(step+1)) := levelStart_mono layout (by omega) + refine ⟨fun x _ hi => p.outside x (.inl (by omega)) (by omega) (by omega),?_⟩ + intro x hx + obtain ⟨lo,hi⟩ := hx + change levelStart layout (first+step)+54 ≤ x at lo + exact (p.outside x (.inr (by omega)) (by omega) (by omega)).symm + +theorem InputFrame.shrinkTail {j : Fin S.steps} {g cap : ℕ} + {X : State (ShrinkBlockInputs.a j) (packingLaneBits (ShrinkBlockInputs.a j) g)} {ms ps} + (r : ShrinkScheduledTail.Result B base positions blocks t cap j X m ms ps) : + InputFrame layout (first+j.val) m (SourceOnline.post m ps) := by + have bound := array_before layout (first+j.val) + rw [Nat.add_assoc] at bound + exact ⟨fun x _ hx => r.earlier x hx,fun x hx => (r.old_data x hx.1 (hx.2.trans_le bound)).symm⟩ + +theorem InputFrame.refreshCore {g cap : ℕ} {X : State S.portExponent (S.portExponent+g)} {c rs} + (r : RefreshCore.Built B base positions blocks t X c cap m rs) : + InputFrame layout (first+S.steps) m (after m (eventLog rs)) := + of_array fun a v hv => Or.inr (r.writes a v hv).1 + +/-- The six copies install the output graph after the current level, so the +input pointer bank and all previous levels retain their actual words. -/ +theorem InputFrame.refreshCopies {a g : ℕ} {Y : State a g} {p : PortRefresh.Allocation.Plan} + {rs : List (Report w)} (r : RefreshCopyPackets.CopyResult Y p L (i+1) m rs) : + InputFrame L i m (after m (eventLog rs)) := by + apply of_array + intro addr val hw + exact Or.inr ((array_before L i).trans ((Nat.le_add_right ..).trans (r.write addr val hw).1)) + +/-- The refresh's singleton placement scan writes only its packed table. -/ +theorem InputFrame.refreshPlacement {start sites : ℕ} (table : arrayBase L i ≤ start) + (room : start+3*sites < 2^w) : + InputFrame L i m (after m (eventLog (RefreshPlacement.log (RefreshPlacement.packed w start sites) 0 sites))) := + of_array fun a v hv => Or.inr (table.trans ((RefreshPlacement.packed_log_access room + (Nat.zero_add sites).le).2 a v hv).1) + +end CompressorRecords.SelectedPayloadHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectedPayloadHistory.lean b/lean/OAI/Computability/VPVNP/CompressorSelectedPayloadHistory.lean new file mode 100644 index 0000000000..f7056acaed --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectedPayloadHistory.lean @@ -0,0 +1,159 @@ +import OAI.Computability.VPVNP.CompressorDescriptorSpace +import OAI.Computability.VPVNP.CompressorExecutionLevels +import OAI.Computability.VPVNP.CompressorSourceTransport +import OAI.Computability.VPVNP.CompressorRecordRefreshLifetime + +/-! +# Retaining the data of each selected pass for native site reads + +The completed pass owns all the tables of its input level. Its selected +output graph lives in the successor incidence bank. Later passes can +replace the successor scalars and scratch tables while preserving that +bank. Each stored occurrence keeps the memory image in which its physical +parser data was produced and an agreement on both regions. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SelectedPayloadHistory + +open BurstRAM Compression DescriptorSpace SourceTransport +variable {w : ℕ} {k A : Type*} [_root_.Field k] [CommRing A] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) + +/-- Pointer words and the packed canonical incidence of an input graph. +Scratch begins at the exclusive end of this range. -/ +def GraphCells (L : Layout) (j x : ℕ) : Prop := + levelStart L j+L.shape.scalarFields ≤ x ∧ x < arrayBase L j + +/-- All the producing level's fields, plus the pointer and incidence bank +of the state produced by that pass. -/ +def Cells (L : Layout) (i x : ℕ) : Prop := + (levelStart L i ≤ x ∧ x < levelStart L (i+1)) ∨ GraphCells L (i+1) x + +private theorem array_mono (L : Layout) : Monotone (arrayBase L) := by + intro i j h + exact Nat.add_le_add_right (Nat.add_le_add_right (levelStart_mono L h) _) _ + +private theorem array_before (L : Layout) (i : ℕ) : arrayBase L i ≤ levelStart L (i+1) := by + simp only [arrayBase,incidenceStart,levelStart,levelWords,Nat.succ_mul,Nat.add_assoc] + omega + +/-- Earlier payloads occupy addresses below the final state's first scratch +table, including the last producing pass's successor incidence. -/ +theorem cells_interval {L : Layout} {i n x : ℕ} (hi : i < n) (hx : Cells L i x) : + levelsBase L ≤ x ∧ x < arrayBase L n := by + have low (j : ℕ) : levelsBase L ≤ levelStart L j := Nat.le_add_right .. + have high : levelStart L n ≤ arrayBase L n := by unfold arrayBase incidenceStart; omega + have edge := levelStart_mono L (show i+1 ≤ n from hi) + rcases hx with ⟨a,b⟩|⟨a,b⟩ + · exact ⟨(low i).trans a,b.trans_le (edge.trans high)⟩ + · exact ⟨(low _).trans ((Nat.le_add_right ..).trans a),b.trans_le (array_mono L hi)⟩ + +/-- At the very next pass only its input pointer and incidence bank can +overlap a previous payload. Every older successor already precedes it. -/ +theorem cells_before_or_input {L : Layout} {i n x : ℕ} (hi : i < n) (hx : Cells L i x) : + (levelsBase L ≤ x ∧ x < levelStart L n) ∨ GraphCells L n x := by + have low := (cells_interval hi hx).1 + rcases hx with ⟨_,b⟩|h + · exact Or.inl ⟨low,b.trans_le (levelStart_mono L hi)⟩ + · rcases eq_or_lt_of_le (show i+1 ≤ n from hi) with e|e + · exact Or.inr (e ▸ h) + · exact Or.inl ⟨low,h.2.trans_le ((array_before L _).trans (levelStart_mono L e))⟩ + +/-- A predicate describing the physical parser data of an actual selected +pass, with its chronological index available to compute physical addresses. -/ +abbrev Data := ℕ → SelectedLevel B f hf → Memory w → Prop + +/-- Store actual producing memory images, preserving the physical words +needed to recover each pass's data in the terminal memory. -/ +def Past (L : Layout) (data : Data (w := w) B f hf) (past : List (SelectedLevel B f hf)) (m : Memory w) : Prop := + ∀ i : Fin past.length, ∃ source, data i.val past[i] source ∧ Agree (Cells L i.val) source m + +variable {B f hf} {L : Layout} {data : Data (w := w) B f hf} {past : List (SelectedLevel B f hf)} +variable {m m' : Memory w} {v : SelectedLevel B f hf} + +theorem Past.empty : Past B f hf L data [] m := fun i => Fin.elim0 i + +/-- Recover a stable physical predicate from its producing snapshot. -/ +theorem Past.atLevel (h : Past B f hf L data past m) (i : Fin past.length) + (stable : ∀ source, data i.val past[i] source → Agree (Cells L i.val) source m → data i.val past[i] m) : + data i.val past[i] m := by + obtain ⟨source,p,agree⟩ := h i + exact stable source p agree + +theorem Past.transfer (h : Past B f hf L data past m) + (frame : ∀ x, levelsBase L ≤ x → x < arrayBase L past.length → m' x = m x) : + Past B f hf L data past m' := by + intro i + obtain ⟨source,p,same⟩ := h i + refine ⟨source,p,fun x hx => ?_⟩ + obtain ⟨lo,hi⟩ := cells_interval i.isLt hx + exact (same x hx).trans (frame x lo hi).symm + +/-- Capture the completed level and retain the selected parser data for +every older occurrence, including the immediately preceding output graph. -/ +theorem Past.append (h : Past B f hf L data past m) + (emitted : data past.length v m') + (older : ∀ x, levelsBase L ≤ x → x < levelStart L past.length → m' x = m x) + (input : Agree (GraphCells L past.length) m m') : + Past B f hf L data (past++[v]) m' := by + intro j + by_cases old : j.val < past.length + · obtain ⟨source,p,same⟩ := h ⟨j.val,old⟩ + simp only [Fin.getElem_fin,List.getElem_append_left old] + refine ⟨source,p,fun x hx => (same x hx).trans ?_⟩ + rcases cells_before_or_input old hx with ⟨lo,hi⟩|live + · exact (older x lo hi).symm + · exact input x live + · have bound : j.val < past.length+1 := by simpa using j.isLt + have eqn : j.val = past.length := by omega + simp only [Fin.getElem_fin] + rw [List.getElem_concat_length eqn j.isLt,eqn] + exact ⟨m',emitted,fun _ _ => rfl⟩ + +/-- Footprints of native worker batches may include scheduler addresses, +input scalars, input scratch, and any successor data. -/ +theorem Past.append_reports (h : Past B f hf L data past m) (rs : List (Report w)) + (emitted : data past.length v (after m (eventLog rs))) + (writes : Writes (fun x => x < levelsBase L ∨ + (levelStart L past.length ≤ x ∧ x < levelStart L past.length+L.shape.scalarFields) ∨ + arrayBase L past.length ≤ x) (eventLog rs)) : + Past B f hf L data (past++[v]) (after m (eventLog rs)) := by + apply h.append emitted + · intro x lo hi + have lower : levelStart L past.length ≤ arrayBase L past.length := by unfold arrayBase incidenceStart; omega + exact after_outside m writes (by omega) + · intro x hx + have lo : levelsBase L ≤ levelStart L past.length := Nat.le_add_right .. + exact (after_outside m writes (by obtain ⟨a,b⟩ := hx; omega)).symm + +section Refresh + +open Compression.Refresh Compression.DegreeRefresh SpectralGeometry PortRefresh PortRefresh.Allocation + +variable {a a₀ g dH t i : ℕ} {K K' : ℝ} {X : State a (a+g)} +variable {E : RegularArcGraph (Fin (2^a)) dH} {hdH : 0 < dH} +variable {conn : (arcSupportGraph E.multiplicity).Connected} +variable {F : RefreshBlock k (expanderSupply E hdH conn) (2^a₀) K K'} +variable {choice : DyadicRefreshChoice X E hdH conn F} {ties : Fin t ≃ Tie (2^a)} {start stride : ℕ} + +/-- Recover the native refresh builder's segment rows, term records and +dense demands from the historical snapshot of the selected occurrence. -/ +theorem refresh_stored {fit : Fintype.card X.Base*2^a*2^g*2^a ≤ 2^w} + (stored : PortRefresh.Build.Stored X E hdH conn F choice ties start stride fit m) + (wide : 2+2^a*dH ≤ stride) (room : (plan X a₀ dH t stride start).stop ≤ 2^w) + (lower : levelStart L i ≤ start) + (upper : (plan X a₀ dH t stride start).supply ≤ levelStart L (i+1)) + (same : Agree (Cells L i) m m') : + PortRefresh.Build.Stored X E hdH conn F choice ties start stride fit m' := + stored.transfer wide room (fun x lo hi => (same x (Or.inl ⟨lower.trans lo,hi.trans_le upper⟩)).symm) + +end Refresh +end CompressorRecords.SelectedPayloadHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectedPayloadReadback.lean b/lean/OAI/Computability/VPVNP/CompressorSelectedPayloadReadback.lean new file mode 100644 index 0000000000..c53e0dc1ed --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectedPayloadReadback.lean @@ -0,0 +1,96 @@ +import OAI.Computability.VPVNP.CompressorSelectedPayloadHistory +import OAI.Computability.VPVNP.CompressorSelectedDirectoryEmission +import OAI.Computability.VPVNP.CompressorShrinkSuccessorIndex + +/-! +# Reading selected role-specific payloads and successor pitches + +The actual scheduled pass determines the type of its selected term. +A shrinking stage always has a successor pass, whose metadata publisher +writes the pitch needed to decode the new-state party operands. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SelectedPayloadHistory + +open BurstRAM Compression DescriptorSpace PairSimulation.LocalHistory +open scoped Fin.CommRing + +variable {w : ℕ} {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) + +/-- Type of predicates relating a selected shrinking term, its tape, and memory at a specified +history level. -/ +abbrev Shrinking := + ∀ (_level : ℕ) (i : Fin S.steps) {g n : ℕ} (h : n = packingLaneBits (S.degreeExponent i.castSucc) g) + (X : State (S.degreeExponent i.castSucc) n), + (B.shrinkPassAt f hf i h X).step.Choice → List Bool → Memory w → Prop + +/-- Type of predicates relating a selected dyadic refresh term, its tape, and memory at a +specified history level. -/ +abbrev Refreshing := + ∀ (_level : ℕ) {g : ℕ} (X : State S.portExponent (S.portExponent+g)), + Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh → List Bool → Memory w → Prop + +variable {B f hf} + +private def atOrigin (shrink : Shrinking (w := w) B f hf) (refresh : Refreshing (w := w) B) + (j : ℕ) {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} : + PassOrigin B f hf p → p.step.Choice → List Bool → Memory w → Prop + | .shrink i h Y => shrink j i h Y + | .refresh Y => refresh j Y + +/-- Dispatch the payload predicate on the pass's typed origin. The +constructor exposes the native choice and input state to the producer. -/ +def byOrigin (shrink : Shrinking (w := w) B f hf) (refresh : Refreshing (w := w) B) : + Data (w := w) B f hf := + fun j v => atOrigin shrink refresh j v.origin v.term v.selector + +theorem byOrigin_shrink (shrink : Shrinking (w := w) B f hf) (refresh : Refreshing (w := w) B) + (j : ℕ) (i : Fin S.steps) {g n : ℕ} (h : n = packingLaneBits (S.degreeExponent i.castSucc) g) + (X : State (S.degreeExponent i.castSucc) n) (c : (B.shrinkPassAt f hf i h X).step.Choice) + (bits : List Bool) (m : Memory w) : + byOrigin shrink refresh j ⟨_,_,_,_,X,_,.shrink i h X,c,bits⟩ m ↔ shrink j i h X c bits m := Iff.rfl + +theorem byOrigin_refresh (shrink : Shrinking (w := w) B f hf) (refresh : Refreshing (w := w) B) + (j : ℕ) {g : ℕ} (X : State S.portExponent (S.portExponent+g)) + (c : Refresh.DyadicRefreshChoice X S.graph (Nat.two_pow_pos _) + (S.port_bound.connected_and_pos S.port_order).1 B.refresh) (bits : List Bool) (m : Memory w) : + byOrigin shrink refresh j ⟨_,_,_,_,X,_,.refresh X,c,bits⟩ m ↔ refresh j X c bits m := Iff.rfl + +variable {L : Layout} {data : Data (w := w) B f hf} {past : List (SelectedLevel B f hf)} {m : Memory w} + +/-- Read any field of an older selected level from its actual published +source record, even if the same level value occurs at multiple ordinals. -/ +theorem Past.read_field (h : Past B f hf L data past m) (i : Fin past.length) {field : ℕ} + {value : Word w} (small : field < levelWords L) + (published : ∀ source, data i.val past[i] source → source (levelStart L i.val+field) = value) : + m (levelStart L i.val+field) = value := by + obtain ⟨source,p,same⟩ := h i + have span (j : ℕ) : levelStart L (j+1) = levelStart L j+levelWords L := by + simp only [levelStart,Nat.succ_mul,Nat.add_assoc] + exact (same _ (Or.inl ⟨Nat.le_add_right ..,by rw [span]; omega⟩)).symm.trans (published source p) + +variable {n : ℕ} {T : ℕ} {hT : T*S.laneBits ≤ n} {X : State (S.degreeExponent 0) n} +variable {z : (B.execute f hf T hT X).Choices} +local notation "vs" => executeLevels B f hf T hT X z + +/-- The shrink's output-state pitch is read from the next actual pass's +native metadata packet, including across the final shrink of each block. -/ +theorem shrink_successor_stride (h : Past B f hf L data vs m) (i : Fin (vs).length) + (shrink : vs[i].origin.ordinal < S.steps) (wide : 15 < levelWords L) + (published : ∀ j : Fin (vs).length, ∀ source, data j.val vs[j] source → + source (levelStart L j.val+15) = ((B.recordLimit+2 : ℕ) : Word w)) : + m (levelStart L (i.val+1)+15) = ((B.recordLimit+2 : ℕ) : Word w) := by + let next : Fin (vs).length := ⟨i.val+1,executeLevels_shrink_succ_lt B f hf T hT X z i shrink⟩ + exact h.read_field next wide (published next) + +end CompressorRecords.SelectedPayloadHistory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectedTermWorker.lean b/lean/OAI/Computability/VPVNP/CompressorSelectedTermWorker.lean new file mode 100644 index 0000000000..af5d5598f3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectedTermWorker.lean @@ -0,0 +1,187 @@ +import OAI.Computability.VPVNP.PairSimulationSelectorReindex +import OAI.Computability.VPVNP.CompressorTermWorkerDispatch + +/-! +# Uniform costs for the selected ordinal-native motif passes + +Only the shrink and refresh grids enter the constants. They are independent +of the width data, branch choices, compression level and number of levels. +Every reset uses the same private-work cap. Calls and probes are charged +against the original physical slots of their level. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.SelectedTermWorker + +open BurstRAM Compression SelectedTerms PairSimulation.LocalHistory + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {A : Type*} [CommRing A] {f : B.Entry → A} {hf : B.IsSolution f} + +/-- Grid-dependent contribution to the word width needed for the scan's bound on each motif +visit. -/ +def siteFit (G : Grid k) : ℕ := + (TermWorker.scan_site_bound G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos).choose + +/-- Common word-width allowance for the grid's term worker, individual visits, and write frame. -/ +def gridFit (G : Grid k) := max (workerFit G) (max (siteFit G) + (TermWorker.frameFit G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos)) + +/-- Word-width allowance sufficient for both the shrinking and refresh term workers. -/ +def fitConstant (B : S.Templates) := max (gridFit (shrinkGrid B)) (gridFit (refreshGrid B)) + +/-- Private instruction budget shared by the selected motif visits at word width `w`. -/ +def clock (B : S.Templates) (w : ℕ) := (SelectedTerms.stepConstant B + 7) * (2*w+1) + +variable {a g b n : ℕ} {X : State a g} {p : StatePass A X b n} (o : PassOrigin B f hf p) + +private theorem grid_fit : gridFit (grid o) ≤ fitConstant B := by + cases o <;> first | exact le_max_left .. | exact le_max_right .. + +theorem frameFit_le : + let G := grid o + TermWorker.frameFit G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos ≤ fitConstant B := + (le_max_right ..).trans ((le_max_right ..).trans (grid_fit o)) + +private theorem grid_constants : workerFit (grid o) ≤ fitConstant B ∧ siteFit (grid o) ≤ fitConstant B ∧ + (grid o).stepConstant ≤ SelectedTerms.stepConstant B ∧ (grid o).charge ≤ SelectedTerms.phaseConstant B := by + refine ⟨(le_max_left ..).trans (grid_fit o), (le_max_left ..).trans ((le_max_right ..).trans (grid_fit o)),?_⟩ + cases o with + | shrink => exact ⟨le_max_left ..,le_max_left ..⟩ + | refresh => exact ⟨le_max_right ..,le_max_right ..⟩ + +theorem budget_le {w M : ℕ} (hfit : fitConstant B+4*Nat.clog 2 (M+1) ≤ w) : + TermWorker.budget (grid o).block (grid o).d (grid o).e w M ≤ clock B w := by + let G := grid o + have plus : TermWorker.budget G.block G.d G.e w M = TermRecordScan.eventsPerRow G.block G.d G.e w M + 7 := by + unfold TermWorker.budget TermRecordScan.eventsPerRow TermRecordScan.prepFuel + omega + have steps := G.steps_le w M + obtain ⟨_,_,hle,_⟩ := grid_constants o + have fit := Nat.mul_le_mul (show G.stepConstant ≤ SelectedTerms.stepConstant B from hle) + (show w+Nat.clog 2 (M+1)+1 ≤ 2*w+1 by omega) + change TermWorker.budget G.block _ _ _ _ ≤ _ + rw [plus,clock,Nat.add_mul] + exact Nat.add_le_add (steps.trans fit) (Nat.le_mul_of_pos_right _ (by omega)) + +/-- The fields provided by the physical level directory suffice to construct +the reindexed worker input using the same instruction cap on every level. -/ +def input {w : ℕ} (hfit : fitConstant B+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (layout : TermRecordScan.Layout o.motifCount (grid o).d (grid o).e w) (addr : Fin 4 → Word w) + (ha : TermWorker.Addresses layout addr) (mem : Memory w) + (hin : TermRecordScan.Inputs (grid o).demandOrder.entries layout (termRows o).demand mem) : WorkerInput o w := + ⟨layout,addr,ha,mem,hin,(Nat.add_le_add_right (grid_constants o).1 _).trans hfit,clock B w,budget_le o hfit⟩ + +private theorem probe_log {w : ℕ} (rs : List (Report w)) : + RAMBuckets.probeCount Report.probes rs = countProbes (eventLog rs) := by + induction rs with + | nil => rfl + | cons r rs ih => + simp only [RAMBuckets.probeCount,eventLog,List.flatMap_cons,DemandPreparation.probes_append] + rw [ih]; rfl + +/-- The selected real-level execution charges one call per motif. The final +memory preserves every field, and the uniform bound applies at each report +and to the complete event log. -/ +theorem run (v : SelectedLevel B f hf) {w : ℕ} (I : WorkerInput v.origin w) + (hfit : fitConstant B+4*Nat.clog 2 (v.input.maxWireWidth+1) ≤ w) : + let G := grid v.origin + let batch := batch v.origin v.term + ∃ rs, I.run (I.termEquiv v.term).val = some rs ∧ + (∀ j, TermRecordScan.Fields G.block G.supplyOrder.entries G.pPos (batch.demand j) + (batch.choice j).val (I.layout.base j) (after I.memory (eventLog rs))) ∧ + (∀ x, (∀ i, I.layout.Outside i x) → after I.memory (eventLog rs) x = I.memory x) ∧ + branchPaths rs = List.ofFn (workerTapes v.origin w v.term) ∧ + rs.length = v.origin.motifCount ∧ RAMBuckets.cost Report.probes rs ≤ SelectedTerms.phaseConstant B * v.oldSlots ∧ + (eventLog rs).length ≤ v.oldSlots * clock B w ∧ (∀ r ∈ rs, r.events.length < clock B w) := by + intro G batch + let D := termRows v.origin + have native := (TermWorker.scan_native G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos).choose_spec + v.origin.motifCount v.input.maxWireWidth w I.width I.layout I.addr I.addresses D.demand D.bounded I.memory I.inputs I.fuel I.clock + obtain ⟨rs,hr,hfield,hframe,_,hlen,hbits,hp,hl⟩ := native.2 (D.rows v.term) + obtain ⟨_,hsite,_,hcharge⟩ := grid_constants v.origin + have localBound := (TermWorker.scan_site_bound G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos).choose_spec + v.origin.motifCount v.input.maxWireWidth w ((Nat.add_le_add_right hsite _).trans hfit) I.layout I.addr I.addresses + D.demand D.bounded I.memory I.inputs I.fuel I.clock _ rs hr + have clocked := budget_le v.origin hfit + refine ⟨rs,hr,fun j => ?_,hframe,hbits,hlen,?_,hl.trans (Nat.mul_le_mul v.origin.motifCount_le clocked),?_⟩ + · dsimp only [batch] + simpa only [D, ← (termRows_batch v.origin v.term).2 j, ← (termRows_batch v.origin v.term).1] using hfield j + · rw [RAMBuckets.cost_eq_length_add_probes,probe_log,hlen] + calc + _ ≤ v.origin.motifCount * G.charge := by + unfold Grid.charge + rw [Nat.mul_add] + exact Nat.add_le_add (Nat.le_mul_of_pos_right _ (by decide)) hp + _ ≤ v.oldSlots * SelectedTerms.phaseConstant B := Nat.mul_le_mul v.origin.motifCount_le hcharge + _ = _ := Nat.mul_comm .. + · exact fun r h => (localBound r h).trans_le clocked + +variable (B f hf) + +theorem executeLevels_width {n w : ℕ} (T : ℕ) (h : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) + (z : (B.execute f hf T h X).Choices) + (fit : fitConstant B + 4*Nat.clog 2 (B.growthConstant^T*(X.maxWireWidth+1)+1) ≤ w) : + ∀ v ∈ executeLevels B f hf T h X z, fitConstant B+4*Nat.clog 2 (v.input.maxWireWidth+1) ≤ w := by + intro v hv + have bound := (executeLevels_limits B f hf T h X z v hv).2 + exact (Nat.add_le_add_left (Nat.mul_le_mul_left _ (Nat.clog_mono_right _ (Nat.add_le_add_right bound 1))) _).trans fit + +private theorem sum_bound {α : Type*} (xs : List α) (cost amount : α → ℕ) (K : ℕ) + (h : ∀ v ∈ xs, cost v ≤ K * amount v) : + (xs.map cost).sum ≤ K*(xs.map amount).sum := by + induction xs with + | nil => simp + | cons v vs ih => + simp only [List.map_cons,List.sum_cons,Nat.mul_add] + exact Nat.add_le_add (h v List.mem_cons_self) (ih (fun x hx => h x (List.mem_cons_of_mem _ hx))) + +/-- Along a selected execution, summing the real calls and probes requires +only a fixed multiple of the descriptor units. The clock is uniform over +the entire branch. -/ +theorem executeLevels_cost {n w : ℕ} (T : ℕ) (h : T*S.laneBits ≤ n) (X : State (S.degreeExponent 0) n) + (z : (B.execute f hf T h X).Choices) + (fit : fitConstant B+4*Nat.clog 2 (B.growthConstant^T*(X.maxWireWidth+1)+1) ≤ w) + (inputs : ∀ v ∈ executeLevels B f hf T h X z, WorkerInput v.origin w) : + let levels := executeLevels B f hf T h X z + ∃ reports : SelectedLevel B f hf → List (Report w), + (∀ v (hv : v ∈ levels), let I := inputs v hv + I.run (I.termEquiv v.term).val = some (reports v) ∧ ∀ r ∈ reports v, r.events.length < clock B w) ∧ + (levels.map (fun v => RAMBuckets.cost Report.probes (reports v))).sum ≤ + SelectedTerms.phaseConstant B * CursorNetwork.descriptorUnits B f hf T h X z ∧ + (levels.map (fun v => (eventLog (reports v)).length)).sum ≤ + clock B w * CursorNetwork.descriptorUnits B f hf T h X z := by + classical + let levels := executeLevels B f hf T h X z + have actual (v : SelectedLevel B f hf) (hv : v ∈ levels) := run v (inputs v hv) + (executeLevels_width B f hf T h X z fit v hv) + let reports (v : SelectedLevel B f hf) := if hv : v ∈ levels then (actual v hv).choose else [] + have same (v : SelectedLevel B f hf) (hv : v ∈ levels) : reports v = (actual v hv).choose := dite_eq_left hv + have total := executeLevels_sum_units B f hf T h X z + refine ⟨reports,fun v hv => ?_,?_,?_⟩ + · rw [same v hv] + exact ⟨(actual v hv).choose_spec.1,(actual v hv).choose_spec.2.2.2.2.2.2.2⟩ + · rw [← total] + apply sum_bound + intro v hv + rw [same v hv] + exact (actual v hv).choose_spec.2.2.2.2.2.1.trans (Nat.mul_le_mul_left _ v.oldSlots_le_units) + · rw [← total] + apply sum_bound + intro v hv + rw [same v hv] + exact (actual v hv).choose_spec.2.2.2.2.2.2.1.trans + ((Nat.mul_le_mul_right _ v.oldSlots_le_units).trans_eq (Nat.mul_comm ..)) + +end CompressorRecords.SelectedTermWorker + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectedTerms.lean b/lean/OAI/Computability/VPVNP/CompressorSelectedTerms.lean new file mode 100644 index 0000000000..432dfec9a0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectedTerms.lean @@ -0,0 +1,249 @@ +import OAI.Computability.VPVNP.CompressorLevelCounts +import OAI.Computability.VPVNP.CompressorTermRecordScan + +/-! +# Native term rows for the selected shrinking and refresh levels + +Both kinds of level run a fixed demand/supply grid. The finite row family +below uses the original pass's choice at the actual motif or port block. +Consequently a successful scan writes the demand grid point, repetition +count and supply coordinates for that same branch. Its charged probes +depend on the number of motifs and fixed grid, while the local arithmetic +also depends on the word width. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +open scoped Classical + +namespace CompressorRecords.SelectedTerms + +open Compression PairSimulation.LocalHistory MotifGrid MotifBlocks MotifSelector MotifConversion BurstRAM + +/-- A single fixed grid, with the physical order of its demand and supply columns. -/ +structure Grid (k : Type*) [_root_.Field k] where + /-- Vertex set shared by the demand and supply graphs of this motif. -/ + J : Type + /-- Index set for the motif's demand edges. -/ + D : Type + /-- Index set for the motif's supply edges. -/ + E : Type + [jFinite : Fintype J] + [dFinite : Fintype D] + [eFinite : Fintype E] + /-- Source vertex of each demand edge. -/ + src : D → J + /-- Target vertex of each demand edge. -/ + dst : D → J + /-- Supply graph on the motif vertices with edges indexed by `E`. -/ + graph : Supply J E + /-- Positive rational weight used to measure the demand on each demand edge. -/ + p : D → ℚ + /-- Positive rational weight used to measure the payload on each supply edge. -/ + q : E → ℚ + /-- Demand-to-supply energy comparison constant used to construct the strict grid. -/ + comparison : ℝ + /-- Coefficient of the squared demand norm in the padded supply-energy bound. -/ + relaxed : ℝ + /-- Fixed motif identities and width bounds for these edges, weights, and comparison + constants. -/ + block : FixedBlock k src dst graph (realWidths p) (realWidths q) comparison relaxed + pPos : ∀ i, 0 < p i + qPos : ∀ i, 0 < q i + /-- Physical order of the demand columns in each motif row. -/ + demandOrder : Order D + /-- Physical order of the supply columns in each selected term record. -/ + supplyOrder : Order E + +attribute [instance] Grid.jFinite Grid.dFinite Grid.eFinite + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} +variable {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + +/-- Grid for the six-vertex shrinking motif, with two demand columns and eight supply columns. -/ +def shrinkGrid (B : S.Templates) : Grid k where + J := Fin 6 + D := Bool + E := Bool × Fin 4 + src := ShrinkMotif.demandSource + dst := ShrinkMotif.demandTarget + graph := ShrinkMotif.supply + p := ShrinkMotif.demandMass + q := ShrinkMotif.supplyMass + comparison := 31/16 + relaxed := shrinkComparison + block := B.shrink + pPos := ShrinkMotif.demandMass_pos + qPos := ShrinkMotif.supplyMass_pos + demandOrder := ⟨2,finTwoEquiv⟩ + supplyOrder := Order.prod ⟨2,finTwoEquiv⟩ (Order.fin 4) + +/-- Grid for a refresh block, with tie demands and supply edges indexed by port and expander +slot. -/ +def refreshGrid (B : S.Templates) : Grid k where + J := Fin (2^S.portExponent) + D := DegreeRefresh.Tie (2^S.portExponent) + E := Fin (2^S.portExponent) × Fin (2^S.expanderExponent) + src := Refresh.tieSource + dst := Refresh.tieTarget + graph := S.portSupply + p := Refresh.tieMass + q := Refresh.expanderMass S.baseDegree + comparison := S.portComparison + relaxed := S.portComparison+1 + block := B.refresh + pPos _ := zero_lt_one + qPos _ := by unfold Refresh.expanderMass BlockSchedule.baseDegree; positivity + demandOrder := ⟨_, (Fintype.equivFin _).symm⟩ + supplyOrder := (Order.fin (2 ^ S.portExponent)).prod (Order.fin (2 ^ S.expanderExponent)) + +variable {a g b n : ℕ} {X : State a g} {p : StatePass R X b n} + +/-- Select the shrinking or refresh grid according to the pass origin. -/ +def grid : (o : PassOrigin B f hf p) → Grid k + | .shrink .. => shrinkGrid B + | .refresh .. => refreshGrid B + +/-- Actual input and selected output rows of the grid, in the same motif order +as the compression pass. -/ +structure Batch (G : Grid k) (m M : ℕ) where + /-- Width requested on each demand edge at each physical motif ordinal. -/ + demand : Fin m → G.D → ℕ + bound : ∀ i e, demand i e ≤ M + /-- Selected admissible term for the demand row at each motif ordinal. -/ + choice : TermRecordScan.Choices G.block demand + +set_option maxHeartbeats 1800000 in +/-- Arrange the actual pass demands and selected terms in physical motif order. -/ +def batch (o : PassOrigin B f hf p) (c : p.step.Choice) : + Batch (grid o) o.motifCount X.maxWireWidth := by + cases o with + | shrink i h X => + subst h + let ids := shrinkMotifOrder X + refine ⟨fun j ↦ X.packingData.shrinkDemandWidths X.shrinkNumber X.packingWidth (ids.entries j), + fun j e ↦ ?_,fun j ↦ c (ids.entries j)⟩ + exact X.packingData.shrinkDemandWidths_le (State.two_le_packingColors _) (Nat.two_pow_pos _) + X.shrinkNumber X.packingWidth (fun _ ↦ X.width_le_maxWireWidth _) _ e + | refresh X => + let ids := (Order.prod ⟨_,X.baseIndex.symm⟩ ⟨_,(bitWordFinEquiv n).symm⟩) + refine ⟨fun j ↦ Refresh.blockDemandWidths (Refresh.splitSlots X) (bitWordFinEquiv _) + (Refresh.splitWidths X) (ids.entries j),fun j e ↦ ?_,fun j ↦ c (ids.entries j)⟩ + change Refresh.internalWidth _ _ (ids.entries j) e ≤ X.maxWireWidth + unfold Refresh.internalWidth + split <;> exact X.width_le_maxWireWidth _ + +namespace Grid + +variable (G : Grid k) + +/-- Number of demand columns scanned in one motif row. -/ +abbrev d := G.demandOrder.length +/-- Number of supply columns written in one motif row. -/ +abbrev e := G.supplyOrder.length + +/-- Fixed contribution to the word width required by this grid's term-record scan. -/ +def fitConstant : ℕ := (TermRecordScan.run_spec G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos).choose + +/-- Upper bound on the cost of scanning one motif, counting the five native calls and the probe +bound for one term row. -/ +def charge : ℕ := 5 + TermRecordScan.probesPerRow G.block G.d G.e + +/-- Grid-dependent coefficient in the event bound for one row as a function of word width and +log demand width. -/ +def stepConstant : ℕ := + 6*G.d + (11*G.d+4)*G.block.grid.demands.toList.length + 8 + + 6*G.d + 7*(∑ i, MotifAdmission.weight G.p i).size + 10 + 8 + + 12*G.e + 2*(G.block.scale*G.block.radius.num.natAbs).size + + 4*(MotifAdmission.denominator G.q).size + 20 + 14 + 4*G.e + +theorem steps_le (w M : ℕ) : TermRecordScan.eventsPerRow G.block G.d G.e w M ≤ + G.stepConstant * (w + Nat.clog 2 (M+1) + 1) := by + have hp := PayloadWrite.storedFuel_le G.block G.e w + let l := Nat.clog 2 (M+1) + have hsteps : TermRecordScan.eventsPerRow G.block G.d G.e w M ≤ G.stepConstant + 14*l + (4*G.e)*w := by + dsimp only [TermRecordScan.eventsPerRow,TermRecordScan.prepFuel,stepConstant,l] + ring_nf at hp ⊢ + omega + have h14 : 14 ≤ G.stepConstant := by unfold stepConstant; omega + have h4e : 4*G.e ≤ G.stepConstant := by unfold stepConstant; omega + calc + _ ≤ G.stepConstant + 14*l + (4*G.e)*w := hsteps + _ ≤ G.stepConstant + G.stepConstant*l + G.stepConstant*w := Nat.add_le_add + (Nat.add_le_add_left (Nat.mul_le_mul_right _ h14) _) (Nat.mul_le_mul_right _ h4e) + _ = _ := by dsimp only [l]; ring + +end Grid + +/-- Common per-row call and probe charge for the two pass grids. -/ +def phaseConstant (B : S.Templates) : ℕ := max (shrinkGrid B).charge (refreshGrid B).charge + +/-- Maximum fixed word-width allowance for the shrinking and refresh term-record scans. -/ +def fitConstant (B : S.Templates) : ℕ := max (shrinkGrid B).fitConstant (refreshGrid B).fitConstant + +/-- Common coefficient in the per-row event bound for the shrinking and refresh grids. -/ +def stepConstant (B : S.Templates) : ℕ := max (shrinkGrid B).stepConstant (refreshGrid B).stepConstant + +private theorem grid_bounds (o : PassOrigin B f hf p) : (grid o).charge ≤ phaseConstant B ∧ + (grid o).fitConstant ≤ fitConstant B ∧ (grid o).stepConstant ≤ stepConstant B := by + cases o with + | shrink => exact ⟨le_max_left ..,le_max_left ..,le_max_left ..⟩ + | refresh => exact ⟨le_max_right ..,le_max_right ..,le_max_right ..⟩ + +private theorem count_log {w : ℕ} (rs : List (Report w)) : + RAMBuckets.probeCount Report.probes rs = countProbes (eventLog rs) := by + induction rs with + | nil => rfl + | cons r rs ih => + simp only [RAMBuckets.probeCount,eventLog,List.flatMap_cons,DemandPreparation.probes_append] + rw [ih] + rfl + +/-- The real five-call scans for all terms of one selected level. The +input is the physical demand array, including its disjoint term-row arena. -/ +theorem run (v : SelectedLevel B f hf) {w : ℕ} + (hw : fitConstant B + 4*Nat.clog 2 (v.input.maxWireWidth+1) ≤ w) + (layout : TermRecordScan.Layout v.origin.motifCount (grid v.origin).d (grid v.origin).e w) + (mem : Memory w) (hin : TermRecordScan.Inputs (grid v.origin).demandOrder.entries layout + (batch v.origin v.term).demand mem) : + let G := grid v.origin + let V := batch v.origin v.term + let tape := fun j ↦ TermRecordScan.tape G.block G.supplyOrder.entries (V.demand j) w (V.choice j).val + ∃ rs : List (Report w), + TermRecordScan.walk G.block G.demandOrder.entries G.supplyOrder.entries layout + (TermRecordScan.prepFuel (p := G.p) G.d v.input.maxWireWidth) tape + (List.finRange v.origin.motifCount) mem = some rs ∧ + (∀ j, TermRecordScan.Fields G.block G.supplyOrder.entries G.pPos (V.demand j) + (V.choice j).val (layout.base j) (after mem (eventLog rs))) ∧ + (∀ x, (∀ j, layout.Outside j x) → after mem (eventLog rs) x = mem x) ∧ + rs.length = 5*v.origin.motifCount ∧ + branchPaths rs = (List.finRange v.origin.motifCount).flatMap (fun j ↦ [[],[],[],[],tape j]) ∧ + RAMBuckets.cost Report.probes rs ≤ phaseConstant B * v.oldSlots ∧ + (eventLog rs).length ≤ v.oldSlots * (stepConstant B * (w+Nat.clog 2 (v.input.maxWireWidth+1)+1)) := by + intro G V tape + obtain ⟨hc,hfit,hstep⟩ := grid_bounds v.origin + have hcap : G.fitConstant + 4*Nat.clog 2 (v.input.maxWireWidth+1) ≤ w := (Nat.add_le_add_right hfit _).trans hw + have hrun := (TermRecordScan.run_spec G.block G.demandOrder.entries G.supplyOrder.entries G.pPos G.qPos).choose_spec + v.origin.motifCount v.input.maxWireWidth w hcap layout V.demand V.bound mem hin + obtain ⟨rs,hr,fields,frame,hlen,hbits,hprobes,hticks⟩ := hrun.2 V.choice + refine ⟨rs,hr,fields,frame,by simpa [Nat.mul_comm] using hlen,hbits,?_,?_⟩ + · rw [RAMBuckets.cost_eq_length_add_probes,count_log,hlen] + calc + _ ≤ v.origin.motifCount * G.charge := by + unfold Grid.charge; rw [Nat.mul_add]; exact Nat.add_le_add_left hprobes _ + _ ≤ v.oldSlots * phaseConstant B := Nat.mul_le_mul v.origin.motifCount_le hc + _ = _ := Nat.mul_comm .. + · exact hticks.trans (Nat.mul_le_mul v.origin.motifCount_le + ((G.steps_le _ _).trans (Nat.mul_le_mul_right _ hstep))) + +end CompressorRecords.SelectedTerms + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectorGroupPost.lean b/lean/OAI/Computability/VPVNP/CompressorSelectorGroupPost.lean new file mode 100644 index 0000000000..a3420b87d9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectorGroupPost.lean @@ -0,0 +1,80 @@ +import OAI.Computability.VPVNP.CompressorDeterministicGroup + +/-! # Identifying the selected physical branch with its source packet + +The packet's source run and recipe at the current ordinal produce one valid +online row. Its calendar, recipe, launcher, worker and closing calls consume +the selected branch's exact tapes. Determinism at the private clock identifies +the two logs and hence their post-memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BurstRAM BlockPlanner DescriptorSpace Schedule SourceTransport +open scoped Fin.CommRing + +variable {w cap small ordinal total : ℕ} {A : Script} {L : Layout} {I : Type*} +variable {pub : Fin 11 → Word w} {m raw : Memory w} {state : Word w} + +local notation "pt" => Workspace.ports (arity A.catalog) (pub 2) +local notation "tag" => LiveStageLink.tagWord w (Online.calendarIndex A.size A.size) + +/-- The memory and private communication charge of this particular choice +follow from its real source packet. -/ +theorem selectorGroupPost (out : SelectorInterval A pub cap small (some state) m I) (i : I) + (pkt : SourceOnline.Packet A w) (group : SourceOnline.Group A L (pub 2) small ordinal total raw [pkt]) + (bits : (out.cut.part i).bits = [] :: [] :: [] :: (pkt.stage.choices ++ [[]])) + (bounds : Online.Run.ControlBounds A.plan small (w := w)) + (arityEq : arity A.catalog = L.shape.arity) (baseEq : (pub 2).val = L.base) + (fit : levelStart L 0 < 2^w) (count : ordinal < total) (room : total ≤ directoryRows L) + (agree : Agree (levelStart L 0 ≤ ·) raw m) (bank : Workspace.Installed (arity A.catalog) (pub 2) m) + (htag : m (pt).tag.val = tag) (ord : (m (pt).ordinal.val).val = ordinal) + (rows : (m (pt).rows.val).val = total) (stride : m ((pt).directory-1).val = (levelWords L : Word w)) : + let mem := (out.cut.part i).memory + Agree (levelStart L 0 ≤ ·) pkt.output mem ∧ + Workspace.Installed (arity A.catalog) (pub 2) mem ∧ mem (pt).tag.val = tag ∧ + (mem (pt).ordinal.val).val = ordinal+1 ∧ (mem (pt).rows.val).val = total ∧ + mem ((pt).directory-1).val = (levelWords L : Word w) ∧ + RAMBuckets.cost Report.probes (out.source i).logs ≤ groupCost A [pkt] := by + intro mem + obtain ⟨input,run,_⟩ := group.chronological + have matchData : Agree (levelStart L 0 ≤ ·) pkt.input m := input.symm ▸ agree + have prepared : SourceOnline.Prepared A L (pub 2) ordinal total pkt := by simpa using group.prepared 0 + obtain ⟨phase,launch⟩ := prepared m matchData ord rows htag stride + have checked := group.checked pkt List.mem_cons_self + have active : m (pt).ordinal.val < m (pt).rows.val := Fin.lt_def.mpr (ord.symm ▸ rows.symm ▸ count) + have space : (m (pt).ordinal.val).val < directoryRows L := ord.symm ▸ count.trans_le room + obtain ⟨valid,ag,position,bound⟩ := SourceOnline.packet A L (pub 2) arityEq baseEq fit pkt.stage pkt.input m + pkt.reports small matchData (ord.symm ▸ phase) active space launch checked.positiveFuel + checked.recipeClock checked.dataClock run checked.progress checked.read checked.write + let step : Online.Run.Step A.size A.size w := ⟨pkt.stage.phase,pkt.stage.row pt m pkt.reports⟩ + let actual := Online.Run.oneRow A.plan pt (state := state) bounds htag step valid + have sameBits : (out.cut.part i).bits = actual.bits := bits + have physical := (out.source i).run + rw [sameBits] at physical + have sameLogs : (out.source i).logs = actual.logs := Option.some.inj (physical.symm.trans actual.run) + have sameMemory : mem = Online.post A.catalog A.size pt step.row := by + rw [show mem = after m (eventLog (out.source i).logs) from (out.source i).memory.symm,sameLogs] + exact Online.Run.oneRow_memory A.plan pt (state := state) bounds htag step valid + have installed := (out.frame.parts i).installed bank (out.cut.part i).logs.length + rw [List.take_length] at installed + have pitch := SourceOnline.pitch_packet A L (pub 2) arityEq baseEq fit pkt.stage m pkt.reports space checked.write + refine ⟨sameMemory.symm ▸ ag,installed,?_,sameMemory.symm ▸ position.trans (congrArg (·+1) ord), + sameMemory.symm ▸ (congrArg Fin.val bound).trans rows,sameMemory.symm ▸ pitch.trans stride,?_⟩ + · rw [sameMemory] + simp [Online.post,writeMemory] + · have cost := Online.Run.interval_cost_bound A.plan pt [step] m (cap := small) ⟨valid,trivial⟩ + rw [sameLogs] + change RAMBuckets.cost Report.probes (Online.rowLog A.plan pt m step.phase step.row) ≤ _ + simpa only [Online.Run.intervalLog, List.append_nil, Online.Run.sourceCost_eq_flatMap, + List.flatMap_cons, List.flatMap_nil, groupCost, List.length_cons, List.length_nil, step, SourceOnline.Visit.row] using cost + +end CompressorRecords.ScheduledTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorSelectorSitePacket.lean b/lean/OAI/Computability/VPVNP/CompressorSelectorSitePacket.lean new file mode 100644 index 0000000000..2869b8464f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorSelectorSitePacket.lean @@ -0,0 +1,119 @@ +import OAI.Computability.VPVNP.PairSimulationWorkspaceSelectorPost +import OAI.Computability.VPVNP.PairSimulationWorkerRebase + +/-! # Installing a native selector from its prepared source visit + +The source worker carries the demand rows in the data suffix. The calendar +and launcher write their own fields below that suffix, so the worker can +use the actual prepared memory at this occurrence. Comparing the launch +with the evaluated recipe identifies all four public address parameters. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace.SelectorSite + +open BurstRAM Compression DescriptorSpace Schedule SourceTransport PairSimulation.LocalHistory +open SelectedTerms BlockPlanner +open scoped Fin.CommRing +attribute [local irreducible] BlockProgram.script + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} + {R : Type*} [CommRing R] {f : B.Entry → R} {hf : B.IsSolution f} + {a g b n w : ℕ} {X : State a g} {p : StatePass R X b n} + {o : PassOrigin B f hf p} {L : Layout} {pub : Fin 11 → Word w} + {cap small ordinal total : ℕ} {m raw : Memory w} + +local notation "script" => BlockProgram.script B +local notation "pt" => Workspace.ports (arity (Script.catalog (BlockProgram.script B))) (pub 2) +local notation "tag" => LiveStageLink.tagWord w (Online.calendarIndex (Script.size (BlockProgram.script B)) + (Script.size (BlockProgram.script B))) +local notation "H" => levelStart L 0 + +/-- Physical worker information for one source packet, independent of the +live calendar memory at which the corresponding row will be installed. -/ +structure SourceWorker (I : WorkerInput o w) (L : Layout) (pkt : SourceOnline.Packet script w) : Prop where + code : (script).catalog pkt.stage.phase = + TermWorker.motifPass (grid o).block (grid o).demandOrder.entries (grid o).e + start : pkt.stage.start = 0 + stop : pkt.stage.stop.val = o.motifCount + params : ∀ j, pkt.stage.params j = TermWorker.catalogWords (grid o).block + (grid o).demandOrder.entries (grid o).supplyOrder.entries (script).catalog pkt.stage.phase I.addr code j + fuel : pkt.stage.fuel = I.fuel + width : SelectedTermWorker.fitConstant B+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w + readable : ∀ i, levelStart L 0 ≤ (I.layout.source i).val + writable : ∀ i, levelStart L 0 ≤ (I.layout.base i).val + inputs : Agree (levelStart L 0 ≤ ·) I.memory pkt.input + +/-- A prepared recipe suffices even at a selector for which there is no +accepting term. No completed choice run is needed to install its table. -/ +noncomputable def ofPrepared (I : WorkerInput o w) (pkt : SourceOnline.Packet script w) + (worker : SourceWorker I L pkt) (prepared : SourceOnline.Prepared script L (pub 2) ordinal total pkt) + (recipeClock : ((script).plan.recipes pkt.stage.phase).2.code.length+1+2*Online.N (script).size (script).size+5 ≤ small) + (dataClock : pkt.stage.fuel+3+4*(((script).catalog pkt.stage.phase).params+1)+2*Online.N (script).size (script).size+5 ≤ small) + (clock : small ≤ cap) (hg : arity (script).catalog = L.shape.arity) (hb : (pub 2).val = L.base) + (fit : H < 2^w) (count : ordinal < total) (room : total ≤ directoryRows L) + (agree : Agree (H ≤ ·) pkt.input m) (htag : m (pt).tag.val = tag) + (ord : (m (pt).ordinal.val).val = ordinal) (rows : (m (pt).rows.val).val = total) + (stride : m ((pt).directory-1).val = (levelWords L : Word w)) : SelectorSite o L pub cap small m := by + let j := pkt.stage.phase + let physical := Directory.prepared (script).catalog pt (Online.rowInput (script).plan pt m j) + have live : m (pt).ordinal.val < m (pt).rows.val := Fin.lt_def.mpr (ord.symm ▸ rows.symm ▸ count) + have atRow : (m (pt).ordinal.val).val < directoryRows L := ord.symm ▸ count.trans_le room + have preserve : Agree (H ≤ ·) m physical := OnlineFootprint.prepared script L (pub 2) hg hb fit m j atRow + let mounted := I.rebase physical H worker.readable (fun x hx => (worker.inputs x hx).trans ((agree x hx).trans (preserve x hx))) + obtain ⟨phase,launch⟩ := prepared m agree ord rows htag stride + have evaluated := SourceOnline.evaluated_launch script (pub 2) L hg hb fit m j pkt.stage.fuel pkt.stage.choices atRow live + have start : (script).operand (pub 2) m j ((script).visit j).initial = 0 := + evaluated.start.symm.trans (launch.start.trans worker.start) + have stop : ((script).operand (pub 2) m j ((script).visit j).stop).val = o.motifCount := + (congrArg Fin.val (evaluated.stop.symm.trans launch.stop)).trans worker.stop + have args (z) : (script).operand (pub 2) m j (((script).visit j).params z) = + TermWorker.catalogWords (grid o).block (grid o).demandOrder.entries (grid o).supplyOrder.entries + (script).catalog j mounted.addr worker.code z := + (congrFun evaluated.params z).symm.trans ((congrFun launch.params z).trans (worker.params z)) + have fuel : mounted.fuel+3+4*(((script).catalog j).params+1)+2*Online.N (script).size (script).size+5 ≤ small := + worker.fuel ▸ dataClock + let boundary := mounted.selectorStart script L (pub 2) hg hb fit m j worker.code worker.width + worker.readable worker.writable start stop args (ord.symm ▸ phase) atRow live + (recipeClock.trans clock) (fuel.trans clock) rfl + refine ⟨mounted,j,boundary,worker.writable,?_,?_⟩ + · rw [boundary.phase] + exact recipeClock + · rw [boundary.fuel,boundary.worker] + exact fuel + +/-- Extract the recipe and the two instruction bounds from an actual +singleton packet group, and mount its worker on the supplied live boundary. -/ +noncomputable def ofPacket (I : WorkerInput o w) (pkt : SourceOnline.Packet script w) + (worker : SourceWorker I L pkt) (group : SourceOnline.Group script L (pub 2) small ordinal total raw [pkt]) + (clock : small ≤ cap) (hg : arity (script).catalog = L.shape.arity) (hb : (pub 2).val = L.base) + (fit : H < 2^w) (count : ordinal < total) (room : total ≤ directoryRows L) + (agree : Agree (H ≤ ·) raw m) (htag : m (pt).tag.val = tag) + (ord : (m (pt).ordinal.val).val = ordinal) (rows : (m (pt).rows.val).val = total) + (stride : m ((pt).directory-1).val = (levelWords L : Word w)) : SelectorSite o L pub cap small m := + ofPrepared I pkt worker (by simpa using group.prepared 0) + (group.checked pkt List.mem_cons_self).recipeClock (group.checked pkt List.mem_cons_self).dataClock + clock hg hb fit count room (group.chronological.1.symm ▸ agree) htag ord rows stride + +/-- The installation callback used to join the prefix, selector and tail of +the native pass. The source packet and its worker are fixed before the live +memory at which the prefix returns. -/ +theorem install_from_packet (I : WorkerInput o w) (pkt : SourceOnline.Packet script w) + (worker : SourceWorker I L pkt) (group : SourceOnline.Group script L (pub 2) small ordinal total raw [pkt]) + (clock : small ≤ cap) (hg : arity (script).catalog = L.shape.arity) (hb : (pub 2).val = L.base) + (fit : H < 2^w) (count : ordinal < total) (room : total ≤ directoryRows L) : + ∀ mid : Memory w, Agree (H ≤ ·) raw mid → + Workspace.Installed (arity (script).catalog) (pub 2) mid → mid (pt).tag.val = tag → + (mid (pt).ordinal.val).val = ordinal → (mid (pt).rows.val).val = total → + mid ((pt).directory-1).val = (levelWords L : Word w) → Nonempty (SelectorSite o L pub cap small mid) := + fun _ agree _ htag ord rows stride => + ⟨ofPacket I pkt worker group clock hg hb fit count room agree htag ord rows stride⟩ + +end CompressorRecords.ScheduledTrace.SelectorSite + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABResident.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABResident.lean new file mode 100644 index 0000000000..914d794d32 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABResident.lean @@ -0,0 +1,100 @@ +import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables +import OAI.Computability.VPVNP.CompressorShrinkBundleFrame + +/-! # Resident inputs for the block's AB calendar + +The term scan preserves the six earlier demand columns. The selected +placement and preimage passes write above those columns. Any intervening +hidden-map passes that preserve the input prefix thus leave all source +records required by the two interval calendars in their original cells. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkOutput + +open Compression Compression.PackingData Compression.ShrinkMotif MotifBlocks MotifGrid +open BurstRAM ShrinkSliceSweep ShrinkBlockInputs SlotLevel ShrinkSlots +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) +variable (sel : SelectedScore.Selection B X) (term stride abs : Word w) (T : IncidenceDirectory w) (start : ℕ) + +local notation "role" => SelectedArena.roleBase X term stride +local notation "keepEnd" => SelectedFinish.stop X term stride +local notation "origin" => SelectedArena.origin X term stride +local notation "sh" => levelShape (b := b i) X + +set_option maxHeartbeats 1600000 in +/-- Transport the rows written by the selected geometry across the subsequent +prefix-preserving passes, with the original demand and absolute-ID tables. -/ +theorem resident_from_geometry (width : ℕ) (selectors : Word w) (p₀ : Fin 14 → Word w) (termMem input : Memory w) + (p : SelectedStage.Passes w) (q : SelectedFinish.Passes w) (wide : 10 ≤ stride.val) + (chosen : SelectedFinish.Built B X term stride selectors p₀ sel termMem p q) + (hiddenFrame : ∀ x < keepEnd, input x = q.final (p.final termMem) x) + (demand : DemandWidths.Stored X.packingData (Shrink.packedIndex X.baseIndex) X.packingWidth + X.shrinkOrder X.shrinkNumber (ShrinkInput.thickBank X T start) (ShrinkInput.cdBank X T start) + (ShrinkInput.piecesBank X T start) input) + (directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber abs input) : + Resident B i X sel term stride abs T start width input := by + let placed := q.final (p.final termMem) + have hbound := old_bounds i X term stride + refine ⟨demand,directory,?_,?_,?_,?_⟩ + · have src := resident_terms (b := b i) B X term stride selectors role width sel placed chosen.terms + apply terms_after B.shrink X term stride.val _ (sh).subdivisions sel placed input src + intro j r hr base + have startLe : base.val ≤ term.val+j.val*stride.val := Nat.mod_le .. + have rowLe := Nat.mul_le_mul_right stride.val j.isLt + rw [Nat.succ_mul] at rowLe + change j.val*stride.val+stride.val ≤ motifCount X*stride.val at rowLe + exact hiddenFrame _ ((show base.val+r < term.val+motifCount X*stride.val by omega).trans_le hbound.1) + · have keep (arc) (j : ℕ) (hj : j < 4) : input (role+4*(DemandRAM.absoluteIndex X arc).val+j) = placed (role+4*(DemandRAM.absoluteIndex X arc).val+j) := by + have hi : (DemandRAM.absoluteIndex X arc).val < absoluteCount X := (DemandRAM.absoluteIndex X arc).isLt + exact hiddenFrame _ (by omega) + constructor + · intro arc; rw [keep arc 3 (by decide)]; exact chosen.roles.cd arc + · intro arc r; rw [keep arc (SlotOwners.roleOffset r) (by cases r <;> decide)]; exact chosen.roles.packed arc r + · exact (hiddenFrame _ hbound.2.2).trans chosen.chosenCell + · exact preimages_retained X term stride chosen.raw.directory hiddenFrame + +set_option maxHeartbeats 1600000 in +/-- The verified term pass, the selected geometry and the intervening +memory frame supply the actual resident inputs for `withAB`. -/ +theorem resident_of_selected (width : ℕ) (selectors : Word w) (p₀ : Fin 14 → Word w) (termMem input : Memory w) + (p : SelectedStage.Passes w) (q : SelectedFinish.Passes w) + (hterm : term = ShrinkInput.termHead X start) (wide : 10 ≤ stride.val) + (termRoom : ShrinkInput.termEnd X start stride.val < 2^w) + (retained : ShrinkInput.Retained X T start termMem) + (chosen : SelectedFinish.Built B X term stride selectors p₀ sel termMem p q) + (hiddenFrame : ∀ x < keepEnd, input x = q.final (p.final termMem) x) + (absEarly : abs.val+motifCount X ≤ origin) + (absolute : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber abs termMem) : + Resident B i X sel term stride abs T start width input := by + have hbound := old_bounds i X term stride + have originEarly : origin ≤ keepEnd := by omega + have early (x : ℕ) (hx : x < origin) : input x = termMem x := + (hiddenFrame x (hx.trans_le originEarly)).trans (chosen.frame x (.inl hx)) + have layout := ShrinkInput.termLayout X T start stride.val termRoom + have headBefore : (ShrinkInput.demandHead (w := w) X start).val ≤ origin := by + have sep := layout.2.2.1 + rw [← hterm] at sep + unfold SelectedArena.origin + omega + apply resident_from_geometry B i X sel term stride abs T start width selectors p₀ termMem input + p q wide chosen hiddenFrame (ShrinkDemandFrame.retain retained.stored layout.2.1 + (fun x hx => early x (hx.trans_le headBefore))) + intro j + exact (congrArg Fin.val (early _ ((Nat.add_lt_add_left j.isLt _).trans_le absEarly))).trans (absolute j) + +end CompressorRecords.ShrinkOutput + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceCalendar.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceCalendar.lean new file mode 100644 index 0000000000..15053c1f9f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceCalendar.lean @@ -0,0 +1,195 @@ +import OAI.Computability.VPVNP.CompressorShrinkABSliceVisits + +/-! +# Chronological realization of the fixed AB slice calendar + +Every visit scans all bundles. The old and new ranks are fixed by the visit, +so each call computes its addresses from the current bundle ordinal. After +the count, interval and incidence visits, each bundle has its exact interval +frames and both compact endpoint lists in the common memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkABSliceRecipe + +open BurstRAM Compression Compression.PackingData PrimedStackRAM ShrinkSliceArrays +open ShrinkABSliceTable IndexedStarts + +variable {w m n rows first : ℕ} + +private theorem fin_walk {J : Type*} {source : J → Memory w → List (Report w) → Prop} {k : ℕ} + (label : Fin k → J) (inv : ℕ → Memory w → Prop) (mem : Memory w) (start : inv 0 mem) + (step : ∀ j : Fin k, ∀ mem, inv j.val mem → + ∃ rs, source (label j) mem rs ∧ inv (j.val+1) (after mem (eventLog rs))) : + ∃ rs, SourceWalk source ((List.finRange k).map label) mem rs ∧ inv k (after mem (eventLog rs)) := by + let js := (List.finRange k).map label + have len : js.length = k := by simp [js] + have hstep (i : Fin js.length) (st : Memory w) (h : inv (0+i.val) st) : + ∃ rs, source js[i.val] st rs ∧ inv (0+i.val+1) (after st (eventLog rs)) := by + let j := i.cast len + have he : js[i.val] = label j := by simp [js,j]; rfl + rw [he,Nat.zero_add] + exact step j st (by change inv i.val st; simpa only [Nat.zero_add] using h) + simpa only [len,Nat.zero_add] using FlatRows.walk js inv 0 mem start hstep + +open private before inputs from OAI.Computability.VPVNP.CompressorShrinkABSliceTable + +variable (I : Inputs) (pub : Fin 5 → Word w) (state : Word w) (ref : Memory w) +variable {t p : Fin 5 → Word w} (L : Layout t p rows m n first) (D : Describes I pub state ref t p rows first) + +include L D + +/-- Exact worker runs for all field ordinals in the fixed catalog. The bank +and frame addresses are the same as the native row-major descriptor builder. -/ +theorem run (old new : Fin rows → List ℕ) (om : ∀ i, (old i).length = m) (nm : ∀ i, (new i).length = n) + (hs : ∀ i, (old i).sum < 2^w) (ht : ∀ i, (new i).sum < 2^w) + (start : Memory w) + (reads : ∀ i : Fin rows, SliceSchedule.Inputs (IndexedStarts.pair (columns t p i.val) (bank first m n i.val) m n) + (old i) (new i) start) + (cap : ℕ) (hcap : 95 ≤ cap) : + ∃ rs, SourceWalk (Source I pub state ref rows cap) (phases m n) start rs ∧ + (∀ i : Fin rows, IndexedStarts.Stored (bank first m n i.val) (old i) (new i) (after start (eventLog rs))) ∧ + ∀ x, x < first ∨ first+rows*capacity m n ≤ x → after start (eventLog rs) x = start x := by + let B (i : Fin rows) := bank (w := w) first m n i.val + let src := Source (m := m) (n := n) I pub state ref rows cap + let Shared (mem : Memory w) := ∀ x, x < first ∨ first+rows*capacity m n ≤ x → mem x = start x + have shared : Shared start := fun _ _ => rfl + have sp (i : Fin rows) : Space (columns t p i.val) (B i) (old i).length (new i).length := + by simpa only [om i,nm i] using ShrinkABSliceTable.space L i + have retain (i : Fin rows) (mem out : Memory w) (h : Shared mem) + (outside : ∀ x, ¬ BankAt (B i) m n x → out x = mem x) : Shared out := by + intro x hx + have hv := bank_val L i + change (B i).val = _ at hv + have hi := Nat.mul_le_mul_right (capacity m n) i.isLt + rw [Nat.succ_mul] at hi + exact (outside x (by dsimp only [BankAt]; omega)).trans (h x hx) + have inp (i : Fin rows) (mem : Memory w) (h : Shared mem) : + SliceSchedule.Inputs (IndexedStarts.pair (columns t p i.val) (B i) (old i).length (new i).length) + (old i) (new i) mem := by + rw [om i,nm i] + have eqn (c : Fin 4) (j : ℕ) (hj : j < (if c.val < 2 then m else n)) : + mem (((columns t p i.val) c).val+j) = start (((columns t p i.val) c).val+j) := + h _ (Or.inl (by have := before L i c; omega)) + constructor <;> intro j hj + · exact (congrArg Fin.val (eqn 0 j (om i ▸ hj))).trans ((reads i).oldStart _ hj) + · exact (congrArg Fin.val (eqn 1 j (om i ▸ hj))).trans ((reads i).oldWidth _ hj) + · exact (congrArg Fin.val (eqn 2 j (nm i ▸ hj))).trans ((reads i).newStart _ hj) + · exact (congrArg Fin.val (eqn 3 j (nm i ▸ hj))).trans ((reads i).newWidth _ hj) + let C (k : ℕ) (i : Fin rows) (mem : Memory w) := Cleared (B i) k mem + let F (k : ℕ) (i : Fin rows) (mem : Memory w) := Frames (B i) (old i) (new i) k mem + let R (k : ℕ) (i : Fin rows) (mem : Memory w) := Dirs (B i) (old i) (new i) k mem + let State (pred : Fin rows → Memory w → Prop) (mem : Memory w) := Shared mem ∧ ∀ i, pred i mem + have ck {k} (hk : k ≤ m+n) (i : Fin rows) (mem out : Memory w) (h : C k i mem) + (eqn : ∀ x, BankAt (B i) m n x → out x = mem x) : C k i out := h.keep hk eqn + have fk {k} (hk : k ≤ m*n) (i : Fin rows) (mem out : Memory w) (h : F k i mem) + (eqn : ∀ x, BankAt (B i) m n x → out x = mem x) : F k i out := + h.keep (om i ▸ nm i ▸ hk) (om i ▸ nm i ▸ eqn) + have rk {k} (hk : k ≤ m*n) (i : Fin rows) (mem out : Memory w) (h : R k i mem) + (eqn : ∀ x, BankAt (B i) m n x → out x = mem x) : R k i out := + h.keep (sp i) (om i ▸ nm i ▸ hk) (om i ▸ nm i ▸ eqn) + have clearStep (j : Fin (m+n)) (mem : Memory w) (cur : State (C j.val) mem) : + ∃ rs, src (.clear j) mem rs ∧ State (C (j.val+1)) (after mem (eventLog rs)) := by + apply phase_run I pub state ref L D (.clear j) cap hcap Shared (C j.val) (C (j.val+1)) retain + (ck j.isLt.le) (ck j.isLt) _ mem cur.1 cur.2 + intro i st _ prev + let k : Fin ((old i).length+(new i).length) := ⟨j.val,by rw [om i,nm i]; exact j.isLt⟩ + obtain ⟨r,hr,he,hd,hframe⟩ := clear_one (sp i) k st prev + exact ⟨r,hr,he ▸ rfl,hd,by simpa only [om i,nm i] using hframe⟩ + obtain ⟨clears,cr,cleared⟩ := fin_walk (Stage.clear (m := m) (n := n)) (fun k => State (C k)) start + ⟨shared,fun _ _ hj => by omega⟩ clearStep + let firstMem := after start (eventLog clears) + let CF (k : ℕ) (i : Fin rows) (mem : Memory w) := C (m+n) i mem ∧ F k i mem + have keepCF {k} (hk : k ≤ m*n) (i : Fin rows) (mem out : Memory w) (h : CF k i mem) + (eqn : ∀ x, BankAt (B i) m n x → out x = mem x) : CF k i out := + ⟨ck le_rfl i _ _ h.1 eqn,fk hk i _ _ h.2 eqn⟩ + have pairStep (j : Fin (m*n)) (mem : Memory w) (cur : State (CF j.val) mem) : + ∃ rs, src (.pair j) mem rs ∧ State (CF (j.val+1)) (after mem (eventLog rs)) := by + apply phase_run I pub state ref L D (.pair j) cap hcap Shared (CF j.val) (CF (j.val+1)) retain + (keepCF j.isLt.le) (keepCF j.isLt) _ mem cur.1 cur.2 + intro i st sh prev + let k : Fin ((old i).length*(new i).length) := ⟨j.val,by rw [om i,nm i]; exact j.isLt⟩ + obtain ⟨r,hr,he,hd,hframe⟩ := frame_one (sp i) k st (hs i) (ht i) (inp i st sh) + (om i ▸ nm i ▸ prev.1) prev.2 + dsimp only [k] at hr hd he + rw [om i,nm i] at hr hframe + exact ⟨r,hr,he ▸ rfl,⟨by simpa only [om i,nm i] using hd.1,hd.2⟩,hframe⟩ + obtain ⟨pairs,pr,framed⟩ := fin_walk (Stage.pair (m := m) (n := n)) (fun k => State (CF k)) firstMem + ⟨cleared.1,fun i => ⟨cleared.2 i,fun _ hj => by omega,fun _ hj _ => by omega⟩⟩ pairStep + let secondMem := after firstMem (eventLog pairs) + let FR (k : ℕ) (i : Fin rows) (mem : Memory w) := F (m*n) i mem ∧ R k i mem + have keepFR {k} (hk : k ≤ m*n) (i : Fin rows) (mem out : Memory w) (h : FR k i mem) + (eqn : ∀ x, BankAt (B i) m n x → out x = mem x) : FR k i out := + ⟨fk le_rfl i _ _ h.1 eqn,rk hk i _ _ h.2 eqn⟩ + have refStep (j : Fin (m*n)) (mem : Memory w) (cur : State (FR j.val) mem) : + ∃ rs, src (.refs j) mem rs ∧ State (FR (j.val+1)) (after mem (eventLog rs)) := by + apply phase_run I pub state ref L D (.refs j) cap hcap Shared (FR j.val) (FR (j.val+1)) retain + (keepFR j.isLt.le) (keepFR j.isLt) _ mem cur.1 cur.2 + intro i st _ prev + let k : Fin ((old i).length*(new i).length) := ⟨j.val,by rw [om i,nm i]; exact j.isLt⟩ + obtain ⟨r,hr,he,hd,hframe⟩ := refs_one (sp i) k st (om i ▸ nm i ▸ prev.1) prev.2 + dsimp only [k] at hr hd he + rw [om i,nm i] at hr hframe + exact ⟨r,hr,he ▸ rfl,⟨by simpa only [om i,nm i] using hd.1,hd.2⟩,hframe⟩ + obtain ⟨refs,rr,final⟩ := fin_walk (Stage.refs (m := m) (n := n)) (fun k => State (FR k)) secondMem + ⟨framed.1,fun i => ⟨(framed.2 i).2,Dirs.zero (sp i) (om i ▸ nm i ▸ (framed.2 i).1)⟩⟩ refStep + have firstTwo := cr.append pr + have second : after start (eventLog (clears++pairs)) = secondMem := SourceWalk.after_append .. + have all := firstTwo.append (second ▸ rr) + have replay : after start (eventLog ((clears++pairs)++refs)) = after secondMem (eventLog refs) := by + rw [SourceWalk.after_append,second] + refine ⟨(clears++pairs)++refs,all,?_,replay ▸ final.1⟩ + rw [replay] + intro i + obtain ⟨frames,dirs⟩ := final.2 i + rw [← om i,← nm i] at frames dirs + exact ⟨frames.lengths,frames.offsets,dirs.oldRows,dirs.newRows⟩ + +omit L D + +section Graph + +variable {V H Tag Lane : Type} {d c nv : ℕ} +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup Lane] +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype Lane] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq Lane] +variable (P : PackingData V H Tag Lane d c) (site : Site V Tag Lane ≃ Fin nv) +variable (width : Arc V H Tag Lane d c → ℕ) (dd : P.ThickNumbering) (cd : P.BundleNumbering) +local notation "ns" => 2^c*d/4 +local notation "nt" => pieceCount d c +local notation "ord" => BundleLists.portIndex site (d := d) + +/-- The native whole-level calendar on the width-and-start columns of the +selected shrinking branch. Each resulting endpoint directory and frame +is interpreted directly in the final memory of the actual calendar. -/ +theorem graph_run (hc : 2 ≤ c) (hd : 0 < d) (t u p : Fin 5 → Word w) (initial : Memory w) + (stored : DemandWidths.Stored P site width dd cd t u p initial) + (layout : Layout t p (nv*d) ns nt first) + (heads : Describes I pub state ref t p (nv*d) first) + (fit : ∀ b, P.bundleWidth width b < 2^w) (cap : ℕ) (hcap : 95 ≤ cap) : + ∃ rs, SourceWalk (Source I pub state ref (nv*d) cap) (phases ns nt) initial rs ∧ + (∀ b, IndexedStarts.Stored (bank first ns nt (ord b).val) (thickWidths P dd width b) + (abWidths P cd width b) (after initial (eventLog rs))) ∧ + ∀ x, x < first ∨ first+(nv*d)*capacity ns nt ≤ x → after initial (eventLog rs) x = initial x := by + let old := fun i => thickWidths P dd width ((ord).symm i) + let new := fun i => abWidths P cd width ((ord).symm i) + have hs (i) : (old i).sum < 2^w := (thickWidths_sum P dd width _).symm ▸ fit _ + have ht (i) : (new i).sum < 2^w := by + dsimp only [new] + rw [abWidths,orderedWidths,List.sum_ofFn, + (cd _).symm.sum_comp (fun z : P.MotifFiber _ => P.abWidth cd width z.1),P.sum_abWidth hc hd cd width _] + exact fit _ + obtain ⟨rs,walk,rows,outside⟩ := run I pub state ref layout heads old new (fun _ => List.length_ofFn) + (fun _ => List.length_ofFn) hs ht initial (inputs P site width dd cd t u p initial stored layout) cap hcap + exact ⟨rs,walk,fun b => by simpa only [old,new,Equiv.symm_apply_apply] using rows (ord b),outside⟩ + +end Graph + +end CompressorRecords.ShrinkABSliceRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceFootprint.lean new file mode 100644 index 0000000000..45c7b2f19f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceFootprint.lean @@ -0,0 +1,93 @@ +import OAI.Computability.VPVNP.CompressorShrinkABSliceCalendar +import OAI.Computability.VPVNP.CompressorShrinkABSliceReads +import OAI.Computability.VPVNP.CompressorSourceObservableFrame + +/-! +# Progress and footprints of the executed AB calendar + +Each reset sequence advances the global bundle cursor and reads inside the +four input columns and the allocated bundle banks. These inputs suffice to +replay the full calendar. Applying the frame theorem to every compatible +initial memory shows that all emitted writes stay in the data region. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkABSliceRecipe + +open BurstRAM SourceTransport ShrinkABSliceTable IndexedStarts + +variable {w m n rows first : ℕ} {data : ℕ → Prop} +variable (I : Inputs) (pub : Fin 5 → Word w) (state : Word w) (ref : Memory w) +variable {t p : Fin 5 → Word w} (L : Layout t p rows m n first) (D : Describes I pub state ref t p rows first) + +/-- The AB worker runs from cursor zero to the row count and all reads and writes in its report +log lie in the supplied data region. -/ +def Guarded (rows cap : ℕ) (data : ℕ → Prop) (j : Stage m n) (mem : Memory w) (rs : List (Report w)) : Prop := + Source I pub state ref rows cap j mem rs ∧ SourceOnline.Progress (Fin.ofNat _ rows) 0 rs ∧ + Reads data (eventLog rs) ∧ Writes data (eventLog rs) + +include L D + +private theorem all_reads (R : ReadRegion t p rows m n first data) (limit : rows < 2^w) {cap : ℕ} + (hcap : 95 ≤ cap) {js : List (Stage m n)} {mem : Memory w} {rs : List (Report w)} + (walk : SourceWalk (Source I pub state ref rows cap) js mem rs) : Reads data (eventLog rs) := by + induction walk with + | done => simp [Reads,eventLog] + | next head _ ih => + have one := (source_progress_reads I pub state ref L D R limit _ cap hcap _ _ head).2 + intro a v h + rcases List.mem_append.mp (show Event.read a v ∈ _ ++ _ from by simpa only [eventLog,List.flatMap_append] using h) with h|h + · exact one a v h + · exact ih a v h + +private theorem guarded_of_writes (R : ReadRegion t p rows m n first data) (limit : rows < 2^w) {cap : ℕ} + (hcap : 95 ≤ cap) {js : List (Stage m n)} {mem : Memory w} {rs : List (Report w)} + (walk : SourceWalk (Source I pub state ref rows cap) js mem rs) (wr : Writes data (eventLog rs)) : + SourceWalk (Guarded (m := m) (n := n) I pub state ref rows cap data) js mem rs := by + induction walk with + | done => exact .done _ + | next head _ ih => + simp only [eventLog,List.flatMap_append] at wr + have ⟨prog,rd⟩ := source_progress_reads I pub state ref L D R limit _ cap hcap _ _ head + exact .next ⟨head,prog,rd,fun a v hv => wr a v (List.mem_append_left _ hv)⟩ + (ih (fun a v hv => wr a v (List.mem_append_right _ hv))) + +/-- The same fixed stage list as the graph builder, with the scheduler's +per-packet progress, read and write predicates proved for its actual reports. -/ +theorem guarded_walk [Nontrivial (Word w)] (R : ReadRegion t p rows m n first data) (limit : rows < 2^w) + (old new : Fin rows → List ℕ) (om : ∀ i, (old i).length = m) (nm : ∀ i, (new i).length = n) + (hs : ∀ i, (old i).sum < 2^w) (ht : ∀ i, (new i).sum < 2^w) (start : Memory w) + (reads : ∀ i : Fin rows, SliceSchedule.Inputs (IndexedStarts.pair (columns t p i.val) (bank first m n i.val) m n) + (old i) (new i) start) + (cap : ℕ) (hcap : 95 ≤ cap) {rs : List (Report w)} + (walk : SourceWalk (Source I pub state ref rows cap) (phases m n) start rs) : + SourceWalk (Guarded I pub state ref rows cap data) (phases m n) start rs := by + apply guarded_of_writes I pub state ref L D R limit hcap walk + apply writes_of_replay + intro mem agree x hx + have read := all_reads I pub state ref L D R limit hcap walk + have replay : SourceWalk (Source I pub state ref rows cap) (phases m n) mem rs := + replay_walk (src := Source I pub state ref rows cap) (fun _ _ _ _ ag rd h => (segment h ag rd).1) walk agree read + have cells (i : Fin rows) (c : Fin 4) (j : ℕ) (hj : j < (if c.val < 2 then m else n)) : + start (((columns t p i.val) c).val+j) = mem (((columns t p i.val) c).val+j) := + agree _ (R.columns i c j hj) + have inputs (i : Fin rows) : SliceSchedule.Inputs + (IndexedStarts.pair (columns t p i.val) (bank first m n i.val) m n) (old i) (new i) mem := by + constructor <;> intro j hj + · exact (cells i 0 j (om i ▸ hj)) ▸ (reads i).oldStart j hj + · exact (cells i 1 j (om i ▸ hj)) ▸ (reads i).oldWidth j hj + · exact (cells i 2 j (nm i ▸ hj)) ▸ (reads i).newStart j hj + · exact (cells i 3 j (nm i ▸ hj)) ▸ (reads i).newWidth j hj + obtain ⟨other,hw,_,out⟩ := run I pub state ref L D old new om nm hs ht mem inputs cap hcap + have unique : other = rs := walk_deterministic (fun _ _ _ _ a b => Option.some.inj (a.symm.trans b)) hw replay + subst other + exact out x (by by_contra h; exact hx (R.bank x (by omega) (by omega))) + +end CompressorRecords.ShrinkABSliceRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceGroup.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceGroup.lean new file mode 100644 index 0000000000..54b400f704 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceGroup.lean @@ -0,0 +1,175 @@ +import OAI.Computability.VPVNP.CompressorShrinkABTraceReplay +import OAI.Computability.VPVNP.CompressorShrinkABSlicePackets +import OAI.Computability.VPVNP.CompressorBlockCapacity +import OAI.Computability.VPVNP.CompressorScheduledSliceRates + +/-! +# Complete AB packet group of the selected shrinking branch + +The first scratch table holds the physical sorted widths and their starts. +The second table holds every AB interval record. The allocated block's end +bound suffices for both. The group uses the real shrinking numberings and +retains its exact external frame and resource bounds at its packet endpoint. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockSlices + +open BurstRAM PhaseRecipe BlockPlanner Compression ShrinkBlockInputs DescriptorSpace +open ShrinkSliceArrays Schedule +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) +variable (base : Word w) (pos blocks round : ℕ) +local notation "scr" => BlockProgram.script B +local notation "F" => BlockProgram.geometry B +local notation "O" => BlockProgram.arena B i.val 0 +local notation "AB" => BlockProgram.arena B i.val 1 +local notation "L" => BlockProgram.layout B base.val pos blocks +local notation "pt" => Workspace.ports (arity (Script.catalog (BlockProgram.script B))) base +local notation "pub" => Ports.data pt +local notation "blockStart" => (S.steps+1)*round +local notation "cur" => blockStart+i.val +local notation "s" => ((levelStart L blockStart : ℕ) : Word w) +local notation "origin" => tableBase L cur (0 : Fin 6) +local notation "first" => tableBase L cur (1 : Fin 6) +local notation "W" => abWindow B i +local notation "Z" => ShrinkInput.plan X origin +local notation "T" => packedIncidence L w cur (DemandRAM.oldCount X) +local notation "t" => ShrinkInput.thickBank X T origin +local notation "u" => ShrinkInput.cdBank X T origin +local notation "p" => ShrinkInput.piecesBank X T origin +local notation "ns" => ShrinkBundlePlan.thickCount (a i) +local notation "nt" => ShrinkBundlePlan.cap (a i) +local notation "sites" => Shrink.packedIndex (a := a i) (g := g) X.baseIndex + +set_option maxHeartbeats 1200000 in +/-- The source data come from the chosen geometry's current memory. Table +sizes, bundle indices and worker clocks are those of the compiled script. -/ +private theorem build_packets_trace (m : Memory w) (hblock : round < blocks) (sitesFit : X.positions ≤ pos) + (fit : endAddress L < 2^w) (widthFit : nt*X.maxWireWidth < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (level : ShrinkBundlePlan.Reads X F i.val O pub s m origin T) + (abHead : m (tableHead L cur (1 : Fin 6)) = (first : Word w)) + (stored : DemandWidths.Stored X.packingData sites X.packingWidth X.shrinkOrder X.shrinkNumber t u p m) + (cap : ℕ) (clock : SourceOnline.scanCap scr 95 ≤ cap) : + ∃ ps : List (SourceOnline.Packet scr w), + ShrinkABSliceRecipe.Describes (abInputs i O AB) pub s m t p (Z).B first ∧ + SourceWalk (ShrinkABSliceRecipe.Source (abInputs i O AB) pub s m (Z).B 95) (ShrinkABSliceRecipe.phases ns nt) + m (ps.flatMap SourceWalk.Packet.reports) ∧ + SourceOnline.Group scr L base cap ((scr).initial.length+round*(scr).block.length+(W).before.length) + (directoryRows L) m ps ∧ ps.map (fun v => v.stage.phase)=(W).indices ∧ + (∀ b, IndexedStarts.Stored (ShrinkABSliceTable.bank first ns nt (BundleLists.portIndex sites b).val) + (thickWidths X.packingData X.shrinkOrder X.packingWidth b) (abWidths X.packingData X.shrinkNumber X.packingWidth b) + (SourceOnline.post m ps)) ∧ + (∀ x, x < first ∨ first+(Z).B*IndexedStarts.capacity ns nt ≤ x → SourceOnline.post m ps x = m x) ∧ + (ps.flatMap SourceWalk.Packet.reports).length = (Z).B*(ns+nt+2*(ns*nt)) ∧ + RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) ≤ (Z).B*(2*(ns+nt)+16*(ns*nt)) := by + have active : cur < (L).levels := by + change (S.steps+1)*round+i.val < 1+(S.steps+1)*blocks + have bound := Nat.mul_le_mul_left (S.steps+1) hblock + rw [Nat.mul_succ] at bound + have hi := i.isLt + omega + let lev : Fin (L).levels := ⟨cur,active⟩ + have rate := (BlockProgram.field_rates B base.val pos blocks).1 + have amount : X.positions*ShrinkLevelSpace.tableFactor S ≤ tableWords L := by + change _ ≤ pos*(L).shape.slots*(L).shape.fields + rw [Nat.mul_assoc]; exact Nat.mul_le_mul sitesFit rate + have bounds := ShrinkLevelSpace.packed_ends S i X origin first 0 0 w + have room := tableStop_lt L lev (0 : Fin 6) amount fit + have termRoom : ShrinkInput.termEnd X origin 10 < 2^w := bounds.2.1.trans_lt room + have fresh : ShrinkInput.stop X origin ≤ first := bounds.1.trans + ((Nat.add_le_add_left amount origin).trans (tableEnd_le_tableBase L cur (a := (0 : Fin 6)) (b := (1 : Fin 6)) (show (0 : Fin 6) < 1 from by decide))) + have abRoom : first+(Z).B*IndexedStarts.capacity ns nt < 2^w := + bounds.2.2.2.2.1.trans_lt (tableStop_lt L lev (1 : Fin 6) amount fit) + have headRoom : tableHead L cur (1 : Fin 6) < 2^w := by + have le : tableHead L cur (1 : Fin 6) < first := by + change levelStart L cur+54+6+1 < (levelStart L cur+66)+_+_; omega + exact le.trans (Nat.lt_of_le_of_lt (Nat.le_add_right ..) abRoom) + let : Nontrivial (Word w) := Fin.nontrivial_iff_two_le.mpr (by + change levelStart L cur+54+6+1 < 2^w at headRoom; omega) + have entry : LevelFields.Entry L blockStart pub s m := ⟨rfl,pitch⟩ + have arena : (AB).eval pub s m = (first : Word w) := + (LevelFields.eval_table entry i.val (1 : Fin 6) headRoom).trans abHead + have rankFit : (Z).stop < 2^w := by + change ShrinkInput.widthBase X origin < _ + change ShrinkInput.widthBase X origin+_+_+_+_ < _ at termRoom; omega + have hd := ab_describes i X T origin level rankFit arena + obtain ⟨rs,walk,ready,outside⟩ := ab_run i X T origin m stored level arena termRoom fresh abRoom widthFit 95 le_rfl + have guarded := ab_guarded i X T origin m stored level arena termRoom fresh abRoom widthFit 95 le_rfl walk + have counts := ScheduledRates.scheduledABCounts (abInputs i O AB) pub s m walk + obtain ⟨ps,group,phase,reports⟩ := ab_packets B i base pos blocks round (Z).B _ t p m rs hblock active fit + rows pitch hd guarded cap clock + refine ⟨ps,hd,reports ▸ walk,group,phase,?_,?_,?_,?_⟩ + · simpa only [SourceOnline.post,reports] using ready + · simpa only [SourceOnline.post,reports] using outside + · rw [reports]; exact counts.1 + · rw [reports]; exact counts.2.1 + +/-- Build the group, endpoint descriptors, external frame and costs of the +physical AB calendar on the admitted state. -/ +theorem build_packets (m : Memory w) (hblock : round < blocks) (sitesFit : X.positions ≤ pos) + (fit : endAddress L < 2^w) (widthFit : nt*X.maxWireWidth < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (level : ShrinkBundlePlan.Reads X F i.val O pub s m origin T) + (abHead : m (tableHead L cur (1 : Fin 6)) = (first : Word w)) + (stored : DemandWidths.Stored X.packingData sites X.packingWidth X.shrinkOrder X.shrinkNumber t u p m) + (cap : ℕ) (clock : SourceOnline.scanCap scr 95 ≤ cap) : + ∃ ps : List (SourceOnline.Packet scr w), + SourceOnline.Group scr L base cap ((scr).initial.length+round*(scr).block.length+(W).before.length) + (directoryRows L) m ps ∧ ps.map (fun v => v.stage.phase)=(W).indices ∧ + (∀ b, IndexedStarts.Stored (ShrinkABSliceTable.bank first ns nt (BundleLists.portIndex sites b).val) + (thickWidths X.packingData X.shrinkOrder X.packingWidth b) (abWidths X.packingData X.shrinkNumber X.packingWidth b) + (SourceOnline.post m ps)) ∧ + (∀ x, x < first ∨ first+(Z).B*IndexedStarts.capacity ns nt ≤ x → SourceOnline.post m ps x = m x) ∧ + (ps.flatMap SourceWalk.Packet.reports).length = (Z).B*(ns+nt+2*(ns*nt)) ∧ + RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) ≤ (Z).B*(2*(ns+nt)+16*(ns*nt)) := by + + obtain ⟨ps,_,_,result⟩ := build_packets_trace B i X base pos blocks round m hblock sitesFit fit widthFit rows pitch level abHead stored cap clock + exact ⟨ps,result⟩ + +/-- Attach the AB report list already present in an ordered shrinking +construction. Its source clock and saved planner header may differ from +the online clock and header; their eight physical operands coincide. -/ +theorem build_packets_of_run (m : Memory w) (hblock : round < blocks) (sitesFit : X.positions ≤ pos) + (fit : endAddress L < 2^w) (widthFit : nt*X.maxWireWidth < 2^w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (level : ShrinkBundlePlan.Reads X F i.val O pub s m origin T) + (abHead : m (tableHead L cur (1 : Fin 6)) = (first : Word w)) + (stored : DemandWidths.Stored X.packingData sites X.packingWidth X.shrinkOrder X.shrinkNumber t u p m) + (ref : Memory w) (nativeCap : ℕ) (rs : List (Report w)) + (heads : ShrinkABSliceRecipe.Describes (abInputs i O AB) pub s ref t p (Z).B first) + (trace : SourceWalk (ShrinkABSliceRecipe.Source (abInputs i O AB) pub s ref (Z).B nativeCap) + (ShrinkABSliceRecipe.phases ns nt) m rs) + (cap : ℕ) (clock : SourceOnline.scanCap scr 95 ≤ cap) : + ∃ ps : List (SourceOnline.Packet scr w), + ps.flatMap SourceWalk.Packet.reports = rs ∧ + SourceOnline.Group scr L base cap ((scr).initial.length+round*(scr).block.length+(W).before.length) + (directoryRows L) m ps ∧ ps.map (fun v => v.stage.phase)=(W).indices ∧ + (∀ b, IndexedStarts.Stored (ShrinkABSliceTable.bank first ns nt (BundleLists.portIndex sites b).val) + (thickWidths X.packingData X.shrinkOrder X.packingWidth b) (abWidths X.packingData X.shrinkNumber X.packingWidth b) + (SourceOnline.post m ps)) ∧ + (∀ x, x < first ∨ first+(Z).B*IndexedStarts.capacity ns nt ≤ x → SourceOnline.post m ps x = m x) ∧ + (ps.flatMap SourceWalk.Packet.reports).length = (Z).B*(ns+nt+2*(ns*nt)) ∧ + RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) ≤ (Z).B*(2*(ns+nt)+16*(ns*nt)) := by + + obtain ⟨ps,localHeads,localWalk,result⟩ := build_packets_trace B i X base pos blocks round m hblock sitesFit fit widthFit rows pitch level abHead stored cap clock + exact ⟨ps,(ShrinkABSliceRecipe.walk_unique (abInputs i O AB) heads localHeads trace localWalk).symm,result⟩ + +end CompressorRecords.BlockSlices + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceOperands.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceOperands.lean new file mode 100644 index 0000000000..6ae95974e2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceOperands.lean @@ -0,0 +1,112 @@ +import OAI.Computability.VPVNP.CompressorBlockSlices +import OAI.Computability.VPVNP.CompressorHeaderOperands + +/-! +# Memory reads of the fixed AB launch recipes + +The row-indexed workers derive their public words from four level scalars, +the first scratch-table head and the AB-bank head. Each prologue parameter +is an affine base, a stride, or the zero bias. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkABSliceRecipe + +open BurstRAM PhaseRecipe BlockPlanner +variable {w : ℕ} (D : ℕ → Prop) (pub : Fin 5 → Word w) (s : Word w) (mem : Memory w) +local notation "reads" => Expr.ReadsFrom D pub s mem + +/-- Evaluating the AB recipe's row count, four input column heads, two strides and bank origin +reads only the allowed memory region. -/ +structure Supported (I : Inputs) : Prop where + rows : reads I.rows + oldStarts : reads I.oldStarts + oldWidths : reads I.oldWidths + oldStride : reads I.oldStride + newStarts : reads I.newStarts + newWidths : reads I.newWidths + newStride : reads I.newStride + firstBank : reads I.firstBank + +variable {I : Inputs} (h : Supported D pub s mem I) + +private theorem arguments_supported {k : ℕ} {par : Fin k → Affine} + (supported : ∀ j, reads (par j).1 ∧ reads (par j).2) (cursor : ℕ) (j : Fin (FlatRows.Params k)) : + reads (arguments par cursor j) := by + let a := finProdFinEquiv.symm j + have all (i : Fin (k+1)) : + let e := Fin.snoc (α := fun _ => Affine) par (constant cursor) i + reads e.1 ∧ reads e.2 := by + cases i using Fin.lastCases with + | last => simp only [Fin.snoc_last]; exact ⟨trivial,trivial⟩ + | cast j => simpa only [Fin.snoc_castSucc] using supported j + let e := Fin.snoc (α := fun _ => Affine) par (constant cursor) a.1 + change reads (![e.1,e.2,.lit 0] a.2) + have p := all a.1 + generalize a.2 = c + fin_cases c <;> first | exact p.1 | exact p.2 | trivial + +include h in +theorem stage_supported {m n : ℕ} (j : Stage m n) : + HeaderOperands.Supported D pub s mem (stage I j) := by + have bank (off : ℕ) : reads (bankField I m n off).1 ∧ reads (bankField I m n off).2 := + ⟨⟨h.firstBank,trivial⟩,trivial⟩ + cases j with + | clear k => exact ⟨trivial,h.rows,arguments_supported D pub s mem (fun _ => bank 0) k.val⟩ + | pair k => + refine ⟨trivial,h.rows,arguments_supported D pub s mem (par := pairParams I m n) ?_ k.val⟩ + intro u; fin_cases u + exacts [⟨trivial,trivial⟩,⟨h.oldStarts,h.oldStride⟩,⟨h.oldWidths,h.oldStride⟩, + ⟨h.newStarts,h.newStride⟩,⟨h.newWidths,h.newStride⟩,bank (m+n)] + | refs k => + refine ⟨trivial,h.rows,arguments_supported D pub s mem (par := refParams I m n) ?_ k.val⟩ + intro u; fin_cases u + exacts [⟨trivial,trivial⟩,⟨trivial,trivial⟩,bank (m+n),bank 0,bank (m+n+3*(m*n)),bank m,bank (m+n+4*(m*n))] + +end CompressorRecords.ShrinkABSliceRecipe + +namespace CompressorRecords.BlockSlices + +open BurstRAM PhaseRecipe BlockPlanner Compression ShrinkBlockInputs ShrinkBundlePlan +open private firstRecord recordsEnd from OAI.Computability.VPVNP.CompressorGreedyLevelPlan + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (i : Fin S.steps) {w : ℕ} +variable (D : ℕ → Prop) (pub : Fin 5 → Word w) (s : Word w) (mem : Memory w) +local notation "reads" => Expr.ReadsFrom D pub s mem + +/-- Exact block operands need four scalar and two table-pointer reads. -/ +theorem ab_supported (origin abArena : Expr) (header : ∀ j : Fin 4, reads (LevelFields.scalar i.val j.val)) + (base : reads origin) (arena : reads abArena) : + ShrinkABSliceRecipe.Supported D pub s mem (abInputs i origin abArena) := by + have vert : reads (LevelFields.vertices i.val) := header 0 + have degree : reads (LevelFields.degree i.val) := header 1 + have lanes : reads (LevelFields.lanes i.val) := header 2 + have residual : reads (LevelFields.residualLanes i.val) := header 3 + have ending (width : ℕ) (x : Expr) (hx : reads x) : reads (recordsEnd i.val width x) := ⟨⟨hx,vert⟩,vert,trivial⟩ + have off : reads (GreedyLevelPlan.offsetBase i.val (a i) origin) := ending _ _ base + have sh : reads (GreedyLevelPlan.shiftBase i.val (a i) origin) := ending _ _ off + have pre : reads (preliminary i.val (a i) origin) := ⟨⟨sh,vert,degree⟩,trivial⟩ + have sites : reads (LevelFields.sites i.val) := ⟨vert,lanes⟩ + have slots : reads (LevelFields.slots i.val) := ⟨sites,degree⟩ + have own : reads (owner i.val (a i) origin) := ⟨pre,trivial,sites⟩ + have c : reads (counts i.val (a i) origin) := ⟨own,trivial,slots⟩ + have b : reads (bundles i.val (a i)) := ⟨⟨vert,trivial,residual⟩,degree⟩ + have bc : reads (bucketCount i.val (a i)) := ⟨trivial,b⟩ + have id : reads (ids i.val (a i) origin) := ⟨c,bc⟩ + have rect : reads (rectangle i.val (a i)) := ⟨bc,trivial⟩ + have rank : reads (ranks i.val (a i) origin) := ⟨⟨id,rect⟩,rect⟩ + have so : reads (sorted i.val (a i) origin) := ⟨rank,slots⟩ + have block : reads (blockSize i.val (a i)) := ⟨b,trivial⟩ + have ps : reads (prefixStart i.val (a i) origin) := ⟨so,trivial,block⟩ + have tot : reads (totalStart i.val (a i) origin) := ⟨ps,trivial,block⟩ + have ab : reads (abStart i.val (a i) origin) := ⟨tot,bc⟩ + exact ⟨b,ps,so,trivial,⟨ab,block⟩,ab,trivial,arena⟩ + +end CompressorRecords.BlockSlices + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSlicePackets.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSlicePackets.lean new file mode 100644 index 0000000000..559e87c0b6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSlicePackets.lean @@ -0,0 +1,128 @@ +import OAI.Computability.VPVNP.CompressorShrinkABSliceWindow +import OAI.Computability.VPVNP.CompressorWindowPackets +import OAI.Computability.VPVNP.CompressorGreedyPlannerFootprint +import OAI.Computability.VPVNP.CompressorSourceScanned + +/-! +# Checked and prepared AB packets at their actual block ordinals + +At each repeated block, the AB window starts after the selected term and +resident directory visits. Its public words read the pitch and six header +cells of the current shrinking level. The online script therefore launches +the actual fixed workers in every live memory that agrees on the persistent +data, with the exact bounds and native reports of the shrinking construction. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockSlices + +open BurstRAM PhaseRecipe BlockPlanner Compression ShrinkBlockInputs DescriptorSpace SourceTransport +open ShrinkABSliceRecipe Schedule +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {w : ℕ} (base : Word w) (pos blocks round : ℕ) +local notation "scr" => BlockProgram.script B +local notation "F" => BlockProgram.geometry B +local notation "O" => BlockProgram.arena B i.val 0 +local notation "AB" => BlockProgram.arena B i.val 1 +local notation "I" => abInputs i O AB +local notation "L" => BlockProgram.layout B base.val pos blocks +local notation "pt" => Workspace.ports (arity (Script.catalog (BlockProgram.script B))) base +local notation "pub" => Ports.data pt +local notation "blockStart" => (S.steps+1)*round +local notation "cur" => blockStart+i.val +local notation "s" => ((levelStart L blockStart : ℕ) : Word w) +local notation "origin" => tableBase L cur (0 : Fin 6) +local notation "first" => tableBase L cur (1 : Fin 6) +local notation "H" => levelStart L 0 +local notation "D" => Window.operandRegion scr L base +local notation "W" => abWindow B i + +private theorem weaken_walk {J : Type*} {src dest : J → Memory w → List (Report w) → Prop} + (f : ∀ j mem rs, src j mem rs → dest j mem rs) {js : List J} {mem : Memory w} {rs : List (Report w)} + (walk : SourceWalk src js mem rs) : SourceWalk dest js mem rs := by + induction walk with + | done => exact .done _ + | next head _ ih => exact .next (f _ _ _ head) ih + +private theorem header_support (m : Memory w) (entry : LevelFields.Entry L blockStart pub s m) + (active : cur < (L).levels) (fit : endAddress L < 2^w) : + Supported (fun x => D x ∧ x < origin) pub s m I := by + have hg : arity (scr).catalog = (L).shape.arity := rfl + have hb : base.val = (L).base := rfl + have hH := (levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit + have gap := (Window.lowCells (A := scr) L base hg hb hH).2 + have low := levelStart_mono L (Nat.zero_le cur) + have earlier : incidenceStart L cur ≤ origin := by + change incidenceStart L cur ≤ incidenceStart L cur+_+_ + omega + have after : incidenceStart L cur ≤ levelStart L (cur+1) := + (earlier.trans (Nat.le_add_right origin (tableWords L))).trans (tableEnd_le_nextLevel L cur (0 : Fin 6)) + have bound := (after.trans (levelStart_mono L active)).trans_lt fit + have pitch : D (pub 1-1).val ∧ (pub 1-1).val < origin := ⟨Or.inr (Or.inl rfl), + gap.trans_le (low.trans ((Nat.le_add_right (levelStart L cur) (levelHeaderWords L)).trans earlier))⟩ + have scalar (off : ℕ) (small : off < 62) : + (LevelFields.scalar i.val off).ReadsFrom (fun x => D x ∧ x < origin) pub s m := by + have inside : levelStart L cur+off < incidenceStart L cur := by + change levelStart L cur+off < levelStart L cur+66 + omega + exact GreedyVisit.scalar_support _ L blockStart i.val off entry pitch + ⟨Or.inr (Or.inr (low.trans (Nat.le_add_right ..))),inside.trans_le earlier⟩ (inside.trans bound) + exact ab_supported i _ pub s m O AB (fun j => scalar j.val (by have := j.isLt; omega)) + (scalar 60 (by decide)) (scalar 61 (by decide)) + +private theorem clocks (cap : ℕ) (hc : SourceOnline.scanCap scr 95 ≤ cap) (j : Fin (scr).size) : + ((scr).plan.recipes j).2.code.length+1+2*Online.N (scr).size (scr).size+5 ≤ cap ∧ + 95+3+4*(((scr).catalog j).params+1)+2*Online.N (scr).size (scr).size+5 ≤ cap := by + have rc := Finset.le_sup (f := fun j : Fin (scr).size => ((scr).plan.recipes j).2.code.length+1+2*Online.N (scr).size (scr).size+5) + (Finset.mem_univ j) + have ar := params_le_arity (scr).catalog j + unfold SourceOnline.scanCap at hc + exact ⟨rc.trans ((le_max_left ..).trans hc),(by omega)⟩ + +set_option maxHeartbeats 900000 in +/-- At the physical AB stage of the live compiled script the stored guard +and interval trace give complete source packets and their actual launches. -/ +theorem ab_packets (rows high : ℕ) (t p : Fin 5 → Word w) (m : Memory w) (rs : List (Report w)) + (hblock : round < blocks) (active : cur < (L).levels) (fit : endAddress L < 2^w) + (total : m (pt).rows.val = (directoryRows L : Word w)) + (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (heads : Describes I pub s m t p rows first) + (walk : SourceWalk (Guarded I pub s m rows 95 (fun x => origin ≤ x ∧ x < high)) + (phases (ShrinkBundlePlan.thickCount (a i)) (ShrinkBundlePlan.cap (a i))) m rs) + (cap : ℕ) (capFit : SourceOnline.scanCap scr 95 ≤ cap) : + ∃ ps : List (SourceOnline.Packet scr w), + SourceOnline.Group scr L base cap ((scr).initial.length+round*(scr).block.length+(W).before.length) + (directoryRows L) m ps ∧ ps.map (fun p => p.stage.phase)=(W).indices ∧ + ps.flatMap SourceWalk.Packet.reports=rs := by + have entry : LevelFields.Entry L blockStart pub s m := ⟨rfl,pitch⟩ + have low : H ≤ origin := (levelStart_mono L (Nat.zero_le cur)).trans (by + change levelStart L cur ≤ levelStart L cur+_+_+_; omega) + have supported := header_support B i base pos blocks round m entry active fit + have native := ab_header_walk I L D origin high t p heads low supported _ m rs walk (fun _ _ => rfl) + have raw : SourceWalk (Window.Raw (A := scr) L base round 95) (intersections i O AB) m rs := by + change SourceWalk _ (List.map (stage I) _) _ _ + exact weaken_walk (fun _ _ _ head => ⟨95,_,le_rfl,head.1,head.2⟩) native + have live (j : Fin (intersections i O AB).length) : + Window.ordinal (A:=scr) round ((W).index j) < directoryRows L := by + rw [Window.ordinal_index,BlockProgram.directory_rows,(scr).calendar_total] + have step := Nat.mul_le_mul_right (scr).block.length hblock + rw [Nat.succ_mul] at step + have loc := ((W).position j).isLt + omega + exact (W).group L base round rfl rfl ((levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit) cap 95 m rs raw + total pitch live (fun j _ => (clocks B cap capFit j).1) (fun j _ => (clocks B cap capFit j).2) + +end CompressorRecords.BlockSlices + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceProgress.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceProgress.lean new file mode 100644 index 0000000000..336aa96345 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceProgress.lean @@ -0,0 +1,211 @@ +import OAI.Computability.VPVNP.CompressorSliceIndexedStarts + +/-! +# Local progress of the transposed AB scans + +A bundle can be visited at a fixed count, interval or incidence ordinal +after any number of calls on other bundles. Its input fields and its own bank +suffice to continue the three stages from their verified prefixes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.IndexedStarts + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SliceRAM SliceSchedule +open private adj_vals adj_space pair_space from OAI.Computability.VPVNP.CompressorSliceIndexedStarts + +variable {w : ℕ} + +/-- The address belongs to one bundle's contiguous bank for the given old and new field counts. -/ +def BankAt (B : Word w) (m n x : ℕ) : Prop := B.val ≤ x ∧ x < B.val+capacity m n + +/-- The first `k` words of this bundle's slice bank have been reset to zero. -/ +def Cleared (B : Word w) (k : ℕ) (mem : Memory w) : Prop := ∀ i < k, mem (B.val+i) = 0 + +/-- For the first `k` old/new field pairs, memory records each intersection length and both +offsets whenever that length is positive. -/ +structure Frames (B : Word w) (old new : List ℕ) (k : ℕ) (mem : Memory w) : Prop where + lengths : ∀ j, j < k → (mem (B.val+old.length+new.length+3*j+2)).val = (sliceAt old new j).length + offsets : ∀ j, j < k → 0 < (sliceAt old new j).length → + (mem (B.val+old.length+new.length+3*j)).val = (sliceAt old new j).sourceOffset ∧ + (mem (B.val+old.length+new.length+3*j+1)).val = (sliceAt old new j).targetOffset + +/-- The old- and new-endpoint directories index the first `k` intersection frames, grouping +them by the old and new field ordinals respectively. -/ +structure Dirs (B : Word w) (old new : List ℕ) (k : ℕ) (mem : Memory w) : Prop where + oldRows : (oldBank (adj B old.length new.length)).Represents mem + (fun j => (sliceAt old new j).length) (· / new.length) k + newRows : (newBank (adj B old.length new.length)).Represents mem + (fun j => (sliceAt old new j).length) (· % new.length) k + +theorem Cleared.keep {B : Word w} {m n k : ℕ} {mem out : Memory w} (hk : k ≤ m+n) + (h : Cleared B k mem) (eqn : ∀ x, BankAt B m n x → out x = mem x) : Cleared B k out := by + intro i hi + rw [eqn _ (by dsimp [BankAt,capacity]; omega)] + exact h i hi + +theorem Frames.keep {B : Word w} {old new : List ℕ} {k : ℕ} {mem out : Memory w} + (hk : k ≤ old.length*new.length) (h : Frames B old new k mem) + (eqn : ∀ x, BankAt B old.length new.length x → out x = mem x) : Frames B old new k out := by + constructor + · intro j hj; rw [eqn _ (by dsimp [BankAt,capacity]; omega)]; exact h.lengths j hj + · intro j hj hl + rw [eqn _ (by dsimp [BankAt,capacity]; omega),eqn _ (by dsimp [BankAt,capacity]; omega)] + exact h.offsets j hj hl + +variable {B : Word w} {old new : List ℕ} {input : Fin 4 → Word w} +variable (space : Space input B old.length new.length) +local notation "m₀" => old.length +local notation "n₀" => new.length + +include space + +theorem Dirs.keep {k : ℕ} {mem out : Memory w} (hk : k ≤ m₀*n₀) (h : Dirs B old new k mem) + (eqn : ∀ x, BankAt B m₀ n₀ x → out x = mem x) : Dirs B old new k out := by + obtain ⟨hn,hm,_,hc,hr,hc',hr'⟩ := adj_vals space + let q := adj B m₀ n₀ + have fit := space.fits + dsimp [capacity] at fit + have ho : (oldBank q).Fits := by + constructor <;> simp only [oldBank,q,AdjBank.stop,hn,hm,hc,hr] <;> omega + have hh : (newBank q).Fits := by + constructor <;> simp only [newBank,q,AdjBank.stop,hn,hm,hc',hr',Nat.mul_comm n₀ m₀] <;> omega + constructor + · apply AdjBank.represents_congr ho h.oldRows + · intro v _ + change _ ≤ (adj B m₀ n₀ 0).val; rw [hn]; exact adjPrefix_old_le _ hk + · intro x hx; simp only [q,oldBank,AdjBank.Inside,AdjBank.stop,hn,hm,hc,hr] at hx + exact eqn _ (by dsimp [BankAt,capacity]; omega) + · apply AdjBank.represents_congr hh h.newRows + · intro v _ + change _ ≤ (adj B m₀ n₀ 1).val; rw [hm]; exact adjPrefix_new_le _ hk + · intro x hx; simp only [q,newBank,AdjBank.Inside,AdjBank.stop,hn,hm,hc',hr',Nat.mul_comm n₀ m₀] at hx + exact eqn _ (by dsimp [BankAt,capacity]; omega) + +theorem Dirs.zero {mem : Memory w} (h : Cleared B (m₀+n₀) mem) : Dirs B old new 0 mem := by + obtain ⟨hn,hm,_,hc,_,hc',_⟩ := adj_vals space + have hf := space.fits + dsimp [capacity] at hf + constructor + · intro v hv + change v.val < (adj B m₀ n₀ 1).val at hv + rw [hm] at hv + have addr : ((oldBank (adj B m₀ n₀)).count v).val = B.val+v.val := by + change (B.val+v.val) % (2^w) = _ + exact Nat.mod_eq_of_lt (by omega) + simp [rowRepresents,adjPrefix,addr]; exact h v.val (by omega) + · intro v hv + change v.val < (adj B m₀ n₀ 0).val at hv + rw [hn] at hv + have addr : ((newBank (adj B m₀ n₀)).count v).val = B.val+(m₀+v.val) := by + rw [newBank,AdjBank.count,Fin.val_add,hc',Nat.mod_eq_of_lt (by omega),Nat.add_assoc] + simp [rowRepresents,adjPrefix,addr]; exact h (m₀+v.val) (by omega) + +omit space + +private theorem single_exec {C : Type*} {P : BurstRAM.Program w C} {f : ℕ} {s : Word w} + {mem : Memory w} {r : Report w} + (h : runSegment P f (some s) mem (List.replicate 1 []) = some [r]) : + execute P f (P.start s) mem [] = some r := by + cases he : execute P f (P.start s) mem [] <;> simp [runSegment,he] at h + exact congrArg some h + +private theorem single (rs : List (Report w)) (h : rs.length = 1) : ∃ r, rs = [r] := by + cases rs with + | nil => simp at h + | cons r rs => exact ⟨r,by simp [List.eq_nil_iff_length_eq_zero.mpr (by simpa using h)]⟩ + +include space + +theorem clear_one (k : Fin (m₀+n₀)) (mem : Memory w) (h : Cleared B k.val mem) : + let idx := Fin.ofNat (2^w) k.val + let M := (template clearOps 0).instantiate w (fun _ => B) + ∃ r, execute M.program 8 (M.program.start idx) mem [] = some r ∧ r.result = some (idx+1) ∧ + Cleared B (k.val+1) (after mem r.events) ∧ + ∀ x, ¬ BankAt B m₀ n₀ x → after mem r.events x = mem x := by + intro idx M + have hf := space.fits + dsimp [capacity] at hf + have hi := k.isLt + have hv : idx.val = k.val := Nat.mod_eq_of_lt (by omega) + have ha : (B+idx).val = B.val+k.val := by rw [Fin.val_add,hv,Nat.mod_eq_of_lt (by omega)] + refine ⟨clearReport B idx,clearVisit_native _ _ _,rfl,?_,?_⟩ + · intro j hj + change writeMemory mem (B+idx) 0 (B.val+j) = 0 + by_cases he : j = k.val + · simp [writeMemory,ha,he] + · simpa [writeMemory,ha,he] using h j (by omega) + · intro x hx + change writeMemory mem (B+idx) 0 x = mem x + exact ite_eq_right (fun e => hx (by rw [e,ha]; dsimp [BankAt,capacity]; omega)) + +theorem frame_one (k : Fin (m₀*n₀)) (mem : Memory w) (hs : old.sum < 2^w) (ht : new.sum < 2^w) + (reads : Inputs (pair input B m₀ n₀) old new mem) (clear : Cleared B (m₀+n₀) mem) + (h : Frames B old new k.val mem) : + let idx := Fin.ofNat (2^w) k.val + let M := IndexedPair.table.instantiate w (pair input B m₀ n₀) + ∃ r, execute M.program 38 (M.program.start idx) mem [] = some r ∧ r.result = some (Fin.ofNat _ (k.val+1)) ∧ + (Cleared B (m₀+n₀) (after mem r.events) ∧ Frames B old new (k.val+1) (after mem r.events)) ∧ + ∀ x, ¬ BankAt B m₀ n₀ x → after mem r.events x = mem x := by + intro idx M + let p := pair input B m₀ n₀ + have hf := space.fits + dsimp [capacity] at hf + have hp : (p 5).val = B.val+m₀+n₀ := Nat.mod_eq_of_lt (by omega) + have ready : FramesAt p old new mem mem k.val := by + exact ⟨reads,fun j hj => hp ▸ h.lengths j hj,fun j hj hl => hp ▸ h.offsets j hj hl,fun _ _ => rfl⟩ + obtain ⟨rs,run,post,ret,len,_,_⟩ := frameSegment_run (pair_space space) hs ht ready 1 k.isLt + obtain ⟨r,rfl⟩ := single rs len + simp only [eventLog,List.flatMap_singleton] at post + change FramesAt p old new mem (after mem r.events) (k.val+1) at post + refine ⟨r,single_exec run,ret,⟨?_,?_⟩,?_⟩ + · intro j hj; rw [post.outside _ (Or.inl (by rw [hp]; omega))]; exact clear j hj + · exact ⟨fun j hj => hp ▸ post.lengths j hj,fun j hj hl => hp ▸ post.offsets j hj hl⟩ + · intro x hx + apply post.outside + dsimp [BankAt,capacity] at hx + rw [hp]; have := k.isLt; omega + +theorem refs_one (k : Fin (m₀*n₀)) (mem : Memory w) (frames : Frames B old new (m₀*n₀) mem) + (dirs : Dirs B old new k.val mem) : + let idx := Fin.ofNat (2^w) k.val + let M := adjTemplate.instantiate w (adj B m₀ n₀) + ∃ r, execute M.program 36 (M.program.start idx) mem [] = some r ∧ r.result = some (Fin.ofNat _ (k.val+1)) ∧ + (Frames B old new (m₀*n₀) (after mem r.events) ∧ Dirs B old new (k.val+1) (after mem r.events)) ∧ + ∀ x, ¬ BankAt B m₀ n₀ x → after mem r.events x = mem x := by + intro idx M + let q := adj B m₀ n₀ + let len := fun j => (sliceAt old new j).length + obtain ⟨hn,hm,hf,hc,hr,hc',hr'⟩ := adj_vals space + have sq : AdjRegions q := adj_space space + have ready : AdjAt q len mem mem k.val := by + refine ⟨?_,?_,fun _ _ _ => rfl⟩ + · simpa only [q,hn] using dirs.oldRows + · simpa only [q,hn] using dirs.newRows + have lengths (j : ℕ) (hj : j < (q 1).val*(q 0).val) : (mem ((q 2).val+3*j+2)).val = len j := by + simpa only [q,hf] using frames.lengths j (by simpa only [q,hm,hn] using hj) + obtain ⟨rs,run,post,ret,size,_,_⟩ := adjSegment_run sq lengths ready 1 (by simpa only [q,hm,hn] using Nat.succ_le_of_lt k.isLt) + obtain ⟨r,rfl⟩ := single rs size + simp only [eventLog,List.flatMap_singleton] at post + change AdjAt q len mem (after mem r.events) (k.val+1) at post + have same (x : ℕ) (lo : B.val+m₀+n₀ ≤ x) (up : x < B.val+m₀+n₀+3*(m₀*n₀)) : + after mem r.events x = mem x := post.frame_eq sq (by simpa only [q,hf] using lo) + (by simpa only [q,hm,hn,hf] using up) + refine ⟨r,single_exec run,ret,⟨?_,?_⟩,?_⟩ + · constructor + · intro j hj; rw [same _ (by omega) (by omega)]; exact frames.lengths j hj + · intro j hj hl; rw [same _ (by omega) (by omega),same _ (by omega) (by omega)]; exact frames.offsets j hj hl + · exact ⟨by simpa only [q,hn] using post.oldRows,by simpa only [q,hn] using post.newRows⟩ + · intro x hx + dsimp [BankAt,capacity] at hx + apply post.outside <;> + simp only [oldBank,newBank,q,AdjBank.Inside,AdjBank.stop,hn,hm,hc,hr,hc',hr',Nat.mul_comm n₀ m₀] <;> omega + +end CompressorRecords.IndexedStarts + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceReads.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceReads.lean new file mode 100644 index 0000000000..aba4b4111d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceReads.lean @@ -0,0 +1,200 @@ +import OAI.Computability.VPVNP.CompressorShrinkABSliceVisits +import OAI.Computability.VPVNP.CompressorSourceOnline + +/-! +# External reads of a whole-level AB slice visit + +Clear reads no cell. Pair tests read the two width and two start columns. +Incidence reads the frame length and at most two counts in the current +bundle's bank. These bounds hold even for arbitrary contents of those +cells. The global-row prologue consists entirely of private operations. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkABSliceRecipe + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM SourceTransport IndexedStarts ShrinkABSliceTable SliceRAM +open scoped Fin.CommRing + +variable {w m n rows first : ℕ} {data : ℕ → Prop} + +open private execute_reads execute_stores reads wordStores from OAI.Computability.VPVNP.CompressorSlicePairVisit +open private appendEvents from OAI.Computability.VPVNP.CompressorSliceAdjacencyNative +open private adj_vals adj_space from OAI.Computability.VPVNP.CompressorSliceIndexedStarts +open private indices_lt from OAI.Computability.VPVNP.CompressorSliceSchedule + +private theorem pair_log (p : Fin 6 → Word w) (id : Word w) (mem : Memory w) + (ok : data (p 1+IndexedPair.oldIndex p id).val ∧ data (p 2+IndexedPair.oldIndex p id).val ∧ + data (p 3+IndexedPair.newIndex p id).val ∧ data (p 4+IndexedPair.newIndex p id).val) : + let M := IndexedPair.table.instantiate w p + ∃ r, execute M.program 38 (M.program.start id) mem [] = some r ∧ r.result.isSome ∧ Reads data r.events := by + intro M + change ∃ r, execute (IndexedPair.table.instantiate w p).program 38 _ _ _ = some r ∧ _ + rw [execute_reads p id mem 14,execute_stores p id mem _ rfl rfl] + refine ⟨_,rfl,rfl,?_⟩ + intro a v h + change Event.read a v ∈ reads p id mem ++ wordStores _ _ _ _ _ at h + rcases List.mem_append.mp h with rd|wr + · simp [reads] at rd + rcases rd with ⟨rfl,_⟩|⟨rfl,_⟩|⟨rfl,_⟩|⟨rfl,_⟩ + exacts [ok.1,ok.2.1,ok.2.2.1,ok.2.2.2] + · have noRead (b s t lo hi : Word w) : Event.read a v ∉ wordStores b s t lo hi := by + by_cases e : lo < hi <;> simp [wordStores,e] + exact (noRead _ _ _ _ _ wr).elim + +private theorem ref_log (q : Fin 7 → Word w) (id : Word w) (mem : Memory w) + (ok : data (adjFrameLength q id).val ∧ data (adjOldCount q (id/q 0)).val ∧ + data (adjNewCount q (id%q 0)).val) : Reads data (adjEvents q mem id) := by + intro a v h + by_cases hz : mem (adjFrameLength q id).val = 0 <;> simp [adjEvents,hz,appendEvents] at h + · exact h.1.symm ▸ ok.1 + · rcases h with ⟨rfl,_⟩|⟨rfl,_⟩|⟨rfl,_⟩ + exacts [ok.1,ok.2.1,ok.2.2] + +private theorem core_log (input : Fin 4 → Word w) (B : Word w) (s : Space input B m n) + (src : ∀ (c : Fin 4) j, j < (if c.val < 2 then m else n) → data ((input c).val+j)) + (bankOk : ∀ x, B.val ≤ x → x < B.val+capacity m n → data x) (j : Stage m n) (mem : Memory w) : + let par : Fin j.pass.params → Word w := match j with + | .clear _ => fun _ => B | .pair _ => IndexedStarts.pair input B m n | .refs _ => adj B m n + let M := j.pass.table.instantiate w par + ∃ r, execute M.program j.fuel (M.program.start (j.localIdx : Word w)) mem [] = some r ∧ + r.result.isSome ∧ Reads data r.events := by + cases j with + | clear k => + exact ⟨_,clearVisit_native B _ _,rfl,fun a v h => by simp [clearReport] at h⟩ + | pair k => + let p := IndexedStarts.pair input B m n + let id : Word w := (k.val : Word w) + have room := s.fits + unfold capacity at room + have hk : id.val = k.val := Nat.mod_eq_of_lt (by have := k.isLt; omega) + have hn : (p 0).val = n := Nat.mod_eq_of_lt (by omega) + obtain ⟨old,new⟩ := indices_lt k.isLt + have lo := (IndexedPair.oldIndex_val p id).trans (by rw [hk,hn]) + have hi := (IndexedPair.newIndex_val p id).trans (by rw [hk,hn]) + have cell (c : Fin 4) (e : Word w) (h : e.val < (if c.val < 2 then m else n)) : data (input c+e).val := by + have fits := s.reads c + rw [Fin.val_add,Nat.mod_eq_of_lt (by have := B.isLt; omega)] + exact src c e.val h + exact pair_log p id mem ⟨cell 0 _ (lo ▸ old),cell 1 _ (lo ▸ old),cell 2 _ (hi ▸ new),cell 3 _ (hi ▸ new)⟩ + | refs k => + let q := adj B m n + let id : Word w := (k.val : Word w) + obtain ⟨hn,hm,hf,_,_,hcn,_⟩ := adj_vals s + have room := s.fits + unfold capacity at room + have hk : id.val = k.val := Nat.mod_eq_of_lt (by have := k.isLt; omega) + have bounded : id.val < (q 1).val*(q 0).val := by rw [hk,hm,hn]; exact k.isLt + have hf' := adjFrameLength_val (adj_space s) bounded + obtain ⟨old,new⟩ := indices_lt k.isLt + have co : (adjOldCount q (id/q 0)).val = B.val+k.val/n := by + change (B.val+id.val/(q 0).val)%(2^w) = _ + rw [hk,hn,Nat.mod_eq_of_lt (by omega)] + have cn : (adjNewCount q (id%q 0)).val = B.val+m+k.val%n := by + change ((q 5).val+id.val%(q 0).val)%(2^w) = _ + rw [hcn,hk,hn,Nat.mod_eq_of_lt (by omega)] + have klt := k.isLt + refine ⟨_,adjVisit_native q mem id,rfl,ref_log q id mem ⟨?_,?_,?_⟩⟩ + · rw [hf',hf,hk]; exact bankOk (B.val+m+n+3*k.val+2) (by omega) (by unfold capacity; omega) + · rw [co]; exact bankOk (B.val+k.val/n) (Nat.le_add_right ..) (by unfold capacity; omega) + · rw [cn]; exact bankOk (B.val+m+k.val%n) (by omega) (by unfold capacity; omega) + +open private stage_flat local_data from OAI.Computability.VPVNP.CompressorShrinkABSliceVisits +open private local_val from OAI.Computability.VPVNP.CompressorShrinkABSliceRecipe + +variable (I : Inputs) (pub : Fin 5 → Word w) (state : Word w) (ref : Memory w) +variable {t p : Fin 5 → Word w} (L : Layout t p rows m n first) (D : Describes I pub state ref t p rows first) + +/-- The four physical input rectangles and the interval banks are the only +regions from which this part of the calendar may read. -/ +structure ReadRegion (t p : Fin 5 → Word w) (rows m n first : ℕ) (data : ℕ → Prop) : Prop where + columns : ∀ (i : Fin rows) (c : Fin 4) j, j < (if c.val < 2 then m else n) → + data (((ShrinkABSliceTable.columns t p i.val) c).val+j) + bank : ∀ x, first ≤ x → x < first+rows*capacity m n → data x + +private theorem noRead {k : ℕ} (a : FlatRows.Public k w) (s : Word w) (mem : Memory w) : + Reads data (FlatRows.events (fun _ => false) a s mem) := by + intro x v h + simp [FlatRows.events,List.mem_flatMap,FlatRows.operandEvents] at h + +include L D + +private theorem row_log (region : ReadRegion t p rows m n first data) + (j : Stage m n) (i : Fin rows) (mem : Memory w) (cap : ℕ) (hcap : 95 ≤ cap) : + let v := stage I j + let P := (v.worker.table.instantiate w (fun k => (v.params k).eval pub state ref)).program + ∃ r, execute P cap (P.start (Fin.ofNat _ i.val)) mem [] = some r ∧ + r.result = some (Fin.ofNat _ (i.val+1)) ∧ Reads data r.events := by + let B := bank (w := w) first m n i.val + have bounds (x) (lo : B.val ≤ x) (hi : x < B.val+capacity m n) : data x := by + have hv : B.val = first+i.val*capacity m n := bank_val L i + have hn := Nat.mul_le_mul_right (capacity m n) i.isLt + rw [Nat.succ_mul] at hn + exact region.bank x (by omega) (by omega) + have source : + let M := j.pass.table.instantiate w (j.data t p i first) + ∃ r, execute M.program j.fuel (M.program.start (j.localIdx : Word w)) mem [] = some r ∧ + r.result.isSome ∧ Reads data r.events := by + cases j <;> apply core_log (columns t p i.val) B (space L i) (region.columns i) bounds _ mem + obtain ⟨r,run,ret,rd⟩ := source + rw [stage_flat] + let args := evaluated pub state ref (j.affineParams I) j.localIdx + let s : Word w := i.val + let P := ((FlatRows.compile j.pass.table (fun _ => false)).instantiate w args).program + have exe := FlatRows.execute_flat j.pass.table (fun _ => false) args s mem [] j.fuel + dsimp only at exe + rw [local_data I pub state ref L D j i mem,local_val pub state ref (j.affineParams I) j.localIdx s mem, + run,Option.map_some] at exe + have lim : j.fuel+(3+7*(j.pass.params+1)) ≤ cap := by cases j <;> dsimp [Stage.fuel,Stage.pass] <;> omega + have ok := execute_extend exe (cap-(j.fuel+(3+7*(j.pass.params+1)))) + rw [Nat.add_sub_of_le lim] at ok + refine ⟨_,ok,?_,?_⟩ + · have hx : r.result.map (fun _ => s+1) = some (s+1) := by + cases h : r.result <;> simp [h] at ret ⊢ + apply hx.trans + change some ((i.val : Word w)+1) = some ((i.val+1 : ℕ) : Word w) + push_cast; rfl + · intro x v h + rcases List.mem_append.mp h with h|h + · exact noRead args s mem x v h + · exact rd x v h + +/-- The real global-bundle cursor advances from zero to the planned stop. +Its emitted events read only the actual columns and bank rectangles. -/ +theorem source_progress_reads (region : ReadRegion t p rows m n first data) (limit : rows < 2^w) + (j : Stage m n) (cap : ℕ) (hcap : 95 ≤ cap) (mem : Memory w) (rs : List (Report w)) + (src : Source I pub state ref rows cap j mem rs) : + SourceOnline.Progress (Fin.ofNat _ rows) 0 rs ∧ Reads data (eventLog rs) := by + let v := stage I j + let P := (v.worker.table.instantiate w (fun k => (v.params k).eval pub state ref)).program + have loop (k len : ℕ) (span : k+len = rows) (s : Memory w) (xs : List (Report w)) + (h : runSegment P cap (some (Fin.ofNat _ k)) s (List.replicate len []) = some xs) : + SourceOnline.Progress (Fin.ofNat _ rows) (Fin.ofNat _ k) xs ∧ Reads data (eventLog xs) := by + induction len generalizing k s xs with + | zero => + obtain rfl := (Option.some.inj h).symm + exact ⟨.done (by simp_all),fun _ _ h => by simp [eventLog] at h⟩ + | succ len ih => + let i : Fin rows := ⟨k,by omega⟩ + obtain ⟨r,exec,ret,rd⟩ := row_log I pub state ref L D region j i s cap hcap + change execute P cap (P.start (Fin.ofNat _ k)) s [] = some r at exec + simp only [List.replicate_succ,runSegment,exec,ret] at h + obtain ⟨more,tail,rfl⟩ := Option.map_eq_some_iff.mp h + obtain ⟨progress,reads⟩ := ih (k+1) (by omega) _ _ tail + have live : Fin.ofNat (2^w) k < Fin.ofNat _ rows := by + change k%(2^w) < rows%(2^w) + rw [Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt limit]; omega + refine ⟨.next live ret progress,fun x v h => ?_⟩ + rcases List.mem_append.mp h with hr|ht + · exact rd x v hr + · exact reads x v ht + exact loop 0 rows (Nat.zero_add _) mem rs src + +end CompressorRecords.ShrinkABSliceRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceRecipe.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceRecipe.lean new file mode 100644 index 0000000000..01669f3508 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceRecipe.lean @@ -0,0 +1,198 @@ +import OAI.Computability.VPVNP.CompressorFlatRowWorker +import OAI.Computability.VPVNP.CompressorShrinkABSliceTable + +/-! +# Whole-level calendar visits for the shrinking AB slice bank + +Each fixed field count or rank pair contributes one catalog visit. The global +cursor ranges over assigned bundles. Register operands are computed from +that ordinal and the level's four sorted width/offset heads. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkABSliceRecipe + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM PhaseRecipe BlockPlanner +open IndexedStarts ShrinkABSliceTable SliceRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- Layout scalars read by the online planner. -/ +structure Inputs where + /-- Recipe expression for the number of bundle rows visited in each whole-level AB scan. -/ + rows : Expr + /-- Base-address expression of the old thick fields' starting offsets. -/ + oldStarts : Expr + /-- Base-address expression of the sorted old thick-field widths. -/ + oldWidths : Expr + /-- Distance in words between consecutive bundle rows of the old width and start columns. -/ + oldStride : Expr + /-- Base-address expression of the starting offsets of the new AB pieces. -/ + newStarts : Expr + /-- Base-address expression of the new AB piece widths. -/ + newWidths : Expr + /-- Distance in words between consecutive bundle rows of the AB width and start columns. -/ + newStride : Expr + /-- Recipe expression for the address of the first bundle's intersection and + endpoint-reference bank. -/ + firstBank : Expr + +/-- Global-row address and stride of one local operand. All AB reads use +direct affine operands, so the worker prologue itself uses zero probes. -/ +abbrev Affine := Expr × Expr + +/-- Represent a constant flat-row operand by its literal base and a zero bundle stride. -/ +def constant (x : ℕ) : Affine := (.lit x,.lit 0) +/-- An operand at a fixed offset inside each bundle's AB bank, with the full bank capacity as +its inter-bundle stride. -/ +def bankField (I : Inputs) (m n off : ℕ) : Affine := (I.firstBank.add (.lit off),.lit (capacity m n)) + +/-- Encode the local affine operands and fixed field cursor as flat-row prologue parameters, +with a base, stride and zero bias for each. -/ +def arguments {k : ℕ} (localParams : Fin k → Affine) (cursor : ℕ) : Fin (FlatRows.Params k) → Expr := + fun j => + let digit := finProdFinEquiv.symm j + let e := Fin.snoc (α := fun _ => Affine) localParams (constant cursor) digit.1 + ![e.1,e.2,.lit 0] digit.2 + +/-- Compile a local AB worker into a visit that scans every bundle at one fixed local cursor. -/ +def flat {r p k : ℕ} (core : Template p r k) (I : Inputs) (par : Fin k → Affine) (cursor : ℕ) : Visit := + ⟨⟨_,_,_,FlatRows.compile core (fun _ => false)⟩,.lit 0,I.rows,arguments par cursor⟩ + +/-- The per-bundle base address from which the clearing worker zeros the endpoint counts. -/ +def clearParams (I : Inputs) (m n : ℕ) : Fin 1 → Affine := fun _ => bankField I m n 0 + +/-- Operands for computing a field-pair intersection, including the new field count, both +width/start column pairs, and the frame destination. -/ +def pairParams (I : Inputs) (m n : ℕ) : Fin 6 → Affine := + ![constant n,(I.oldStarts,I.oldStride),(I.oldWidths,I.oldStride),(I.newStarts,I.newStride), + (I.newWidths,I.newStride),bankField I m n (m+n)] + +/-- The field counts, intersection frames, endpoint counts and reference arrays used to link +positive intersections into the two directories. -/ +def refParams (I : Inputs) (m n : ℕ) : Fin 7 → Affine := + ![constant n,constant m,bankField I m n (m+n),bankField I m n 0, + bankField I m n (m+n+3*(m*n)),bankField I m n m,bankField I m n (m+n+4*(m*n))] + +/-- One indexed whole-bundle scan that clears endpoint counts, computes an intersection frame +or appends its endpoint references. -/ +inductive Stage (m n : ℕ) + | clear (i : Fin (m+n)) + | pair (i : Fin (m*n)) + | refs (i : Fin (m*n)) + +/-- Select the clear, pair or reference worker and build its whole-level visit at the specified +local index. -/ +def stage {m n : ℕ} (I : Inputs) : Stage m n → Visit + | .clear i => flat (template clearOps 0) I (clearParams I m n) i.val + | .pair i => flat IndexedPair.table I (pairParams I m n) i.val + | .refs i => flat adjTemplate I (refParams I m n) i.val + +/-- The AB execution order, clearing every endpoint count before computing all field-pair +frames and then linking their references. -/ +def phases (m n : ℕ) : List (Stage m n) := + ((List.finRange (m+n)).map .clear ++ (List.finRange (m*n)).map .pair) ++ (List.finRange (m*n)).map .refs + +/-- The catalog visits implementing the complete AB schedule for the given input columns and +field counts. -/ +def visits (I : Inputs) (m n : ℕ) : List Visit := (phases m n).map (stage I) + +theorem visits_length (I : Inputs) (m n : ℕ) : (visits I m n).length = m+n+2*(m*n) := by + simp [visits,phases]; omega + +variable (I : Inputs) (pub : Fin 5 → Word w) (s : Word w) (mem : Memory w) + +/-- The recipe expressions evaluate to the actual row count, bank origin, and old and AB column +heads and strides. -/ +structure Describes (t p : Fin 5 → Word w) (rows first : ℕ) : Prop where + rowsAt : I.rows.eval pub s mem = (rows : Word w) + start : I.firstBank.eval pub s mem = (first : Word w) + oldStarts : I.oldStarts.eval pub s mem = t 3 + oldWidths : I.oldWidths.eval pub s mem = t 2 + oldStride : I.oldStride.eval pub s mem = t 1 + newStarts : I.newStarts.eval pub s mem = p 4 + newWidths : I.newWidths.eval pub s mem = p 3 + newStride : I.newStride.eval pub s mem = p 1 + +/-- The flat worker's concrete public words obtained by evaluating its affine parameter +expressions and fixed local index in the reference memory. -/ +def evaluated {k : ℕ} (par : Fin k → Affine) (localIdx : ℕ) : FlatRows.Public k w := + fun j => (arguments par localIdx j).eval pub s mem + + +private theorem affine {k : ℕ} (par : Fin k → Affine) (j : Fin k) (id : ℕ) (row : Word w) (m : Memory w) : + FlatRows.value (fun _ => false) (evaluated pub s mem par id) row m j.castSucc = + (par j).1.eval pub s mem+row*(par j).2.eval pub s mem := by + simp [FlatRows.value,FlatRows.addr,evaluated,arguments,FlatRows.field,Expr.eval] + +private theorem local_val {k : ℕ} (par : Fin k → Affine) (id : ℕ) (row : Word w) (m : Memory w) : + FlatRows.value (fun _ => false) (evaluated pub s mem par id) row m (Fin.last k) = (id : Word w) := by + simp [FlatRows.value,FlatRows.addr,evaluated,arguments,FlatRows.field,Expr.eval,constant] + +private theorem bank_add (B i cap offset : ℕ) : + (B : Word w)+(offset : Word w)+(i : Word w)*(cap : Word w) = Fin.ofNat _ (B+i*cap+offset) := by + change _ = ((B+i*cap+offset : ℕ) : Word w) + push_cast; ring + +variable {t p : Fin 5 → Word w} {rows first : ℕ} +variable (D : Describes I pub s mem t p rows first) +include D + +theorem clear_operands (m n id row : ℕ) (m' : Memory w) : + (fun j : Fin 1 => FlatRows.value (fun _ => false) (evaluated pub s mem (clearParams I m n) id) + (row : Word w) m' j.castSucc) = (fun _ => bank first m n row) := by + funext j + rw [affine] + change I.firstBank.eval pub s mem+0+(row : Word w)*((capacity m n : ℕ) : Word w) = _ + rw [D.start,add_zero] + change _ = ((first+row*capacity m n : ℕ) : Word w) + push_cast; rfl + +theorem pair_operands {m n : ℕ} (L : Layout t p rows m n first) (id : ℕ) (i : Fin rows) (m' : Memory w) : + (fun j : Fin 6 => FlatRows.value (fun _ => false) (evaluated pub s mem (pairParams I m n) id) + (i.val : Word w) m' j.castSucc) = IndexedStarts.pair (columns t p i.val) (bank first m n i.val) m n := by + funext j + rw [affine] + have hb := bank_val L i + fin_cases j + · simp [pairParams,constant,IndexedStarts.pair,Expr.eval] + · change I.oldStarts.eval pub s mem+_ * I.oldStride.eval pub s mem = Fin.ofNat _ ((t 3).val+i.val*(t 1).val) + rw [D.oldStarts,D.oldStride]; change _ = (((t 3).val+i.val*(t 1).val : ℕ) : Word w); push_cast; rfl + · change I.oldWidths.eval pub s mem+_ * I.oldStride.eval pub s mem = Fin.ofNat _ ((t 2).val+i.val*(t 1).val) + rw [D.oldWidths,D.oldStride]; change _ = (((t 2).val+i.val*(t 1).val : ℕ) : Word w); push_cast; rfl + · change I.newStarts.eval pub s mem+_ * I.newStride.eval pub s mem = Fin.ofNat _ ((p 4).val+i.val*(p 1).val) + rw [D.newStarts,D.newStride]; change _ = (((p 4).val+i.val*(p 1).val : ℕ) : Word w); push_cast; rfl + · change I.newWidths.eval pub s mem+_ * I.newStride.eval pub s mem = Fin.ofNat _ ((p 3).val+i.val*(p 1).val) + rw [D.newWidths,D.newStride]; change _ = (((p 3).val+i.val*(p 1).val : ℕ) : Word w); push_cast; rfl + · change I.firstBank.eval pub s mem+((m+n : ℕ) : Word w)+(i.val : Word w)*((capacity m n : ℕ) : Word w) = + Fin.ofNat _ ((bank (w := w) first m n i.val).val+m+n) + rw [D.start,hb,bank_add]; congr 1; omega + +theorem refs_operands {m n : ℕ} (L : Layout t p rows m n first) (id : ℕ) (i : Fin rows) (m' : Memory w) : + (fun j : Fin 7 => FlatRows.value (fun _ => false) (evaluated pub s mem (refParams I m n) id) + (i.val : Word w) m' j.castSucc) = IndexedStarts.adj (bank first m n i.val) m n := by + funext j + rw [affine] + have hb := bank_val L i + have fieldVal (o : ℕ) : (bankField I m n o).1.eval pub s mem+(i.val : Word w)*(bankField I m n o).2.eval pub s mem = + Fin.ofNat (2^w) ((bank (w := w) first m n i.val).val+o) := by + change I.firstBank.eval pub s mem+(o : Word w)+(i.val : Word w)*(capacity m n : Word w) = _ + rw [D.start,bank_add,hb] + fin_cases j + · change (n : Word w)+(i.val : Word w)*0 = Fin.ofNat _ n; simp + · change (m : Word w)+(i.val : Word w)*0 = Fin.ofNat _ m; simp + · apply (fieldVal (m+n)).trans; congr 1; omega + · apply (fieldVal 0).trans; exact Fin.ext (Nat.mod_eq_of_lt (bank (w := w) first m n i.val).isLt) + · apply (fieldVal (m+n+3*(m*n))).trans; congr 1; omega + · exact fieldVal m + · apply (fieldVal (m+n+4*(m*n))).trans; congr 1; omega + +end CompressorRecords.ShrinkABSliceRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceTable.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceTable.lean new file mode 100644 index 0000000000..82ac657816 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceTable.lean @@ -0,0 +1,312 @@ +import OAI.Computability.VPVNP.CompressorSliceIndexedStarts +import OAI.Computability.VPVNP.CompressorShrinkKernelSlices +import OAI.Computability.VPVNP.CompressorRecordsDemandWidths + +/-! +# All AB copy slices in the shrinking graph + +Each assigned bundle receives a contiguous bank. The three native scans +clear the endpoint counts, read both existing prefix columns to write +interval frames, and link positive frames into the two endpoint directories. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkABSliceTable + +open BurstRAM Compression Compression.PackingData BundleLists ShrinkSliceArrays +open IndexedStarts + +variable {w : ℕ} + +/-- Four source columns are packed by a common bundle ordinal, with +independent row strides for the old thick and the AB fields. -/ +def columns (thick ab : Fin 5 → Word w) (i : ℕ) : Fin 4 → Word w := + ![Fin.ofNat _ ((thick 3).val+i*(thick 1).val), Fin.ofNat _ ((thick 2).val+i*(thick 1).val), + Fin.ofNat _ ((ab 4).val+i*(ab 1).val), Fin.ofNat _ ((ab 3).val+i*(ab 1).val)] + +/-- The starting word address of bundle `i` in the consecutive AB banks, using the capacity for +`m` old and `n` new fields. -/ +def bank (first m n i : ℕ) : Word w := Fin.ofNat _ (first+i*capacity m n) + +/-- The AB banks fit in machine addresses, the two row strides accommodate their field counts, +and all four input columns end before the banks. -/ +structure Layout (thick ab : Fin 5 → Word w) (rows m n first : ℕ) : Prop where + fits : first+rows*capacity m n < 2^w + oldStride : m ≤ (thick 1).val + newStride : n ≤ (ab 1).val + oldWidths : (thick 2).val+rows*(thick 1).val ≤ first + oldStarts : (thick 3).val+rows*(thick 1).val ≤ first + newWidths : (ab 3).val+rows*(ab 1).val ≤ first + newStarts : (ab 4).val+rows*(ab 1).val ≤ first + +variable {thick ab : Fin 5 → Word w} {rows m n first : ℕ} +variable (L : Layout thick ab rows m n first) + +private theorem mul_step {i stride : ℕ} (hi : i < rows) : + i*stride+stride ≤ rows*stride := (Nat.succ_mul i stride) ▸ Nat.mul_le_mul_right stride hi + +include L + +theorem bank_val (i : Fin rows) : (bank (w := w) first m n i.val).val = first+i.val*capacity m n := by + have := mul_step (stride := capacity m n) i.isLt + exact Nat.mod_eq_of_lt (by have := L.fits; omega) + +theorem columns_val (i : Fin rows) : + let p := columns thick ab i.val + (p 0).val = (thick 3).val+i.val*(thick 1).val ∧ (p 1).val = (thick 2).val+i.val*(thick 1).val ∧ + (p 2).val = (ab 4).val+i.val*(ab 1).val ∧ (p 3).val = (ab 3).val+i.val*(ab 1).val := by + have := mul_step (stride := (thick 1).val) i.isLt + have := mul_step (stride := (ab 1).val) i.isLt + have := L.fits + obtain ⟨_,_,_,h₀,h₁,h₂,h₃⟩ := L + exact ⟨Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt (by omega), + Nat.mod_eq_of_lt (by omega),Nat.mod_eq_of_lt (by omega)⟩ + +private theorem before (i : Fin rows) (t : Fin 4) : + ((columns thick ab i.val) t).val+(if t.val < 2 then m else n) ≤ first := by + have := mul_step (stride := (thick 1).val) i.isLt + have := mul_step (stride := (ab 1).val) i.isLt + obtain ⟨h₀,h₁,h₂,h₃⟩ := columns_val L i + obtain ⟨_,s₀,s₁,b₀,b₁,b₂,b₃⟩ := L + fin_cases t + · change ((columns thick ab i.val) 0).val+m ≤ first + rw [h₀]; omega + · change ((columns thick ab i.val) 1).val+m ≤ first + rw [h₁]; omega + · change ((columns thick ab i.val) 2).val+n ≤ first + rw [h₂]; omega + · change ((columns thick ab i.val) 3).val+n ≤ first + rw [h₃]; omega + +theorem space (i : Fin rows) : + Space (columns thick ab i.val) (bank first m n i.val) m n := by + have := mul_step (stride := capacity m n) i.isLt + have h := bank_val L i + constructor + · rw [h]; have := L.fits; omega + · intro t; exact (before L i t).trans (by omega) + +omit L + +/-- Actual banks for all absolute bundle ordinals. -/ +inductive Runs (thick ab : Fin 5 → Word w) (first m n : ℕ) : + List (Fin rows) → Memory w → List (Report w) → Prop where + | nil (mem) : Runs thick ab first m n [] mem [] + | cons {i is mem rs ds} : + Native (columns thick ab i.val) (bank first m n i.val) m n mem rs → + Runs thick ab first m n is (after mem (eventLog rs.all)) ds → + Runs thick ab first m n (i::is) mem (rs.all++ds) + +/-- Row data in the final table. Only the cells of this row's bank are +consulted when following either endpoint directory. -/ +def Image (B : Word w) (old new : List ℕ) (out : Memory w) : Prop := + ∃ staged, IndexedStarts.Stored B old new staged ∧ + ∀ x, B.val ≤ x → x < B.val+capacity old.length new.length → out x = staged x + +theorem Image.stored {B : Word w} {old new : List ℕ} {out : Memory w} {input : Fin 4 → Word w} + (space : Space input B old.length new.length) (img : Image B old new out) : + IndexedStarts.Stored B old new out := by + obtain ⟨staged,stored,same⟩ := img + exact stored.transfer space same + +section Graph + +variable {V H Tag Lanes : Type} {d c nv : ℕ} +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype Lanes] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq Lanes] +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup Lanes] +variable (P : PackingData V H Tag Lanes d c) (site : Site V Tag Lanes ≃ Fin nv) +variable (width : Arc V H Tag Lanes d c → ℕ) (dd : P.ThickNumbering) (cd : P.BundleNumbering) + +local notation "ns" => 2^c*d/4 +local notation "nt" => pieceCount d c +local notation "ord" => portIndex site (d := d) + +set_option maxHeartbeats 600000 in +private theorem inputs (t u p : Fin 5 → Word w) (mem : Memory w) + (h : DemandWidths.Stored P site width dd cd t u p mem) + (l : Layout t p (nv*d) ns nt first) (i : Fin (nv*d)) : + let b := (ord).symm i + let src := thickWidths P dd width b + let dst := abWidths P cd width b + let B := bank (w := w) first ns nt i.val + SliceSchedule.Inputs (pair (columns t p i.val) B ns nt) src dst mem := by + intro b src dst B + have hb : ord b = i := (ord).apply_symm_apply _ + have hm : src.length = ns := List.length_ofFn + have hn : dst.length = nt := List.length_ofFn + obtain ⟨s₀,w₀,s₁,w₁⟩ := columns_val l i + let data := pair (columns t p i.val) B ns nt + constructor + · intro j hj + let k : Fin ns := ⟨j,hm ▸ hj⟩ + let a := (dd b).symm k + have read := h.thickStarts b a + rw [hb,show dd b a = k from (dd b).apply_symm_apply k] at read + have start := congrArg Field.start (fieldAt_ordered (dd b) (fun a : P.ThickFiber b => width a.1.1) a) + rw [show dd b a = k from (dd b).apply_symm_apply k] at start + change (src.take j).sum = _ at start + change (mem (((columns t p i.val) 0).val+j)).val = _ + rw [s₀,start]; exact read + · intro j hj + let k : Fin ns := ⟨j,hm ▸ hj⟩ + have read := h.thickWidths b k + rw [hb] at read + change (mem (((columns t p i.val) 1).val+j)).val = _ + rw [w₀]; simp only [src,thickWidths,orderedWidths,List.getElem_ofFn]; exact read + · intro j hj + let k : Fin nt := ⟨j,hn ▸ hj⟩ + let a := (cd b).symm k + have read := h.ab.starts b k + rw [hb] at read + have start := congrArg Field.start (fieldAt_ordered (cd b) (fun z : P.MotifFiber b => P.abWidth cd width z.1) a) + rw [show cd b a = k from (cd b).apply_symm_apply k] at start + change (dst.take j).sum = _ at start + change (mem (((columns t p i.val) 2).val+j)).val = _ + rw [s₁,start]; exact read + · intro j hj + let k : Fin nt := ⟨j,hn ▸ hj⟩ + have read := h.ab.widths b k + rw [hb] at read + change (mem (((columns t p i.val) 3).val+j)).val = _ + rw [w₁]; simp only [dst,abWidths,orderedWidths,List.getElem_ofFn]; exact read + +/-- Given the single snapshot produced by the native thick/CD and AB scans, +materialize every bundle's frame lengths, offsets and both endpoint directories +in a separate bank, leaving the complete input area intact. -/ +theorem graph_run (hc : 2 ≤ c) (hd : 0 < d) (t u p : Fin 5 → Word w) (initial : Memory w) + (h : DemandWidths.Stored P site width dd cd t u p initial) + (l : Layout t p (nv*d) ns nt first) (fit : ∀ b, P.bundleWidth width b < 2^w) : + ∃ rs, Runs t p first ns nt (List.finRange (nv*d)) initial rs ∧ + (∀ b, Image (bank first ns nt (ord b).val) (thickWidths P dd width b) (abWidths P cd width b) + (after initial (eventLog rs))) ∧ + (∀ x, x < first ∨ first+(nv*d)*capacity ns nt ≤ x → after initial (eventLog rs) x = initial x) ∧ + rs.length = (nv*d)*(ns+nt+2*(ns*nt)) ∧ + (rs.map Report.probes).sum ≤ (nv*d)*(ns+nt+14*(ns*nt)) ∧ + (rs.map fun r => r.events.length+1).sum ≤ (nv*d)*(8*(ns+nt)+74*(ns*nt)) := by + let old (i : Fin (nv*d)) := thickWidths P dd width ((ord).symm i) + let new (i : Fin (nv*d)) := abWidths P cd width ((ord).symm i) + let B (i : Fin (nv*d)) := bank (w := w) first ns nt i.val + let Q := capacity ns nt + have om (i) : (old i).length = ns := List.length_ofFn + have nm (i) : (new i).length = nt := List.length_ofFn + have outside (i : Fin (nv*d)) (x : ℕ) (hx : x < first ∨ first+(nv*d)*Q ≤ x) : + x < (B i).val ∨ (B i).val+Q ≤ x := by + have hv := bank_val l i + change (B i).val = first+i.val*Q at hv + have := mul_step (stride := Q) i.isLt + omega + have segment (is : List (Fin (nv*d))) (nd : is.Nodup) (mem : Memory w) + (same : ∀ x < first, mem x = initial x) : + ∃ rs, Runs t p first ns nt is mem rs ∧ + (∀ i ∈ is, Image (B i) (old i) (new i) (after mem (eventLog rs))) ∧ + (∀ x, (∀ i ∈ is, x < (B i).val ∨ (B i).val+Q ≤ x) → after mem (eventLog rs) x = mem x) ∧ + rs.length = is.length*(ns+nt+2*(ns*nt)) ∧ + (rs.map Report.probes).sum ≤ is.length*(ns+nt+14*(ns*nt)) ∧ + (rs.map fun r => r.events.length+1).sum ≤ is.length*(8*(ns+nt)+74*(ns*nt)) := by + induction is generalizing mem with + | nil => exact ⟨[],.nil _,by simp,fun _ _ => rfl,by simp,by simp,by simp⟩ + | cons i is ih => + let data := pair (columns t p i.val) (B i) ns nt + have ready := inputs P site width dd cd t u p initial h l i + have field (col : Fin 4) (j : ℕ) (hj : j < (if col.val < 2 then ns else nt)) : + mem (((columns t p i.val) col).val+j) = initial (((columns t p i.val) col).val+j) := by + have := before l i col + exact same _ (by omega) + have actual : SliceSchedule.Inputs data (old i) (new i) mem := by + constructor <;> intro j hj + · exact (congrArg Fin.val (field 0 j (om i ▸ hj))).trans (ready.oldStart j hj) + · exact (congrArg Fin.val (field 1 j (om i ▸ hj))).trans (ready.oldWidth j hj) + · exact (congrArg Fin.val (field 2 j (nm i ▸ hj))).trans (ready.newStart j hj) + · exact (congrArg Fin.val (field 3 j (nm i ▸ hj))).trans (ready.newWidth j hj) + have oldFit : (old i).sum < 2^w := (thickWidths_sum P dd width _).symm ▸ fit _ + have newFit : (new i).sum < 2^w := by + change (abWidths P cd width _).sum < _ + rw [abWidths,orderedWidths,List.sum_ofFn,(cd _).symm.sum_comp (fun z : P.MotifFiber _ => P.abWidth cd width z.1), + P.sum_abWidth hc hd cd width _]; exact fit _ + have sp : Space (columns t p i.val) (B i) (old i).length (new i).length := om i ▸ nm i ▸ space l i + obtain ⟨r,run,image,frame,cl,cp,ci⟩ := IndexedStarts.build (old i) (new i) (columns t p i.val) (B i) mem + sp oldFit newFit (om i ▸ nm i ▸ actual) + rw [om i,nm i] at run frame cl cp ci + let mid := after mem (eventLog r.all) + have nd' := List.nodup_cons.mp nd + obtain ⟨s,tail,images,tframe,tl,tp,ti⟩ := ih nd'.2 mid + (fun x hx => (frame x (outside i x (Or.inl hx))).trans (same x hx)) + have replay : after mem (eventLog (r.all++s)) = after mid (eventLog s) := by + simp only [mid,after,eventLog,List.flatMap_append,List.foldl_append] + refine ⟨r.all++s,.cons run tail,?_,?_,?_,?_,?_⟩ + · intro j hj + rw [replay] + rcases List.mem_cons.mp hj with rfl | hj + · refine ⟨mid,image,fun x hlo hhi => tframe x fun k hk => ?_⟩ + rw [om j,nm j] at hhi + have ne : j.val ≠ k.val := fun e => nd'.1 ((Fin.ext e).symm ▸ hk) + have hvj := bank_val l j + have hvk := bank_val l k + change (B j).val = first+j.val*Q at hvj + change (B k).val = first+k.val*Q at hvk + change x < (B j).val+Q at hhi + rcases lt_or_gt_of_ne ne with hlt | hlt + · have := mul_step (stride := Q) hlt; omega + · have := mul_step (stride := Q) hlt; omega + · exact images _ hj + · intro x hx + rw [replay,tframe x (fun k hk => hx k (List.mem_cons_of_mem _ hk))] + exact frame x (hx i List.mem_cons_self) + · rw [List.length_append,cl,tl,List.length_cons,Nat.add_mul,one_mul]; omega + · rw [List.map_append,List.sum_append,List.length_cons,Nat.add_mul,one_mul]; omega + · rw [List.map_append,List.sum_append,List.length_cons,Nat.add_mul,one_mul]; omega + obtain ⟨rs,run,imgs,frame,cl,cp,ci⟩ := segment (List.finRange _) (List.nodup_finRange _) initial (fun _ _ => rfl) + exact ⟨rs,run,fun b => by simpa only [old,new,Equiv.symm_apply_apply] using imgs (ord b) (by simp), + fun x hx => frame x (fun i _ => outside i x hx),by simpa using cl,by simpa using cp,by simpa using ci⟩ + +/-- Follow the exact frame of the old wire and motif at either packed +endpoint. Its offsets characterize the demand bit bijection used by both +`localAWord` and `localBWord`. -/ +theorem image_bits (hc : 2 ≤ c) (hd : 0 < d) (b : Port V Tag Lanes d) {B : Word w} {out : Memory w} + (img : Image B (thickWidths P dd width b) (abWidths P cd width b) out) + (a : P.ThickFiber b) (z : P.MotifFiber b) (x : Fin (width a.1.1)) + (y : Fin (P.abWidth cd width z.1)) : + let id := (dd b a).val*nt+(cd b z).val + let f := B.val+ns+nt+3*id + P.demandBitEquiv hc hd cd dd width b ⟨z,y⟩ = ⟨a,x⟩ ↔ + ∃ k < (out (f+2)).val, x.val = (out f).val+k ∧ y.val = (out (f+1)).val+k := by + intro id f + obtain ⟨staged,h,same⟩ := img + have om : (thickWidths P dd width b).length = ns := List.length_ofFn + have nm : (abWidths P cd width b).length = nt := List.length_ofFn + have hr : id < ns*nt := by + calc + _ < (dd b a).val*nt+nt := Nat.add_lt_add_left (cd b z).isLt _ + _ = ((dd b a).val+1)*nt := (Nat.succ_mul ..).symm + _ ≤ _ := Nat.mul_le_mul_right _ (dd b a).isLt + have hr' : id < (thickWidths P dd width b).length * (abWidths P cd width b).length := by + simpa only [om,nm] using hr + have eqn := ab_sliceAt P cd dd width b a z + have sameFrame (j : ℕ) (hj : j < 3) : out (f+j) = staged (f+j) := by + apply same + · dsimp [f]; omega + · rw [om,nm]; dsimp only [capacity,f]; omega + have len := h.lengths id hr' + rw [om,nm,eqn] at len + change (staged (f+2)).val = _ at len + rw [P.demandBitEquiv_eq_iff_slice cd dd width b hc hd,sameFrame 2 (by decide),len] + dsimp only + by_cases pos : 0 < (P.demandSlice cd dd width b a z).length + · obtain ⟨hs,ht⟩ := h.offsets id hr' (eqn ▸ pos) + rw [om,nm,eqn] at hs ht + change (staged f).val = _ at hs + change (staged (f+1)).val = _ at ht + rw [show out f = staged f from sameFrame 0 (by decide),sameFrame 1 (by decide),hs,ht] + · simp [show (P.demandSlice cd dd width b a z).length = 0 by omega] + +end Graph + +end CompressorRecords.ShrinkABSliceTable + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceVisits.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceVisits.lean new file mode 100644 index 0000000000..e996593142 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceVisits.lean @@ -0,0 +1,164 @@ +import OAI.Computability.VPVNP.CompressorShrinkABSliceRecipe +import OAI.Computability.VPVNP.CompressorShrinkABSliceProgress +import OAI.Computability.VPVNP.CompressorFlatRowScan +import OAI.Computability.VPVNP.LiveHeaderProtectedCore + +/-! # Native whole-bundle segments of the AB calendar -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkABSliceRecipe + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM BlockPlanner +open ShrinkABSliceTable IndexedStarts SliceRAM + +variable {w m n rows first : ℕ} + +/-- The local worker template executed at this AB stage before compilation into a whole-bundle +scan. -/ +def Stage.pass : Stage m n → Schedule.Pass + | .clear _ => ⟨_,_,_,template clearOps 0⟩ + | .pair _ => ⟨_,_,_,IndexedPair.table⟩ + | .refs _ => ⟨_,_,_,adjTemplate⟩ + +/-- The fixed endpoint or field-pair index that this stage processes at every bundle. -/ +def Stage.localIdx : Stage m n → ℕ | .clear i | .pair i | .refs i => i.val +/-- Local call fuel for an AB stage, with 8 steps for clearing, 38 for a field pair and 36 for +references. -/ +def Stage.fuel : Stage m n → ℕ | .clear _ => 8 | .pair _ => 38 | .refs _ => 36 + +/-- Select the clear, intersection or reference operand expressions for the stage's local +worker. -/ +def Stage.affineParams (I : Inputs) : (j : Stage m n) → Fin j.pass.params → Affine + | .clear _ => clearParams I m n + | .pair _ => pairParams I m n + | .refs _ => refParams I m n + +/-- The local worker's concrete operand words for a single bundle, using its actual input +columns and bank address. -/ +def Stage.data (t p : Fin 5 → Word w) (i : Fin rows) (first : ℕ) : (j : Stage m n) → Fin j.pass.params → Word w + | .clear _ => fun _ => bank first m n i.val + | .pair _ => IndexedStarts.pair (columns t p i.val) (bank first m n i.val) m n + | .refs _ => IndexedStarts.adj (bank first m n i.val) m n + +private theorem stage_flat (I : Inputs) (j : Stage m n) : + stage I j = flat j.pass.table I (j.affineParams I) j.localIdx := by cases j <;> rfl + +/-- Executing the stage's flat worker from zero with one empty choice stream per bundle +produces the specified source reports. -/ +def Source (I : Inputs) (pub : Fin 5 → Word w) (state : Word w) (ref : Memory w) (rows cap : ℕ) + (j : Stage m n) (mem : Memory w) (rs : List (Report w)) : Prop := + let v := stage I j + let M := v.worker.table.instantiate w (fun a => (v.params a).eval pub state ref) + runSegment M.program cap (some 0) mem (List.replicate rows []) = some rs + +variable (I : Inputs) (pub : Fin 5 → Word w) (state : Word w) (ref : Memory w) +variable {t p : Fin 5 → Word w} (L : Layout t p rows m n first) (D : Describes I pub state ref t p rows first) + +open scoped Fin.CommRing + +include L D + +private theorem local_data (j : Stage m n) (i : Fin rows) (mem : Memory w) : + (fun x : Fin j.pass.params => + FlatRows.value (fun _ => false) (evaluated pub state ref (j.affineParams I) j.localIdx) + (i.val : Word w) mem x.castSucc) = j.data t p i first := by + cases j with + | clear v => exact clear_operands I pub state ref D _ _ _ _ _ + | pair v => exact pair_operands I pub state ref D L _ _ _ + | refs v => exact refs_operands I pub state ref D L _ _ _ + +open private local_val from OAI.Computability.VPVNP.CompressorShrinkABSliceRecipe + +/-- Lifting one local instruction-table execution to the calendar's global +bundle cursor preserves its entire memory effect. -/ +theorem one (j : Stage m n) (i : Fin rows) (mem : Memory w) (cap : ℕ) (hcap : 95 ≤ cap) (r : Report w) + (run : let M := j.pass.table.instantiate w (j.data t p i first) + execute M.program j.fuel (M.program.start (j.localIdx : Word w)) mem [] = some r) + (ret : r.result.isSome) : + let v := stage I j + let P := (v.worker.table.instantiate w (fun a => (v.params a).eval pub state ref)).program + ∃ s, execute P cap (P.start (i.val : Word w)) mem [] = some s ∧ + s.result = some (Fin.ofNat _ (i.val+1)) ∧ after mem s.events = after mem r.events := by + rw [stage_flat] + let a := evaluated pub state ref (j.affineParams I) j.localIdx + let row : Word w := i.val + let t' := FlatRows.events (fun _ => false) a row mem + let flatProg := ((FlatRows.compile j.pass.table (fun _ => false)).instantiate w a).program + let s' : Report w := ⟨t'++r.events, some (row+1)⟩ + change ∃ s, execute flatProg cap (flatProg.start row) mem [] = some s ∧ _ ∧ _ + have ld := local_data I pub state ref L D j i mem + have result := FlatRows.execute_flat j.pass.table (fun _ => false) a row mem [] j.fuel + dsimp only at result + rw [ld,local_val pub state ref (j.affineParams I) j.localIdx row mem,run,Option.map_some] at result + have hs : r.result.map (fun _ => row+1) = some (row+1) := by + cases hr : r.result <;> simp [hr] at ret ⊢ + rw [hs] at result + have hlim : j.fuel+(3+7*(j.pass.params+1)) ≤ cap := by + cases j <;> dsimp [Stage.fuel,Stage.pass] <;> omega + have hdone := execute_extend result (cap-(j.fuel+(3+7*(j.pass.params+1)))) + rw [Nat.add_sub_of_le hlim] at hdone + refine ⟨s',hdone,?_,?_⟩ + · apply congrArg some + change (i.val : Word w)+1 = ((i.val+1 : ℕ) : Word w) + push_cast; rfl + · have hm := (FlatRows.events_cost (fun _ => false) a row mem).2.2.1 + change List.foldl update mem (t'++r.events) = _ + rw [List.foldl_append,show List.foldl update mem t' = mem from hm]; rfl + +omit D + +/-- Distinct bundle ordinals have disjoint output banks, including when the +fixed shape has zero occupied fields. -/ +theorem banks_disjoint {i j : Fin rows} (h : i ≠ j) (x : ℕ) + (hx : BankAt (bank (w := w) first m n i.val) m n x) : + ¬ BankAt (bank (w := w) first m n j.val) m n x := by + intro hy + have hn : i.val ≠ j.val := fun eqn => h (Fin.ext eqn) + simp only [BankAt,bank_val L i,bank_val L j] at hx hy + rcases lt_or_gt_of_ne hn with hlt | hlt + · have h := Nat.mul_le_mul_right (capacity m n) hlt + rw [Nat.succ_mul] at h; omega + · have h := Nat.mul_le_mul_right (capacity m n) hlt + rw [Nat.succ_mul] at h; omega + +include D + +/-- Every whole-level visit threads actual native reports through the banks +and preserves the shared inputs. -/ +theorem phase_run (j : Stage m n) (cap : ℕ) (hcap : 95 ≤ cap) + (shared : Memory w → Prop) (before done : Fin rows → Memory w → Prop) + (keepShared : ∀ i : Fin rows, ∀ mem out, shared mem → + (∀ x, ¬ BankAt (bank (w := w) first m n i.val) m n x → out x = mem x) → shared out) + (keepB : ∀ i mem out, before i mem → + (∀ x, BankAt (bank (w := w) first m n i.val) m n x → out x = mem x) → before i out) + (keepD : ∀ i mem out, done i mem → + (∀ x, BankAt (bank (w := w) first m n i.val) m n x → out x = mem x) → done i out) + (localStep : ∀ i : Fin rows, ∀ mem, shared mem → before i mem → + let M := j.pass.table.instantiate w (j.data t p i first) + ∃ r, execute M.program j.fuel (M.program.start (j.localIdx : Word w)) mem [] = some r ∧ + r.result.isSome ∧ done i (after mem r.events) ∧ + ∀ x, ¬ BankAt (bank (w := w) first m n i.val) m n x → after mem r.events x = mem x) + (mem : Memory w) (hs : shared mem) (hb : ∀ i, before i mem) : + ∃ rs, Source I pub state ref rows cap j mem rs ∧ shared (after mem (eventLog rs)) ∧ + ∀ i, done i (after mem (eventLog rs)) := by + let v := stage I j + let P := (v.worker.table.instantiate w (fun a => (v.params a).eval pub state ref)).program + have worker (i : Fin rows) (st : Memory w) (h₁ : shared st) (h₂ : before i st) : + ∃ r, execute P cap (P.start (Fin.ofNat _ i.val)) st [] = some r ∧ + r.result = some (Fin.ofNat _ (i.val+1)) ∧ shared (after st r.events) ∧ done i (after st r.events) ∧ + ∀ x, ¬ BankAt (bank (w := w) first m n i.val) m n x → after st r.events x = st x := by + obtain ⟨r,run,ret,hd,frame⟩ := localStep i st h₁ h₂ + obtain ⟨s,hr,hc,hm⟩ := one I pub state ref L D j i st cap hcap r run ret + exact ⟨s,hr,hc,hm ▸ keepShared i st _ h₁ frame,hm ▸ hd,hm ▸ frame⟩ + obtain ⟨rs,run,_,_,hs',hd,_⟩ := FlatRows.scan P cap rows shared (fun i => BankAt (bank first m n i.val) m n) + (banks_disjoint L) before done keepB keepD worker mem hs hb + exact ⟨rs,run,hs',hd⟩ + +end CompressorRecords.ShrinkABSliceRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceWindow.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceWindow.lean new file mode 100644 index 0000000000..6a858f338d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABSliceWindow.lean @@ -0,0 +1,108 @@ +import OAI.Computability.VPVNP.CompressorShrinkABSliceOperands +import OAI.Computability.VPVNP.CompressorBlockABSliceFootprint +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorScriptWindow +import OAI.Computability.VPVNP.CompressorBlockHeaderPacket + +/-! +# Native AB visits in the fixed shrinking script + +The AB section starts after the thirty-six demand and selection visits and +the twelve resident-list visits. Its scalar expressions read the current +level header before the scratch region. Every source stage therefore uses +the operands evaluated from its own chronological input memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.BlockSlices + +open BurstRAM PhaseRecipe BlockPlanner Compression ShrinkBlockInputs DescriptorSpace SourceTransport +open ShrinkABSliceRecipe +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) + +local notation "A" => BlockProgram.script B +local notation "F" => BlockProgram.geometry B +local notation "O" => BlockProgram.arena B i.val 0 +local notation "AB" => BlockProgram.arena B i.val 1 + +/-- The shrinking visits preceding the AB intersection window, including term selection and +construction of the resident lists. -/ +def preceding := + let chosen := selectedInputs B F i O + beforeSlices B F i O ++ ShrinkResidentsPlan.visits chosen (BlockProgram.arena B i.val 5) + (LevelFields.atLevel i.val) (ShrinkBundlePlan.absoluteCD i.val (a i) O) (a i) + +/-- The contiguous window of AB intersection visits in the fixed script for this shrinking +substep. -/ +abbrev abWindow : Window A (intersections i O AB) := BlockGroups.shrink B i 6 + +theorem preceding_length : (preceding B i).length = 48 := by + rw [preceding,List.length_append,beforeSlices_length,ShrinkResidentsPlan.visits_length] + +theorem abWindow_offset : (abWindow B i).before.length = (BlockIndex.earlier B i).length+48 := by + rw [abWindow,BlockGroups.shrink_offset,← preceding_length B i] + congr 2 + +variable {w : ℕ} {pub : Fin 5 → Word w} {state : Word w} {ref : Memory w} + +private theorem expr_agree (e : Expr) (D : ℕ → Prop) (start : ℕ) (mem : Memory w) + (ok : e.ReadsFrom (fun x => D x ∧ x < start) pub state ref) (same : Agree (· < start) ref mem) : + e.eval pub state ref = e.eval pub state mem ∧ e.ReadsFrom D pub state mem := by + induction e with + | lit | publicWord | state => exact ⟨rfl,trivial⟩ + | binary op x y ix iy => + obtain ⟨hx,rx⟩ := ix ok.1 + obtain ⟨hy,ry⟩ := iy ok.2 + exact ⟨congrArg₂ op.eval hx hy,rx,ry⟩ + | load x ih => + obtain ⟨hx,rx⟩ := ih ok.1 + exact ⟨(same _ ok.2.2).trans (congrArg (fun j : Word w => mem j.val) hx),rx,hx ▸ ok.2.1⟩ + +/-- A guarded whole-level run produces the precise operand and execution +contract of every member of the script window. -/ +theorem ab_header_walk {m n rows first : ℕ} (I : Inputs) (L : DescriptorSpace.Layout) + (D : ℕ → Prop) (start high : ℕ) (t p : Fin 5 → Word w) + (heads : Describes I pub state ref t p rows first) (low : levelStart L 0 ≤ start) + (ok : Supported (fun x => D x ∧ x start≤x ∧ x HeaderPacket.Run L pub state v cur logs 95 (List.replicate rows []) ∧ + HeaderOperands.Supported D pub state cur v) (js.map (stage I)) mem rs := by + induction walk with + | done => exact .done _ + | @next j js cur xs ys head tail ih => + obtain ⟨run,progress,rd,wr⟩ := head + let v := stage I j + have ops := stage_supported (fun x => D x ∧ x < start) pub state ref ok j + have first := expr_agree v.initial D start cur ops.initial same + have last := expr_agree v.stop D start cur ops.stop same + have args (k) := expr_agree (v.params k) D start cur (ops.params k) same + have init : v.initial.eval pub state cur = 0 := by cases j <;> rfl + have stop : v.stop.eval pub state cur = (rows : Word w) := last.1.symm.trans (by cases j <;> exact heads.rowsAt) + have he : (fun k => (v.params k).eval pub state ref) = (fun k => (v.params k).eval pub state cur) := + funext fun k => (args k).1 + have next : Agree (· < start) ref (after cur (eventLog xs)) := + fun x hx => (same x hx).trans (after_outside cur wr (fun h => (Nat.not_le_of_lt hx) h.1)).symm + refine .next ⟨⟨by decide,?_,?_,fun x a h => low.trans (rd x a h).1,fun x a h => low.trans (wr x a h).1⟩, + ⟨first.2,last.2,fun k => (args k).2⟩⟩ (ih next) + · change runSegment (v.worker.table.instantiate w (fun k => (v.params k).eval pub state cur)).program + 95 (some (v.initial.eval pub state cur)) cur (List.replicate rows []) = some xs + rw [init,← he]; exact run + · change SourceOnline.Progress (v.stop.eval pub state cur) (v.initial.eval pub state cur) xs + rw [init,stop]; exact progress + +end CompressorRecords.BlockSlices + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkABTraceReplay.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkABTraceReplay.lean new file mode 100644 index 0000000000..678fcb222a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkABTraceReplay.lean @@ -0,0 +1,89 @@ +import OAI.Computability.VPVNP.CompressorShrinkABSliceOperands +import OAI.Computability.VPVNP.CompressorScheduledSliceRates +import OAI.Computability.VPVNP.CompressorSourceObservableFrame + +/-! +# Replay of an admitted AB trace with another clock and header snapshot + +The flattened parameters depend only on the eight planner head values. +Thus the accepted deterministic trace is unique even when the graph +builder and the online packet maker use different source clocks or +equivalent saved header memories. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkABSliceRecipe + +open BurstRAM PhaseRecipe BlockPlanner +open scoped Fin.CommRing + +variable {w m n rows first : ℕ} {t p : Fin 5 → Word w} +variable {pub : Fin 5 → Word w} {state : Word w} {ref mem : Memory w} (I : Inputs) +local notation "eqWord" => fun e : Expr => Expr.eval pub state ref e = Expr.eval pub state mem e + +private theorem args_eq {k : ℕ} (par : Fin k → Affine) (cursor : ℕ) + (parEq : ∀ j, eqWord (par j).1 ∧ eqWord (par j).2) (j : Fin (FlatRows.Params k)) : + eqWord (arguments par cursor j) := by + let a := finProdFinEquiv.symm j + have all (i : Fin (k+1)) : let e := Fin.snoc (α := fun _ => Affine) par (constant cursor) i + eqWord e.1 ∧ eqWord e.2 := by + cases i using Fin.lastCases with + | last => simp only [Fin.snoc_last]; exact ⟨rfl,rfl⟩ + | cast j => simpa only [Fin.snoc_castSucc] using parEq j + let e := Fin.snoc (α := fun _ => Affine) par (constant cursor) a.1 + change eqWord (![e.1,e.2,.lit 0] a.2) + have pair := all a.1 + generalize a.2 = c + fin_cases c <;> first | exact pair.1 | exact pair.2 | rfl + +theorem params_eq (d : Describes I pub state ref t p rows first) (e : Describes I pub state mem t p rows first) + (j : Stage m n) (i : Fin (stage I j).worker.params) : eqWord ((stage I j).params i) := by + have bank (off : ℕ) : eqWord (bankField I m n off).1 ∧ eqWord (bankField I m n off).2 := + ⟨congrArg (·+(off : Word w)) (d.start.trans e.start.symm),rfl⟩ + cases j with + | clear k => exact args_eq (clearParams I m n) k.val (fun _ => bank 0) i + | pair k => + apply args_eq (pairParams I m n) k.val _ i + intro u; fin_cases u + exacts [⟨rfl,rfl⟩,⟨d.oldStarts.trans e.oldStarts.symm,d.oldStride.trans e.oldStride.symm⟩, + ⟨d.oldWidths.trans e.oldWidths.symm,d.oldStride.trans e.oldStride.symm⟩, + ⟨d.newStarts.trans e.newStarts.symm,d.newStride.trans e.newStride.symm⟩, + ⟨d.newWidths.trans e.newWidths.symm,d.newStride.trans e.newStride.symm⟩,bank (m+n)] + | refs k => + apply args_eq (refParams I m n) k.val _ i + intro u; fin_cases u + exacts [⟨rfl,rfl⟩,⟨rfl,rfl⟩,bank (m+n),bank 0,bank (m+n+3*(m*n)),bank m,bank (m+n+4*(m*n))] + +open private useFixedFuel abTotal from OAI.Computability.VPVNP.CompressorScheduledSliceRates + +private theorem short_walk (d : Describes I pub state ref t p rows first) (e : Describes I pub state mem t p rows first) + {js : List (Stage m n)} {s : Memory w} {rs : List (Report w)} {cap : ℕ} + (walk : SourceWalk (Source I pub state ref rows cap) js s rs) : SourceWalk + (fun j cur xs => Source I pub state mem rows (ScheduledRates.abFuel j) j cur xs) js s rs := by + induction walk with + | done => exact .done _ + | @next j _ cur xs _ h _ ih => + let P := stage I j + change runSegment (P.worker.table.instantiate w (fun k => (P.params k).eval pub state ref)).program cap + (some 0) cur (List.replicate rows []) = some xs at h + rw [show (fun k => (P.params k).eval pub state ref) = (fun k => (P.params k).eval pub state mem) from + funext (params_eq I d e j)] at h + exact .next (useFixedFuel _ (abTotal I j _) h) ih + +/-- Accepted native AB schedules with the same installed heads give the +same report list and memory endpoint, independently of the source cap. -/ +theorem walk_unique (d : Describes I pub state ref t p rows first) (e : Describes I pub state mem t p rows first) + {js : List (Stage m n)} {s : Memory w} {xs ys : List (Report w)} {c₁ c₂ : ℕ} + (a : SourceWalk (Source I pub state ref rows c₁) js s xs) + (b : SourceWalk (Source I pub state mem rows c₂) js s ys) : xs = ys := + SourceTransport.walk_deterministic (fun _ _ _ _ h g => Option.some.inj (h.symm.trans g)) + (short_walk I d e a) (short_walk I e e b) + +end CompressorRecords.ShrinkABSliceRecipe + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkAllocatedTables.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkAllocatedTables.lean new file mode 100644 index 0000000000..868bfe474d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkAllocatedTables.lean @@ -0,0 +1,202 @@ +import OAI.Computability.VPVNP.CompressorShrinkSelectedOutput +import OAI.Computability.VPVNP.CompressorBlockABSliceRun +import OAI.Computability.VPVNP.CompressorScheduledSliceRates + +/-! # Separate AB, surviving-width and ordered-slot tables in the physical block + +The block calendar builds the AB intersections before its four surviving +role scans. Each table has its own advised base address. The incidence +directory, endpoint lists, and both kinds of interval descriptors are +readable in the same final memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkOutput + +open Compression Compression.PackingData Compression.ShrinkMotif MotifBlocks MotifGrid +open BurstRAM PhaseRecipe ShrinkSliceSweep ShrinkBlockInputs SlotLevel ShrinkSlots +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} {δ : ℝ} (X : State (a i) (packingLaneBits (a i) g)) +variable (ready : Ready (2^(a i)) (Shrink.colors (a i)) (2^(b i)) δ) (sel : SelectedScore.Selection B X) +variable (term stride abs : Word w) (T : IncidenceDirectory w) (start : ℕ) + +local notation "sh" => levelShape (b := b i) X +local notation "role" => SelectedArena.roleBase X term stride +local notation "keepEnd" => SelectedFinish.stop X term stride +local notation "ns" => ShrinkBundlePlan.thickCount (a i) +local notation "nt" => ShrinkBundlePlan.cap (a i) +local notation "z" => ShrinkInput.plan X start +local notation "sitesOrd" => Shrink.packedIndex (a := a i) (g := g) X.baseIndex +local notation "thick" => ShrinkInput.thickBank X T start +local notation "cd" => ShrinkInput.cdBank X T start +local notation "pieces" => ShrinkInput.piecesBank X T start +local notation "chosenSide" => SelectedFinish.chosen B X sel +local notation "bankAt" => splitBank (b := b i) X B.shrink sel term stride.val role + +theorem old_bounds : + term.val+motifCount X*stride.val ≤ keepEnd ∧ role+4*absoluteCount X ≤ keepEnd ∧ + SelectedArena.origin X term stride+2 < keepEnd := by + have hc : motifCount X = SelectedArena.motifs X := + ((Fintype.card_congr (ShrinkMotifOrder.stateNumber X)).trans (Fintype.card_fin _)).symm + unfold SelectedFinish.stop SelectedFinish.rowStart SelectedFinish.countStart + SelectedArena.endAddr SelectedArena.roleBase SelectedArena.placementBase SelectedArena.origin + rw [hc] + unfold absoluteCount + omega + +/-- The requested width-table base is used exactly when the preceding +resident fields fit below it. -/ +theorem width_at_eq (width : ℕ) (low : keepEnd ≤ width) : widthBase X term.val stride.val role width = width := by + have h := old_bounds i X term stride + unfold widthBase + rw [max_eq_right (h.2.1.trans low),max_eq_right (h.1.trans low)] + +/-- Readbacks inherited by the AB and surviving-width workers from the +term, placement and preimage passes. -/ +structure Resident (width : ℕ) (mem : Memory w) : Prop where + demand : DemandWidths.Stored X.packingData sitesOrd X.packingWidth X.shrinkOrder X.shrinkNumber thick cd pieces mem + directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber abs mem + terms : Terms X.packingData X.shrinkNumber sitesOrd (bankAt width) B.shrink X.packingWidth sel mem + roles : DemandRAM.RoleColumns X chosenSide role mem + chosen : mem (SelectedArena.origin X term stride+2) = ((chosenSide).toNat : Word w) + preimages : ShrinkPreimages.Directory X chosenSide (SelectedFinish.counts X term stride) (SelectedFinish.rows X term stride) mem + +variable {F : DescriptorSpace.Shape} {origin abArena : Expr} {pub : Fin 5 → Word w} {state : Word w} {ref : Memory w} + +/-- Every assigned bundle's final bank stores the intersections between its old thick fields +and new AB pieces in the prescribed orders. -/ +abbrev ABFields (first : ℕ) (out : Memory w) := + ∀ bundle, IndexedStarts.Stored (ShrinkABSliceTable.bank first ns nt (BundleLists.portIndex sitesOrd bundle).val) + (ShrinkSliceArrays.thickWidths X.packingData X.shrinkOrder X.packingWidth bundle) + (ShrinkSliceArrays.abWidths X.packingData X.shrinkNumber X.packingWidth bundle) out + +/-- The successive reports of the AB phase and both output phases. -/ +structure TablesRun (w : ℕ) where + /-- Reports emitted by the initial AB intersection scans before construction of the surviving + and ordered-slot tables. -/ + intersections : List (Report w) + /-- The remaining shrinking passes after the AB intersections, including their final memory. -/ + remainder : Passes w + +/-- Replay the intersection reports on the input memory to obtain the starting memory of the +remaining passes. -/ +def TablesRun.postAB (r : TablesRun w) (mem : Memory w) := after mem (eventLog r.intersections) +/-- The complete report sequence, with the AB intersection scans followed by the remaining +table-building passes. -/ +def TablesRun.reports (r : TablesRun w) := r.intersections++r.remainder.reports +/-- The final memory of the remaining passes after the AB, surviving-width and ordered-slot +tables have been built. -/ +def TablesRun.final (r : TablesRun w) := r.remainder.final + +/-- The chronological AB and remaining passes build all three tables, preserve memory outside +the AB bank during its construction, and replay to the claimed final memory. -/ +structure CompleteTables (I : ShrinkABSliceRecipe.Inputs) (pub : Fin 5 → Word w) (state : Word w) (ref : Memory w) + (first width slotStart cap : ℕ) (mem : Memory w) (r : TablesRun w) : Prop where + abRun : SourceWalk (ShrinkABSliceRecipe.Source I pub state ref (z).B cap) (ShrinkABSliceRecipe.phases ns nt) + mem r.intersections + abFrame : ∀ x, x < first ∨ first+(z).B*IndexedStarts.capacity ns nt ≤ x → r.postAB mem x = mem x + remainder : Complete B X ready sel term stride abs cap (r.postAB mem) r.remainder width slotStart + abFields : ABFields i X first r.final + replay : after mem (eventLog r.reports) = r.final + +/-- The number of calls and probes includes the native AB work, all four +role scans, and the complete ordered-slot passes. -/ +theorem CompleteTables.cost {I : ShrinkABSliceRecipe.Inputs} {first width slotStart cap : ℕ} {mem : Memory w} + {r : TablesRun w} (h : CompleteTables B i X ready sel term stride abs start I pub state ref first width slotStart cap mem r) : + RAMBuckets.cost Report.probes r.reports ≤ (z).B*(2*(ns+nt)+16*(ns*nt)) + + (18*(motifCount X*(bankAt width).stride)+slotProbes sh) := by + have ab := ScheduledRates.scheduledABCounts I pub state ref h.abRun + exact (RAMBuckets.cost_append Report.probes r.intersections r.remainder.reports).le.trans + (Nat.add_le_add ab.2.1 h.remainder.probes.le) + +set_option maxHeartbeats 2400000 in +/-- Run the actual AB source visits, then the native surviving-role and slot +workers. The source memory may already contain the hidden history records. +Only established readbacks of its existing columns and selected terms are +needed. All three output tables are built from those inputs. -/ +theorem withAB (first width slotStart cap : ℕ) (mem : Memory w) + (level : ShrinkBundlePlan.Reads X F i.val origin pub state ref start T) + (arena : abArena.eval pub state ref = (first : Word w)) + (termRoom : ShrinkInput.termEnd X start stride.val < 2^w) (fresh : ShrinkInput.stop X start ≤ first) + (widthRoom : nt*X.maxWireWidth < 2^w) + (abAfter : keepEnd ≤ first) (widthAfter : first+(z).B*IndexedStarts.capacity ns nt ≤ width) + (slotAfter : (bankAt width).last ≤ slotStart) (slotRoom : finish sh (heads sh role slotStart) < 2^w) + (wide : 10 ≤ stride.val) (hw : FitsWords (b := b i) X B.shrink term stride.val role width) + (absBefore : abs.val+motifCount X ≤ keepEnd) + (resident : Resident B i X sel term stride abs T start width mem) + (abFuel : 95 ≤ cap) (sweepFuel : SurvivingNative.ops.length < cap) : + ∃ r, CompleteTables B i X ready sel term stride abs start (BlockSlices.abInputs i origin abArena) pub state ref + first width slotStart cap mem r := by + have lower : keepEnd ≤ width := abAfter.trans ((Nat.le_add_right first _).trans widthAfter) + have we := width_at_eq i X term stride width lower + have fit := fits X B.shrink sel term stride.val role width ready wide hw.room + have widthFit : width < 2^w := we ▸ (width_le_slots (b := b i) X term stride.val role width).trans_lt + ((slots_le_stop X term stride.val role width).trans_lt hw.room) + let abEnd := first+(z).B*IndexedStarts.capacity ns nt + have abRoom : abEnd < 2^w := widthAfter.trans_lt widthFit + obtain ⟨rows,walk,abFields,frame⟩ := BlockSlices.ab_run i X T start mem resident.demand level arena termRoom fresh abRoom widthRoom cap abFuel + let mid := after mem (eventLog rows) + have old (x : ℕ) (hx : x < keepEnd) : mid x = mem x := frame x (.inl (hx.trans_le abAfter)) + have hb := old_bounds i X term stride + have roleCopy : DemandRAM.RoleColumns X chosenSide role mid := by + have keep (arc) (j : ℕ) (hj : j < 4) : mid (role+4*(DemandRAM.absoluteIndex X arc).val+j) = mem (role+4*(DemandRAM.absoluteIndex X arc).val+j) := by + apply old + have hi := (DemandRAM.absoluteIndex X arc).isLt + change (DemandRAM.absoluteIndex X arc).val < absoluteCount X at hi + omega + constructor + · intro arc; rw [keep arc 3 (by decide)]; exact resident.roles.cd arc + · intro arc r; rw [keep arc (SlotOwners.roleOffset r) (by cases r <;> decide)]; exact resident.roles.packed arc r + have termsCopy : Terms X.packingData X.shrinkNumber sitesOrd (bankAt width) B.shrink X.packingWidth sel mid := by + apply terms_after B.shrink X term stride.val _ (sh).subdivisions sel mem mid resident.terms + intro j q hq b + have hd : b.val ≤ term.val+j.val*stride.val := Nat.mod_le .. + have hi := Nat.mul_le_mul_right stride.val j.isLt + rw [Nat.succ_mul] at hi + change j.val*stride.val+stride.val ≤ motifCount X*stride.val at hi + exact old _ ((show b.val+q < term.val+motifCount X*stride.val by omega).trans_le hb.1) + have ids : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber abs mid := by + intro j + exact (congrArg Fin.val (old _ ((Nat.add_lt_add_left j.isLt _).trans_le absBefore))).trans (resident.directory j) + obtain ⟨passes,done⟩ := build_at B X ready sel term stride abs mid width slotStart lower wide hw slotAfter slotRoom + absBefore ids termsCopy roleCopy ((old _ hb.2.2).trans resident.chosen) (preimages_retained X term stride resident.preimages old) cap sweepFuel + let r : TablesRun w := ⟨rows,passes⟩ + refine ⟨r,⟨walk,frame,done,?_,?_⟩⟩ + · intro bundle + let ix := BundleLists.portIndex sitesOrd bundle + let A := BlockSlices.ab_layout i X T start termRoom fresh abRoom + let oldRow := ShrinkSliceArrays.thickWidths X.packingData X.shrinkOrder X.packingWidth bundle + let newRow := ShrinkSliceArrays.abWidths X.packingData X.shrinkNumber X.packingWidth bundle + have olen : oldRow.length = ns := List.length_ofFn + have nlen : newRow.length = nt := List.length_ofFn + have room := ShrinkABSliceTable.space A ix + have stored := abFields bundle + apply stored.transfer (input := ShrinkABSliceTable.columns thick pieces ix.val) + · rwa [olen,nlen] + · intro x _ hx + have hv := ShrinkABSliceTable.bank_val A ix + have hi := Nat.mul_le_mul_right (IndexedStarts.capacity ns nt) ix.isLt + rw [Nat.succ_mul] at hi + change ix.val*IndexedStarts.capacity ns nt+IndexedStarts.capacity ns nt ≤ (z).B*IndexedStarts.capacity ns nt at hi + change x < (ShrinkABSliceTable.bank first ns nt ix.val : Word w).val+IndexedStarts.capacity oldRow.length newRow.length at hx + rw [olen,nlen,hv] at hx + apply done.construction.frame x (.inl ?_) + rw [we] + omega + · exact (show after mem (eventLog (rows++passes.reports)) = after mid (eventLog passes.reports) by + simp only [mid,after,eventLog,List.flatMap_append,List.foldl_append]).trans done.replay + +end CompressorRecords.ShrinkOutput + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBlockInputs.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBlockInputs.lean new file mode 100644 index 0000000000..11564881e6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBlockInputs.lean @@ -0,0 +1,108 @@ +import OAI.Computability.VPVNP.CompressorShrinkBundlePlan +import OAI.Computability.VPVNP.CompressorShrinkSelectedPlan +import OAI.Computability.VPVNP.CompressorShrinkSlotPlan +import OAI.Computability.VPVNP.CompressorBlockHeaderPlan + +/-! +# Connecting the shrinking passes to the fixed block + +A single persistent arena starts with the two greedy directories. The +ranked AB and CD inputs determine the fused motif worker's term addresses. +The stored terms determine the score, selected placement, arc roles and +child directory. All later slot visitors read the same common layout bit. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkBlockInputs + +open BurstRAM PhaseRecipe BlockPlanner Compression Compression.ShrinkMotif + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + (F : DescriptorSpace.Shape) (i : Fin S.steps) + +/-- The input degree exponent of this shrinking substep in the block schedule. -/ +abbrev a (i : Fin S.steps) := S.degreeExponent i.castSucc +/-- The degree exponent of the output level produced by this shrinking substep. -/ +abbrev b (i : Fin S.steps) := S.degreeExponent i.succ + +/-- Expression for the packed output site count, multiplying the base-vertex count by the tag +count and residual lane count. -/ +def newSites := (LevelFields.vertices i.val).mul + ((Expr.lit (2^(Shrink.J (a i)))).mul (LevelFields.residualLanes i.val)) + +/-- The fixed tag, degree, color and subdivision parameters used to build the ordered output +slots of this shrinking substep. -/ +def slotTemplate : ShrinkSlotPlan.Template := + let d := 2^(a i) + let c := Shrink.colors (a i) + let d' := 2^(b i) + ⟨2^(Shrink.J (a i)),d,c,subdivisions d c d',d'⟩ + +/-- The physical motif table has a grid index, a repetition count and eight +supply coordinates for the two layouts. -/ +def termVisits (origin : Expr) : List Visit := + let I := ShrinkBundlePlan.termInputs i.val (a i) origin + let count := ShrinkTermRecipe.count (a i) I + let src := ShrinkDemandGather.pass + let term := TermWorker.motifPass B.shrink finTwoEquiv 8 + [⟨src,.lit 0,count,ShrinkTermRecipe.gatherOperands (a i) I⟩, + ⟨term,.lit 0,count,TermWorker.motifExprs B.shrink finTwoEquiv SelectedScore.supplyOrder.entries + (ShrinkTermRecipe.termHeads (a i) 10 I)⟩] + +/-- The level sizes, term-record addresses, selector width and placement operands needed to +score and materialize a selected shrinking term. -/ +def selectedInputs (origin : Expr) : SelectedPlan.Inputs := + let I := ShrinkBundlePlan.termInputs i.val (a i) origin + ⟨LevelFields.sites i.val,newSites i,LevelFields.slots i.val,ShrinkTermRecipe.count (a i) I, + ShrinkTermRecipe.term (a i) I,10,B.shrink.selectorBits,ShrinkBundlePlan.placementParams F + i.val (a i) origin, + LevelFields.incidence F i.val 3⟩ + +/-- Role offsets, subdivision counts, cyclic successor and the append/sort +workspace occupy disjoint intervals of the slot arena. -/ +def slotInputs (origin slotArena : Expr) : ShrinkSlotPlan.Inputs := + let chosen := selectedInputs B F i origin + let cyclic := slotArena.add (.lit 8) + let subdiv := cyclic.add (newSites i) + ⟨LevelFields.vertices i.val,LevelFields.residualLanes i.val,SelectedPlan.roleBase chosen, + slotArena,subdiv,cyclic,subdiv.add (.lit 4)⟩ + +/-- The deterministic header and greedy visits, followed by bundle preparation, term choice and +selected placement before the slice scans. -/ +def beforeSlices (origin : Expr) : List Visit := + BlockHeaderPlan.substep F i.val (.shrink (a i) (b i)) ++ + GreedyLevelPlan.visits F i.val (a i) origin ++ ShrinkBundlePlan.visits F i.val (a i) origin ++ + termVisits B i origin ++ SelectedPlan.visits (selectedInputs B F i origin) (a i) + +/-- Generate the ordered output-slot visits using this substep's template, selected layout bit, +slot arena and split index. -/ +def slots (origin slotArena split : Expr) : List Visit := + ShrinkSlotPlan.visits (slotTemplate i) (slotInputs B F i origin slotArena) + (SelectedPlan.layout (selectedInputs B F i origin)) split F i.val + +theorem termVisits_length (origin : Expr) : (termVisits B i origin).length = 2 := rfl + +theorem beforeSlices_length (origin : Expr) : (beforeSlices B F i origin).length = 36 := by + simp only [beforeSlices, List.length_append, BlockHeaderPlan.substep_length, + GreedyLevelPlan.visits_length, + ShrinkBundlePlan.visits_length,termVisits_length,SelectedPlan.visits_length] + +theorem slots_length (origin slotArena split : Expr) : (slots B F i origin slotArena split).length + = 22 := + ShrinkSlotPlan.visits_length .. + +theorem slot_shape {g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) : + (slotTemplate i).shape (Fintype.card X.Base) (2^g) = ShrinkSlots.levelShape (b := b i) X := rfl + +end CompressorRecords.ShrinkBlockInputs + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBranchResident.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBranchResident.lean new file mode 100644 index 0000000000..852ef5bfd7 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBranchResident.lean @@ -0,0 +1,60 @@ +import OAI.Computability.VPVNP.CompressorShrinkABResident +import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch + +/-! # The resident shrink tables on a legal term branch + +The absolute-ID gather, term selection and selected geometry use the same +compact motif order. Their memory frames preserve the original demand columns +through the branch and the subsequent hidden-map writes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkOutput + +open Compression BurstRAM ShrinkBlockInputs +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X) +variable (T : IncidenceDirectory w) (start : ℕ) (stride selectors : Word w) (cap : ℕ) +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "ids" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w +local notation "keepEnd" => SelectedFinish.stop X (ShrinkInput.termHead (w := w) X start) stride + +set_option maxHeartbeats 1200000 in +/-- The legal native branch supplies every resident input for the allocated +AB, surviving-width and incidence-slot passes. -/ +theorem resident_of_branch {m : Memory w} (p : ShrinkBranch.Prefix X T start cap m) + (v : ShrinkBranch.Selected B X T start stride selectors cap m p sel) + (fit : ShrinkBranch.PrefixFits B X T start stride cap) (width : ℕ) (input : Memory w) + (hiddenFrame : ∀ x < keepEnd, input x = v.beforeOutput x) : + Resident B i X sel term stride ids T start width input := by + have room := fit.termRoom + unfold ShrinkInput.termEnd at room + have endRoom : ShrinkInput.stop X start < 2^w := by omega + have stopTerm : ShrinkInput.stop X start ≤ (term).val := by + change _ ≤ (_+_ : ℕ) % 2^w + rw [Nat.mod_eq_of_lt (by omega)] + omega + have hbound := old_bounds i X term stride + have stopEarly : ShrinkInput.stop X start ≤ keepEnd := by omega + have frame (x : ℕ) (hx : x < ShrinkInput.stop X start) : + input x = after p.input.post (eventLog p.absolute) x := + (hiddenFrame x (hx.trans_le stopEarly)).trans (v.lowerFrame x hx) + have stored := p.input.keepAbsoluteFrame endRoom p.absoluteRun.frame + have earlier := (ShrinkInput.termLayout X T start stride.val fit.termRoom).2.1 + have headLe : (ShrinkInput.demandHead (w := w) X start).val ≤ ShrinkInput.stop X start := Nat.mod_le .. + apply resident_from_geometry B i X sel term stride ids T start width selectors + (ShrinkInput.placementBank X T start) (after p.beforeTerm (eventLog v.terms)) input + v.geometry.placed v.geometry.children fit.wide v.postTerm.geometry hiddenFrame + (ShrinkDemandFrame.retain stored.stored earlier (fun x hx => frame x (hx.trans_le headLe))) + exact p.absoluteRun.directory_after p.input frame + +end CompressorRecords.ShrinkOutput + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundleAbsolute.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleAbsolute.lean new file mode 100644 index 0000000000..c009b12db0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleAbsolute.lean @@ -0,0 +1,157 @@ +import OAI.Computability.VPVNP.CompressorShrinkBundlePlan + +/-! +# Installing absolute motif identifiers after the width and AB scans + +The old gathered-key rectangle is available after ranking. The final scan +reads the retained classifier keys, owners and ranks, and replaces the two +halves of this rectangle with the thick auxiliary words and dense CD arc IDs. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkBundlePlan + +open BurstRAM PrimedStackRAM Compression Compression.PackingData BundleKeys BundleWidthScatter +open scoped Classical Fin.CommRing +open private offset_lt from OAI.Computability.VPVNP.CompressorRecordsBundleWidthScatter + +variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ} +variable {m : Memory w} (r : ShrinkInput.Run X T start m) + +local notation "Z" => ShrinkInput.plan X start +local notation "A" => ShrinkRankSpace.Shape.A (ShrinkInput.plan X start) +local notation "B" => ShrinkRankSpace.Shape.B (ShrinkInput.plan X start) +local notation "Q" => ShrinkRankSpace.Shape.Q (ShrinkInput.plan X start) +local notation "p" => absoluteBank Z w +local notation "cols" => MotifAbsolute.columns (absoluteBank Z w) +local notation "arcOrder" => BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex +local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex + +/-- The first absolute CD motif-ID address in the second half of the reused gathered-key +rectangle. -/ +def absoluteHead (z : ShrinkRankSpace.Shape) (w : ℕ) : Word w := Fin.ofNat _ (z.gathered+z.B*z.Q) + +/-- The old classifier and rank cells still contain the data for each original +outgoing port. The width and AB stages all ran above these addresses. -/ +theorem absolute_inputs (fit : (Z).stop < 2^w) : + MotifAbsolute.Inputs X.slots X.baseIndex p r.post X.shrinkNumber X.shrinkOrder := by + have val := (Z).values T (ShrinkInput.placementBank X T start) Fintype.card_pos fit + have space := absolute_layout X (start := start) fit + have endBefore (t : Fin 3) : (cols (t.castAdd 2)).val+A ≤ ShrinkInput.widthBase X start := by + change _ ≤ (Z).ranks+A + fin_cases t + · change (Fin.ofNat (2^w) (Z).owner).val+A ≤ _ + rw [show (Fin.ofNat (2^w) (Z).owner).val = _ from val.owner] + apply Nat.add_le_add_right + unfold ShrinkRankSpace.Shape.owner ShrinkRankSpace.Shape.ranks ShrinkRankSpace.Shape.gathered + ShrinkRankSpace.Shape.ids ShrinkRankSpace.Shape.counts + omega + · change (Fin.ofNat (2^w) (Z).ranks).val+A ≤ _ + rw [val.ranks] + · change (Fin.ofNat (2^w) (Z).key).val+A ≤ _ + rw [show (Fin.ofNat (2^w) (Z).key).val = _ from val.key] + apply Nat.add_le_add_right + unfold ShrinkRankSpace.Shape.key ShrinkRankSpace.Shape.ranks ShrinkRankSpace.Shape.gathered + ShrinkRankSpace.Shape.ids ShrinkRankSpace.Shape.counts + omega + have read (t : Fin 3) (e : OldArc X.Base a g) : + r.post (source cols t (arcWord arcOrder e)).val = + r.rankPost ((cols (t.castAdd 2)).val + (arcOrder e).val) := by + have hi : (arcOrder e).val < A := (arcOrder e).isLt + have hb := endBefore t + have hr := space.sourceFits t + rw [source,arcWord,Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt (by omega)] + exact r.afterRank _ (by omega) + constructor + · intro e; rw [read] + exact r.ranking.owners e + · intro e; rw [read] + by_cases h : X.packingData.thick (sourcePosition e) ∧ X.packingData.thick (sourcePosition (X.packingData.actual e)) + · let x : X.packingData.ThickFiber e.1 := ⟨⟨e,h⟩,rfl⟩ + rw [show rankOf X.packingData X.shrinkNumber X.shrinkOrder e = (X.shrinkOrder e.1 x).val from + rank_thick X.packingData X.shrinkNumber X.shrinkOrder x] + exact r.ranking.thick _ x + · let y : X.packingData.Motif := ⟨e,h⟩ + let x : X.packingData.MotifFiber (X.packingData.bundle y) := ⟨y,rfl⟩ + rw [show rankOf X.packingData X.shrinkNumber X.shrinkOrder e = (X.shrinkNumber _ x).val from + rank_motif X.packingData X.shrinkNumber X.shrinkOrder x] + exact r.ranking.motifs _ x + · intro e; rw [read] + have hk := r.ranking.ranked.keys e.val + rw [show BundleRAM.bothThick X.slots X.baseIndex e.val = false from decide_eq_false e.property] at hk + exact hk + +/-- Native absolute-ID scan, its exact charge, and the interval containing all writes. -/ +structure AbsoluteRun (rs : List (Report w)) : Prop where + native : runSegment ((template MotifAbsolute.visit 0).instantiate w p).program 25 (some 0) r.post + (List.replicate A []) = some rs + cursor : endState (some 0) rs = some (Fin.ofNat _ A) + count : rs.length = A + work : ∀ z ∈ rs, z.events.length = 24 ∧ z.probes = 4 + charge : RAMBuckets.cost Report.probes rs = 5*A + directory : MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber (absoluteHead Z w) + (after r.post (eventLog rs)) + frame : ∀ j, j < (Z).gathered ∨ (Z).ranks ≤ j → after r.post (eventLog rs) j = r.post j + +theorem run_absolute (fit : (Z).stop < 2^w) : ∃ rs, AbsoluteRun r rs := by + have layout := absolute_layout X (start := start) fit + have hinput := absolute_inputs r fit + have hv := (Z).values T (ShrinkInput.placementBank X T start) Fintype.card_pos fit + have scalars := (Z).scalarFits Fintype.card_pos fit + have hd : (p 5).val = 2^a := Nat.mod_eq_of_lt scalars.2.2.2.1 + have hl : (p 6).val = 2^g := Nat.mod_eq_of_lt scalars.2.2.2.2.1 + have stride : (cols 3).val = Q := hv.stride + have out : (cols 4).val = (Z).gathered := hv.gathered + have rect : (Z).gathered+(B+B)*Q = (Z).ranks := by + change (Z).gathered+(B+B)*Q = (Z).gathered+(2*B)*Q + rw [two_mul] + have room : (Z).ranks+A < 2^w := fit + have hhead : (absoluteHead Z w).val = (cols 4).val+B*Q := by + rw [out] + have h := Nat.le_add_left (B*Q) (B*Q) + rw [Nat.add_mul] at rect + exact Nat.mod_eq_of_lt (by omega) + obtain ⟨rs,hn,he,hf,hc,hw,charge,dir⟩ := MotifAbsolute.graph_run X.slots X.baseIndex + p r.post X.shrinkNumber X.shrinkOrder (absoluteHead Z w) layout hd hl stride hhead hinput + refine ⟨rs,hn,he,hc,hw,charge,dir,?_⟩ + let old := fun e ↦ (BundleWidthScatter.width cols r.post (arcWord arcOrder e)).val + have ranked : RankedInput X.packingData X.shrinkNumber X.shrinkOrder arcOrder sites cols r.post old := + ⟨hinput.owners,hinput.ranks,fun _ ↦ rfl⟩ + intro addr ha + apply hf.frame + intro i hi + let e := (arcOrder).symm ⟨i,hi⟩ + have he : (arcOrder e).val = i := congrArg Fin.val ((arcOrder).apply_symm_apply _) + have eqn := output_eq X.packingData X.shrinkNumber X.shrinkOrder arcOrder sites layout ranked e + have bound := offset_lt X.packingData X.shrinkNumber X.shrinkOrder sites layout e + unfold arcWord at eqn + rw [he,out,stride] at eqn + rw [stride] at bound + change _ < (B+B)*Q at bound + omega + +/-- A later demand gather or term selector preserves the absolute IDs by +preserving memory below the shrinking input endpoint. -/ +theorem AbsoluteRun.directory_after {rs : List (Report w)} (h : AbsoluteRun r rs) {out : Memory w} + (frame : ∀ j < ShrinkInput.stop X start, out j = after r.post (eventLog rs) j) : + MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber (absoluteHead Z w) out := by + intro i + have hi : i.val < B*Q := i.isLt + have head : (absoluteHead Z w).val ≤ (Z).gathered+B*Q := Nat.mod_le .. + have top : (Z).gathered+B*Q+B*Q = (Z).ranks := by + change (Z).gathered+B*Q+B*Q = (Z).gathered+(2*B)*Q + rw [two_mul,Nat.add_mul,Nat.add_assoc] + have last : (Z).ranks ≤ ShrinkInput.stop X start := by + change (Z).ranks ≤ (Z).ranks+A+6*(B*Q)+2*B + omega + rw [frame _ (by omega)] + exact h.directory i + +end CompressorRecords.ShrinkBundlePlan + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundleAccess.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleAccess.lean new file mode 100644 index 0000000000..babb60852a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleAccess.lean @@ -0,0 +1,233 @@ +import OAI.Computability.VPVNP.CompressorShrinkWidthFootprints +import OAI.Computability.VPVNP.CompressorShrinkBundleWalk + +/-! +# External accesses of the last five dense shrinking visits + +The width scatter, both prefixes, the AB pass and the absolute-ID scatter +have increasing ordinal cursors. Their concrete read and write intervals +are derived from the shrinking run's allocated physical columns. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkBundlePlan.Scheduled + +open BurstRAM Compression Compression.PackingData BundleWidthScatter ShrinkWidthFootprints +open SlotFillFootprint (InColumn) +open scoped Fin.CommRing Classical +open private offset_lt from OAI.Computability.VPVNP.CompressorRecordsBundleWidthScatter + +variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ} +variable {m : Memory w} (r : ShrinkInput.Run X T start m) + +local notation "Z" => ShrinkInput.plan X start +local notation "N" => Fintype.card X.Base +local notation "A" => ShrinkRankSpace.Shape.A (ShrinkInput.plan X start) +local notation "B" => ShrinkRankSpace.Shape.B (ShrinkInput.plan X start) +local notation "Q" => ShrinkRankSpace.Shape.Q (ShrinkInput.plan X start) +local notation "q" => ShrinkRankSpace.Shape.collectBank (ShrinkInput.plan X start) w +local notation "rankWord" => Fin.ofNat (2^w) (ShrinkRankSpace.Shape.ranks (ShrinkInput.plan X start)) +local notation "W" => ShrinkInput.widthBase X start +local notation "s" => ShrinkWidthArena.scatterBank T q rankWord W +local notation "t" => ShrinkWidthArena.prefixBank X T q rankWord W false +local notation "u" => ShrinkWidthArena.prefixBank X T q rankWord W true +local notation "ab" => ShrinkWidthArena.abBank X T q rankWord W +local notation "ap" => absoluteBank Z w +local notation "acols" => MotifAbsolute.columns (absoluteBank Z w) +local notation "arcOrder" => BundleKeys.oldArcOrder (a := a) (g := g) X.baseIndex +local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex +local notation "nSites" => (Fintype.card X.Base*(2^(Shrink.J a)*2^g) : ℕ) + +private theorem write_bound {p : Fin 5 → Word w} {mem : Memory w} {old : BundleKeys.OldArc X.Base a g → ℕ} + (layout : Layout p A nSites (2^a) (Shrink.colors a)) + (ranked : RankedInput X.packingData X.shrinkNumber X.shrinkOrder arcOrder sites p mem old) + (j : ℕ) (hj : j first | exact own | exact hr + have he : (arcOrder e).val < A := (arcOrder e).isLt + change ((s ((k.castAdd 1).castAdd 2)).val+((arcOrder e).val % (2^w))) % (2^w) < _ + exact (Nat.mod_le ..).trans_lt ((Nat.add_lt_add_left ((Nat.mod_le ..).trans_lt he) _).trans_le before) + let oldWidth := fun e ↦ (width s r.rankPost (arcWord arcOrder e)).val + have ranked : RankedInput X.packingData X.shrinkNumber X.shrinkOrder arcOrder sites s r.rankPost oldWidth := + ⟨fun e ↦ (keep 0 e).symm.trans (ai.owners e),fun e ↦ (keep 1 e).symm.trans (ai.ranks e),fun _ ↦ rfl⟩ + have wscan := width_scan s A B r.rankPost r.scatter layout.sourceFits (write_bound layout ranked) + (regions_of_layout X.packingData X.shrinkNumber X.shrinkOrder arcOrder sites layout ranked) r.widths.scatter + have aLayout := absolute_layout X (start := start) fit + let oldKey := fun e ↦ (width acols r.post (arcWord arcOrder e)).val + have aRanked : RankedInput X.packingData X.shrinkNumber X.shrinkOrder arcOrder sites acols r.post oldKey := + ⟨ai.owners,ai.ranks,fun _ ↦ rfl⟩ + have ascan := absolute_scan ap A B r.post abs aLayout.sourceFits (write_bound aLayout aRanked) + (regions_of_layout X.packingData X.shrinkNumber X.shrinkOrder arcOrder sites aLayout aRanked) last.native + have color : 2 ≤ Shrink.colors a := State.two_le_packingColors a + have starts : (s 4).val+2*(B*(s 3).val) ≤ ShrinkWidthArena.prefixBase X q W := by + rw [show (s 4).val = W from Nat.mod_eq_of_lt fit]; rfl + obtain ⟨prefixes,abLayout,abSize,_,_⟩ := DemandWidths.allocation s (ShrinkWidthArena.prefixBase X q W) + color (Nat.two_pow_pos a) layout starts endWidth + have th := prefix_scan t B prefixes.thick _ r.thickPrefixes r.widths.prefixes.thick.executed + have cd := prefix_scan u B prefixes.motif _ r.cdPrefixes r.widths.prefixes.motif.executed + have abCount : (ab 0).val = Q := abSize + have abScan := ab_scan ab B abLayout (ShrinkWidthArena.prefixedMemory r.rankPost r.scatter r.thickPrefixes r.cdPrefixes) + r.abPieces (by rw [abCount]; exact r.widths.ab) + have thCount : (t 0).val = thickCount a := prefixes.thickSize + have cdCount : (u 0).val = Q := prefixes.motifSize + rw [thCount] at th; rw [cdCount] at cd; rw [abCount] at abScan + exact ⟨wscan,th,cd,abScan,ascan⟩ + +private theorem checked_mono {num : ℕ} {rd wr rd' wr' : ℕ → Prop} {rs : List (Report w)} + (h : Checked num rd wr rs) (read : ∀ x, rd x → rd' x) (write : ∀ x, wr x → wr' x) : + Checked num rd' wr' rs := ⟨h.1,fun a v he ↦ read a.val (h.2.1 a v he),fun a v he ↦ write a.val (h.2.2 a v he)⟩ + +/-- All five write ranges lie inside the fresh shrinking arena. The only +earlier read range is the original arc-width column. -/ +theorem width_footprints {abs : List (Report w)} (last : AbsoluteRun r abs) + (lo : ℕ) (low : lo ≤ T.width.val) (room : ShrinkInput.stop X start < 2^w) : + let rd := fun x ↦ lo ≤ x ∧ x < ShrinkInput.stop X start + let wr := fun x ↦ start ≤ x ∧ x < ShrinkInput.stop X start + Checked A rd wr r.scatter ∧ Checked (B*thickCount a) rd wr r.thickPrefixes ∧ + Checked (B*Q) rd wr r.cdPrefixes ∧ Checked (B*Q) rd wr r.abPieces ∧ Checked A rd wr abs := by + let endAddr := ShrinkInput.stop X start + let K := B*Q + let ok (z len : ℕ) := start ≤ z ∧ z+len ≤ endAddr + have rr := ShrinkInput.range_bounds X start + have rankFit : (Z).stop < 2^w := rr.2.2.2.trans_lt room + have hv := (Z).values T (ShrinkInput.placementBank X T start) Fintype.card_pos rankFit + have wStart : start ≤ W := rr.1.trans (rr.2.1.trans rr.2.2.1) + have wHead : (s 4).val = W := Nat.mod_eq_of_lt rankFit + have wStride : (s 3).val = Q := hv.stride + have endEq : endAddr = W+6*K+2*B := rfl + have bound {z n x : ℕ} (hz : ok z n) (hx : InColumn z n x) : start ≤ x ∧ x < endAddr := + ⟨hz.1.trans hx.1,hx.2.trans_le hz.2⟩ + have head (z : ℕ) (hz : z ≤ endAddr) : (Fin.ofNat (2^w) z).val = z := Nat.mod_eq_of_lt (hz.trans_lt room) + have ownerLe : start ≤ (Z).owner := rr.1.trans rr.2.1 + have own : (Z).owner+A ≤ (Z).gathered := by + unfold ShrinkRankSpace.Shape.owner ShrinkRankSpace.Shape.gathered ShrinkRankSpace.Shape.ids ShrinkRankSpace.Shape.counts + omega + have key : (Z).key+A ≤ (Z).gathered := by + unfold ShrinkRankSpace.Shape.key ShrinkRankSpace.Shape.gathered ShrinkRankSpace.Shape.ids ShrinkRankSpace.Shape.counts + omega + have ownKey : (Z).key = (Z).owner+A := rfl + have rect : (Z).ranks = (Z).gathered+2*K := by + change (Z).gathered+(2*B)*Q = (Z).gathered+2*(B*Q) + rw [Nat.mul_assoc] + have wEq : W = (Z).ranks+A := rfl + have gHead : (acols 4).val = (Z).gathered := hv.gathered + have aStride : (acols 3).val = Q := hv.stride + have absoluteCols (i : Fin 3) : ok (acols (i.castAdd 2)).val A := by + fin_cases i + · change ok (Fin.ofNat (2^w) (Z).owner).val A; rw [head _ (by omega)]; change start ≤ _ ∧ (Z).owner+A ≤ endAddr; omega + · change ok (Fin.ofNat (2^w) (Z).ranks).val A; rw [head _ (by omega)]; change start ≤ _ ∧ (Z).ranks+A ≤ endAddr; omega + · change ok (Fin.ofNat (2^w) (Z).key).val A; rw [head _ (by omega)]; change start ≤ _ ∧ (Z).key+A ≤ endAddr; omega + have widthOut : ok (s 4).val ((B+B)*(s 3).val) := by rw [wHead,wStride,Nat.add_mul]; change start ≤ W ∧ W+(K+K) ≤ endAddr; omega + have absOut : ok (acols 4).val ((B+B)*(acols 3).val) := by rw [gHead,aStride,Nat.add_mul]; change start ≤ (Z).gathered ∧ (Z).gathered+(K+K) ≤ endAddr; omega + have pb : ShrinkWidthArena.prefixBase X q W = W+2*K := by rw [ShrinkWidthArena.prefixBase,hv.stride] + have abBase : ShrinkWidthArena.abBase X q W = W+2*K+2*K+2*B := by rw [ShrinkWidthArena.abBase,pb,hv.stride] + have prefixHead (b : Bool) (i : Fin 3) : + ((ShrinkWidthArena.prefixBank X T q rankWord W b) (i.natAdd 2)).val = + (![if b then W+K else W,if b then W+2*K+K else W+2*K, + if b then W+2*K+2*K+B else W+2*K+2*K] : Fin 3 → ℕ) i := by + cases b <;> fin_cases i + · change (Fin.ofNat (2^w) (s 4).val).val = W + rw [wHead]; exact head _ (by omega) + · change (Fin.ofNat (2^w) (ShrinkWidthArena.prefixBase X q W)).val = W+2*K + rw [pb]; exact head _ (by omega) + · change (Fin.ofNat (2^w) (ShrinkWidthArena.prefixBase X q W+2*(B*(s 3).val))).val = W+2*K+2*K + rw [pb,wStride]; exact head _ (by change W+2*K+2*K ≤ endAddr; omega) + · change (Fin.ofNat (2^w) ((s 4).val+B*(s 3).val)).val = W+K + rw [wHead,wStride]; exact head _ (by change W+K ≤ endAddr; omega) + · change (Fin.ofNat (2^w) (ShrinkWidthArena.prefixBase X q W+B*(s 3).val)).val = W+2*K+K + rw [pb,wStride]; exact head _ (by change W+2*K+K ≤ endAddr; omega) + · change (Fin.ofNat (2^w) (ShrinkWidthArena.prefixBase X q W+2*(B*(s 3).val)+B)).val = W+2*K+2*K+B + rw [pb,wStride]; exact head _ (by change W+2*K+2*K+B ≤ endAddr; omega) + have pr (b : Bool) (i : Fin 3) : ok ((ShrinkWidthArena.prefixBank X T q rankWord W b) (i.natAdd 2)).val + (if i.val=2 then B else K) := by + rw [prefixHead]; cases b <;> fin_cases i <;> simp [ok,endEq] <;> omega + have abHd : (ab 3).val = W+2*K+2*K+2*B := by + change (Fin.ofNat (2^w) (ShrinkWidthArena.abBase X q W)).val = _ + rw [abBase,head _ (by omega)] + have abOff : (ab 4).val = W+2*K+2*K+2*B+K := by + change (Fin.ofNat (2^w) (ShrinkWidthArena.abBase X q W+K)).val = _ + rw [abBase,head _ (by omega)] + have abStride : (ab 1).val = Q := hv.stride + have abOut (i : Fin 2) : ok (ab (i.natAdd 3)).val (B*(ab 1).val) := by + rw [abStride]; fin_cases i + · change ok (ab 3).val K; rw [abHd]; change start ≤ _ ∧ _ ≤ endAddr; omega + · change ok (ab 4).val K; rw [abOff]; change start ≤ _ ∧ _ ≤ endAddr; omega + have old := r.greedy.old 5 + change T.width.val+A ≤ start at old + have read {x : ℕ} (h : start ≤ x ∧ x < endAddr) : lo ≤ x ∧ x < endAddr := ⟨by omega,h.2⟩ + have prefixCoverage (b : Bool) : + let pp := ShrinkWidthArena.prefixBank X T q rankWord W b + (∀ x, prefixReads pp B x → lo ≤ x ∧ x < endAddr) ∧ + ∀ x, prefixWrites pp B x → start ≤ x ∧ x < endAddr := by + intro pp + have stride : (pp 1).val = Q := hv.stride + constructor + · intro x hx; apply read; rcases hx with h | h + · rw [stride] at h; exact bound (pr b 0) h + · exact bound (pr b 2) h + · intro x hx; rcases hx with h | h + · rw [stride] at h; exact bound (pr b 1) h + · exact bound (pr b 2) h + obtain ⟨ws,ts,us,bs,as⟩ := width_sources r last room + dsimp only + refine ⟨checked_mono ws ?_ (fun _ h ↦ bound widthOut h), + checked_mono ts (prefixCoverage false).1 (prefixCoverage false).2, + checked_mono us (prefixCoverage true).1 (prefixCoverage true).2, + checked_mono bs (fun _ h ↦ read (bound (pr false 2) h)) ?_, + checked_mono as ?_ (fun _ h ↦ bound absOut h)⟩ + · rintro x ⟨i,h⟩; fin_cases i + · exact read (bound (absoluteCols 0) h) + · exact read (bound (absoluteCols 1) h) + · change InColumn T.width.val A x at h + exact ⟨low.trans h.1,h.2.trans_le (old.trans (wStart.trans rr.2.2.2))⟩ + · rintro x ⟨i,h⟩; exact bound (abOut i) h + · rintro x ⟨i,h⟩; exact read (bound (absoluteCols i) h) + +end CompressorRecords.ShrinkBundlePlan.Scheduled + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundleCertificates.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleCertificates.lean new file mode 100644 index 0000000000..0bc377527d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleCertificates.lean @@ -0,0 +1,53 @@ +import OAI.Computability.VPVNP.CompressorShrinkBundleExecution +import OAI.Computability.VPVNP.CompressorShrinkBundleAccess +import OAI.Computability.VPVNP.CompressorShrinkPreparationAccess +import OAI.Computability.VPVNP.CompressorSourceWalkJoin + +/-! # Native shrinking source packets with their cursor and data certificates -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkBundlePlan.Scheduled + +open BurstRAM Compression PhaseRecipe ShrinkWidthFootprints + +variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ} +variable {m : Memory w} (r : ShrinkInput.Run X T start m) + +/-- The scheduled bundle stage has the stated source run and cursor limit, and its external +reads and writes stay within the respective shrinking regions. -/ +def Certified (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) (start lo : ℕ) + (shape : DescriptorSpace.Shape) (step : ℕ) (origin : Expr) (j : Stage) (mem : Memory w) + (rs : List (Report w)) : Prop := + Source X T start shape step origin j mem rs ∧ Checked (j.limit X start) + (fun x ↦ lo ≤ x ∧ x < ShrinkInput.stop X start) (fun x ↦ start ≤ x ∧ x < ShrinkInput.stop X start) rs + +/-- The sources and their actual footprints have the same report boundaries +throughout the eleven workers, including both prefix scans. -/ +theorem certified_sources (shape : DescriptorSpace.Shape) (step : ℕ) (origin : Expr) {abs : List (Report w)} + (last : AbsoluteRun r abs) (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) (room : ShrinkInput.stop X start < 2^w) : + SourceWalk (Certified X T start lo shape step origin) order r.greedy.post (preparationReports X T start r ++ abs) := by + have fit := (ShrinkInput.range_bounds X start).2.2.2.trans_lt room + have tail : SourceWalk (Source X T start shape step origin) [.absolute] r.post abs := .singleton last.native + rw [← preparation_post X T start r] at tail + have native := (preparation_sources shape step origin X T start r fit).append tail + let cert (j : Stage) (_ : Memory w) (rs : List (Report w)) := + Checked (j.limit X start) (fun x ↦ lo ≤ x ∧ x < ShrinkInput.stop X start) + (fun x ↦ start ≤ x ∧ x < ShrinkInput.stop X start) rs + have hc : SourceWalk cert order r.greedy.post (preparationReports X T start r ++ abs) := by + obtain ⟨sites,clear,cl,ap,ga,rk⟩ := r.preparation_footprints lo low room + obtain ⟨sw,tp,cp,ab,ac⟩ := width_footprints r last lo (low 5) room + simp only [preparationReports,order,preparationOrder,List.append_assoc,List.cons_append,List.nil_append] + exact .next sites (.next clear (.next cl (.next ap (.next ga (.next rk (.next sw (.next tp + (.next cp (.next ab (.singleton ac)))))))))) + apply SourceWalk.and_of_counts (Stage.limit X start) _ _ native hc + · exact fun _ _ _ hs ↦ source_calls shape step origin X T start hs + · exact fun _ _ _ hs ↦ hs.1.calls + +end CompressorRecords.ShrinkBundlePlan.Scheduled + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundleExecution.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleExecution.lean new file mode 100644 index 0000000000..9f726f801d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleExecution.lean @@ -0,0 +1,82 @@ +import OAI.Computability.VPVNP.CompressorShrinkBundleAbsolute +import OAI.Computability.VPVNP.CompressorShrinkBundleFrame +import OAI.Computability.VPVNP.CompressorShrinkBundleWalk + +/-! +# The eleven scheduled sources of the dense shrinking setup + +The ten setup scans begin at the completed greedy directory. The absolute-ID +scatter starts in their joint post-memory, leaving the typed old directory and +the sorted demand tables available for selection. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkBundlePlan.Scheduled + +open BurstRAM Compression PhaseRecipe + +variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ} +variable {m : Memory w} (r : ShrinkInput.Run X T start m) + +local notation "Z" => ShrinkInput.plan X start +local notation "S" => (Fintype.card X.Base * 2^(packingLaneBits a g) : ℕ) +local notation "A" => ShrinkRankSpace.Shape.A (ShrinkInput.plan X start) +local notation "B" => ShrinkRankSpace.Shape.B (ShrinkInput.plan X start) +local notation "Q" => ShrinkRankSpace.Shape.Q (ShrinkInput.plan X start) + +private theorem walk_charge {rs : List (Report w)} (abs : AbsoluteRun r rs) : + RAMBuckets.cost Report.probes (preparationReports X T start r ++ rs) = + 9*S+4*B+(Q+38)*A+4*(B*Q) := by + have sites := r.siteWork.cost + have clear := r.ranking.clearCharge + have rank := r.ranking.ranked.cost + have widths := r.widths.cost + change RAMBuckets.cost Report.probes r.sites = 9*S at sites + change RAMBuckets.cost Report.probes r.clear = 4*B at clear + change RAMBuckets.cost Report.probes r.classify + RAMBuckets.cost Report.probes r.append + + RAMBuckets.cost Report.probes r.gather + RAMBuckets.cost Report.probes r.rank = (Q+23)*A at rank + change RAMBuckets.cost Report.probes r.scatter + RAMBuckets.cost Report.probes r.thickPrefixes + + RAMBuckets.cost Report.probes r.cdPrefixes + RAMBuckets.cost Report.probes r.abPieces = 10*A+4*(B*Q) at widths + simp only [preparationReports,RAMBuckets.cost_append] + have last := abs.charge + rw [Nat.add_mul] at rank ⊢ + omega + +/-- Actual native sources from the first placement read through the last CD +identifier, with the physical state supplied to the demand and term workers. -/ +theorem dense_sources (shape : DescriptorSpace.Shape) (step : ℕ) (origin : Expr) + (room : ShrinkInput.stop X start < 2^w) : + ∃ rs, SourceWalk (Source X T start shape step origin) order r.greedy.post rs ∧ + let out := after r.greedy.post (eventLog rs) + ShrinkInput.Retained X T start out ∧ + MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber (absoluteHead Z w) out ∧ + RAMBuckets.cost Report.probes rs = 9*S+4*B+(Q+38)*A+4*(B*Q) ∧ + rs.length = S+2*B+7*A+B*Q ∧ + (∀ j, j < (Z).gathered ∨ (Z).ranks ≤ j → out j = r.post j) ∧ + ∀ next : Memory w, (∀ j < ShrinkInput.stop X start, next j = out j) → + MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber (absoluteHead Z w) next := by + have fit : (Z).stop < 2^w := by change (Z).stop+6*(B*Q)+2*B < _ at room; omega + obtain ⟨rs,abs⟩ := run_absolute r fit + have head := preparation_sources shape step origin X T start r fit + have run : Source X T start shape step origin .absolute r.post rs := abs.native + have tail := SourceWalk.singleton run + rw [← preparation_post X T start r] at tail + have full := head.append tail + refine ⟨_,full,?_⟩ + dsimp only + rw [SourceWalk.after_append,preparation_post] + refine ⟨r.keepAbsoluteFrame room abs.frame,abs.directory,walk_charge r abs,?_,abs.frame,fun _ keep ↦ abs.directory_after r keep⟩ + have size := full.report_count (Stage.limit X start) (fun _ _ _ source ↦ source_calls shape step origin X T start source) + have split := BundleKeys.bundle_rows_total (Fintype.card X.Base) a g + change B*thickCount a+B*Q = A at split + change _ = S+(2*B+(A+(A+(A+(A+(A+(B*thickCount a+(B*Q+(B*Q+(A+0)))))))))) at size + omega + +end CompressorRecords.ShrinkBundlePlan.Scheduled + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundleFrame.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleFrame.lean new file mode 100644 index 0000000000..b7da3d33c5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleFrame.lean @@ -0,0 +1,119 @@ +import OAI.Computability.VPVNP.CompressorShrinkInputTerms + +/-! +# Reusing the gathered-key rectangle + +After ranking, the sorted widths and their starts are above the gathered-key +rectangle. The old incidence, greedy assignments and preliminary placements +are below it. All these tables survive when the absolute motif directory +replaces the gathered keys. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkInput + +open BurstRAM Compression ShrinkRankSpace +open scoped Classical + +variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ} +local notation "Z" => plan X start +local notation "sh" => placementBank X T start +local notation "wb" => widthBase X start +local notation "thick" => thickBank X T start +local notation "cd" => cdBank X T start +local notation "ab" => piecesBank X T start + +/-- Physical readbacks still required after the absolute motif directory is written. -/ +structure Retained (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) (start : ℕ) (out : Memory w) : Prop where + incidence : T.Represents X out + placement : ShrinkRAM.PlacementColumns X.slots X.baseIndex (placementBank X T start) false out + directory : Shrink.Directory X.slots X.baseIndex + (ShrinkRAM.column (placementBank X T start) out 6) (ShrinkRAM.column (placementBank X T start) out 7) + (ShrinkRAM.column (placementBank X T start) out 8) (ShrinkRAM.column (placementBank X T start) out 9) + stored : ShrinkTermSelection.oldRows X (thickBank X T start) (cdBank X T start) (piecesBank X T start) out + +namespace Run + +variable {m : Memory w} (r : Run X T start m) + +private theorem keepGeometry {out : Memory w} (room : stop X start < 2^w) + (low : ∀ z < (Z).gathered, out z = r.post z) : + T.Represents X out ∧ ShrinkRAM.PlacementColumns X.slots X.baseIndex sh false out ∧ + Shrink.Directory X.slots X.baseIndex + (ShrinkRAM.column sh out 6) (ShrinkRAM.column sh out 7) + (ShrinkRAM.column sh out 8) (ShrinkRAM.column sh out 9) := by + obtain ⟨h₁,h₂,_,_⟩ := range_bounds X start + have hg : rankBase X start ≤ (Z).gathered := by + change rankBase X start ≤ rankBase X start+2*(Z).A+2*(Z).B+(Z).rectangleSize + omega + exact ⟨r.incidence.retain (fun c ↦ (r.greedy.old c).trans (h₁.trans (h₂.trans hg))) low, + (r.placement room).retain (fun t ↦ (pre_starts X T start room t).trans hg) low, + r.directory_before (fun z hz ↦ low z (hz.trans_le (h₂.trans hg)))⟩ + +theorem keepAbsoluteFrame {out : Memory w} (room : stop X start < 2^w) + (frame : ∀ z, z < (Z).gathered ∨ (Z).ranks ≤ z → out z = r.post z) : + Retained X T start out := by + have h₄ := (range_bounds X start).2.2.2 + obtain ⟨inc,place,dir⟩ := r.keepGeometry room (fun z h ↦ frame z (.inl h)) + refine ⟨inc,place,dir,?_⟩ + let B := (Z).B + let Q := (Z).Q + let q := Shape.collectBank (plan X start) w + let block := B*(q 4).val + have hv := (Z).values T sh Fintype.card_pos (h₄.trans_lt room) + have bs : block = B*Q := by change B*(q 4).val = _; rw [hv.stride] + have limit : wb+6*block+2*B < 2^w := bs.symm ▸ room + have rankBefore : (Z).ranks ≤ wb := Nat.le_add_right .. + have hbase : wb % (2^w) = wb := Nat.mod_eq_of_lt (by omega) + have t₂ : (thick 2).val = wb := by + change (wb % (2^w)) % (2^w) = wb + rw [hbase,hbase] + have c₂ : (cd 2).val = wb+block := by + change (wb % (2^w)+block) % (2^w) = wb+block + rw [hbase,Nat.mod_eq_of_lt (by omega)] + have t₃ : (thick 3).val = wb+2*block := + Nat.mod_eq_of_lt (show wb+2*block < 2^w by omega) + have c₃ : (cd 3).val = wb+2*block+block := + Nat.mod_eq_of_lt (show wb+2*block+block < 2^w by omega) + have a₃ : (ab 3).val = wb+2*block+2*block+2*B := + Nat.mod_eq_of_lt (show wb+2*block+2*block+2*B < 2^w by omega) + have a₄ : (ab 4).val = wb+2*block+2*block+2*B+B*Q := + Nat.mod_eq_of_lt (show wb+2*block+2*block+2*B+B*Q < 2^w by omega) + have keep (base i j : ℕ) (h : wb ≤ base) : + (out (base+i+j)).val = (r.post (base+i+j)).val := + congrArg Fin.val (frame _ (.inr (by omega))) + exact ⟨fun b i ↦ (keep _ _ _ t₂.ge).trans (r.stored.thickWidths b i), + fun b i ↦ (keep _ _ _ (by omega : wb ≤ (cd 2).val)).trans (r.stored.cdWidths b i), + fun b x ↦ (keep _ _ _ (by omega : wb ≤ (thick 3).val)).trans (r.stored.thickStarts b x), + fun b x ↦ (keep _ _ _ (by omega : wb ≤ (cd 3).val)).trans (r.stored.cdStarts b x), + ⟨fun b i ↦ (keep _ _ _ (by omega : wb ≤ (ab 3).val)).trans (r.stored.ab.widths b i), + fun b i ↦ (keep _ _ _ (by omega : wb ≤ (ab 4).val)).trans (r.stored.ab.starts b i)⟩⟩ + +/-- An absolute-ID pass can be followed by a demand or term pass which +writes into higher addresses. All the input readbacks still hold. -/ +theorem keepAbsoluteThenTerms {abs out : Memory w} + (frameAbs : ∀ z, z < (Z).gathered ∨ (Z).ranks ≤ z → abs z = r.post z) + (stride : ℕ) (room : termEnd X start stride < 2^w) + (frameTerms : ∀ z < stop X start, out z = abs z) : Retained X T start out := by + have endRoom : stop X start < 2^w := by unfold termEnd at room; omega + have lo : (Z).gathered ≤ stop X start := by + change (Z).gathered ≤ (Z).gathered+(Z).rectangleSize+(Z).A+6*((Z).B*(Z).Q)+2*(Z).B + omega + obtain ⟨inc,place,dir⟩ := r.keepGeometry endRoom fun z hz ↦ + (frameTerms z (hz.trans_le lo)).trans (frameAbs z (.inl hz)) + have absRows := (r.keepAbsoluteFrame endRoom frameAbs).stored + have earlier := (termLayout X T start stride room).2.1 + have hd : (demandHead (w := w) X start).val = stop X start := Nat.mod_eq_of_lt endRoom + rw [hd] at earlier + exact ⟨inc,place,dir,ShrinkDemandFrame.retain absRows earlier frameTerms⟩ + +end Run + +end CompressorRecords.ShrinkInput + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundleOperandSupport.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleOperandSupport.lean new file mode 100644 index 0000000000..53b4e4eb3e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleOperandSupport.lean @@ -0,0 +1,119 @@ +import OAI.Computability.VPVNP.CompressorShrinkGreedyPlannerSupport +import OAI.Computability.VPVNP.CompressorShrinkBundleWalk + +/-! # Header reads of the dense shrinking visits + +All eleven workers compute their cursor bounds and public operands from +the old level's scalars, incidence heads and first table head. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkBundlePackets + +open BurstRAM Compression BlockPlanner DescriptorSpace PhaseRecipe ShrinkBundlePlan +open scoped Fin.CommRing + +variable {w : ℕ} {D : ℕ → Prop} {pub : Fin 5 → Word w} {s : Word w} {m : Memory w} +local notation "R" => Expr.ReadsFrom D pub s m + +private theorem visit_reads (F : Shape) (step a : ℕ) (origin : Expr) + (vert : R (LevelFields.vertices step)) (degree : R (LevelFields.degree step)) + (lanes : R (LevelFields.lanes step)) (resid : R (LevelFields.residualLanes step)) + (inc : ∀ c : Fin 6, R (LevelFields.incidence F step c)) (base : R origin) + (j : Scheduled.Stage) : HeaderOperands.Supported D pub s m (j.visit F step a origin) := by + have sites : R (LevelFields.sites step) := ⟨vert,lanes⟩ + have slots : R (LevelFields.slots step) := ⟨sites,degree⟩ + have off : R (GreedyLevelPlan.offsetBase step a origin) := ⟨⟨base,vert⟩,vert,trivial⟩ + have shift : R (GreedyLevelPlan.shiftBase step a origin) := ⟨⟨off,vert⟩,vert,trivial⟩ + have pre : R (preliminary step a origin) := ⟨⟨shift,vert,degree⟩,trivial⟩ + have col (n : Fin 4) : R (placementColumn step a origin n) := ⟨pre,trivial,sites⟩ + have own : R (owner step a origin) := ⟨pre,trivial,sites⟩ + have keys : R (key step a origin) := ⟨own,slots⟩ + have cnt : R (counts step a origin) := ⟨own,trivial,slots⟩ + have b : R (bundles step a) := ⟨⟨vert,trivial,resid⟩,degree⟩ + have buckets : R (bucketCount step a) := ⟨trivial,b⟩ + have idHeads : R (ids step a origin) := ⟨cnt,buckets⟩ + have rect : R (rectangle step a) := ⟨buckets,trivial⟩ + have gather : R (gathered step a origin) := ⟨idHeads,rect⟩ + have rank : R (ranks step a origin) := ⟨gather,rect⟩ + have widths : R (sorted step a origin) := ⟨rank,slots⟩ + have block : R (blockSize step a) := ⟨b,trivial⟩ + have pref : R (prefixStart step a origin) := ⟨widths,trivial,block⟩ + have total : R (totalStart step a origin) := ⟨pref,trivial,block⟩ + have abHead : R (abStart step a origin) := ⟨total,buckets⟩ + cases j with + | positions => + refine ⟨trivial,sites,?_⟩ + intro n; change Fin 14 at n; fin_cases n + exacts [resid,trivial,degree,trivial,trivial,trivial,base,off,inc 0,inc 2, + col 0,col 1,col 2,col 3] + | clear => exact ⟨trivial,buckets,fun _ ↦ cnt⟩ + | classify => + refine ⟨trivial,slots,?_⟩ + intro n; change Fin 11 at n; fin_cases n + exacts [degree,resid,trivial,trivial,b,inc 3,col 1,col 0,col 2,own,keys] + | collect => + refine ⟨trivial,slots,?_⟩ + intro n; change Fin 6 at n; fin_cases n + exacts [slots,own,buckets,cnt,trivial,idHeads] + | gather => + refine ⟨trivial,slots,?_⟩ + intro n; change Fin 7 at n; fin_cases n + exacts [trivial,trivial,b,trivial,idHeads,keys,gather] + | rank => + refine ⟨trivial,slots,?_⟩ + intro n; change Fin 6 at n; fin_cases n + exacts [own,keys,gather,trivial,cnt,rank] + | scatter => + refine ⟨trivial,slots,?_⟩ + intro n; change Fin 5 at n; fin_cases n + exacts [own,rank,inc 5,trivial,widths] + | thickPrefix => + refine ⟨trivial,⟨b,trivial⟩,?_⟩ + intro n; change Fin 5 at n; fin_cases n + exacts [trivial,trivial,widths,pref,total] + | motifPrefix => + refine ⟨trivial,block,?_⟩ + intro n; change Fin 5 at n; fin_cases n + exacts [trivial,trivial,⟨widths,block⟩,⟨pref,block⟩,⟨total,b⟩] + | ab => + refine ⟨trivial,block,?_⟩ + intro n; change Fin 5 at n; fin_cases n + exacts [trivial,trivial,total,abHead,⟨abHead,block⟩] + | absolute => + refine ⟨trivial,slots,?_⟩ + intro n; change Fin 7 at n; fin_cases n + exacts [own,rank,keys,trivial,gather,degree,resid] + +/-- In each dense stage the pitch and the first 61 cells of the active +header suffice for all planner reads. -/ +theorem expr_reads {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + (i : Fin S.steps) {w g first start : ℕ} + {X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)} + {T : IncidenceDirectory w} {L : Layout} {pub : Fin 5 → Word w} {s : Word w} {m : Memory w} + (h : ShrinkHeaderReads.Header i X T start L first m) (entry : LevelFields.Entry L first pub s m) + (D : ℕ → Prop) (pitch : D (pub 1 - 1).val) + (cells : ∀ n ≤ 60, D (levelStart L (first + i.val) + n)) + (j : Scheduled.Stage) : + HeaderOperands.Supported D pub s m (j.visit (BlockProgram.geometry B) i.val + (ShrinkBlockInputs.a i) (BlockProgram.arena B i.val 0)) := by + have field (n : ℕ) (hn : n ≤ 60) : (LevelFields.scalar i.val n).ReadsFrom D pub s m := + GreedyVisit.scalar_support D L first i.val n entry pitch (cells n hn) + ((Nat.add_le_add_left hn _).trans_lt h.room) + exact visit_reads (BlockProgram.geometry B) i.val (ShrinkBlockInputs.a i) + (BlockProgram.arena B i.val 0) (field 0 (by decide)) (field 1 (by decide)) + (field 2 (by decide)) (field 3 (by decide)) + (fun c => field (54+c.val) (by have := c.isLt; omega)) (field 60 le_rfl) j + +end CompressorRecords.ShrinkBundlePackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundlePackets.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundlePackets.lean new file mode 100644 index 0000000000..1f684da362 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundlePackets.lean @@ -0,0 +1,214 @@ +import OAI.Computability.VPVNP.CompressorBlockIndex +import OAI.Computability.VPVNP.CompressorScriptWindow +import OAI.Computability.VPVNP.CompressorSourceScanned +import OAI.Computability.VPVNP.CompressorShrinkBundleCertificates + +/-! +# Dense shrinking packets at their global block-program ordinals + +The window starts after the three header visits and six greedy visits of +the selected shrinking substep. Each packet uses the corresponding worker +table, physical bank and number of empty choice tapes from the native run. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkBundlePackets + +open BurstRAM BlockPlanner Compression ShrinkBundlePlan SourceOnline DescriptorSpace +open ShrinkBundlePlan.Scheduled (Stage) +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) + +/-- The fixed block-program geometry used to locate the shrinking bundle's level headers and +operand tables. -/ +abbrev shape := BlockProgram.geometry B +/-- The scratch-table-zero address expression used as the origin of bundle preparation in this +substep. -/ +abbrev origin := BlockProgram.arena B i.val 0 +/-- The input degree exponent selecting the dimensions of this substep's bundle workers. -/ +abbrev exponent := ShrinkBlockInputs.a i +/-- The planned catalog visits for the eleven dense bundle stages at this shrinking substep. -/ +abbrev entries := ShrinkBundlePlan.Scheduled.order.map (Stage.visit (shape B) i.val (exponent i) (origin B i)) +private abbrev earlier := BlockHeaderPlan.substep (shape B) i.val (.shrink (exponent i) (ShrinkBlockInputs.b i)) ++ + GreedyLevelPlan.visits (shape B) i.val (exponent i) (origin B i) + +private theorem substep_split : ∃ suffix, BlockProgram.shrink B i = earlier B i ++ entries B i ++ suffix := by + unfold BlockProgram.shrink ShrinkBlockInputs.beforeSlices earlier entries + rw [ShrinkBundlePlan.Scheduled.order_visits] + simp only [List.append_assoc] + exact ⟨_,rfl⟩ + +/-- Locate all dense bundle visits together in the fixed block, after the header and greedy +passes and before later shrinking work. -/ +def window : Window (BlockProgram.script B) (entries B i) where + before := BlockIndex.earlier B i ++ earlier B i + after := (substep_split B i).choose ++ BlockIndex.later B i + block := by + have h := congrArg (fun xs ↦ BlockIndex.earlier B i ++ xs ++ BlockIndex.later B i) (substep_split B i).choose_spec + exact (BlockIndex.split_block B i).trans (h.trans (by simp only [List.append_assoc])) + +/-- The ordered bundle stages from preliminary placement to the absolute motif-ID scan. -/ +abbrev stages := ShrinkBundlePlan.Scheduled.order +local notation "A" => BlockProgram.script B + +/-- Reindex a stage's position in the bundle order as a position in the matching visit list. -/ +abbrev localIndex (j : Fin stages.length) : Fin (entries B i).length := Fin.cast (by simp [entries,stages]) j + +/-- The global script index of the bundle stage at the given position in this substep's window. -/ +def index (j : Fin stages.length) : Fin (A).size := (window B i).index (localIndex B i j) + +theorem index_visit (j : Fin stages.length) : (A).visit (index B i j) = + (stages[j.val]).visit (shape B) i.val (exponent i) (origin B i) := by + simpa only [index,localIndex,entries,List.getElem_map,Fin.val_cast] using (window B i).visit (localIndex B i j) + +theorem ordinal (block : ℕ) (j : Fin stages.length) : + let ord := (A).initial.length+block*(A).block.length+(BlockIndex.earlier B i).length+9+j.val + (Schedule.Online.calendar (A).plan).phase ord = (index B i j).val ∧ + (Schedule.Online.calendar (A).plan).level ord = block := by + have nine : (earlier B i).length = 9 := rfl + have pos : ((window B i).position (localIndex B i j)).val = (BlockIndex.earlier B i).length+9+j.val := by + change (BlockIndex.earlier B i ++ earlier B i).length+j.val = _ + rw [List.length_append,nine] + have he := (A).block_phase block ((window B i).position (localIndex B i j)) + rw [pos] at he + simpa only [index,Window.index,Nat.add_assoc] using he + +variable {g w : ℕ} (X : State (exponent i) (packingLaneBits (exponent i) g)) (T : IncidenceDirectory w) (start : ℕ) +local notation "Z" => ShrinkInput.plan X start +local notation "worker" => Stage.visit (shape B) i.val (exponent i) (origin B i) + +/-- Build the source packet for one bundle stage with its global worker index, physical operand +bank, cursor range and empty choice tapes. -/ +def visit (j : Fin stages.length) : SourceOnline.Visit A w := + let s := stages[j.val] + let v := worker s + SourceOnline.Visit.ofWorker (index B i j) v.worker (congrArg BlockPlanner.Visit.worker (index_visit B i j)) + (v.worker.pcs-1) 0 (s.limit X start : Word w) + (s.bank X T start ∘ Fin.cast (s.params (shape B) i.val (exponent i) (origin B i))) (List.replicate (s.limit X start) []) + +theorem runs (j : Fin stages.length) (mem : Memory w) (rs : List (Report w)) + (h : ShrinkBundlePlan.Scheduled.Source X T start (shape B) i.val (origin B i) stages[j.val] mem rs) : + (visit B i X T start j).Runs mem rs := by + unfold visit + exact (SourceOnline.Visit.ofWorker_runs _ _ (congrArg BlockPlanner.Visit.worker (index_visit B i j)) _ _ _ _ _ mem rs).mpr h + +/-- Runtime expressions for the global occurrence give the physical packet's +two cursors and operand bank, including the cast from the catalog arity. -/ +theorem field_values (j : Fin stages.length) {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w} + (h : ShrinkBundlePlan.Reads X (shape B) i.val (origin B i) pub state mem start T) (fit : (Z).stop < 2^w) : + let v := visit B i X T start j + let raw := (A).visit (index B i j) + raw.initial.eval pub state mem = v.start ∧ raw.stop.eval pub state mem = v.stop ∧ + ∀ u, (raw.params u).eval pub state mem = v.params u := by + let s := stages[j.val] + let raw := worker s + have eq := index_visit B i j + have hstart : raw.initial.eval pub state mem = 0 := by cases hs : s <;> simp only [raw,hs] <;> rfl + have hstop := s.stop X h + have operands := s.operands X h fit + dsimp only + refine ⟨(congrArg (fun z : BlockPlanner.Visit ↦ z.initial.eval pub state mem) eq).trans hstart, + (congrArg (fun z : BlockPlanner.Visit ↦ z.stop.eval pub state mem) eq).trans hstop,?_⟩ + intro u + have atParam {v z : BlockPlanner.Visit} (eqn : v = z) (n : Fin v.worker.params) : + v.params n = z.params (Fin.cast (congrArg (fun x : BlockPlanner.Visit ↦ x.worker.params) eqn) n) := by + subst z; rfl + rw [atParam eq u] + exact congrFun operands _ + +private theorem limit_fit (j : Stage) (fit : (Z).stop < 2^w) : j.limit X start < 2^w := by + have scalars := (Z).scalarFits Fintype.card_pos fit + have sum := BundleKeys.bundle_rows_total (Fintype.card X.Base) (exponent i) g + change (Z).B*thickCount (exponent i)+(Z).B*(Z).Q = (Z).A at sum + have hf := scalars.1 + have hb := scalars.2.1 + cases j <;> first + | exact hf | exact hb | exact (Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _)).trans_lt hf + | change (Z).B*thickCount (exponent i) < 2^w; omega | change (Z).B*(Z).Q < 2^w; omega + +/-- A finite worker-fuel cap for this substep, independent of input length. -/ +def maxFuel : ℕ := Finset.univ.sup fun j : Fin stages.length ↦ (worker stages[j.val]).worker.pcs-1 + +theorem visit_checked (L : DescriptorSpace.Layout) (j : Fin stages.length) (mem : Memory w) (rs : List (Report w)) + (fit : (Z).stop < 2^w) (before : levelStart L 0 ≤ start) {cap : ℕ} + (clock : SourceOnline.scanCap A (maxFuel B i) ≤ cap) + (cert : ShrinkBundlePlan.Scheduled.Certified X T start (levelStart L 0) (shape B) i.val (origin B i) + stages[j.val] mem rs) : + SourceOnline.Checked A L cap ⟨visit B i X T start j,mem,rs⟩ := by + let stage := stages[j.val] + let pkt : SourceWalk.Packet (SourceOnline.Visit A w) w := ⟨visit B i X T start j,mem,rs⟩ + have fuel : pkt.stage.fuel = (worker stage).worker.pcs-1 := rfl + have positive : 0 < pkt.stage.fuel := by + rw [fuel]; cases stage <;> change 0 < _ + 2 - 1 <;> omega + have budget : pkt.stage.fuel ≤ maxFuel B i := Finset.le_sup (f := fun l : Fin stages.length ↦ (worker stages[l.val]).worker.pcs-1) + (Finset.mem_univ j) + obtain ⟨rc,dc⟩ := SourceOnline.scanCap_clocks (p := pkt) (maxFuel B i) budget clock + exact SourceOnline.Checked.ofScanned (p := pkt) positive rc dc (first := 0) rfl rfl (limit_fit i X start stage fit) + cert.2.1 cert.2.2.1 cert.2.2.2 (fun _ hx ↦ hx.1) (fun _ hx ↦ before.trans hx.1) + +theorem checked_walk (L : DescriptorSpace.Layout) {cap : ℕ} (clock : SourceOnline.scanCap A (maxFuel B i) ≤ cap) + {m : Memory w} (r : ShrinkInput.Run X T start m) {abs : List (Report w)} (last : AbsoluteRun r abs) + (room : ShrinkInput.stop X start < 2^w) (low : ∀ c, levelStart L 0 ≤ (T.column c).val) : + SourceWalk (fun v mem rs ↦ v.Runs mem rs ∧ SourceOnline.Checked A L cap ⟨v,mem,rs⟩ ∧ + SourceTransport.Writes (fun x ↦ start ≤ x ∧ x < ShrinkInput.stop X start) (eventLog rs)) + (List.ofFn (visit B i X T start)) r.greedy.post + (ShrinkBundlePlan.Scheduled.preparationReports X T start r ++ abs) := by + have raw := ShrinkBundlePlan.Scheduled.certified_sources r (shape B) i.val (origin B i) last (levelStart L 0) low room + have before : levelStart L 0 ≤ start := (low 5).trans ((Nat.le_add_right ..).trans (r.greedy.old 5)) + have fit := (ShrinkInput.range_bounds X start).2.2.2.trans_lt room + apply raw.mapAt + intro j mem rs h + exact ⟨runs B i X T start j mem rs h.1, visit_checked B i X T start L j mem rs fit before clock h,h.2.2.2⟩ + +private theorem packet_chain {script : Script} (L : DescriptorSpace.Layout) (cap low top : ℕ) + (first raw : Memory w) (ps : List (SourceWalk.Packet (SourceOnline.Visit script w) w)) + (prior : ∀ j < low, raw j = first j) + (chain : SourceWalk.Chronological (fun v mem rs ↦ v.Runs mem rs ∧ + SourceOnline.Checked script L cap ⟨v,mem,rs⟩ ∧ SourceTransport.Writes (fun j ↦ low ≤ j ∧ j < top) (eventLog rs)) + raw ps) : + SourceWalk.Chronological SourceOnline.Visit.Runs raw ps ∧ + ∀ p ∈ ps, SourceOnline.Checked script L cap p ∧ ∀ j < low, p.input j = first j := by + induction ps generalizing raw with + | nil => exact ⟨trivial,by simp⟩ + | cons p ps ih => + obtain ⟨atEntry,⟨run,check,writes⟩,tail⟩ := chain + have entry (j : ℕ) (hj : j < low) : p.input j = first j := (congrFun atEntry j).trans (prior j hj) + have next (j : ℕ) (hj : j < low) : p.output j = first j := + (SourceTransport.after_outside p.input writes (by omega : ¬ (low ≤ j ∧ j < top))).trans (entry j hj) + obtain ⟨chron,checked⟩ := ih p.output next tail + refine ⟨⟨atEntry,run,chron⟩,?_⟩ + intro pkt hp + rcases List.mem_cons.mp hp with rfl | h + · exact ⟨check,entry⟩ + · exact checked _ h + +/-- All global packets run on consecutive data memories. Each packet retains +the physical header, row-count cell and pitch whenever they precede the arena. -/ +theorem packets (L : DescriptorSpace.Layout) (cap : ℕ) (clock : SourceOnline.scanCap A (maxFuel B i) ≤ cap) + {m : Memory w} (r : ShrinkInput.Run X T start m) (abs : List (Report w)) (last : AbsoluteRun r abs) + (room : ShrinkInput.stop X start < 2^w) (low : ∀ c, levelStart L 0 ≤ (T.column c).val) : + ∃ ps : List (SourceWalk.Packet (SourceOnline.Visit A w) w), + ps.map SourceWalk.Packet.stage = List.ofFn (visit B i X T start) ∧ + ps.flatMap SourceWalk.Packet.reports = ShrinkBundlePlan.Scheduled.preparationReports X T start r ++ abs ∧ + SourceWalk.Chronological SourceOnline.Visit.Runs r.greedy.post ps ∧ + (∀ p ∈ ps, SourceOnline.Checked A L cap p ∧ ∀ j < start, p.input j = r.greedy.post j) ∧ + after r.greedy.post (eventLog (ps.flatMap SourceWalk.Packet.reports)) = after r.post (eventLog abs) := by + obtain ⟨ps,order,logs,chain⟩ := (checked_walk B i X T start L clock r last room low).packets + obtain ⟨chron,check⟩ := packet_chain L cap start (ShrinkInput.stop X start) r.greedy.post r.greedy.post ps + (fun _ _ ↦ rfl) chain + refine ⟨ps,order,logs,chron,check,?_⟩ + rw [logs,SourceWalk.after_append,ShrinkBundlePlan.Scheduled.preparation_post] + +end CompressorRecords.ShrinkBundlePackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundlePlan.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundlePlan.lean new file mode 100644 index 0000000000..ad8338888a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundlePlan.lean @@ -0,0 +1,466 @@ +import OAI.Computability.VPVNP.CompressorGreedyLevelPlan +import OAI.Computability.VPVNP.CompressorRecordsShrinkInput +import OAI.Computability.VPVNP.CompressorShrinkTermRecipe +import OAI.Computability.VPVNP.CompressorShrinkMotifAbsolute +import OAI.Computability.VPVNP.CompressorBundleSortedWidths +import OAI.Computability.VPVNP.CompressorSlicePreparation + +/-! +# Dense shrinking visits between greedy preparation and term selection + +The preliminary placement uses layout zero. Classification, append, gather +and rank work in the dyadic rank arena. After ranking, its gathered-key +rectangle becomes the absolute motif ID rectangle. Sorted widths, the two +prefixes and AB pieces occupy the consecutive width arena. The resulting +heads are the inputs to the motif demand and term planners. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkBundlePlan + +open BurstRAM BurstRAM.PrivateRAM Compression Compression.PackingData PhaseRecipe BlockPlanner +open scoped Fin.CommRing + +variable (step a : ℕ) (origin : Expr) + +/-- Number of thick fields per bundle, one quarter of the product of the color-word count and +the input degree. -/ +abbrev thickCount := 2^(Shrink.colors a) * 2^a / 4 +/-- Per-bucket capacity used throughout the shrinking rank and width rectangles at this degree +exponent. -/ +abbrev cap := ShrinkRankSpace.cap a + +/-- Compute the number of directed bundles from the base vertices, tag count, residual lanes +and input degree. -/ +def bundles := ((LevelFields.vertices step).mul ((Expr.lit (2^(Shrink.J a))).mul + (LevelFields.residualLanes step))).mul (LevelFields.degree step) + +/-- Address where preliminary placement begins, immediately after the greedy allocation. -/ +def preliminary := GreedyLevelPlan.greedyStop step a origin +/-- Base address of one of the four preliminary placement columns, each reserving one word per +old site. -/ +def placementColumn (j : Fin 4) := (preliminary step a origin).add + ((Expr.lit j.val).mul (LevelFields.sites step)) +/-- Start of the old-port owner column following the four preliminary site columns. -/ +def owner := (preliminary step a origin).add ((Expr.lit 4).mul (LevelFields.sites step)) +/-- Start of the classifier-key column following the owner word for every old port. -/ +def key := (owner step a origin).add (LevelFields.slots step) +/-- First address of the per-bucket counts, following the old-port owner and key columns. -/ +def counts := (owner step a origin).add ((Expr.lit 2).mul (LevelFields.slots step)) +/-- Number of rank buckets, with one thick and one motif bucket for every directed bundle. -/ +def bucketCount := (Expr.lit 2).mul (bundles step a) +/-- First address of the rectangle holding the appended old-port identifiers for the rank +buckets. -/ +def ids := (counts step a origin).add (bucketCount step a) +/-- Total words in a rank rectangle, multiplying the number of thick and motif buckets by their +common capacity. -/ +def rectangle := (bucketCount step a).mul (.lit (cap a)) +/-- Start of the gathered-key rectangle, reused for absolute identifiers once the ranks have +been computed. -/ +def gathered := (ids step a origin).add (rectangle step a) +/-- Start of the per-old-port rank column immediately following the gathered-key rectangle. -/ +def ranks := (gathered step a origin).add (rectangle step a) +/-- First address of the sorted thick and motif width rectangles, after the rank column. -/ +def sorted := (ranks step a origin).add (LevelFields.slots step) +/-- Words in one bundle-by-rank rectangle, for either the thick or the motif entries. -/ +def blockSize := (bundles step a).mul (.lit (cap a)) +/-- The expression for the CD absolute-ID rectangle head, one bundle-by-rank rectangle past the +gathered-key base. -/ +def absoluteCD := (gathered step a origin).add (blockSize step a) +/-- First address of the thick and motif prefix-offset rectangles, following both sorted-width +rectangles. -/ +def prefixStart := (sorted step a origin).add ((Expr.lit 2).mul (blockSize step a)) +/-- First address of the per-bundle totals for the thick and motif prefix scans. -/ +def totalStart := (prefixStart step a origin).add ((Expr.lit 2).mul (blockSize step a)) +/-- First address of the AB piece-width rectangle, following the per-bucket totals. -/ +def abStart := (totalStart step a origin).add (bucketCount step a) + +/-- Collect the level dimensions, sorted widths, capacity and AB piece head needed by the +shrinking demand and term recipes. -/ +def termInputs : ShrinkTermRecipe.Inputs := + ⟨LevelFields.vertices step,LevelFields.degree step,LevelFields.lanes step,LevelFields.residualLanes step, + sorted step a origin,.lit (cap a),abStart step a origin⟩ + +variable (shape : DescriptorSpace.Shape) + +/-- The original greedy labels, full base displacements and a fresh four-column +output. Only the preliminary use fixes the layout operand to zero. -/ +def placementParams (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : Fin 14 → Expr := + Fin.append (![LevelFields.residualLanes step,.lit (2^(Shrink.J a)),LevelFields.degree step, + .lit (2^(Shrink.colors a)),.lit (Shrink.colors a - 1),.lit 0, + origin,GreedyLevelPlan.offsetBase step a origin,LevelFields.incidence shape step 0, + LevelFields.incidence shape step 2] : Fin 10 → Expr) (placementColumn step a origin) + +/-- The classifier's eleven public operands, including level dimensions, old incidence, +preliminary placement columns and the owner and key destinations. -/ +def classifyParams (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : Fin 11 → Expr := + ![LevelFields.degree step,LevelFields.residualLanes step,.lit (2^(Shrink.J a)),.lit (2^(Shrink.colors a)), + bundles step a,LevelFields.incidence shape step 3,placementColumn step a origin 1,placementColumn step a origin 0, + placementColumn step a origin 2,owner step a origin,key step a origin] + +/-- Public operands for appending the old slots to their owner buckets, including counts, +capacity and the ID rectangle. -/ +def collectParams : Fin 6 → Expr := + ![LevelFields.slots step,owner step a origin,bucketCount step a,counts step a origin,.lit (cap a),ids step a origin] + +/-- Public operands for gathering the classified keys by bundle and rank, including the +thick-entry count and both rectangle heads. -/ +def gatherParams : Fin 7 → Expr := + ![.lit (thickCount a + cap a),.lit (thickCount a),bundles step a,.lit (cap a), + ids step a origin,key step a origin,gathered step a origin] + +/-- Public operands for finding each old port's rank from its owner, key, bucket count and the +gathered-key rectangle. -/ +def rankParams : Fin 6 → Expr := + ![owner step a origin,key step a origin,gathered step a origin,.lit (cap a),counts step a origin,ranks step a origin] + +/-- Public operands for scattering old incidence widths into the sorted rectangle at each +port's owner and rank. -/ +def widthParams (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : Fin 5 → Expr := + ![owner step a origin,ranks step a origin,LevelFields.incidence shape step 5,.lit (cap a),sorted step a origin] + +/-- Public operands for replacing gathered keys by absolute identifiers, using owner, rank, +key, degree and residual-lane data. -/ +def absoluteParams : Fin 7 → Expr := + ![owner step a origin,ranks step a origin,key step a origin,.lit (cap a),gathered step a origin, + LevelFields.degree step,LevelFields.residualLanes step] + +/-- Select the width, start-offset and total columns for either the thick or the motif prefix +scan, together with its field count and row stride. -/ +def prefixParams (motif : Bool) : Fin 5 → Expr := + let widths := sorted step a origin + let starts := prefixStart step a origin + let totals := totalStart step a origin + let advance (x : Expr) := if motif then x.add (blockSize step a) else x + ![.lit (if motif then cap a else thickCount a),.lit (cap a),advance widths,advance starts, + if motif then totals.add (bundles step a) else totals] + +/-- The AB piece worker's capacity, row stride, input total column and output heads for piece +widths and starts. -/ +def abParams : Fin 5 → Expr := + ![.lit (cap a),.lit (cap a),totalStart step a origin,abStart step a origin,(abStart step a origin).add (blockSize step a)] + +/-- Eleven chronological scans, each with its exact fixed instruction table, +return register, cursor bound and operand arity. -/ +def visits (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) : List Visit := + let fromZero {r k : ℕ} (code : List (PrimedStackRAM.Op r k)) (out : Fin r) (stop : Expr) (p : Fin k → Expr) := + ops code out (.lit 0) stop p + let A := LevelFields.slots step + [fromZero ShrinkRAM.visit 0 (LevelFields.sites step) (placementParams shape step a origin), + fromZero SliceRAM.clearOps 0 (bucketCount step a) (fun _ ↦ counts step a origin), + fromZero BundleRAM.visit 0 A (classifyParams shape step a origin), + fromZero collectPreimage 3 A (collectParams step a origin), + fromZero BundleGather.Fixed.visit 0 A (gatherParams step a origin), + fromZero (PortRankRAM.visit (cap a)) 0 A (rankParams step a origin), + fromZero BundleWidthScatter.visit 0 A (widthParams shape step a origin), + fromZero BundlePrefixRAM.visit 0 ((bundles step a).mul (.lit (thickCount a))) (prefixParams step a origin false), + fromZero BundlePrefixRAM.visit 0 (blockSize step a) (prefixParams step a origin true), + fromZero ABWidths.visit 0 (blockSize step a) (abParams step a origin), + fromZero MotifAbsolute.visit 0 A (absoluteParams step a origin)] + +theorem visits_length : (visits shape step a origin).length = 11 := rfl + +theorem operand_counts : (visits shape step a origin).map (fun v ↦ v.worker.params) = + [14,1,11,6,7,6,5,5,5,5,7] := rfl + + +section Readback + +variable {step a shape origin} {g w : ℕ} (X : State a (packingLaneBits a g)) +variable {pub : Fin 5 → Word w} {state : Word w} {m : Memory w} {T : IncidenceDirectory w} {start : ℕ} + +local notation "ev" => Expr.eval pub state m +local notation "N" => Fintype.card X.Base +local notation "S" => (Fintype.card X.Base * 2^(packingLaneBits a g) : ℕ) +local notation "Z" => ShrinkInput.plan X start +local notation "q" => ShrinkRankSpace.Shape.collectBank (ShrinkInput.plan X start) w +local notation "sh" => ShrinkInput.placementBank X T start +local notation "rankWord" => (Fin.ofNat (2^w) (ShrinkRankSpace.Shape.ranks (ShrinkInput.plan X start))) +local notation "W" => ShrinkInput.widthBase X start +local notation "scatter" => ShrinkWidthArena.scatterBank T q rankWord W +local notation "prefix" => ShrinkWidthArena.prefixBase X q W + +/-- Each expression in the setup uses the input level's published scalars and +the greedy arena already installed at the supplied origin. -/ +structure Reads (X : State a (packingLaneBits a g)) (shape : DescriptorSpace.Shape) (step : ℕ) + (origin : Expr) (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) + (start : ℕ) (T : IncidenceDirectory w) : Prop extends + GreedyLevelPlan.Reads shape step a origin pub state m (Fintype.card X.Base) g start T where + lanes : (LevelFields.lanes step).eval pub state m = ((2^(packingLaneBits a g) : ℕ) : Word w) + +variable (h : Reads X shape step origin pub state m start T) + +include h in +private theorem eval_sites : ev (LevelFields.sites step) = (S : Word w) := by + change ev (LevelFields.vertices step)*ev (LevelFields.lanes step) = _ + rw [h.vertices,h.lanes,Nat.cast_mul] + +include h in +private theorem eval_slots : ev (LevelFields.slots step) = ((Z).A : Word w) := by + change ev (LevelFields.sites step)*ev (LevelFields.degree step) = ((S*2^a : ℕ) : Word w) + simp only [eval_sites X h,h.degree,Nat.cast_mul] + +include h in +private theorem eval_bundles : ev (bundles step a) = ((Z).B : Word w) := by + change (ev (LevelFields.vertices step)*(((2^(Shrink.J a) : ℕ) : Word w)*ev (LevelFields.residualLanes step)))*ev (LevelFields.degree step) = _ + rw [h.vertices,h.residual,h.degree,← Nat.cast_mul,← Nat.cast_mul,← Nat.cast_mul]; rfl + +private theorem eval_add (x y : Expr) : ev (x.add y) = ev x + ev y := rfl +private theorem eval_mul (x y : Expr) : ev (x.mul y) = ev x * ev y := rfl +private theorem eval_lit (k : ℕ) : ev (.lit k) = (k : Word w) := rfl + +/-- Evaluation of the bundle-plan expressions yields the physical placement columns, rank-arena +addresses and capacities for this input graph. -/ +structure HeadValues (X : State a (packingLaneBits a g)) (step : ℕ) (origin : Expr) + (pub : Fin 5 → Word w) (state : Word w) (m : Memory w) (start : ℕ) : Prop where + placement (j : Fin 4) : Expr.eval pub state m (placementColumn step a origin j) = ((ShrinkInput.placementBase X start+j.val*(Fintype.card X.Base*2^(packingLaneBits a g)) : ℕ) : Word w) + owner : Expr.eval pub state m (owner step a origin) = ((ShrinkInput.plan X start).owner : Word w) + key : Expr.eval pub state m (key step a origin) = ((ShrinkInput.plan X start).key : Word w) + counts : Expr.eval pub state m (counts step a origin) = ((ShrinkInput.plan X start).counts : Word w) + bucketCount : Expr.eval pub state m (bucketCount step a) = ((2*(ShrinkInput.plan X start).B : ℕ) : Word w) + ids : Expr.eval pub state m (ids step a origin) = ((ShrinkInput.plan X start).ids : Word w) + rectangle : Expr.eval pub state m (rectangle step a) = ((ShrinkInput.plan X start).rectangleSize : Word w) + gathered : Expr.eval pub state m (gathered step a origin) = ((ShrinkInput.plan X start).gathered : Word w) + ranks : Expr.eval pub state m (ranks step a origin) = ((ShrinkInput.plan X start).ranks : Word w) + sorted : Expr.eval pub state m (sorted step a origin) = (ShrinkInput.widthBase X start : Word w) + blockSize : Expr.eval pub state m (blockSize step a) = (((ShrinkInput.plan X start).B*(ShrinkInput.plan X start).Q : ℕ) : Word w) + absoluteCD : Expr.eval pub state m (absoluteCD step a origin) = (((ShrinkInput.plan X start).gathered + (ShrinkInput.plan X start).B*(ShrinkInput.plan X start).Q : ℕ) : Word w) + +include h in +theorem head_values : HeadValues X step origin pub state m start := by + have pre : ev (preliminary step a origin) = (ShrinkInput.placementBase X start : Word w) := + GreedyLevelPlan.eval_greedyStop h.toReads + have ho : ev (owner step a origin) = ((Z).owner : Word w) := by + rw [owner,eval_add,eval_mul,eval_lit,pre,eval_sites X h,← Nat.cast_mul,← Nat.cast_add]; rfl + have hk : ev (key step a origin) = ((Z).key : Word w) := by + rw [key,eval_add,ho,eval_slots X h,← Nat.cast_add]; rfl + have hc : ev (counts step a origin) = ((Z).counts : Word w) := by + rw [counts,eval_add,ho,eval_mul,eval_lit,eval_slots X h,← Nat.cast_mul,← Nat.cast_add]; rfl + have hb : ev (bucketCount step a) = ((2*(Z).B : ℕ) : Word w) := by + rw [bucketCount,eval_mul,eval_lit,eval_bundles X h,Nat.cast_mul] + have hi : ev (ids step a origin) = ((Z).ids : Word w) := by rw [ids,eval_add,hc,hb,← Nat.cast_add]; rfl + have rect : ev (rectangle step a) = ((Z).rectangleSize : Word w) := by + rw [rectangle,eval_mul,hb,eval_lit,← Nat.cast_mul] + have hg : ev (gathered step a origin) = ((Z).gathered : Word w) := by + rw [gathered,eval_add,hi,rect,← Nat.cast_add]; rfl + have hr : ev (ranks step a origin) = ((Z).ranks : Word w) := by + rw [ranks,eval_add,hg,rect,← Nat.cast_add]; rfl + have hs : ev (sorted step a origin) = (W : Word w) := by + rw [sorted,eval_add,hr,eval_slots X h,← Nat.cast_add]; rfl + have block : ev (blockSize step a) = (((Z).B*(Z).Q : ℕ) : Word w) := by + rw [blockSize,eval_mul,eval_bundles X h,eval_lit,← Nat.cast_mul] + refine ⟨?_,ho,hk,hc,hb,hi,rect,hg,hr,hs,block,?_⟩ + · intro j + simp only [placementColumn,eval_add,pre,eval_mul,eval_lit,eval_sites X h,Nat.cast_add,Nat.cast_mul] + · rw [absoluteCD,eval_add,hg,block,Nat.cast_add] + +include h in +theorem placement_bank : (fun i ↦ ev (placementParams shape step a origin i)) = sh := by + have heads := head_values X h + have off := GreedyLevelPlan.eval_offsetBase h.toReads + funext i + fin_cases i + · exact h.residual + · rfl + · exact h.degree + · rfl + · rfl + · rfl + · exact h.origin + · exact off + · exact h.incidence 0 + · exact h.incidence 2 + · exact heads.placement 0 + · exact heads.placement 1 + · exact heads.placement 2 + · exact heads.placement 3 + +include h in +theorem rank_banks (fit : (Z).stop < 2^w) : + (fun i ↦ ev (classifyParams shape step a origin i)) = (Z).classifyBank T sh ∧ + (fun i ↦ ev (collectParams step a origin i)) = q ∧ + (fun i ↦ ev (gatherParams step a origin i)) = BundleGather.Fixed.parameters ((Z).gatheredTable w T) ∧ + (fun i ↦ ev (rankParams step a origin i)) = + BundleGather.rankPublic q (Fin.ofNat _ (Z).key) (Fin.ofNat _ (Z).gathered) rankWord ∧ + (fun i ↦ ev (widthParams shape step a origin i)) = scatter := by + have v := head_values X h + have hz := (Z).values T sh Fintype.card_pos fit + have stride : ev (.lit (cap a)) = Fin.ofNat (2^w) (q 4).val := by rw [hz.stride]; rfl + refine ⟨?_,?_,?_,?_,?_⟩ + · funext i; fin_cases i + · exact h.degree + · exact h.residual + · rfl + · rfl + · exact eval_bundles X h + · exact h.incidence 3 + · exact v.placement 1 + · exact v.placement 0 + · exact v.placement 2 + · exact v.owner + · exact v.key + · funext i; fin_cases i + · exact eval_slots X h + · exact v.owner + · exact v.bucketCount + · exact v.counts + · rfl + · exact v.ids + · funext i; fin_cases i + · rfl + · rfl + · exact eval_bundles X h + · exact stride + · exact v.ids + · exact v.key + · exact v.gathered + · funext i; fin_cases i + · exact v.owner + · exact v.key + · exact v.gathered + · rfl + · exact v.counts + · exact v.ranks + · funext i; fin_cases i + · exact v.owner + · exact v.ranks + · exact h.incidence 5 + · rfl + · exact v.sorted + +/-- The two scattered classes reuse the gathered keys after the rank scan. -/ +def absoluteBank (z : ShrinkRankSpace.Shape) (w : ℕ) : Fin 7 → Word w := + ![z.owner,z.ranks,z.key,z.Q,z.gathered,(2^z.degreeBits : ℕ),(2^z.residualBits : ℕ)] + +include h in +theorem absolute_bank : (fun i ↦ ev (absoluteParams step a origin i)) = absoluteBank Z w := by + have v := head_values X h + funext i; fin_cases i + · exact v.owner + · exact v.ranks + · exact v.key + · rfl + · exact v.gathered + · exact h.degree + · exact h.residual + +/-- The old gather rectangle ends at the rank column. The other two inputs +(owner and key) end before that rectangle. This establishes the scatter's +frame without allocating another pair of rectangles. -/ +theorem absolute_layout (fit : (Z).stop < 2^w) : + BundleWidthScatter.Layout (MotifAbsolute.columns (absoluteBank Z w)) (Z).A + (N*(2^(Shrink.J a)*2^g)) (2^a) (Shrink.colors a) := by + have scalar := (Z).scalarFits Fintype.card_pos fit + have stride : (MotifAbsolute.columns (absoluteBank Z w) 3).val = (Z).Q := Nat.mod_eq_of_lt scalar.2.2.1 + have bound : (Z).ranks+(Z).A < 2^w := fit + have rect : (Z).gathered+((Z).B+(Z).B)*(Z).Q = (Z).ranks := by + change (Z).gathered+((Z).B+(Z).B)*(Z).Q = (Z).gathered+(2*(Z).B)*(Z).Q + rw [two_mul] + have ho : (Z).owner+(Z).A ≤ (Z).gathered := by + simp only [ShrinkRankSpace.Shape.owner,ShrinkRankSpace.Shape.gathered,ShrinkRankSpace.Shape.ids, + ShrinkRankSpace.Shape.counts] + omega + have hk : (Z).key+(Z).A ≤ (Z).gathered := by + simp only [ShrinkRankSpace.Shape.key,ShrinkRankSpace.Shape.gathered,ShrinkRankSpace.Shape.ids, + ShrinkRankSpace.Shape.counts] + omega + have buckets := scalar.2.1 + have out : (MotifAbsolute.columns (absoluteBank Z w) 4).val = (Z).gathered := Nat.mod_eq_of_lt (by omega) + have ownVal : (Fin.ofNat (2^w) (Z).owner).val = (Z).owner := Nat.mod_eq_of_lt (by omega) + have keyVal : (Fin.ofNat (2^w) (Z).key).val = (Z).key := Nat.mod_eq_of_lt (by omega) + have rankVal : (Fin.ofNat (2^w) (Z).ranks).val = (Z).ranks := Nat.mod_eq_of_lt (by omega) + refine ⟨stride.ge,?_,?_,?_,?_⟩ + · change (Z).B+(Z).B ≤ 2^w; omega + · intro i; fin_cases i + · change (Fin.ofNat (2^w) (Z).owner).val+(Z).A ≤ _; rw [ownVal]; omega + · change (Fin.ofNat (2^w) (Z).ranks).val+(Z).A ≤ _; rw [rankVal]; omega + · change (Fin.ofNat (2^w) (Z).key).val+(Z).A ≤ _; rw [keyVal]; omega + · rw [stride,out]; change (Z).gathered+((Z).B+(Z).B)*(Z).Q ≤ _; omega + · intro i; rw [stride,out]; fin_cases i + · left; change (Fin.ofNat (2^w) (Z).owner).val+_ ≤ _; rwa [ownVal] + · right + change (Z).gathered+((Z).B+(Z).B)*(Z).Q ≤ (Fin.ofNat (2^w) (Z).ranks).val + rw [rankVal,rect] + · left; change (Fin.ofNat (2^w) (Z).key).val+_ ≤ _; rwa [keyVal] + +include h in +private theorem end_heads (fit : (Z).stop < 2^w) : + ev (prefixStart step a origin) = (prefix : Word w) ∧ + ev (totalStart step a origin) = ((prefix+2*((Z).B*(Z).Q) : ℕ) : Word w) ∧ + ev (abStart step a origin) = (ShrinkWidthArena.abBase X q W : Word w) := by + have v := head_values X h + have stride := ((Z).values T sh Fintype.card_pos fit).stride + have p : ev (prefixStart step a origin) = (prefix : Word w) := by + rw [prefixStart,eval_add,v.sorted,eval_mul,eval_lit,v.blockSize,← Nat.cast_mul,← Nat.cast_add, + ShrinkWidthArena.prefixBase,stride] + have t : ev (totalStart step a origin) = ((prefix+2*((Z).B*(Z).Q) : ℕ) : Word w) := by + rw [totalStart,eval_add,p,eval_mul,eval_lit,v.blockSize,← Nat.cast_mul,← Nat.cast_add] + refine ⟨p,t,?_⟩ + rw [abStart,eval_add,t,v.bucketCount,← Nat.cast_add,ShrinkWidthArena.abBase,stride] + +include h in +theorem prefix_bank (motif : Bool) (fit : (Z).stop < 2^w) : + (fun i ↦ ev (prefixParams step a origin motif i)) = ShrinkWidthArena.prefixBank X T q rankWord W motif := by + have v := head_values X h + obtain ⟨hp,ht,_⟩ := end_heads X h fit + have stride : (scatter 3).val = (Z).Q := ((Z).values T sh Fintype.card_pos fit).stride + have width : (scatter 4).val = W := Nat.mod_eq_of_lt fit + cases motif <;> funext i <;> fin_cases i + · rfl + · rfl + · change ev (sorted step a origin) = Fin.ofNat _ (scatter 4).val + rw [width]; exact v.sorted + · exact hp + · change ev (totalStart step a origin) = Fin.ofNat _ (prefix+2*((Z).B*(scatter 3).val)) + rw [stride]; exact ht + · rfl + · rfl + · change ev ((sorted step a origin).add (blockSize step a)) = Fin.ofNat _ ((scatter 4).val+(Z).B*(scatter 3).val) + rw [eval_add,v.sorted,v.blockSize,width,stride,← Nat.cast_add]; rfl + · change ev ((prefixStart step a origin).add (blockSize step a)) = Fin.ofNat _ (prefix+(Z).B*(scatter 3).val) + rw [eval_add,hp,v.blockSize,stride,← Nat.cast_add]; rfl + · change ev ((totalStart step a origin).add (bundles step a)) = + Fin.ofNat _ (prefix+2*((Z).B*(scatter 3).val)+(Z).B) + rw [eval_add,ht,eval_bundles X h,stride,← Nat.cast_add]; rfl + +include h in +theorem ab_bank (fit : (Z).stop < 2^w) : + (fun i ↦ ev (abParams step a origin i)) = ShrinkWidthArena.abBank X T q rankWord W := by + have ab := (end_heads X h fit).2.2 + have total := congrFun (prefix_bank X h false fit) 4 + have v := head_values X h + funext i; fin_cases i + · rfl + · rfl + · exact total + · exact ab + · change ev ((abStart step a origin).add (blockSize step a)) = _ + rw [eval_add,ab,v.blockSize,← Nat.cast_add]; rfl + +include h in +theorem term_input (fit : (Z).stop < 2^w) : + ShrinkTermRecipe.Describes (termInputs step a origin) X pub state m scatter (ShrinkWidthArena.abBase X q W) := + ⟨h.vertices,h.degree,h.lanes,h.residual,(head_values X h).sorted,rfl,(end_heads X h fit).2.2⟩ + +include h in +/-- Cursor bounds in native order. The first position scan includes every old +site. Each subsequent classification or scatter visits the old arcs, while +the two prefix scans visit the populated parts of the thick and CD rows. -/ +theorem stop_counts : + (visits shape step a origin).map (fun v ↦ ev v.stop) = + List.map (fun j : ℕ ↦ (j : Word w)) [S,2*(Z).B,(Z).A,(Z).A,(Z).A,(Z).A,(Z).A, + (Z).B*thickCount a,(Z).B*(Z).Q,(Z).B*(Z).Q,(Z).A] := by + have v := head_values X h + simp only [visits,List.map_cons,List.map_nil,ops,eval_sites X h,eval_slots X h,v.bucketCount,v.blockSize, + eval_mul,eval_lit,eval_bundles X h,← Nat.cast_mul] + +end Readback + +end CompressorRecords.ShrinkBundlePlan + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundlePrepared.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundlePrepared.lean new file mode 100644 index 0000000000..b5068aba5c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundlePrepared.lean @@ -0,0 +1,190 @@ +import OAI.Computability.VPVNP.CompressorShrinkBundlePackets +import OAI.Computability.VPVNP.CompressorShrinkBundleOperandSupport +import OAI.Computability.VPVNP.CompressorShrinkGreedyHeaderValues +import OAI.Computability.VPVNP.CompressorWindowPackets +import OAI.Computability.VPVNP.CompressorSourceGroups + +/-! +# Preparing the eleven dense shrinking visits in the repeated block + +The level header and table-zero pointer are read in each packet's actual +input memory. The greedy pass and preceding dense workers preserve these +cells, the scheduler row count, and the pitch below the scratch allocation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkBundlePackets + +open BurstRAM BlockPlanner Compression DescriptorSpace Schedule +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (exponent i) (packingLaneBits (exponent i) g)) (T : IncidenceDirectory w) (start : ℕ) +variable (base : Word w) (positions blocks t : ℕ) +local notation "script₀" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (arity (Script.catalog (BlockProgram.script B))) base +local notation "first" => ((S.steps+1)*t) +local notation "st" => (levelStart L first : Word w) +local notation "H" => levelStart L 0 +local notation "Pkt" => SourceWalk.Packet (SourceOnline.Visit script₀ w) w + +/-- Chronological calendar ordinal of the first bundle packet in the indicated block repetition +and shrinking substep. -/ +def startOrdinal := (script₀).initial.length+t*(script₀).block.length+(window B i).before.length + +theorem startOrdinal_eq : startOrdinal B i t = + (script₀).initial.length+t*(script₀).block.length+(BlockIndex.earlier B i).length+9 := by + simp only [startOrdinal,window,List.length_append,Nat.add_assoc] + rfl + +/-- Read a dense visit's complete bank and launch its global worker at the +corresponding live directory row. -/ +theorem prepared (j : Fin stages.length) (raw : Memory w) (rs : List (Report w)) + (header : ShrinkHeaderReads.Header i X T start L first raw) + (rows : raw (pt).rows.val = (directoryRows L : Word w)) + (pitch : raw ((pt).directory-1).val = (levelWords L : Word w)) + (fit : (ShrinkInput.plan X start).stop < 2^w) (within : t < blocks) : + SourceOnline.Prepared script₀ L base (startOrdinal B i t+j.val) (directoryRows L) + ⟨visit B i X T start j,raw,rs⟩ := by + let D := Window.operandRegion script₀ L base + have lo : H ≤ levelStart L (first+i.val) := levelStart_mono L (Nat.zero_le _) + have hfit : H < 2^w := lo.trans_lt ((Nat.le_add_right ..).trans_lt header.room) + have entry : LevelFields.Entry L first (pt).data st raw := ⟨rfl,pitch⟩ + have values := field_values B i X T start j (header.reads B entry) fit + have supp : HeaderOperands.Supported D (pt).data st raw ((script₀).visit (index B i j)) := by + rw [index_visit] + exact expr_reads B i header entry D (.inr (.inl rfl)) + (fun n _ ↦ .inr (.inr (lo.trans (Nat.le_add_right _ n)))) _ + let l := localIndex B i j + let pos := (window B i).position l + have live : (script₀).initial.length+t*(script₀).block.length+pos.val < directoryRows L := by + rw [BlockProgram.directory_rows,(script₀).calendar_total] + have h := Nat.mul_le_mul_right (script₀).block.length within + rw [Nat.succ_mul] at h + have hp := pos.isLt + omega + have ordinalEq : startOrdinal B i t+j.val = (script₀).initial.length+t*(script₀).block.length+pos.val := + Nat.add_assoc .. + rw [ordinalEq] + exact (window B i).prepared L base (BlockProgram.layout_arity ..).symm rfl hfit l t + ⟨visit B i X T start j,raw,rs⟩ raw (fun _ _ ↦ rfl) rows pitch live + ⟨rfl,values.1,values.2.1,values.2.2,supp.initial,supp.stop,supp.params⟩ + +/-- Every source packet sees the row total, immutable pitch and six incidence +heads from the published input header, through its own physical prefix of +worker writes. -/ +theorem prepared_packets {m : Memory w} (r : ShrinkInput.Run X T start m) + (header : ShrinkGreedyHeaderValues.Header i X T L first start (pt).data st m) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (fit : (ShrinkInput.plan X start).stop < 2^w) (within : t < blocks) + (ps : List Pkt) (stagesEq : ps.map SourceWalk.Packet.stage = List.ofFn (visit B i X T start)) + (frame : ∀ p ∈ ps, ∀ x < start, p.input x = r.greedy.post x) (j : Fin ps.length) : + SourceOnline.Prepared script₀ L base (startOrdinal B i t+j.val) (directoryRows L) ps[j.val] := by + let p := ps[j.val] + have len : ps.length = stages.length := by + simpa only [List.length_map,List.length_ofFn] using congrArg List.length stagesEq + let n := j.cast len + have phase : p.stage = visit B i X T start n := by + have he := congrArg (fun xs : List (SourceOnline.Visit script₀ w) ↦ xs[j.val]?) stagesEq + change ps[j.val].stage = visit B i X T start ⟨j.val,n.isLt⟩ + simpa only [List.getElem?_map,List.getElem?_eq_getElem j.isLt,Option.map_some, + List.getElem?_ofFn,dite_eq_left (show j.val < stages.length from n.isLt),Option.some.injEq] using he + have same (x : ℕ) (hx : x < start) : p.input x = m x := + (frame p (List.getElem_mem ..) x hx).trans (r.greedy.below x hx) + have hdr := header.keep_below same + have lo := levelStart_mono L (Nat.zero_le (first+i.val)) + have room := header.raw.room + have bounds := Window.lowCells (A := script₀) L base (BlockProgram.layout_arity ..).symm rfl + (lo.trans_lt ((Nat.le_add_right ..).trans_lt room)) + have before := header.fieldsBelow + have row := (same _ (bounds.1.trans (lo.trans_lt ((Nat.le_add_right ..).trans_lt before)))).trans rows + have hp : (⟨visit B i X T start n,p.input,p.reports⟩ : Pkt) = p := by rw [← phase] + have prep := prepared B i X T start base positions blocks t n p.input p.reports hdr.raw + row hdr.entry.pitch fit within + rw [hp] at prep + exact prep + +/-- The dense segment joins the greedy and term packet groups at its exact +directory offset and physical post-memory. -/ +theorem group {m : Memory w} (r : ShrinkInput.Run X T start m) (abs : List (Report w)) + (last : ShrinkBundlePlan.AbsoluteRun r abs) (room : ShrinkInput.stop X start < 2^w) + (low : ∀ c, H ≤ (T.column c).val) (within : t < blocks) + (header : ShrinkGreedyHeaderValues.Header i X T L first start (pt).data st m) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (cap : ℕ) (clock : SourceOnline.scanCap script₀ (maxFuel B i) ≤ cap) : + ∃ ps : List Pkt, + SourceOnline.Group script₀ L base cap (startOrdinal B i t) (directoryRows L) r.greedy.post ps ∧ + ps.map SourceWalk.Packet.stage = List.ofFn (visit B i X T start) ∧ + ps.flatMap SourceWalk.Packet.reports = ShrinkBundlePlan.Scheduled.preparationReports X T start r ++ abs ∧ + SourceOnline.post r.greedy.post ps = after r.post (eventLog abs) := by + obtain ⟨ps,labels,logs,chron,checks,final⟩ := packets B i X T start L cap clock r abs last room low + have fit := (ShrinkInput.range_bounds X start).2.2.2.trans_lt room + exact ⟨ps,⟨chron,fun p hp ↦ (checks p hp).1, + prepared_packets B i X T start base positions blocks t r header rows fit within ps labels + (fun p hp ↦ (checks p hp).2)⟩,labels,logs,final⟩ + +/-- The repeated online block executes the eleven dense workers, retaining +their reports and branch tapes and ending at the absolute-ID post-memory +throughout the data suffix. -/ +theorem interval {m : Memory w} (r : ShrinkInput.Run X T start m) (abs : List (Report w)) + (last : ShrinkBundlePlan.AbsoluteRun r abs) (room : ShrinkInput.stop X start < 2^w) + (low : ∀ c, H ≤ (T.column c).val) (within : t < blocks) + (header : ShrinkGreedyHeaderValues.Header i X T L first start (pt).data st m) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (cap : ℕ) (clock : SourceOnline.scanCap script₀ (maxFuel B i) ≤ cap) (live : Memory w) + (data : SourceTransport.Agree (H ≤ ·) r.greedy.post live) + (atRow : (live (pt).ordinal.val).val = startOrdinal B i t) + (total : (live (pt).rows.val).val = directoryRows L) + (tag : live (pt).tag.val = LiveStageLink.tagWord w (Online.calendarIndex (script₀).size (script₀).size)) + (pitch : live ((pt).directory-1).val = (levelWords L : Word w)) : + ∃ ss : List (Online.Run.Step (script₀).size (script₀).size w), + Online.Run.Interval (script₀).plan pt cap live ss ∧ + ss.map Online.Run.Step.phase = List.ofFn (index B i) ∧ + ss.flatMap (fun s ↦ s.row.reports) = ShrinkBundlePlan.Scheduled.preparationReports X T start r ++ abs ∧ + ss.map (fun s ↦ s.row.choices) = List.ofFn (fun j ↦ (visit B i X T start j).choices) ∧ + let post := Online.Run.finalMemory (C := (script₀).catalog) pt live ss + SourceTransport.Agree (H ≤ ·) (after r.post (eventLog abs)) post ∧ + (post (pt).ordinal.val).val = startOrdinal B i t+11 ∧ post (pt).rows.val = live (pt).rows.val ∧ + post ((pt).directory-1).val = live ((pt).directory-1).val ∧ + SourceBankFrame.Stable (base.val+6) live (Online.Run.intervalLog (script₀).plan pt live ss) := by + obtain ⟨ps,grp,labels,logs,final⟩ := + group B i X T start base positions blocks t r abs last room low within header rows cap clock + have hfit := (levelStart_mono L (Nat.zero_le (first+i.val))).trans_lt + ((Nat.le_add_right ..).trans_lt header.raw.room) + have len : ps.length = stages.length := by + simpa only [List.length_map,List.length_ofFn] using congrArg List.length labels + have bound : startOrdinal B i t+ps.length ≤ directoryRows L := by + rw [BlockProgram.directory_rows,(script₀).calendar_total,startOrdinal,len,stages] + have block := congrArg List.length (window B i).block + simp only [List.length_append,entries,List.length_map] at block + have steps := Nat.mul_le_mul_right (script₀).block.length within + rw [Nat.succ_mul] at steps + omega + obtain ⟨ss,actual,phases,reports,choices,agree,done,sameRows,samePitch,stable⟩ := + SourceOnline.interval_stable script₀ L base (BlockProgram.layout_arity ..).symm rfl hfit cap + (startOrdinal B i t) (directoryRows L) live r.greedy.post ps grp.chronological + grp.checked grp.prepared bound le_rfl data atRow total tag pitch + refine ⟨ss,actual,?_,?_,?_,final ▸ agree,done.trans (congrArg (startOrdinal B i t+·) len),sameRows,samePitch,stable⟩ + · apply phases.trans + change ps.map (fun p ↦ p.stage.phase) = List.ofFn (fun j ↦ (visit B i X T start j).phase) + simpa only [List.map_map,List.map_ofFn,Function.comp_def] using + congrArg (List.map SourceOnline.Visit.phase) labels + · change (ss.map (fun s ↦ s.row.reports)).flatten = _ + rw [reports]; exact logs + · apply choices.trans + simpa only [List.map_map,List.map_ofFn,Function.comp_def] using + congrArg (List.map SourceOnline.Visit.choices) labels + +end CompressorRecords.ShrinkBundlePackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkBundleWalk.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleWalk.lean new file mode 100644 index 0000000000..50ddca810a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkBundleWalk.lean @@ -0,0 +1,201 @@ +import OAI.Computability.VPVNP.CompressorShrinkBundlePlan +import OAI.Computability.VPVNP.CompressorShrinkSlotPlan +import OAI.Computability.VPVNP.CompressorSourceWalk + +/-! +# Native sources for dense shrinking visits + +Each stage indexes its worker in the block planner. The first ten stages +replay the placement, rank and width reports from the physical shrinking +run, starting in the memory left by the two greedy assignments. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkBundlePlan.Scheduled + +open BurstRAM BurstRAM.PrivateRAM Compression PhaseRecipe BlockPlanner +open scoped Fin.CommRing + +/-- The eleven dense bundle worker stages, from preliminary placement and rank preparation to +AB pieces and absolute identifiers. -/ +inductive Stage where + | positions | clear | classify | collect | gather | rank | scatter + | thickPrefix | motifPrefix | ab | absolute + deriving DecidableEq + +/-- Number a bundle stage from zero for placement to ten for the final absolute-ID pass. -/ +def Stage.index : Stage → Fin 11 + | .positions => 0 + | .clear => 1 + | .classify => 2 + | .collect => 3 + | .gather => 4 + | .rank => 5 + | .scatter => 6 + | .thickPrefix => 7 + | .motifPrefix => 8 + | .ab => 9 + | .absolute => 10 + +/-- The first ten bundle stages that prepare the sorted widths, both prefix tables and AB +pieces. -/ +def preparationOrder : List Stage := + [.positions,.clear,.classify,.collect,.gather,.rank,.scatter,.thickPrefix,.motifPrefix,.ab] + +/-- The full bundle-stage sequence, ending with the absolute-ID scan after preparation. -/ +def order := preparationOrder ++ [.absolute] + +variable (shape : DescriptorSpace.Shape) (step a : ℕ) (origin : Expr) + +/-- Select the planned catalog visit corresponding to a bundle stage at the specified level and +arena. -/ +def Stage.visit (j : Stage) : Visit := + (visits shape step a origin)[j.index.val]'(by rw [visits_length]; exact j.index.isLt) + +theorem order_visits : order.map (Stage.visit shape step a origin) = visits shape step a origin := rfl + +/-- Number of public operands required by the local worker for this bundle stage. -/ +abbrev Stage.arity : Stage → ℕ + | .positions => 14 + | .clear => 1 + | .classify => 11 + | .collect | .rank => 6 + | .gather | .absolute => 7 + | .scatter | .thickPrefix | .motifPrefix | .ab => 5 + +theorem Stage.params (j : Stage) : (j.visit shape step a origin).worker.params = j.arity := by + cases j <;> rfl + +variable {a} {w g : ℕ} (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) (start : ℕ) + +local notation "Z" => ShrinkInput.plan X start +local notation "q" => ShrinkRankSpace.Shape.collectBank (ShrinkInput.plan X start) w +local notation "sh" => ShrinkInput.placementBank X T start +local notation "rankWord" => (Fin.ofNat (2^w) (ShrinkRankSpace.Shape.ranks (ShrinkInput.plan X start))) +local notation "W" => ShrinkInput.widthBase X start + +/-- Exclusive cursor bound for the stage, determined by its scan over sites, ports, bucket +counts or bundle fields. -/ +def Stage.limit : Stage → ℕ + | .positions => Fintype.card X.Base * 2^(packingLaneBits a g) + | .clear => 2*(Z).B + | .classify | .collect | .gather | .rank | .scatter | .absolute => (Z).A + | .thickPrefix => (Z).B * thickCount a + | .motifPrefix | .ab => (Z).B * (Z).Q + +/-- The stage-specific public operand words assembled from the input incidence directory, +preliminary placement and rank and width arenas. -/ +def Stage.bank : (j : Stage) → Fin j.arity → Word w + | .positions => sh + | .clear => fun _ ↦ q 3 + | .classify => (Z).classifyBank T sh + | .collect => q + | .gather => BundleGather.Fixed.parameters ((Z).gatheredTable w T) + | .rank => BundleGather.rankPublic q (Fin.ofNat _ (Z).key) (Fin.ofNat _ (Z).gathered) rankWord + | .scatter => ShrinkWidthArena.scatterBank T q rankWord W + | .thickPrefix => ShrinkWidthArena.prefixBank X T q rankWord W false + | .motifPrefix => ShrinkWidthArena.prefixBank X T q rankWord W true + | .ab => ShrinkWidthArena.abBank X T q rankWord W + | .absolute => absoluteBank Z w + +section Readback + +variable {shape step origin start T} {pub : Fin 5 → Word w} {state : Word w} {m : Memory w} + (h : Reads X shape step origin pub state m start T) + +include h in +theorem Stage.stop (j : Stage) : + (j.visit shape step a origin).stop.eval pub state m = (j.limit X start : Word w) := by + have e := congrArg (fun l : List (Word w) ↦ l[j.index.val]?) (stop_counts X h) + cases j <;> exact Option.some.inj e + +include h in +theorem Stage.operands (j : Stage) (fit : (Z).stop < 2^w) : + (fun i ↦ ((j.visit shape step a origin).params i).eval pub state m) = + j.bank X T start ∘ Fin.cast (j.params shape step a origin) := by + obtain ⟨hc,hl,hg,hr,hw⟩ := rank_banks X h fit + cases j with + | positions => exact placement_bank X h + | clear => funext i; exact (head_values X h).counts + | classify => exact hc + | collect => exact hl + | gather => exact hg + | rank => exact hr + | scatter => exact hw + | thickPrefix => exact prefix_bank X h false fit + | motifPrefix => exact prefix_bank X h true fit + | ab => exact ab_bank X h fit + | absolute => exact absolute_bank X h + +include h in +theorem Stage.words (j : Stage) (fit : (Z).stop < 2^w) (tag : Word w) : + ShrinkSlotPlan.words (j.visit shape step a origin) tag pub state m = + tag :: 0 :: (j.limit X start : Word w) :: List.ofFn (j.bank X T start) := by + rw [ShrinkSlotPlan.words,j.stop X h,j.operands X h fit] + cases j <;> rfl + +end Readback + +/-- The checked segment for a worker from the planner, with its physical bank +and one empty choice tape per cursor value. -/ +def Source (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) (start : ℕ) + (shape : DescriptorSpace.Shape) (step : ℕ) (origin : Expr) (j : Stage) + (mem : Memory w) (rs : List (Report w)) : Prop := + let v := j.visit shape step a origin + let bank := j.bank X T start ∘ Fin.cast (j.params shape step a origin) + runSegment (v.worker.table.instantiate w bank).program (v.worker.pcs-1) (some 0) mem + (List.replicate (j.limit X start) []) = some rs + +variable {m : Memory w} + +/-- Concatenate the physical reports of the first ten preparation scans in their execution +order through AB piece construction. -/ +def preparationReports (r : ShrinkInput.Run X T start m) : List (Report w) := + r.sites ++ r.clear ++ r.classify ++ r.append ++ r.gather ++ r.rank ++ + r.scatter ++ r.thickPrefixes ++ r.cdPrefixes ++ r.abPieces + +theorem preparation_post (r : ShrinkInput.Run X T start m) : + after r.greedy.post (eventLog (preparationReports X T start r)) = r.post := by + simp only [preparationReports,SourceWalk.after_append] + rfl + +/-- All ten deterministic report lists in their native chronological order. -/ +theorem preparation_sources (r : ShrinkInput.Run X T start m) (fit : (Z).stop < 2^w) : + SourceWalk (Source X T start shape step origin) preparationOrder r.greedy.post (preparationReports X T start r) := by + classical + have hQ := ((Z).scalarFits Fintype.card_pos fit).2.2.1 + have ht : thickCount a ≤ (Z).Q := by + change 2^(Shrink.colors a)*2^a/4 ≤ 3*(2^(Shrink.colors a)*2^a)/4 + omega + have thick := r.widths.prefixes.thick.executed + have motif := r.widths.prefixes.motif.executed + have thickSize : (ShrinkWidthArena.prefixBank X T q rankWord W false 0).val = thickCount a := + Nat.mod_eq_of_lt (ht.trans_lt hQ) + have motifSize : (ShrinkWidthArena.prefixBank X T q rankWord W true 0).val = (Z).Q := + Nat.mod_eq_of_lt hQ + rw [thickSize] at thick + rw [motifSize] at motif + have ranked := r.ranking.ranked.rank.executed + rw [Nat.add_comm 1] at ranked + simp only [preparationOrder,preparationReports,List.append_assoc] + exact .next r.positions (.next r.ranking.clear (.next r.ranking.ranked.classify + (.next r.ranking.ranked.append (.next r.ranking.ranked.gather (.next ranked + (.next r.widths.scatter (.next thick (.next motif (.singleton r.widths.ab))))))))) + +theorem source_paths {j : Stage} {rs : List (Report w)} + (run : Source X T start shape step origin j m rs) : + branchPaths rs = List.replicate (j.limit X start) [] := + ((runSegment_iff ..).mp run).2.2 + +theorem source_calls {j : Stage} {rs : List (Report w)} + (run : Source X T start shape step origin j m rs) : rs.length = j.limit X start := by + simpa [branchPaths] using congrArg List.length (source_paths shape step origin X T start run) + +end CompressorRecords.ShrinkBundlePlan.Scheduled + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkCurrentBounds.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkCurrentBounds.lean new file mode 100644 index 0000000000..10ac23db15 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkCurrentBounds.lean @@ -0,0 +1,51 @@ +import OAI.Computability.VPVNP.CompressorShrinkCurrentBranch + +/-! +# Constructing all shrinking continuations within the input-length bounds + +One threshold fixes the word width for the entire physical shrinking +boundary. After publication the actual selector and geometry runs exist +for every typed choice, independently of the later branch. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkCurrentBranch + +open BurstRAM Compression DescriptorSpace CurrentGraph CursorBounds Filter +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) + +theorem eventually_build (factor : ℕ) (hb : 1 ≤ factor) : ∀ᶠ n : ℕ in atTop, + ∀ {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g : ℕ} + (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)), + X.positions ≤ initialPositions factor n → X.maxWireWidth ≤ n → ∀ (base blocks : ℕ) + (old new : Fin (BlockProgram.layout B base (initialPositions factor n) blocks).levels) + (m : Memory (wordBits factor n)) (fuel : ℕ), + let L := BlockProgram.layout B base (initialPositions factor n) blocks + let w := wordBits factor n + let start := tableBase L old (0 : Fin 6) + let T := packedIncidence L w old (DemandRAM.oldCount X) + Current L old X n m → old.val+1=new.val → endAddress L < 2^w → ShrinkBranch.prefixClock B factor n ≤ fuel → + ShrinkBranch.PrefixFits B X T start (10 : Word w) fuel ∧ + Nonempty (Common B f hf i X base (initialPositions factor n) blocks old new m fuel) := by + filter_upwards [ShrinkBranch.eventually_prefixFits B factor hb,PrefixLevelScale.eventually_scores B factor hb, + CursorRAM.eventual_word_room factor hb (CursorRAM.bounded_positions factor), + CursorRAM.eventual_word_room factor hb (PolynomiallyBounded.const (slotDegree S))] with n prefixes scores sites degrees + intro R _ f hf i g X pos mx base blocks old new m fuel L w start T current next fit clock + have pre := prefixes i X pos mx base blocks old fit fuel clock + exact ⟨pre,build B f hf i X base _ blocks old new m n fuel current next pos (pos.trans_lt sites) degrees fit pre + (Nat.mod_eq_of_lt scores.1) scores.2.1 (scores.2.2 i X pos mx)⟩ + +end CompressorRecords.ShrinkCurrentBranch + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkCurrentBranch.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkCurrentBranch.lean new file mode 100644 index 0000000000..2792da5ec5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkCurrentBranch.lean @@ -0,0 +1,130 @@ +import OAI.Computability.VPVNP.CompressorCurrentGraph +import OAI.Computability.VPVNP.CompressorDefaultSelection +import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory +import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch +import OAI.Computability.VPVNP.CompressorPrefixScoreFit +import OAI.Computability.VPVNP.CompressorShrinkPublishedHeader + +/-! +# The common physical prefix at a shrinking boundary + +All terms have identical header reports, so the current packed graph +starts one deterministic prefix before any term is read. The branch at +its endpoint accepts precisely the typed shrinking terms and runs the +selected score and geometry construction for each one. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkCurrentBranch + +open BurstRAM Compression Compression.ShrinkMotif BlockHeaderRun DescriptorSpace CurrentGraph +open PairSimulation.LocalHistory PairSimulation.TraversalRows PortRefresh.TraversalHeaders CursorBounds Filter +open scoped Classical Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) +variable {g w : ℕ} (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) + +/-- The shrinking pass occurrence at the given substep and input state. -/ +abbrev origin : PassOrigin B f hf (B.shrinkPassAt f hf i rfl X) := .shrink i rfl X +/-- The default selected term of this shrinking occurrence, used to describe the header shared +by every choice. -/ +abbrev defaultTerm := defaultSelection (origin B f hf i X) +/-- The selected level with the default term and an empty choice stream, used for the common +header before branching. -/ +abbrev beforeLevel := shrinkLevel B f hf i X (defaultTerm B f hf i X) [] + +variable (base positions blocks : ℕ) +local notation "L" => BlockProgram.layout B base positions blocks +variable (old new : Fin (BlockProgram.layout B base positions blocks).levels) (m : Memory w) +local notation "V" => beforeLevel B f hf i X +local notation "start" => tableBase L old (ShrinkHeaderReads.firstTable B base positions blocks) +local notation "T" => packedIncidence L w old (DemandRAM.oldCount X) +local notation "post" => finalMemory V L old new m +local notation "stride" => (10 : Word w) +/-- The shrinking template's selector-bit count encoded at the host word width. -/ +abbrev selectorWord (w : ℕ) : Word w := (B.shrink.selectorBits : Word w) +local notation "selBits" => selectorWord B w +local notation "N" => ShrinkTermInputs.motifCount X + +theorem capacity_eq : slotCapacity L = positions*slotDegree S := rfl + +theorem scalarFit : 6 ≤ (L).shape.scalarFields := by change 6 ≤ 54; decide + +theorem header_eq (s : SelectedScore.Selection B X) (bits : List Bool) : + finalMemory (shrinkLevel B f hf i X s bits) L old new m = post ∧ + reports (shrinkLevel B f hf i X s bits) L old new m = reports V L old new m := ⟨rfl,rfl⟩ + +attribute [local irreducible] BlockProgram.script BlockProgram.layout BlockHeaderRun.finalMemory + PairSimulation.LocalHistory.defaultSelection + +/-- Data at the common selection boundary and the true execution on +every continuation. The level indices are relative to the given layout. -/ +structure Boundary (L₀ : Layout) (old₀ new₀ : Fin L₀.levels) (six : 6 ≤ L₀.shape.scalarFields) + (T₀ : IncidenceDirectory w) (begin₀ fuel : ℕ) (input₀ : Memory w) where + /-- The common shrinking prefix run from the post-header memory through the input and demand + preparation before term selection. -/ + pre : ShrinkBranch.Prefix X T₀ begin₀ fuel (finalMemory V L₀ old₀ new₀ input₀) + header : ∀ (s : SelectedScore.Selection B X) (bits : List Bool), + Substep (w := w) (shrinkLevel B f hf i X s bits) L₀ old₀ new₀ six input₀ + incidence : T₀.Represents X (finalMemory V L₀ old₀ new₀ input₀) + oldHeads : HeadBank L₀ old₀ (DemandRAM.oldCount X) (finalMemory V L₀ old₀ new₀ input₀) + nextHeads : ∀ (s : SelectedScore.Selection B X) (bits : List Bool), + HeadBank L₀ new₀ (shrinkLevel B f hf i X s bits).outputSlots (finalMemory V L₀ old₀ new₀ input₀) + legal : ∀ bs : Fin N → List Bool, + (runSegment (ShrinkTermSelection.termProgram B.shrink (ShrinkInput.demandHead X begin₀) + (ShrinkInput.termHead X begin₀) 10) fuel (some 0) pre.beforeTerm (List.ofFn bs)).isSome ↔ + ∃! s : X.ShrinkSelection B.shrink, bs = ShrinkTermSelection.tapes B.shrink X s w + selected : ∀ s : SelectedScore.Selection B X, Nonempty (ShrinkBranch.Selected B X T₀ begin₀ stride selBits + fuel (finalMemory V L₀ old₀ new₀ input₀) pre s) + +/-- The physical branch boundary for this packed shrinking level, specialized to the block's +scalar bounds, headers, scratch base and entry memory. -/ +abbrev Common (fuel : ℕ) := + Boundary B f hf i X L old new (scalarFit B base positions blocks) T start fuel m + +set_option maxHeartbeats 1000000 in +theorem build (length fuel : ℕ) (current : Current L old X length m) (next : old.val+1 = new.val) + (sites : X.positions ≤ positions) (sitesFit : X.positions < 2^w) (degreeFit : slotDegree S < 2^w) + (fit : endAddress L < 2^w) (prefixFit : ShrinkBranch.PrefixFits B X T start stride fuel) + (bitsFit : (selBits).val = B.shrink.selectorBits) (weights : ∀ t, MotifAdmission.weight relativeMass t < 2^w) + (scores : ∀ s : SelectedScore.Selection B X, ∀ l, + layoutScore relativeMass (X.packingData.termWidths B.shrink X.shrinkNumber X.packingWidth s) l < 2^w) : + Nonempty (Common B f hf i X base positions blocks old new m fuel) := by + have count : IncidenceDirectory.slotCount X ≤ slotCapacity L := by + have eqn : Fintype.card X.Base*2^(packingLaneBits (S.degreeExponent i.castSucc) g) = X.positions := by + simp only [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv _),Fintype.card_fin] + have deg : 2^S.degreeExponent i.castSucc ≤ slotDegree S := + (Finset.le_sup (f := fun j : Fin (S.steps+1) => 2^S.degreeExponent j) (Finset.mem_univ _)).trans (le_max_right ..) + rw [capacity_eq] + change Fintype.card X.Base*2^_*2^_ ≤ positions*slotDegree S + rw [eqn]; exact Nat.mul_le_mul sites deg + have publish (s : SelectedScore.Selection B X) (bits : List Bool) := + Current.publish («L» := L) (n := length) (B := B) (f := f) (hf := hf) (m := m) + (shrinkLevel B f hf i X s bits) old new current next (scalarFit B base positions blocks) + fit count sitesFit degreeFit + obtain ⟨_,rep,heads,_⟩ := publish (defaultTerm B f hf i X) [] + have geometry := ShrinkBranch.selected_geometry_fit B i X base positions blocks old sites fit + obtain ⟨p,legal,selected⟩ := ShrinkBranch.build B X T start stride selBits fuel post rep prefixFit bitsFit weights geometry + have ten : (stride).val = 10 := by + have h := prefixFit.wide + exact (Nat.mod_eq_of_lt (h.trans_lt (stride).isLt)) + rw [ten] at legal + have nextHeads (s : SelectedScore.Selection B X) (bits : List Bool) : + HeadBank (w := w) L new (shrinkLevel B f hf i X s bits).outputSlots post := by + rw [← (header_eq B f hf i X base positions blocks old new m s bits).1] + exact (publish s bits).2.2.2 + exact ⟨⟨p,fun s bits => (publish s bits).1,rep,heads,nextHeads,legal,fun s => selected s (scores s)⟩⟩ + +end CompressorRecords.ShrinkCurrentBranch + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkCurrentResident.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkCurrentResident.lean new file mode 100644 index 0000000000..dbc9cac57d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkCurrentResident.lean @@ -0,0 +1,179 @@ +import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory +import OAI.Computability.VPVNP.CompressorShrinkScheduledTail +import OAI.Computability.VPVNP.CompressorBlockMetadataShrinkReadback +import OAI.Computability.VPVNP.CompressorBlockMetadataGraphFrame +import OAI.Computability.VPVNP.CompressorSelectedDirectoryEmission +import OAI.Computability.VPVNP.CompressorCurrentResident + +/-! +# The resident boundary after a shrinking pass + +The three final publication groups install the old-level directory operands +and successor DFS fields. Their writes leave the canonical successor +incidence columns, previously recorded levels and original cursor frame +available to the next calendar interval. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkScheduledTail + +open BurstRAM Compression DescriptorSpace BlockPlanner SourceOnline BlockHeaderRun +open SelectedDirectoryHistory PairSimulation.TraversalRows PairSimulation.TraversalRoles +open PairSimulation.LocalHistory +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} {B : S.Templates} +variable {f : B.Entry → R} {hf : B.IsSolution f} {i : Fin S.steps} {w g : ℕ} +variable {X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)} +variable {sel : SelectedScore.Selection B X} {tape : List Bool} +variable {workspace : Word w} {positions blocks t cap n : ℕ} {m : Memory w} +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B workspace.val positions blocks +local notation "first" => Script.levelsPerBlock scr * t +local notation "cur" => first + i.val +local notation "head" => levelStart L cur +local notation "nxt" => levelStart L (cur + 1) +local notation "start" => tableBase L cur (0 : Fin 6) +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog scr)) workspace +local notation "v" => shrinkLevel B f hf i X sel tape +variable {ms ps : List (Packet (BlockProgram.script B) w)} +variable (r : Result (g := g) B workspace positions blocks t cap i X m ms ps) + +private theorem room_between : head + 66 ≤ nxt := by + have size : levelHeaderWords L = 66 := rfl + simp only [levelStart, Nat.succ_mul, levelWords, size] + omega + +/-- The exact operand vector at offsets 21, 22, 24, 25 and 26 agrees +with the bank used to collect this pass's child directory. -/ +def Result.emission (T : IncidenceDirectory w) + (d : LevelDirectory v m nxt) (shr : Fin 14 → Word w) + (bank : d.pub = SelectedFinish.params X term 10 shr) (lower : head + 54 ≤ (d.pub 1).val) + (header : ShrinkHeaderReads.Header i X T start L first m) + (pitch : m ((pt).directory - 1).val = (levelWords L : Word w)) + (termFit : ShrinkInput.termEnd X start 10 < 2 ^ w) + (rows : m (pt).rows.val = (directoryRows L : Word w)) + (length : m (levelStart L 0 + 29) = (n : Word w)) : + Emission L cur v m (post m ps) := by + have oldCount : (v).input.positions = ShrinkPreimages.oldCount X := by + change X.positions = _ + rw [State.positions, Fintype.card_prod, Fintype.card_congr (bitWordFinEquiv _), + Fintype.card_fin] + have p : BlockMetadata.Published B workspace positions blocks t i.val + (BlockMetadata.producingRole (v).origin) + (BlockMetadata.shrinkFields B i) m (v).input.positions + (ms.flatMap SourceWalk.Packet.reports) := + oldCount.symm ▸ r.baseFields + have payload := r.baseFields.shrink_payload B i X T start workspace positions blocks t + header ⟨rfl, pitch⟩ termFit rows n length + have values : PlacementWords (fun j => post m ms (head + 15 + j.val)) d.pub := by + rw [bank] + exact ⟨payload 6, payload 7, payload 9, payload 10, payload 11⟩ + let emitted := Emission.ofPublished p d (by omega) values + have gap : head + 66 ≤ nxt := room_between + have pubEq : emitted.dir.pub = d.pub := by + unfold emitted Emission.ofPublished + rcases values with ⟨_, _, _, _, _⟩ + rfl + apply emitted.transfer + · intro x hx + rw [pubEq] at hx + have lo := (Directory.cells_interval d hx).1 + exact (r.metaCell x (.inr (lower.trans lo))).symm + · intro o ho + simp only [List.mem_cons, List.not_mem_nil, or_false] at ho + exact r.metaCell _ (.inl (by omega)) + · intro o _ + exact r.metaCell _ (.inr (by omega)) + +include r + +/-- The final 21 packets retain the scalar and pointer fields of the new +graph together with the first-level counts and original eight inputs. -/ +theorem Result.graph_frame (x : ℕ) + (hx : CurrentGraph.graphCell L (cur + 1) x ∨ CurrentGraph.startupCell L x + ∨ CurrentGraph.frameCell L x) : + post m ps x = m x := by + have floor := levelStart_mono L (Nat.zero_le cur) + have gap : head + 66 ≤ nxt := room_between + have tail : x < head + 36 ∨ head + 54 ≤ x := by + rcases hx with g | s | h + · rcases g with h | h <;> exact .inr (by omega) + · obtain ⟨j, hj, rfl⟩ := s + simp only [List.mem_cons, List.not_mem_nil, or_false] at hj + exact .inl (by omega) + · unfold CurrentGraph.frameCell at h + exact .inl (by omega) + apply (r.metaCell x tail).trans + rcases hx with h|h|h + · exact r.baseFields.graphFrame x (.inr (.inl h)) + · exact r.baseFields.graphFrame x (.inr (.inr h)) + · exact r.baseFields.cursorFrame x h + +/-- Extend the selected history in the native post-memory. The pre-tail +frame permits writes to the six old-level resident heads at offsets 30–35 +and to the new incidence columns installed by the slot stage. -/ +theorem Result.advance {initial : TaggedLayer} {initialFrame : Fin 8 → Word w} + {past : List (SelectedLevel B f hf)} + {before : Memory w} (old new : Fin (L).levels) (atOld : old.val = cur) + (next : old.val + 1 = new.val) + (index : past.length = old.val) + (stored : CurrentResident.resident B f hf initial L (endAddress L) n initialFrame past X before) + (sub : Substep v L old new (by change 6 ≤ 54; decide) before) + (fit : endAddress L < 2 ^ w) + (slots : IncidenceDirectory.slotCount ((v).pass.next (v).term) ≤ slotCapacity L) + (columns : (packedIncidence L w new + (IncidenceDirectory.slotCount ((v).pass.next (v).term))).Represents + ((v).pass.next (v).term) m) + (emitted : Emission L cur v m (post m ps)) + (throughSlots : ∀ x, levelStart L 0 ≤ x → x < head + 30 ∨ CurrentGraph.graphCell L (cur + 1) x → + m x = finalMemory v L old new before x) : + CurrentResident.resident B f hf initial L (endAddress L) n initialFrame (past ++ [v]) + ((v).pass.next (v).term) (post m ps) := by + have newAt : new.val = cur + 1 := by omega + have ix : past.length = cur := index.trans atOld + have gap : head + 66 ≤ nxt := room_between + have floor := levelStart_mono L (Nat.zero_le cur) + have nextEq : levelStart L (first + (i.val + 1)) = nxt := by rw [Nat.add_assoc] + have headEq : levelStart L old = head := congrArg _ atOld + have newEq : levelStart L new = nxt := congrArg _ newAt + have keepOld (j : ℕ) (hj : j = 14 ∨ j = 27) : m (head + j) = before (head + j) := by + apply (throughSlots _ (by omega) (.inl (by omega))).trans + apply sub.outside <;> first | exact .inr (by omega) | exact .inl (by omega) + apply CurrentResident.append_substep old new index next stored (by change 30 ≤ 54; decide) fit sub + · rw [ix] + exact emitted.prepend (keepOld 14 (.inl rfl)) (keepOld 27 (.inr rfl)) + · apply CurrentGraph.incidence_keep L new _ fit slots columns + intro x lo _ + have h : incidenceStart L new = nxt + 66 := by rw [newAt]; rfl + exact r.next_data x (by omega) + · intro x hx + rw [newAt] at hx + apply (r.graph_frame x hx).trans + rcases hx with h|⟨j, hj, rfl⟩|h + · have ge : nxt ≤ x := by rcases h with h|h <;> omega + exact throughSlots x (by omega) (.inr h) + · simp only [List.mem_cons, List.not_mem_nil, or_false] at hj + exact throughSlots _ (by omega) (.inl (by omega)) + · unfold CurrentGraph.frameCell at h + exact throughSlots _ (by omega) (.inl (by omega)) + · intro x lo hi + rw [ix] at hi + have floor' : levelStart L 0 ≤ x := by + simpa only [levelStart, Nat.zero_mul, Nat.add_zero] using lo + exact (r.earlier x hi).trans + ((throughSlots x floor' (.inl (by omega))).trans (sub.before v next x (by omega))) + +end CompressorRecords.ShrinkScheduledTail + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkDemandFrame.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkDemandFrame.lean new file mode 100644 index 0000000000..fd7e302c46 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkDemandFrame.lean @@ -0,0 +1,67 @@ +import OAI.Computability.VPVNP.CompressorRecordsDemandWidths + +/-! +# Retaining the sorted width and field-start rectangles + +The dense demand array and term records can be allocated beyond the old +width tables. Any scan that preserves the preceding addresses then keeps +the six width and field-start columns required by the interval kernels. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkDemandFrame + +open Compression Compression.PackingData BurstRAM + +variable {w B k q : ℕ} + +/-- The two old rectangles have their own strides. The balanced AB rectangle +has one live entry per CD rank. All six columns precede the scratch arena. -/ +structure Before (B k q : ℕ) (thick cdRows ab : Fin 5 → BurstRAM.Word w) (head : ℕ) : Prop where + thickRanks : k ≤ (thick 1).val + cdRanks : q ≤ (cdRows 1).val + abRanks : q ≤ (ab 1).val + thickWidths : (thick 2).val+B*(thick 1).val ≤ head + thickStarts : (thick 3).val+B*(thick 1).val ≤ head + cdWidths : (cdRows 2).val+B*(cdRows 1).val ≤ head + cdStarts : (cdRows 3).val+B*(cdRows 1).val ≤ head + abWidths : (ab 3).val+B*(ab 1).val ≤ head + abStarts : (ab 4).val+B*(ab 1).val ≤ head + +private theorem cell_lt {base head stride : ℕ} (b : Fin B) (i : Fin k) (hs : k ≤ stride) + (h : base+B*stride ≤ head) : base+b.val*stride+i.val < head := by + have row := Nat.mul_le_mul_right stride b.isLt + rw [Nat.succ_mul] at row + have := i.isLt + omega + +variable {V H T L : Type} {d c n : ℕ} [AddCommGroup H] [AddCommGroup T] [AddCommGroup L] +variable [Fintype V] [Fintype H] [Fintype T] [Fintype L] +variable [DecidableEq V] [DecidableEq T] [DecidableEq L] +variable {P : PackingData V H T L d c} {site : Site V T L ≃ Fin n} {old : Arc V H T L d c → ℕ} +variable {dd : P.ThickNumbering} {cd : P.BundleNumbering} {thick cdRows ab : Fin 5 → BurstRAM.Word w} + +/-- The six source columns still represent the same old widths and starts +after the dense demand and term phases. -/ +theorem retain {mem out : Memory w} {head : ℕ} + (stored : DemandWidths.Stored P site old dd cd thick cdRows ab mem) + (earlier : Before (n*d) (2^c*d/4) (pieceCount d c) thick cdRows ab head) + (keep : ∀ a < head, out a = mem a) : + DemandWidths.Stored P site old dd cd thick cdRows ab out := by + let idx := BundleLists.portIndex (d := d) site + refine ⟨fun b i => ?_,fun b i => ?_,fun b x => ?_,fun b x => ?_,⟨fun b i => ?_,fun b i => ?_⟩⟩ + · rw [keep _ (cell_lt (idx b) i earlier.thickRanks earlier.thickWidths)]; exact stored.thickWidths b i + · rw [keep _ (cell_lt (idx b) i earlier.cdRanks earlier.cdWidths)]; exact stored.cdWidths b i + · rw [keep _ (cell_lt (idx b) (dd b x) earlier.thickRanks earlier.thickStarts)]; exact stored.thickStarts b x + · rw [keep _ (cell_lt (idx b) (cd b x) earlier.cdRanks earlier.cdStarts)]; exact stored.cdStarts b x + · rw [keep _ (cell_lt (idx b) i earlier.abRanks earlier.abWidths)]; exact stored.ab.widths b i + · rw [keep _ (cell_lt (idx b) i earlier.abRanks earlier.abStarts)]; exact stored.ab.starts b i + +end CompressorRecords.ShrinkDemandFrame + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkDemandGather.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkDemandGather.lean new file mode 100644 index 0000000000..27ba289790 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkDemandGather.lean @@ -0,0 +1,202 @@ +import OAI.Computability.VPVNP.CompressorShrinkDemandGatherCall +import OAI.Computability.VPVNP.RAMChain +import OAI.Computability.VPVNP.CompressorRecordGreedy + +/-! +# Gathering the two rectangular shrink demands in motif order + +The AB and CD rectangles may use different strides. Each visit reads one +cell of each rectangle and writes both values into the next dense demand +row. The output is disjoint from both sources. Source padding is never read. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkDemandGather + +open BurstRAM BurstRAM.PrivateRAM + +variable {w B Q : ℕ} {p : Fin 6 → Word w} + +/-- The two source rectangles need room for their strides and the destination +needs two cells per motif. Either rectangle can precede or follow the output. -/ +structure Layout (B Q : ℕ) (p : Fin 6 → Word w) : Prop where + columns : (p 0).val = Q + abStride : Q ≤ (p 1).val + cdStride : Q ≤ (p 2).val + abFit : (p 3).val+B*(p 1).val ≤ 2^w + cdFit : (p 4).val+B*(p 2).val ≤ 2^w + denseFit : (p 5).val+2*(B*Q) ≤ 2^w + abApart : (p 3).val+B*(p 1).val ≤ (p 5).val ∨ (p 5).val+2*(B*Q) ≤ (p 3).val + cdApart : (p 4).val+B*(p 2).val ≤ (p 5).val ∨ (p 5).val+2*(B*Q) ≤ (p 4).val + +private abbrev word (i : ℕ) : Word w := Fin.ofNat _ i + +private def sourceCell (p : Fin 6 → Word w) (Q i : ℕ) (s a : Fin 6) : ℕ := + (p a).val+(i/Q)*(p s).val+i%Q + +private theorem packed_lt {b r B Q : ℕ} (hb : b < B) (hr : r < Q) : b*Q+r < B*Q := by + have h := Nat.mul_le_mul_right Q hb + rw [Nat.succ_mul] at h + omega + +private theorem source_bounds (L : Layout B Q p) {i : ℕ} (hi : i < B*Q) (s a : Fin 6) + (stride : Q ≤ (p s).val) (fit : (p a).val+B*(p s).val ≤ 2^w) + (apart : (p a).val+B*(p s).val ≤ (p 5).val ∨ (p 5).val+2*(B*Q) ≤ (p a).val) : + (src p (word i) s a).val = sourceCell p Q i s a ∧ + (sourceCell p Q i s a < (p 5).val ∨ (p 5).val+2*(B*Q) ≤ sourceCell p Q i s a) := by + have hq : 0 < Q := by + by_contra! hz + simp [Nat.eq_zero_of_le_zero hz] at hi + have ho := packed_lt ((Nat.div_lt_iff_lt_mul hq).mpr hi) ((Nat.mod_lt i hq).trans_le stride) + have hx : i < 2^w := by have := L.denseFit; omega + have hv : (word (w := w) i).val = i := Nat.mod_eq_of_lt hx + have hdiv : (BinaryOp.div.eval (word i) (p 0)).val = i/Q := by + change ((word (w := w) i).val / (p 0).val) % (2^w) = _ + rw [hv, L.columns, Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt hx)] + have hmod : (BinaryOp.mod.eval (word i) (p 0)).val = i%Q := by + change ((word (w := w) i).val % (p 0).val) % (2^w) = _ + rw [hv, L.columns, Nat.mod_eq_of_lt ((Nat.mod_le ..).trans_lt hx)] + constructor + · simp only [src, Fin.val_add, Fin.val_mul, hdiv, hmod, Nat.mod_add_mod, Nat.add_mod_mod, sourceCell] + apply Nat.mod_eq_of_lt + omega + · unfold sourceCell + omega + +/-- Each physical read address belongs to its live input rectangle. -/ +theorem source_range (L : Layout B Q p) {i : ℕ} (hi : i < B*Q) (s a : Fin 6) + (stride : Q ≤ (p s).val) (fit : (p a).val+B*(p s).val ≤ 2^w) + (apart : (p a).val+B*(p s).val ≤ (p 5).val ∨ (p 5).val+2*(B*Q) ≤ (p a).val) : + (p a).val ≤ (src p (word i) s a).val ∧ (src p (word i) s a).val < (p a).val+B*(p s).val := by + rw [(source_bounds L hi s a stride fit apart).1] + have hq : 0 < Q := by by_contra! hz; simp [Nat.eq_zero_of_le_zero hz] at hi + have h := packed_lt ((Nat.div_lt_iff_lt_mul hq).mpr hi) ((Nat.mod_lt i hq).trans_le stride) + unfold sourceCell + omega + +theorem dest_bounds (L : Layout B Q p) {i : ℕ} (hi : i < B*Q) : + (dst p (word i)).val = (p 5).val+2*i ∧ (dst p (word i)+1).val = (p 5).val+2*i+1 := by + have h := L.denseFit + have hv : (word (w := w) i).val = i := Nat.mod_eq_of_lt (by omega) + have h₁ : (dst p (word i)).val = (p 5).val+2*i := by + rw [dst, Fin.val_add, Fin.val_add, hv, Nat.mod_add_mod, Nat.mod_eq_of_lt (by omega)] + omega + exact ⟨h₁, by rw [Fin.val_add, h₁, Fin.val_one', Nat.add_mod_mod, Nat.mod_eq_of_lt (by omega)]⟩ + +private structure Prefix (p : Fin 6 → Word w) (Q k : ℕ) (ref mem : Memory w) : Prop where + rows : ∀ j < k, mem ((p 5).val+2*j) = ref (sourceCell p Q j 1 3) ∧ + mem ((p 5).val+2*j+1) = ref (sourceCell p Q j 2 4) + frame : ∀ a, a < (p 5).val ∨ (p 5).val+2*k ≤ a → mem a = ref a + +private theorem step (L : Layout B Q p) {ref mem : Memory w} {i : ℕ} (hi : i < B*Q) + (old : Prefix p Q i ref mem) : Prefix p Q (i+1) ref (after mem (visits p (word i) mem).events) := by + obtain ⟨ha, fa⟩ := source_bounds L hi 1 3 L.abStride L.abFit L.abApart + obtain ⟨hb, fb⟩ := source_bounds L hi 2 4 L.cdStride L.cdFit L.cdApart + obtain ⟨hd, he⟩ := dest_bounds L hi + have hA := old.frame (sourceCell p Q i 1 3) (by omega) + have hC := old.frame (sourceCell p Q i 2 4) (by omega) + rw [visit_after] + constructor + · intro j hj + simp only [writeMemory, ha, hb, hd, he, hA, hC] + rcases Nat.eq_or_lt_of_le (Nat.le_of_lt_succ hj) with heq | h + · subst j + simp + · simpa only [ite_eq_right (show (p 5).val+2*j ≠ (p 5).val+2*i by omega), + ite_eq_right (show (p 5).val+2*j ≠ (p 5).val+2*i+1 by omega), + ite_eq_right (show (p 5).val+2*j+1 ≠ (p 5).val+2*i by omega), + ite_eq_right (show (p 5).val+2*j+1 ≠ (p 5).val+2*i+1 by omega)] using old.rows j h + · intro a h + simpa only [writeMemory, hd, he, ite_eq_right (show a ≠ (p 5).val+2*i by omega), + ite_eq_right (show a ≠ (p 5).val+2*i+1 by omega)] using old.frame a (by omega) + +private def SiteCost (r : Report w) : Prop := + r.events.length = cost ∧ countProbes r.events = 4 ∧ choiceBits r.events = [] ∧ r.events.count .tick = 20 + +private theorem segment (L : Layout B Q p) {ref mem : Memory w} {i cap : ℕ} + (hcap : cost < cap) (old : Prefix p Q i ref mem) (steps : ℕ) (bound : i+steps ≤ B*Q) : + ∃ rs, runSegment (program p) cap (some (word i)) mem (List.replicate steps []) = some rs ∧ + endState (some (word i)) rs = some (word (i+steps)) ∧ + Prefix p Q (i+steps) ref (after mem (eventLog rs)) ∧ rs.length = steps ∧ ∀ r ∈ rs, SiteCost r := by + induction steps generalizing i mem with + | zero => exact ⟨[], rfl, rfl, old, rfl, by simp⟩ + | succ s ih => + let r := visits p (word i) mem + have hn : word (w := w) i+1 = word (i+1) := by + apply Fin.ext + simp [word, Fin.val_add, Nat.add_mod_mod, Nat.mod_add_mod] + have hr : r.result = some (word (i+1)) := by rw [show r.result = _ from visits_result p (word i) mem, hn] + have hs : i+1+s = i+(s+1) := by omega + obtain ⟨rs, run, stop, state, len, costs⟩ := ih (step L (by omega) old) (by omega) + refine ⟨r::rs, ?_, ?_, ?_, by simp [len], ?_⟩ + · rw [List.replicate_succ, runSegment, visit_run p (word i) mem hcap] + change (runSegment _ _ r.result (after mem r.events) _).map _ = _ + rw [hr, run]; rfl + · change endState r.result rs = _ + rw [hr, stop, hs] + · change Prefix p Q _ ref ((r.events ++ eventLog rs).foldl BurstRAM.update mem) + rw [List.foldl_append, ← hs]; exact state + · intro z hz + rcases List.mem_cons.mp hz with rfl | h + · obtain ⟨e, pr, bs⟩ := visit_cost p (word i) mem + exact ⟨e, pr, bs, visit_ticks p (word i) mem⟩ + · exact costs z h + +/-- Exact execution, dense row contents, frame, and costs of one shrink gather pass. -/ +structure Gathered (B Q : ℕ) (p : Fin 6 → Word w) (cap : ℕ) (ref : Memory w) (rs : List (Report w)) : Prop where + run : runSegment (program p) cap (some 0) ref (List.replicate (B*Q) []) = some rs + endCursor : endState (some 0) rs = some (Fin.ofNat (2^w) (B*Q)) + readAB : ∀ b < B, ∀ r < Q, after ref (eventLog rs) ((p 5).val+2*(b*Q+r)) = + ref ((p 3).val+b*(p 1).val+r) + readCD : ∀ b < B, ∀ r < Q, after ref (eventLog rs) ((p 5).val+2*(b*Q+r)+1) = + ref ((p 4).val+b*(p 2).val+r) + frame : ∀ a, a < (p 5).val ∨ (p 5).val+2*(B*Q) ≤ a → after ref (eventLog rs) a = ref a + count : rs.length = B*Q + perCall : ∀ r ∈ rs, r.events.length = cost ∧ countProbes r.events = 4 ∧ + choiceBits r.events = [] ∧ r.events.count .tick = 20 + events : (eventLog rs).length = cost*(B*Q) + probes : countProbes (eventLog rs) = 4*(B*Q) + ticks : (eventLog rs).count .tick = 20*(B*Q) + +private theorem total (rs : List (Report w)) (h : ∀ r ∈ rs, SiteCost r) : + (eventLog rs).length = cost*rs.length ∧ countProbes (eventLog rs) = 4*rs.length ∧ + (eventLog rs).count .tick = 20*rs.length := by + induction rs with + | nil => exact ⟨rfl, rfl, rfl⟩ + | cons r rs ih => + obtain ⟨le, pr, _, ticks⟩ := h r List.mem_cons_self + obtain ⟨ls, ps, ts⟩ := ih fun z hz => h z (List.mem_cons_of_mem r hz) + change (r.events ++ eventLog rs).length = _ ∧ countProbes (r.events ++ eventLog rs) = _ ∧ + (r.events ++ eventLog rs).count .tick = _ + rw [List.length_append, Greedy.probes_append, List.count_append, le, pr, ticks, ls, ps, ts, + List.length_cons] + simp only [Nat.mul_add, Nat.mul_one] + omega + +/-- The scan reads the original source cell at every bundle and rank, even +when earlier rows have already been written to dense memory. -/ +theorem gather (L : Layout B Q p) (ref : Memory w) {cap : ℕ} (hcap : cost < cap) : + ∃ rs, Gathered B Q p cap ref rs := by + have start : Prefix p Q 0 ref ref := ⟨fun _ h => by omega, fun _ _ => rfl⟩ + obtain ⟨rs, run, stop, state, len, costs⟩ := segment L hcap start (B*Q) (by omega) + simp only [Nat.zero_add] at stop state + have row {b r : ℕ} (hb : b BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "fst" => Script.levelsPerBlock scr * round +local notation "cur" => fst + i.val +local notation "head" => levelStart L cur +local notation "nextHead" => levelStart L (cur + 1) +local notation "tab" => (fun j : Fin 6 => tableBase L cur j) +local notation "T" => packedIncidence L w cur (DemandRAM.oldCount X) +local notation "term" => ShrinkInput.termHead (w := w) X (tab 0) +local notation "v" => shrinkLevel B f hf i X sel bits + +variable {raw : Memory w} +variable {p : ShrinkBranch.Prefix X + (packedIncidence (BlockProgram.layout B base.val positions blocks) w + ((S.steps + 1) * round + i.val) (DemandRAM.oldCount X)) + (tableBase (BlockProgram.layout B base.val positions blocks) + ((S.steps + 1) * round + i.val) (0 : Fin 6)) fuel raw} +variable (branch : ShrinkBranch.Selected B X + (packedIncidence (BlockProgram.layout B base.val positions blocks) w + ((S.steps + 1) * round + i.val) (DemandRAM.oldCount X)) + (tableBase (BlockProgram.layout B base.val positions blocks) + ((S.steps + 1) * round + i.val) (0 : Fin 6)) + 10 (B.shrink.selectorBits : Word w) fuel raw p sel) +variable {ps₅ ps₆ ps₇ ps₈ metadata tail : List (Packet (BlockProgram.script B) w)} +variable {r : ShrinkOutput.TablesRun w} +variable (z : Finish B i X sel base positions blocks round cap + branch.beforeOutput ps₅ ps₆ ps₇ ps₈ metadata tail r) +variable (live : round < blocks) (size : X.positions ≤ positions) + (fit : endAddress (BlockProgram.layout B base.val positions blocks) < 2 ^ w) +local notation "mid" => post branch.beforeOutput (((ps₅ ++ ps₆) ++ ps₇) ++ ps₈) +local notation "out" => post mid tail + +include z live size fit in +private theorem Finish.before_tail (x : ℕ) + (safe : (x < tab 1 ∧ (x < head + 30 ∨ head + 36 ≤ x)) ∨ + (nextHead ≤ x ∧ x < incidenceStart L (cur + 1))) : mid x = branch.beforeOutput x := by + have bnd := ShrinkResidentSources.bounds B i X base positions blocks round live size fit + have beforeNext : tab 1 ≤ nextHead := (Nat.le_add_right ..).trans + (tableEnd_le_nextLevel L cur (1 : Fin 6)) + have beforeFive : tab 1 ≤ tab 5 := (Nat.le_add_right ..).trans + (tableEnd_le_tableBase L cur (show (1 : Fin 6) < 5 by decide)) + have headerBefore : head + 66 ≤ nextHead := by + have h : head + 66 ≤ tab 1 := by + change head + 66 ≤ head + 66 + 6 * slotCapacity L + 1 * tableWords L + omega + exact h.trans beforeNext + rcases safe with ⟨hi, h⟩|⟨lo, hi⟩ + · apply (z.output.frame live size fit x (.inl hi) + (.inl ((hi.trans_le beforeNext).trans_le (Nat.le_add_right ..)))).trans + apply z.output.residents.preserved + rintro (d|d) + · exact (hi.trans_le beforeFive).not_ge d.1 + · change head + 30 ≤ x ∧ x < head + 36 at d + omega + · apply (z.output.frame live size fit x (.inr (bnd.slotEnd.trans lo)) (.inl hi)).trans + apply z.output.residents.preserved + rintro (d|d) + · exact (d.2.trans_le bnd.residentEnd).not_ge lo + · change head + 30 ≤ x ∧ x < head + 36 at d + omega + +include z live size fit in +/-- Actual preimage collection, physical slot frame and metadata reports +give the directory in the final memory, including its successor's DFS base. -/ +def Finish.selectedEmission (length : mid (levelStart L 0 + 29) = (n : Word w)) : + Emission L cur v mid out := by + have bnd := ShrinkResidentSources.bounds B i X base positions blocks round live size fit + have ins := z.output.tail_inputs live size fit + have nextFit := (levelStart_mono L bnd.nextLive.le).trans_lt fit + have beforeNext : tab 1 ≤ nextHead := (Nat.le_add_right ..).trans + (tableEnd_le_nextLevel L cur (1 : Fin 6)) + have headerBefore : head + 66 ≤ tab 0 := by + change head + 66 ≤ head + 66 + 6 * slotCapacity L + 0 * tableWords L + omega + apply z.published.selectedEmission T branch.postTerm.geometry + (bnd.selectedBefore.trans beforeNext) + nextFit bnd.termRoom _ ins.header ins.pitch ins.rows length + intro x lo hi + change tab 0 ≤ x at lo + exact z.before_tail branch live size fit x + (.inl ⟨hi.trans_le bnd.selectedBefore, .inr (by omega)⟩) + +include z live size fit in +/-- Starting at the actual substep, append one occurrence to both the DFS +history and the retained parser snapshots. The geometry frame is the one +returned by the first 36 calendar visits. -/ +theorem Finish.advance {initial : TaggedLayer} {initialFrame : Fin 8 → Word w} + {past : List (SelectedLevel B f hf)} {before : Memory w} + (old new : Fin (L).levels) (oldAt : old.val = cur) (next : old.val + 1 = new.val) + (index : past.length = old.val) + (stored : CompiledResident.resident B f hf base positions blocks n initial initialFrame + past X before) + (sub : Substep v L old new (by change 6 ≤ 54; decide) before) + (geometry : ∀ x, x < tab 0 ∨ nextHead ≤ x + → branch.beforeOutput x = finalMemory v L old new before x) : + CompiledResident.resident B f hf base positions blocks n initial initialFrame + (past ++ [v]) ((v).pass.next (v).term) out := by + have newAt : new.val = cur + 1 := by omega + have ix := index.trans oldAt + have floor := levelStart_mono L (Nat.zero_le cur) + have cut : head + 66 ≤ tab 0 := by + change head + 66 ≤ head + 66 + 6 * slotCapacity L + 0 * tableWords L + omega + have order : tab 0 ≤ tab 1 := (Nat.le_add_right ..).trans + (tableEnd_le_tableBase L cur (show (0 : Fin 6) < 1 by decide)) + have nextBound : levelStart L (cur + 1) ≤ incidenceStart L (cur + 1) := Nat.le_add_right .. + have through (x : ℕ) (hx : x < head + 30 ∨ CurrentGraph.graphCell L (cur + 1) x) : + mid x = finalMemory v L old new before x := by + rcases hx with low | h + · exact (z.before_tail branch live size fit x (.inl ⟨by omega, .inl low⟩)).trans + (geometry x (.inl (by omega))) + · have a : nextHead ≤ x ∧ x < incidenceStart L (cur + 1) := by + rcases h with h|h + · change _ ∧ x < nextHead + 66; omega + · exact ⟨(Nat.le_add_right ..).trans h.1, h.2⟩ + exact (z.before_tail branch live size fit x (.inr a)).trans (geometry x (.inr a.1)) + have earlier : InputFrame L cur before (finalMemory v L old new before) := + oldAt ▸ InputFrame.substep sub next + have post8Frame : InputFrame L cur (finalMemory v L old new before) mid := by + refine ⟨fun x _ hi => through x (.inl (by omega)), ?_⟩ + intro x hx + obtain ⟨lo, hi⟩ := hx + change head + 54 ≤ x at lo + have cutEq : arrayBase L cur = tab 0 := by change _ = _ + 0 * _; omega + rw [cutEq] at hi + exact ((z.before_tail branch live size fit x (.inl ⟨hi.trans_le order, .inr (by omega)⟩)).trans + (geometry x (.inl hi))).symm + have stable := (earlier.trans post8Frame).trans (InputFrame.shrinkTail z.published) + have length : mid (levelStart L 0 + 29) = (n : Word w) := by + apply (through _ (.inl (by omega))).trans + apply (sub.firstScalarTail v next 29 (by decide) (by change 29 < 54; decide)).trans + exact (Fin.cast_val_eq_self _).symm.trans + (congrArg (fun x : ℕ => (x : Word w)) stored.1.2.1.startup.length) + have bnd := ShrinkResidentSources.bounds B i X base positions blocks round live size fit + have ins := z.output.tail_inputs live size fit + have counts := (ShrinkSlots.next_counts X B.shrink (S.shrink i) sel).2 + have countEq : IncidenceDirectory.slotCount ((v).pass.next (v).term) = + ShrinkSlots.actualCount (ShrinkSlots.levelShape (b := b i) X) := counts + have current := z.published.advance old new oldAt next index stored.1 sub fit + (countEq.symm ▸ bnd.nextCapacity) (by + rw [newAt, countEq] + exact z.output.readbacks.incidence) + (z.selectedEmission branch live size fit length) (fun x _ h => through x h) + apply DetailedResident.append stored current + · rw [ix] + change CompiledResident.ShrinkPayload B base positions blocks n cur i X sel out + refine ⟨bnd, ShrinkResidentSources.Data.capture branch z.output z.published live size fit, + ShrinkResidentHeaders.Words.of_tail z.published ins.header ins.oldHeads ins.nextHeads + z.output.readbacks ins.rows ins.pitch length live size fit, + SelectedChildDirectory.Stored.of_shrink_tail z.published ins.header ins.pitch + bnd.termRoom ins.rows length, + ⟨ShrinkInput.demandHead (w := w) X (tab 0), fuel, p.beforeTerm, branch.terms, ?_⟩⟩ + have ten : (10 : Word w).val = 10 := + Nat.mod_eq_of_lt (show (10 : ℕ) < 2 ^ w by have := ins.header.room; omega) + have tr := branch.termRun + rw [ten] at tr + exact tr + · simpa only [ix] using stable.earlier + · simpa only [ix] using stable.graph + +end CompressorRecords.ShrinkScheduledFinish + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkForward.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkForward.lean new file mode 100644 index 0000000000..3d23dc5e54 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkForward.lean @@ -0,0 +1,96 @@ +import OAI.Computability.VPVNP.CompressorBlockGroups +import OAI.Computability.VPVNP.CompressorSourceGroups + +/-! +# Joining the scheduled shrinking visit windows + +The concrete script breaks a shrinking substep into twelve chronological groups. +The live ordinal of each group's first visit includes the initial startup rows, all +completed compression blocks, all preceding shrinking substeps, and all earlier +groups of this substep. Source runs, clock and memory checks, and operand readback +are transported across these offsets by concatenating the true packet lists. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.SourceOnline + +open BurstRAM BlockPlanner DescriptorSpace + +variable {w : ℕ} {A : Script} {L : Layout} {base : Word w} {cap total : ℕ} + +namespace Group + +/-- Concatenate finitely many checked groups, each evaluated from the post-memory of +all groups before it. The earlier packet lengths determine the current ordinal. -/ +theorem flatten (ordinal : ℕ) (m : Memory w) (batches : List (List (Packet A w))) + (runs : ∀ i : Fin batches.length, + Group A L base cap (ordinal+(batches.take i.val).flatten.length) total + (post m (batches.take i.val).flatten) batches[i.val]) : + Group A L base cap ordinal total m batches.flatten := by + induction batches generalizing ordinal m with + | nil => exact nil + | cons ps batches ih => + have head : Group A L base cap ordinal total m ps := by simpa [post,eventLog,after] using runs 0 + have tail (i : Fin batches.length) : + Group A L base cap (ordinal+ps.length+(batches.take i.val).flatten.length) total + (post (post m ps) (batches.take i.val).flatten) batches[i.val] := by + have h := runs (Fin.succ i) + simpa only [Fin.val_succ,List.take_succ_cons,List.flatten_cons,List.length_append, + Nat.add_assoc,List.getElem_cons_succ,post_append] using h + exact head.append (ih (ordinal+ps.length) (post m ps) tail) + +end Group + +end CompressorRecords.SourceOnline + +namespace CompressorRecords.ShrinkForward + +open BurstRAM Compression BlockPlanner DescriptorSpace SourceOnline + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {w : ℕ} (L : Layout) (base : Word w) (cap total round : ℕ) +local notation "A" => BlockProgram.script B + +/-- Ordinal of the first call in the substep, including all earlier iterations. -/ +noncomputable def first := (A).initial.length + round*(A).block.length + (BlockIndex.earlier B i).length + +/-- The static visit count in a prefix of the twelve constituent windows. -/ +noncomputable def visitsBefore (j : ℕ) := ((BlockGroups.parts B i).take j).flatten.length + +/-- A physical group retains all data and guard checks, and is attached to the actual +catalog occurrences of this particular shrinking substep. -/ +structure Groups (m : Memory w) (rows : Fin 12 → List (Packet A w)) : Prop where + length : ∀ j, (rows j).length = ((BlockGroups.parts B i)[j.val]'j.isLt).length + checked : ∀ j, + Group A L base cap (first B i round + visitsBefore B i j.val) total + (post m ((List.ofFn rows).take j.val).flatten) (rows j) + +/-- Source execution and operand/clock/footprint facts for the whole chronological +window of the actual online script. -/ +theorem joined (m : Memory w) (rows : Fin 12 → List (Packet A w)) + (h : Groups B i L base cap total round m rows) : + Group A L base cap (first B i round) total m (List.ofFn rows).flatten := by + apply Group.flatten + intro j + let u : Fin 12 := ⟨j.val, by simpa using j.isLt⟩ + have lengths : (List.ofFn rows).map List.length = (BlockGroups.parts B i).map List.length := by + apply List.ext_getElem + · simp [BlockGroups.parts_length] + · intro z hz hz' + have hv : z<12 := by simpa using hz + simp only [List.getElem_map,List.getElem_ofFn] + exact h.length ⟨z,hv⟩ + have offset : ((List.ofFn rows).take j.val).flatten.length = visitsBefore B i j.val := by + rw [visitsBefore,List.length_flatten,List.length_flatten,List.map_take,List.map_take,lengths] + rw [offset] + rw [List.getElem_ofFn] + exact h.checked u + +end CompressorRecords.ShrinkForward + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkGatherDispatch.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkGatherDispatch.lean new file mode 100644 index 0000000000..79a4d25d9d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkGatherDispatch.lean @@ -0,0 +1,99 @@ +import OAI.Computability.VPVNP.CompressorShrinkDemandGather +import OAI.Computability.VPVNP.CompressorRecordsOrdinalFootprint +import OAI.Computability.VPVNP.RAMChoicePrefix + +/-! +# Dispatching the shrinking width gather + +The finite width worker reads only its two sorted rectangles. Its +writes stay within the dense demand pairs. The same reports can thus +be replayed after the online scheduler has prepared the active frame. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkDemandGather + +open BurstRAM Schedule OrdinalRun SourceTransport +open scoped Fin.CommRing + +variable {B Q w : ℕ} (p : Fin 6 → Word w) (L : Layout B Q p) + +/-- Union of the two source rectangles from which the gather worker may read across `B` rows, +each with its own base and stride. -/ +def ReadRegion (B : ℕ) (p : Fin 6 → Word w) (x : ℕ) : Prop := + ((p 3).val ≤ x ∧ x < (p 3).val+B*(p 1).val) ∨ ((p 4).val ≤ x ∧ x < (p 4).val+B*(p 2).val) + +/-- Dense output interval for the width pairs, containing two words for each of the `B * Q` +visited motifs. -/ +def WriteRegion (B Q : ℕ) (p : Fin 6 → Word w) (x : ℕ) : Prop := + (p 5).val ≤ x ∧ x < (p 5).val+2*(B*Q) + +include L in +private theorem row_footprint {j : ℕ} (hj : j < B*Q) (mem : Memory w) : + Reads (ReadRegion B p) (visits p (j : Word w) mem).events ∧ + Writes (WriteRegion B Q p) (visits p (j : Word w) mem).events := by + obtain ⟨dst,dst'⟩ := dest_bounds L hj + change (ShrinkDemandGather.dst p (j : Word w)).val = _ at dst + change (ShrinkDemandGather.dst p (j : Word w)+1).val = _ at dst' + have ab := source_range L hj 1 3 L.abStride L.abFit L.abApart + have cd := source_range L hj 2 4 L.cdStride L.cdFit L.cdApart + constructor + · intro a v h + simp [visits] at h + rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ + · exact .inl ab + · exact .inr cd + · intro a v h + simp [visits] at h + rcases h with ⟨rfl,_⟩ | ⟨rfl,_⟩ + · unfold WriteRegion; rw [dst]; omega + · unfold WriteRegion; rw [dst']; omega + +variable {cap : ℕ} (hcap : cost < cap) (mem : Memory w) (rs : List (Report w)) +variable (run : runSegment (program p) cap (some 0) mem (List.replicate (B*Q) []) = some rs) + +include L hcap run + +/-- All reads can be transported across control-memory changes. All writes +are confined to the dense output even for the last pair. -/ +theorem footprints : Reads (ReadRegion B p) (eventLog rs) ∧ Writes (WriteRegion B Q p) (eventLog rs) := by + let cursor (i : ℕ) : Word w := i + apply OrdinalRun.footprint (program p) cap cursor (B*Q) (fun _ _ => True) _ _ _ 0 _ mem rs (by simp) trivial run + intro j hj m _ bits r h + have eqn := (execute_prefix_unique (visit_run p (j : Word w) m hcap) + (show execute (program p) cap ((program p).start (j : Word w)) m ([] ++ bits) = some r from h)).2 + subst r + obtain ⟨rd,wr⟩ := row_footprint p L hj m + exact ⟨by simp [cursor,visits_result],trivial,rd,wr⟩ + +/-- The complete dense gather satisfies every exclusive guard and preserves +the frame, tag, ordinal and row count of the online dispatcher. -/ +theorem valid_trace {d : ℕ} (C : Catalog d) (worker : Fin d) (ports : Ports w) + (pub : Fin (C worker).params → Word w) (stopFit : B*Q < 2^w) + (apart : ∀ x, ControlCell (C worker).params ports x → ¬ WriteRegion B Q p x) + (ready : Ready C worker ports pub (B*Q : ℕ) mem) : + ValidTrace C worker ports pub (B*Q : ℕ) 0 mem rs ∧ Preserved (C worker).params ports mem (after mem (eventLog rs)) := by + let cursor (i : ℕ) : Word w := i + have active (i : ℕ) (hi : i < B*Q) : cursor i < cursor (B*Q) := by + change i%(2^w) < (B*Q)%(2^w) + rwa [Nat.mod_eq_of_lt (hi.trans stopFit),Nat.mod_eq_of_lt stopFit] + have advance (j : ℕ) (hj : j < B*Q) (m : Memory w) (_ : True) (bits : List Bool) (r : Report w) + (h : execute (program p) cap ((program p).start (cursor j)) m bits = some r) : + r.result = some (cursor (j+1)) ∧ True ∧ Preserved (C worker).params ports m (after m r.events) := by + have eqn := (execute_prefix_unique (visit_run p (j : Word w) m hcap) + (show execute (program p) cap ((program p).start (j : Word w)) m ([] ++ bits) = some r from h)).2 + subst r + exact ⟨by simp [cursor,visits_result],trivial,fun x hx => + after_outside m (row_footprint p L hj m).2 (apart x hx)⟩ + obtain ⟨h,_,keep⟩ := OrdinalRun.validTrace C worker ports (program p) cap pub (cursor (B*Q)) cursor (B*Q) + (fun _ _ => True) active le_rfl advance 0 _ mem rs (by simp) trivial ready run + exact ⟨h,keep⟩ + +end CompressorRecords.ShrinkDemandGather + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryCharge.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryCharge.lean new file mode 100644 index 0000000000..92db5bd22b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryCharge.lean @@ -0,0 +1,104 @@ +import OAI.Computability.VPVNP.CompressorGroupCost +import OAI.Computability.VPVNP.CompressorShrinkSelectedGroup +import OAI.Computability.VPVNP.CompressorShrinkResidentCosts +import OAI.Computability.VPVNP.CompressorShrinkLevelSpace + +/-! # Calls and probes of installed selected shrinking geometry -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ScheduledTrace + +open BlockPlanner BurstRAM Schedule + +/-- The catalog bounds frame probes per source call and scheduler probes +per packet. Both constants are fixed with the script. -/ +def groupRate (A : Script) (dataRate rowRate : ℕ) := + dataRate*(arity A.catalog+3)+rowRate*(Online.Run.maxReads A.plan+4*arity A.catalog+26) + +theorem groupCost_le {w : ℕ} (A : Script) (ps : List (SourceOnline.Packet A w)) (units dataRate rowRate : ℕ) + (data : RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) ≤ units*dataRate) + (rows : ps.length ≤ units*rowRate) : groupCost A ps ≤ units*groupRate A dataRate rowRate := by + rw [groupRate,Nat.mul_add,← Nat.mul_assoc,← Nat.mul_assoc] + exact Nat.add_le_add (Nat.mul_le_mul_right _ data) (Nat.mul_le_mul_right _ rows) + +end CompressorRecords.ScheduledTrace + +namespace CompressorRecords.SelectedTailPackets + +open BurstRAM Compression BlockPlanner DescriptorSpace Schedule ScheduledTrace +open scoped Fin.CommRing Classical +open private positions_eq packed_le from OAI.Computability.VPVNP.CompressorShrinkLevelSpace + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) +variable (T : IncidenceDirectory w) (start : ℕ) (stride selectors : Word w) +variable {fuel : ℕ} {s : SelectedScore.Selection B X} {m : Memory w} {p : ShrinkBranch.Prefix X T start fuel m} +variable (v : ShrinkBranch.Selected B X T start stride selectors fuel m p s) + +/-- Source cost per incoming position. It uses the stronger dense-motif +bound of one motif per old arc. -/ +def geometryRate (a : ℕ) := 51*2^a+23 + +theorem geometry_charge : + RAMBuckets.cost Report.probes v.geometry.reports ≤ X.positions*geometryRate a ∧ + v.geometry.reports.length = selectedCalls X := by + let P := X.positions + let M := SelectedArena.motifs X + let V := ShrinkPreimages.newCount X + let old := SelectedArena.positions X + let arcs := DemandRAM.oldCount X + have hp : old=P := positions_eq X + have ho : ShrinkPreimages.oldCount X=P := positions_eq X + have ha : arcs=P*2^a := congrArg (·*2^a) (positions_eq X) + have hm : M ≤ P*2^a := (ShrinkResidentLayout.motif_le_slots X).trans_eq (congrArg (·*2^a) ho) + have hv : V ≤ P := packed_le X + have pos : 1 ≤ P := X.positions_pos + have ch := ChosenGeometry.Run.charge B X _ stride selectors _ T s _ _ v.geometry v.postTerm + change RAMBuckets.cost Report.probes v.geometry.reports = (40*M+7)+9*old+11*arcs+(2*V+5*ShrinkPreimages.oldCount X) at ch + constructor + · rw [ch,hp,ha,ho] + change _ ≤ P*(51*2^a+23) + rw [Nat.mul_add,Nat.mul_left_comm P 51] + linarith only [hm,hv,pos] + · let calls {Q : Type} {prog : BurstRAM.Program w Q} {f : ℕ} {st : Option (Word w)} {mem : Memory w} {n : ℕ} {rs : List (Report w)} + (h : runSegment prog f st mem (List.replicate n [])=some rs) : rs.length=n := by + simpa only [branchPaths,List.length_map,List.length_replicate] using congrArg List.length ((runSegment_iff ..).mp h).2.2 + have len := v.postTerm.scores + have lp := calls v.postTerm.placed.positions + have lr := calls v.postTerm.placed.roles + have lc := v.postTerm.geometry.raw.clearCount + have la := v.postTerm.geometry.raw.collectCount + simp only [ChosenGeometry.Construction.reports,SelectedStage.Passes.all,List.length_append,len,lp,lr,lc,la,selectedCalls,Nat.add_assoc] + +/-- Changing the two score cursors preserves the number of calls and the +full event log, hence the exact calls-plus-probes cost. -/ +theorem geometry_cost_eq {A : Script} {mem : Memory w} {ps : List (SourceOnline.Packet A w)} + (chron : SourceWalk.Chronological SourceOnline.Visit.Runs mem ps) + (events : eventLog (ps.flatMap SourceWalk.Packet.reports)=eventLog v.geometry.reports) + (tapes : ps.flatMap (fun q => q.stage.choices)=List.replicate (selectedCalls X) []) : + RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) = RAMBuckets.cost Report.probes v.geometry.reports := by + have count := congrArg List.length ((PublishedHeads.chronological_tapes mem ps chron).symm.trans tapes) + simp only [branchPaths,List.length_map,List.length_replicate] at count + rw [SourceOnline.packet_cost,SourceOnline.packet_cost,events,count,(geometry_charge B X T start stride selectors v).2] + +/-- Pass the exact report boundary and choice count of the fourteen installed +rows to the scheduler's weighted cost. -/ +theorem geometry_groupCost {A : Script} {L : Layout} {base : Word w} {cap ordinal total : ℕ} + {mem : Memory w} {ps : List (SourceOnline.Packet A w)} + (group : SourceOnline.Group A L base cap ordinal total mem ps) (rows : ps.length=14) + (events : eventLog (ps.flatMap SourceWalk.Packet.reports)=eventLog v.geometry.reports) + (tapes : ps.flatMap (fun q => q.stage.choices)=List.replicate (selectedCalls X) []) : + groupCost A ps ≤ X.positions*groupRate A (geometryRate a) 14 := by + have data := geometry_cost_eq B X T start stride selectors v group.chronological events tapes + apply groupCost_le A ps _ _ _ (data.le.trans (geometry_charge B X T start stride selectors v).1) + rw [rows] + exact Nat.le_mul_of_pos_left _ X.positions_pos + +end CompressorRecords.SelectedTailPackets + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryHeadBanks.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryHeadBanks.lean new file mode 100644 index 0000000000..7cc03c9950 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryHeadBanks.lean @@ -0,0 +1,49 @@ +import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory +import OAI.Computability.VPVNP.CompressorRefreshTraversalHeaders +import OAI.Computability.VPVNP.CompressorSlotWidthState +import OAI.Computability.VPVNP.CompressorRecordsDemandOutput + +/-! # Physical incidence pointers after the shrinking substep header + +The old level retains its pointer bank. The successor publisher uses precisely +the number of lane slots traversed by the shrinking construction. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkGeometryHeadBanks + +open BurstRAM Compression DescriptorSpace BlockHeaderRun ShrinkSlots +open PortRefresh.TraversalHeaders PairSimulation.TraversalRows + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g w : ℕ} +variable (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) +variable (sel : SelectedScore.Selection B X) (bits : List Bool) + +local notation "lv" => shrinkLevel B f hf i X sel bits +local notation "sh" => levelShape (b := S.degreeExponent i.succ) X + +theorem output_slots : (lv).outputSlots = actualCount sh := by + let Y := X.shrinkNext B.shrink (S.shrink i) sel + change Y.positions * 2^S.degreeExponent i.succ = _ + rw [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv g),Fintype.card_fin] + exact (next_counts X B.shrink (S.shrink i) sel).2 + +/-- The actual scalar and pointer publishers install both banks in the same +memory, with the compact lengths required by the slot and incidence workers. -/ +theorem after_substep {L : Layout} {old new : Fin L.levels} {six : 6 ≤ L.shape.scalarFields} {m : Memory w} + (sub : Substep lv L old new six m) (later : old.val < new.val) + (heads : HeadBank L old (DemandRAM.oldCount X) m) : + HeadBank L old (DemandRAM.oldCount X) (finalMemory lv L old new m) ∧ + HeadBank L new (actualCount sh) (finalMemory lv L old new m) := by + obtain ⟨oldHeads,newHeads⟩ := headBanks_of_substep sub later heads + exact ⟨oldHeads,(output_slots B f hf i X sel bits) ▸ newHeads⟩ + +end CompressorRecords.ShrinkGeometryHeadBanks + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryHeadRetention.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryHeadRetention.lean new file mode 100644 index 0000000000..c4588b2486 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryHeadRetention.lean @@ -0,0 +1,118 @@ +import OAI.Computability.VPVNP.CompressorBlockLevelFit +import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch +import OAI.Computability.VPVNP.CompressorShrinkGeometryHeadBanks +import OAI.Computability.VPVNP.CompressorShrinkInputUpperFrame + +/-! # Header retention through the selected shrinking geometry + +After the substep publishes its two headers, the input scans, absolute-ID +scatter, gather, term writer and selected child-directory construction run +in table zero. Their interval bounds preserve the current header below the +table and every cell at or beyond the successor header. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkGeometryHeadBanks + +open BurstRAM Compression BlockHeaderRun DescriptorSpace PairSimulation.TraversalRows +open PortRefresh.TraversalHeaders ShrinkSlots +open scoped Fin.CommRing + +set_option maxHeartbeats 1600000 + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) +variable (sel : SelectedScore.Selection B X) (base positions blocks : ℕ) +local notation "lay" => BlockProgram.layout B base positions blocks +variable (old new : Fin (BlockProgram.layout B base positions blocks).levels) +local notation "start" => tableBase lay old (0 : Fin 6) +local notation "z" => ShrinkInput.plan X start +local notation "stop" => ShrinkInput.stop X start +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "num" => ShrinkTermSelection.bundles X * ShrinkTermSelection.ranks (ShrinkBlockInputs.a i) +local notation "top" => levelStart lay new + +/-- The original chronological reports preserve the lower and upper frame +of the active shrinking level, uniformly in the selected terms. -/ +theorem beforeOutput_table_frame {headPost : Memory w} {fuel : ℕ} + (p : ShrinkBranch.Prefix X (packedIncidence lay w old (DemandRAM.oldCount X)) start fuel headPost) + (v : ShrinkBranch.Selected B X (packedIncidence lay w old (DemandRAM.oldCount X)) start + 10 (B.shrink.selectorBits : Word w) fuel headPost p sel) + (sites : X.positions ≤ positions) (room : endAddress lay < 2^w) : + ∀ j, j < start ∨ start+tableWords lay ≤ j → v.beforeOutput j = headPost j := by + let T := packedIncidence lay w old (DemandRAM.oldCount X) + obtain ⟨inputFit,termFit,selectedFit,_⟩ := + BlockLevelFit.shrink (w := w) (L := lay) B base positions blocks old rfl i X sites room + have stopFit : stop < 2^w := inputFit.word + have termEnd : stop+2*num+num*10 ≤ start+tableWords lay := termFit.within + have termRoom : stop+2*num+num*10 < 2^w := termFit.word + have tv : (term).val = stop+2*num := Nat.mod_eq_of_lt ((Nat.le_add_right ..).trans_lt termRoom) + have dv : (ShrinkInput.pairBank X T start 5 : Word w).val = stop := Nat.mod_eq_of_lt stopFit + have countEq := ShrinkTermSelection.motifCount_eq X + have widthBound : (10 : Word w).val ≤ 10 := Nat.mod_le .. + have fits : (term).val + ShrinkTermInputs.motifCount X * (10 : Word w).val ≤ start+tableWords lay := by + rw [tv,countEq] + exact (Nat.add_le_add_left (Nat.mul_le_mul_left _ widthBound) _).trans termEnd + have inputRanges := ShrinkInput.range_bounds X start + have early : start ≤ (z).gathered := by + refine (inputRanges.1.trans inputRanges.2.1).trans ?_ + change ShrinkInput.rankBase X start ≤ ((ShrinkInput.rankBase X start+2*(z).A)+2*(z).B)+(z).rectangleSize + exact ((Nat.le_add_right ..).trans (Nat.le_add_right ..)).trans (Nat.le_add_right ..) + have ranks : (z).ranks ≤ stop := (Nat.le_add_right (z).ranks (z).A).trans inputRanges.2.2.2 + intro j outside + rcases outside with low | high + · have below : j < stop := low.trans_le (inputRanges.1.trans (inputRanges.2.1.trans + (inputRanges.2.2.1.trans inputRanges.2.2.2))) + exact (v.lowerFrame j below).trans ((p.absoluteRun.frame j (.inl (low.trans_le early))).trans (p.input.below j low)) + · have selected : SelectedFinish.stop X term 10 ≤ j := selectedFit.within.trans high + have gathered : (ShrinkInput.pairBank X T start 5 : Word w).val + 2*num ≤ j := by rw [dv]; exact (Nat.le_add_right ..).trans (termEnd.trans high) + exact (v.postTerm.geometry.frame j (.inr selected)).trans + ((v.termRun.frame j (.inr (fits.trans high))).trans + ((p.gatherRun.frame j (.inr gathered)).trans + ((p.absoluteRun.frame j (.inr (ranks.trans ((Nat.le_add_right ..).trans (dv ▸ gathered))))).trans + (p.input.post_upper stopFit j ((Nat.le_add_right ..).trans (dv ▸ gathered)))))) + +/-- The successor's header starts beyond the end of the current scratch table. -/ +theorem beforeOutput_frame (next : old.val+1 = new.val) {headPost : Memory w} {fuel : ℕ} + (p : ShrinkBranch.Prefix X (packedIncidence lay w old (DemandRAM.oldCount X)) start fuel headPost) + (v : ShrinkBranch.Selected B X (packedIncidence lay w old (DemandRAM.oldCount X)) start + 10 (B.shrink.selectorBits : Word w) fuel headPost p sel) + (sites : X.positions ≤ positions) (room : endAddress lay < 2^w) : + ∀ j, j < start ∨ top ≤ j → v.beforeOutput j = headPost j := by + intro j outside + apply beforeOutput_table_frame B i X sel base positions blocks old p v sites room j + refine outside.imp id (fun high ↦ ?_) + exact (tableEnd_le_nextLevel lay old (0 : Fin 6)).trans (next.symm ▸ high) + +/-- Transport both actual pointer banks from the scalar/header substep +through the term-dependent geometry and into the resident workers. -/ +theorem beforeOutput_heads {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) + (bits : List Bool) (next : old.val+1 = new.val) (m : Memory w) {fuel : ℕ} : + let lv := shrinkLevel B f hf i X sel bits + let headPost := finalMemory lv lay old new m + ∀ (_ : Substep lv lay old new (by change 6 ≤ 54; decide) m) + (p : ShrinkBranch.Prefix X (packedIncidence lay w old (DemandRAM.oldCount X)) start fuel headPost) + (v : ShrinkBranch.Selected B X (packedIncidence lay w old (DemandRAM.oldCount X)) start + 10 (B.shrink.selectorBits : Word w) fuel headPost p sel), + HeadBank lay old (DemandRAM.oldCount X) m → X.positions ≤ positions → endAddress lay < 2^w → + HeadBank lay old (DemandRAM.oldCount X) v.beforeOutput ∧ + HeadBank lay new (actualCount (levelShape (b := ShrinkBlockInputs.b i) X)) v.beforeOutput := by + intro lv headPost sub p v bank sites room + obtain ⟨oldHeads,newHeads⟩ := after_substep B f hf i X sel bits sub (by omega) bank + have same := beforeOutput_frame B i X sel base positions blocks old new next p v sites room + constructor + · apply oldHeads.keep + intro n hn + apply same _ (.inl ?_) + change levelStart lay old+n < levelStart lay old+levelHeaderWords lay+6*slotCapacity lay+0*tableWords lay + omega + · exact newHeads.keep (fun n _ => same _ (.inr (Nat.le_add_right _ n))) + +end CompressorRecords.ShrinkGeometryHeadBanks + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryRate.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryRate.lean new file mode 100644 index 0000000000..d1f2159565 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkGeometryRate.lean @@ -0,0 +1,52 @@ +import OAI.Computability.VPVNP.CompressorShrinkScheduledGeometry +import OAI.Computability.VPVNP.CompressorShrinkPrefixCharge + +/-! # Charging the selected group after a common shrinking prefix -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkScheduledGeometry + +open BurstRAM BlockPlanner DescriptorSpace Compression BlockHeaderRun SourceOnline +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable {B : S.Templates} {f : B.Entry → R} {hf : B.IsSolution f} {i : Fin S.steps} +variable {g w : ℕ} {X : GreedyArena.ShrinkingState (ShrinkBlockInputs.a i) g} +variable {sel : SelectedScore.Selection B X} {tape : List Bool} {base : Word w} {positions blocks t : ℕ} +local notation "prog" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "level" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape +local notation "Pkt" => SourceOnline.Packet prog w +variable {old new : Fin (BlockProgram.layout B base.val positions blocks).levels} {m : Memory w} +local notation "start" => tableBase L old (0 : Fin 6) +local notation "T" => packedIncidence L w old (DemandRAM.oldCount X) +local notation "initial" => finalMemory level L old new m +local notation "headers" => BlockHeaderRun.reports level L old new m + +set_option maxHeartbeats 1000000 in +/-- A prefix with the same native reports and number of calendar rows as +this branch incurs the same traffic when the chosen geometry follows it. -/ +theorem Result.prefix_rate {fuel : ℕ} {p : ShrinkBranch.Prefix X T start fuel initial} + {v : ShrinkBranch.Selected B X T start (10 : Word w) (B.shrink.selectorBits : Word w) fuel initial p sel} + {pre : List Pkt} {selector : Pkt} {tail : List Pkt} {cap : ℕ} + (h : Result B f hf i X sel tape base positions blocks t old new m fuel p v cap pre selector tail) + (shared : List Pkt) (count : shared.length=21) + (logs : shared.flatMap SourceWalk.Packet.reports = headers++p.reports) : + ScheduledTrace.groupCost prog (shared++selector::tail) ≤ + X.positions*ScheduledTrace.groupRate prog (ShrinkScheduledPrefix.prefixRate B i) 36 := + (ShrinkScheduledPrefix.group_charge B f hf i X sel tape base positions blocks old new m T start + (10 : Word w) (B.shrink.selectorBits : Word w) (p:=p) v (pre:=shared) (last:=selector) (geo:=tail) + (mem:=selector.output) logs h.selectReports count h.suffixLength h.suffix.chronological h.suffixEvents h.suffixTapes).2.2 + +end CompressorRecords.ShrinkScheduledGeometry + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkGreedyHeaderValues.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkGreedyHeaderValues.lean new file mode 100644 index 0000000000..d0960e7cad --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkGreedyHeaderValues.lean @@ -0,0 +1,110 @@ +import OAI.Computability.VPVNP.CompressorShrinkHeaderReads +import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory +import OAI.Computability.VPVNP.CompressorBlockHeaderRun +import OAI.Computability.VPVNP.CompressorGreedyPlannerFootprint + +/-! +# The greedy workers' physical input header after a shrinking substep + +The three header calls publish the selected input scalars, initialize the +next level and publish its array heads. The old incidence heads, table-zero +pointer and pitch lie outside those writes. All fields used by the shrinking +planner lie strictly below its first scratch address. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkGreedyHeaderValues + +open BurstRAM Compression DescriptorSpace BlockHeaderRun ShrinkBlockInputs +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} + (B : S.Templates) (i : Fin S.steps) {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) + (T : IncidenceDirectory w) + +/-- The memory certificate can be transported through every native greedy +visit using only the write bound at the start of the scratch allocation. -/ +structure Header (L : Layout) (first start : ℕ) (pub : Fin 5 → Word w) (st : Word w) (m : Memory w) : Prop where + raw : ShrinkHeaderReads.Header i X T start L first m + entry : LevelFields.Entry L first pub st m + fieldsBelow : levelStart L (first+i.val)+60 < start + pitchBelow : (pub 1-1).val < start + strideFits : levelWords L < 2^w + +variable {i X T} {L : Layout} {first start : ℕ} {pub : Fin 5 → Word w} {st : Word w} + {m m' : Memory w} + +theorem Header.keep_below (h : Header i X T L first start pub st m) + (same : ∀ x < start, m' x = m x) : Header i X T L first start pub st m' := + ⟨h.raw.keep_below h.fieldsBelow same, ⟨h.entry.pointer,(same _ h.pitchBelow).trans h.entry.pitch⟩, + h.fieldsBelow,h.pitchBelow,h.strideFits⟩ + +theorem Header.reads_at (h : Header i X T L first start pub st m) + (same : ∀ x < start, m' x = m x) : + GreedyLevelPlan.Reads (BlockProgram.geometry B) i.val (a i) (BlockProgram.arena B i.val 0) + pub st m' (Fintype.card X.Base) g start T := by + have h' := h.keep_below same + exact (ShrinkHeaderReads.Header.reads B h'.raw h'.entry).1 + +variable (f : B.Entry → R) (hf : B.IsSolution f) (i X) (sel : SelectedScore.Selection B X) + (tape : List Bool) (base : Word w) (positions blocks : ℕ) +local notation "lay" => BlockProgram.layout B base.val positions blocks +local notation "v" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape + +/-- Read the actual old heads through the relabel/advance/publication call +sequence, using its published input fields and its three write intervals. -/ +theorem post_header (T : IncidenceDirectory w) (first : ℕ) (old new : Fin (lay).levels) + (hOld : old.val = first+i.val) (hNew : new.val = old.val+1) (m : Memory w) + (run : Substep v lay old new (by change 6 ≤ 54; decide) m) + (fit : endAddress lay < 2^w) (pub : Fin 5 → Word w) (st : Word w) + (entry : LevelFields.Entry lay first pub st m) (pitch : (pub 1-1).val < levelStart lay old) + (heads : ∀ c : Fin 6, m (incidenceHead lay old c) = T.column c) + (scratch : m (tableHead lay old (0 : Fin 6)) = (tableBase lay old (0 : Fin 6) : Word w)) : + Header i X T lay first (tableBase lay old (0 : Fin 6)) pub st (finalMemory v lay old new m) := by + let here := levelStart lay old + let next := levelStart lay new + let post := finalMemory v lay old new m + have sz : (lay).shape.scalarFields = 54 := rfl + have ts : (lay).shape.tables = 6 := rfl + have words : 66 ≤ levelWords lay := by simp only [levelWords,levelHeaderWords,sz,ts]; omega + have step : next = here+levelWords lay := by simp [here,next,hNew,levelStart,Nat.succ_mul,Nat.add_assoc] + have fitNext : next < 2^w := by + change levelStart lay new < _; rw [hNew]; exact level_room lay fit old + have room : here+60 < 2^w := by omega + have fieldBelow : here+60 < tableBase lay old (0 : Fin 6) := by + simp only [tableBase,arrayBase,incidenceStart,levelHeaderWords,sz,ts,Fin.val_zero,Nat.zero_mul,Nat.add_zero] + change here+60 < here+66+6*slotCapacity lay + omega + have keep (j : ℕ) (lo : 6 ≤ j) (hi : j ≤ 60) : post (here+j) = m (here+j) := by + apply run.outside + · right; change here+6 ≤ here+j; omega + · left; change here+j < next; omega + · left; change here+j < next+(lay).shape.scalarFields; omega + have hpitch : post (pub 1-1).val = m (pub 1-1).val := by + change (pub 1-1).val < here at pitch + apply run.outside + · exact .inl pitch + · left; change (pub 1-1).val < next; omega + · left; change (pub 1-1).val < next+(lay).shape.scalarFields; omega + refine ⟨?_,⟨entry.pointer,hpitch.trans entry.pitch⟩,hOld ▸ fieldBelow,?_,by omega⟩ + · have now := run.input + refine ⟨hOld ▸ room,hOld ▸ now.vertices,hOld ▸ now.degree,hOld ▸ now.lanes, + hOld ▸ now.residual,?_,?_⟩ + · intro c + rw [← hOld] + apply (keep (54+c.val) (by omega) (by have := c.isLt; omega)).trans + simpa only [incidenceHead,sz,here,Nat.add_assoc] using heads c + · rw [← hOld] + apply (keep 60 (by decide) le_rfl).trans + simpa only [tableHead,sz,Fin.val_zero,Nat.add_zero,Nat.add_assoc] using scratch + · change (pub 1-1).val < here at pitch + omega + +end CompressorRecords.ShrinkGreedyHeaderValues + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkGreedyPlannerSupport.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkGreedyPlannerSupport.lean new file mode 100644 index 0000000000..db407ea973 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkGreedyPlannerSupport.lean @@ -0,0 +1,38 @@ +import OAI.Computability.VPVNP.CompressorGreedyPlannerFootprint +import OAI.Computability.VPVNP.CompressorShrinkHeaderReads + +/-! # Operand footprints from the published shrinking header -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkHeaderGreedyPackets + +open BurstRAM Compression BlockPlanner DescriptorSpace +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {w g start first : ℕ} (X : GreedyArena.ShrinkingState (ShrinkBlockInputs.a i) g) + {T : IncidenceDirectory w} {L : Layout} {pub : Fin 5 → Word w} {s : Word w} {m : Memory w} + +theorem operand_support (h : ShrinkHeaderReads.Header i X T start L first m) + (entry : LevelFields.Entry L first pub s m) (D : ℕ → Prop) (pitch : D (pub 1-1).val) + (cells : ∀ n ≤ 60, D (levelStart L (first+i.val)+n)) (j : GreedyVisit.Stage) : + HeaderOperands.Supported D pub s m (GreedyVisit.visit (BlockProgram.geometry B) i.val (ShrinkBlockInputs.a i) + (BlockProgram.arena B i.val 0) j) := by + have field (n : ℕ) (hn : n ≤ 60) : (LevelFields.scalar i.val n).ReadsFrom D pub s m := + GreedyVisit.scalar_support D L first i.val n entry pitch (cells n hn) ((Nat.add_le_add_left hn _).trans_lt h.room) + exact GreedyVisit.planner_reads D pub s m (BlockProgram.geometry B) i.val (ShrinkBlockInputs.a i) + (BlockProgram.arena B i.val 0) (field 0 (by decide)) (field 1 (by decide)) (field 3 (by decide)) + (fun c => field (54+c.val) (by have := c.isLt; omega)) (field 60 le_rfl) j + +end CompressorRecords.ShrinkHeaderGreedyPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderGreedyPackets.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderGreedyPackets.lean new file mode 100644 index 0000000000..4585d3c4ab --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderGreedyPackets.lean @@ -0,0 +1,118 @@ +import OAI.Computability.VPVNP.CompressorShrinkHeaderVisitWalk +import OAI.Computability.VPVNP.CompressorShrinkGreedyPlannerSupport +import OAI.Computability.VPVNP.CompressorGreedyPacketWalk +import OAI.Computability.VPVNP.CompressorGreedyPacketFootprints +import OAI.Computability.VPVNP.CompressorShrinkGreedyHeaderValues +import OAI.Computability.VPVNP.CompressorRecordsShrinkInput + +/-! # Online source packets for the shrinking header and greedy assignment + +The global calendar first relabels the old level, publishes the next header +and its pointers, then executes the six greedy kernels. All nine visits use +their computed operands and actual source traces. The post-memory is the +typed greedy result used by the subsequent placement and rank scans. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkHeaderGreedyPackets + +open BurstRAM Compression BlockPlanner DescriptorSpace BlockHeaderRun SourceTransport +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) + (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g : ℕ} + (X : GreedyArena.ShrinkingState (ShrinkBlockInputs.a i) g) + (sel : SelectedScore.Selection B X) (tape : List Bool) +local notation "v" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape +local notation "script₀" => BlockProgram.script B +variable {w : ℕ} (base : Word w) (positions blocks t : ℕ) +local notation "L" => BlockProgram.layout B (Fin.val base) positions blocks +local notation "pt" => Workspace.ports (Schedule.arity (BlockPlanner.Script.catalog script₀)) base +local notation "pub" => Schedule.Ports.data pt +local notation "first₀" => BlockPlanner.Script.levelsPerBlock script₀*t +local notation "st" => (levelStart L first₀ : Word w) +local notation "H" => levelStart L 0 +local notation "W" => window B i + +/-- Common private-fuel bound for a single header or greedy worker call in this shrinking +substep. -/ +def fuelBound := max (headerClock B i) (GreedyVisit.maxFuel (ShrinkBlockInputs.a i)) + +/-- A single clock suffices for all inputs and all block repetitions. Its +finite sum is over the actual nine catalog positions of this substep. -/ +def clock := + (((W).indices).map (fun j => ((script₀).plan.recipes j).2.code.length+1+2*Schedule.Online.N (script₀).size (script₀).size+5 + + (fuelBound B i+3+4*(((script₀).catalog j).params+1)+2*Schedule.Online.N (script₀).size (script₀).size+5))).sum + +theorem group (old new : Fin (L).levels) (hOld : first₀+i.val=old.val) (hNew : old.val+1=new.val) + (m : Memory w) (sub : Substep v L old new (by change 6 ≤ 54; decide) m) + (T : IncidenceDirectory w) + (r : GreedyArena.Run X T (tableBase L old (0 : Fin 6)) (finalMemory v L old new m)) + (heads : ∀ c : Fin 6, m (incidenceHead L old c)=T.column c) + (scratch : m (tableHead L old (0 : Fin 6))=(tableBase L old (0 : Fin 6) : Word w)) + (low : ∀ c, H ≤ (T.column c).val) + (fit : endAddress L < 2^w) + (rows : m (pt).rows.val=(directoryRows L : Word w)) (pitch : m ((pt).directory-1).val=(levelWords L : Word w)) + (ht : t < blocks) (cap : ℕ) (hc : clock B i ≤ cap) : + ∃ ps : List (SourceOnline.Packet script₀ w), + SourceOnline.Group script₀ L base cap ((script₀).initial.length+t*(script₀).block.length+(BlockIndex.earlier B i).length) + (directoryRows L) m ps ∧ ps.map (fun p => p.stage.phase)=(W).indices ∧ + ps.flatMap SourceWalk.Packet.reports=reports v L old new m++r.reports ∧ + SourceOnline.post m ps=r.post := by + let origin := tableBase L old (0 : Fin 6) + let D := Window.operandRegion script₀ L base + have hH : H < 2^w := (levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit + have cells := Window.lowCells (A:=script₀) L base (BlockProgram.layout_arity B ..).symm rfl hH + have atOld : H ≤ levelStart L old := levelStart_mono L (Nat.zero_le _) + have entry : LevelFields.Entry L first₀ pub st m := ⟨rfl,pitch⟩ + have head : BlockHeaderPlan.firstHeader.eval pub st m=header w L 0 := + BlockHeaderPlan.firstHeader_eval L base m st (Fin.ofNat_val_eq_self base).symm rows + have headersRun := header_walk B f hf i X sel tape base positions blocks t old new hOld (by omega) m sub fit entry head + (cells.2.trans_le atOld) (cells.1.trans_le atOld) (fuelBound B i) (Nat.le_max_left ..) + have geom := ShrinkGreedyHeaderValues.post_header B i X f hf sel tape base positions blocks T first₀ old new + hOld.symm hNew.symm m sub fit pub st entry (cells.2.trans_le atOld) heads scratch + have initial := geom.reads_at B (fun _ _ => rfl) + have lo := levelStart_mono L (Nat.zero_le (first₀+i.val)) + have lowSupp := operand_support B i X geom.raw geom.entry (· < origin) geom.pitchBelow + (fun j hj => by have hi := geom.fieldsBelow; change _ < tableBase L old (0 : Fin 6); omega) + have supp := operand_support B i X geom.raw geom.entry D (.inr (.inl rfl)) + (fun j _ => Or.inr (Or.inr (lo.trans (Nat.le_add_right ..)))) + have floor : H ≤ origin := by have h := geom.fieldsBelow; exact lo.trans ((Nat.le_add_right ..).trans h.le) + have access := GreedyVisit.packet_access r H low + have tailRun := GreedyVisit.packet_walk r L (BlockProgram.geometry B) i.val (BlockProgram.arena B i.val 0) + pub st D initial lowSupp supp floor (fun j a x he => ((access j).1 a x he).1) + (fun j a x he => ((access j).2 a x he).1) (fuelBound B i) (Nat.le_max_right ..) + have totalRun : SourceWalk (Window.Raw (A:=script₀) L base t (fuelBound B i)) (visits B i) m + (reports v L old new m++r.reports) := by + apply headersRun.append + rw [reports_after]; exact tailRun + have live (j : Fin (visits B i).length) : Window.ordinal (A:=script₀) t ((W).index j) < directoryRows L := by + rw [(W).ordinal_index,BlockProgram.directory_rows,(script₀).calendar_total] + have hj := ((W).position j).isLt + have hmul := Nat.mul_le_mul_right (script₀).block.length ht + rw [Nat.succ_mul] at hmul + omega + let rowTime (j : Fin (script₀).size) := ((script₀).plan.recipes j).2.code.length+1+2*Schedule.Online.N (script₀).size (script₀).size+5 + let dataTime (j : Fin (script₀).size) := fuelBound B i+3+4*(((script₀).catalog j).params+1)+2*Schedule.Online.N (script₀).size (script₀).size+5 + have time (j : Fin (script₀).size) (hj : j ∈ (W).indices) : rowTime j + dataTime j ≤ clock B i := by + apply List.single_le_sum (fun _ _ => Nat.zero_le _) + exact List.mem_map.mpr ⟨j,hj,rfl⟩ + obtain ⟨ps,group,phases,logs⟩ := (W).group L base t (BlockProgram.layout_arity B ..).symm rfl hH cap + (fuelBound B i) m _ totalRun rows pitch live (fun j hj => (Nat.le_add_right ..).trans ((time j hj).trans hc)) + (fun j hj => (Nat.le_add_left ..).trans ((time j hj).trans hc)) + refine ⟨ps,group,phases,logs,?_⟩ + rw [SourceOnline.post,logs,SourceWalk.after_append,reports_after] + exact r.post_reports + +end CompressorRecords.ShrinkHeaderGreedyPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderGreedyTapes.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderGreedyTapes.lean new file mode 100644 index 0000000000..76cec95fa2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderGreedyTapes.lean @@ -0,0 +1,82 @@ +import OAI.Computability.VPVNP.CompressorBlockHeaderRun +import OAI.Computability.VPVNP.CompressorSourceGroups +import OAI.Computability.VPVNP.CompressorRecordsShrinkGreedy + +/-! +# Branch tapes in the shrinking header and greedy visits + +For a successful native call the supplied branch tape equals the choice +bits in its report. The three header visits and six greedy visits all +produce empty tapes, including the indirect operand readers. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkHeaderGreedyPackets + +open BurstRAM Compression BlockHeaderRun SourceOnline DescriptorSpace BlockPlanner + +variable {w : ℕ} + +private theorem segment_empty {C : Type*} {P : BurstRAM.Program w C} {fuel count : ℕ} {s : Option (Word w)} + {m : Memory w} {rs : List (Report w)} + (run : runSegment P fuel s m (List.replicate count []) = some rs) (r : Report w) (hr : r ∈ rs) : + choiceBits r.events = [] := by + have h : choiceBits r.events ∈ branchPaths rs := List.mem_map_of_mem hr + rw [(runSegment_iff ..).mp run |>.2.2] at h + exact (List.mem_replicate.mp h).2 + +/-- All reports of the six native greedy visits have empty branch paths. -/ +theorem greedy_reports_empty {a g origin : ℕ} {X : GreedyArena.ShrinkingState a g} + {T : IncidenceDirectory w} {m : Memory w} (run : GreedyArena.Run X T origin m) + (r : Report w) (hr : r ∈ run.reports) : choiceBits r.events = [] := by + simp only [GreedyArena.Run.reports,List.mem_append] at hr + rcases hr with (((proj|prep)|read)|off)|tag + · exact (run.projection.work r proj).2.2 + · exact segment_empty run.color.prepRun r prep + · exact segment_empty run.color.readRun r read + · exact segment_empty run.offsets.prepRun r off + · exact segment_empty run.offsets.readRun r tag + +private theorem packet_runs {A : Script} {m : Memory w} {ps : List (SourceOnline.Packet A w)} + (chron : SourceWalk.Chronological Visit.Runs m ps) {p : SourceOnline.Packet A w} (hp : p ∈ ps) : + p.stage.Runs p.input p.reports := by + induction ps generalizing m with + | nil => exact False.elim (List.not_mem_nil hp) + | cons q qs ih => + rcases List.mem_cons.mp hp with rfl|hp + · exact chron.2.1 + · exact ih chron.2.2 hp + +/-- In any chronological packetization of these actual source reports, every +individual call consumes an empty branch tape. -/ +theorem empty_choices {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} + {B : S.Templates} {f : B.Entry → R} {hf : B.IsSolution f} (v : SelectedLevel B f hf) + {L : Layout} {old new : Fin L.levels} {m : Memory w} {six : 6 ≤ L.shape.scalarFields} + (sub : Substep v L old new six m) + {a g origin : ℕ} {X : GreedyArena.ShrinkingState a g} {T : IncidenceDirectory w} {start : Memory w} + (run : GreedyArena.Run X T origin start) {A : Script} {ps : List (SourceOnline.Packet A w)} + (chron : SourceWalk.Chronological Visit.Runs m ps) + (logs : ps.flatMap SourceWalk.Packet.reports = reports v L old new m ++ run.reports) : + ∀ p ∈ ps, ∀ b ∈ p.stage.choices, b = [] := by + intro p hp b hb + have actual := packet_runs chron hp + rw [← ((runSegment_iff ..).mp actual).2.2] at hb + obtain ⟨r, hr, rfl⟩ := List.mem_map.mp hb + have mem : r ∈ ps.flatMap SourceWalk.Packet.reports := List.mem_flatMap.mpr ⟨p,hp,hr⟩ + rw [logs] at mem + rcases List.mem_append.mp mem with head|tail + · simp only [reports,List.mem_cons,List.not_mem_nil,or_false] at head + rcases head with rfl|rfl|rfl + · exact (execute_spec sub.relabel.1).2.2 + · exact (execute_spec sub.advance.1).2.2 + · exact sub.heads.cost.2.2 + · exact greedy_reports_empty run r tail + +end CompressorRecords.ShrinkHeaderGreedyPackets + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderGreedyWindow.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderGreedyWindow.lean new file mode 100644 index 0000000000..41244fa029 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderGreedyWindow.lean @@ -0,0 +1,73 @@ +import OAI.Computability.VPVNP.CompressorBlockIndex +import OAI.Computability.VPVNP.CompressorScriptWindow + +/-! # The nine initial visits in each shrinking substep + +The three header workers and six greedy workers occupy a contiguous window +of the full native block. The static phase and the repeated calendar ordinal +are recovered from the lengths of the actual preceding substeps. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkHeaderGreedyPackets + +open Compression BlockPlanner DescriptorSpace + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) + +/-- The three scheduled visits that publish the shrinking substep's input scalars, output +scalars and directory heads. -/ +def headers := BlockHeaderPlan.substep (BlockProgram.geometry B) i.val + (Scalars.Pass.shrink (ShrinkBlockInputs.a i) (ShrinkBlockInputs.b i)) + +/-- The six greedy visits for this substep, using its old degree exponent and the first scratch +arena of its level. -/ +def greedy := GreedyLevelPlan.visits (BlockProgram.geometry B) i.val (ShrinkBlockInputs.a i) + (BlockProgram.arena B i.val 0) + +/-- The first nine visits of the shrinking substep, with the three header publications +preceding the six greedy visits. -/ +def visits := headers B i ++ greedy B i + +theorem visits_length : (visits B i).length = 9 := rfl + +private theorem remaining : ∃ tail, BlockProgram.shrink B i = visits B i ++ tail := by + unfold BlockProgram.shrink ShrinkBlockInputs.beforeSlices visits headers greedy + simp only [List.append_assoc] + exact ⟨_,rfl⟩ + +/-- Locate the nine header and greedy visits as a consecutive segment of the full block script +at shrinking index `i`. -/ +def window : Window (BlockProgram.script B) (visits B i) where + before := BlockIndex.earlier B i + after := (remaining B i).choose ++ BlockIndex.later B i + block := by + let tail := (remaining B i).choose + have sub : BlockProgram.shrink B i = visits B i ++ tail := (remaining B i).choose_spec + exact (BlockIndex.split_block B i).trans ((congrArg + (fun xs => BlockIndex.earlier B i ++ xs ++ BlockIndex.later B i) sub).trans + (by simp only [List.append_assoc,tail])) + +theorem window_phase (t : ℕ) (j : Fin (visits B i).length) : + let A := BlockProgram.script B + let ordinal := A.initial.length+t*A.block.length+(BlockIndex.earlier B i).length+j.val + (Schedule.Online.calendar A.plan).phase ordinal = ((window B i).index j).val ∧ + (Schedule.Online.calendar A.plan).level ordinal = t := by + dsimp only + rw [show (BlockProgram.script B).initial.length+t*(BlockProgram.script B).block.length+ + (BlockIndex.earlier B i).length+j.val = (BlockProgram.script B).initial.length+t*(BlockProgram.script B).block.length+ + ((window B i).position j).val by change _ = _ + ((BlockIndex.earlier B i).length+j.val); omega] + exact (BlockProgram.script B).block_phase t ((window B i).position j) + +end CompressorRecords.ShrinkHeaderGreedyPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderReads.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderReads.lean new file mode 100644 index 0000000000..ae21f2ccd0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderReads.lean @@ -0,0 +1,74 @@ +import OAI.Computability.VPVNP.CompressorBlockProgram +import OAI.Computability.VPVNP.CompressorSourceCalendarEntry + +/-! +# Published level fields read by the shrinking calendar recipes + +The old site, degree and residual-lane counts, the six incidence heads +and the first scratch pointer are read from the actual level header. +Agreement on the shared data region transports these values through the +scheduler's launch. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkHeaderReads + +open BurstRAM BlockPlanner Compression DescriptorSpace ShrinkBlockInputs SourceTransport +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (T : IncidenceDirectory w) (start : ℕ) +variable (L : Layout) (first : ℕ) + +local notation "here" => levelStart L (first+i.val) + +/-- Only the fields actually used by the term planner are specified. -/ +structure Header (mem : Memory w) : Prop where + room : here+60 < 2^w + vertices : mem (here+0) = (Fintype.card X.Base : Word w) + degree : mem (here+1) = ((2^(a i) : ℕ) : Word w) + lanes : mem (here+2) = ((2^(packingLaneBits (a i) g) : ℕ) : Word w) + residual : mem (here+3) = ((2^g : ℕ) : Word w) + incidence : ∀ c : Fin 6, mem (here+(54+c.val)) = T.column c + scratch : mem (here+60) = (start : Word w) + +variable {i X T start L first} + +theorem Header.keep {before after : Memory w} (h : Header i X T start L first before) + (same : Agree (levelStart L 0 ≤ ·) before after) : Header i X T start L first after := by + have lo : levelStart L 0 ≤ here := levelStart_mono L (Nat.zero_le _) + have field (n : ℕ) : after (here+n) = before (here+n) := (same _ (by omega)).symm + exact ⟨h.room,(field 0).trans h.vertices,(field 1).trans h.degree,(field 2).trans h.lanes, + (field 3).trans h.residual,fun c => (field _).trans (h.incidence c),(field 60).trans h.scratch⟩ + +theorem Header.keep_below {before after : Memory w} (h : Header i X T start L first before) + (below : here+60 < start) (same : ∀ addr < start, after addr = before addr) : + Header i X T start L first after := by + have field (n : ℕ) (hn : n ≤ 60) : after (here+n) = before (here+n) := same _ (by omega) + exact ⟨h.room,(field 0 (by decide)).trans h.vertices,(field 1 (by decide)).trans h.degree, + (field 2 (by decide)).trans h.lanes,(field 3 (by decide)).trans h.residual, + fun c => (field _ (by have := c.isLt; omega)).trans (h.incidence c),(field 60 le_rfl).trans h.scratch⟩ + +theorem Header.reads {pub : Fin 5 → Word w} {state : Word w} {mem : Memory w} + (h : Header i X T start L first mem) (entry : LevelFields.Entry L first pub state mem) : + ShrinkBundlePlan.Reads X (BlockProgram.geometry B) i.val (BlockProgram.arena B i.val 0) pub state mem start T := by + have cell (offset : ℕ) (hoff : offset ≤ 60) : + (LevelFields.scalar i.val offset).eval pub state mem = mem (here+offset) := + LevelFields.eval_scalar entry i.val offset ((Nat.add_le_add_left hoff _).trans_lt h.room) + refine ⟨⟨(cell 0 (by decide)).trans h.vertices,(cell 1 (by decide)).trans h.degree, + (cell 3 (by decide)).trans h.residual,fun c => ?_,(cell 60 le_rfl).trans h.scratch⟩, + (cell 2 (by decide)).trans h.lanes⟩ + exact (cell (54+c.val) (by have := c.isLt; omega)).trans (h.incidence c) + +end CompressorRecords.ShrinkHeaderReads + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderVisitWalk.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderVisitWalk.lean new file mode 100644 index 0000000000..651797791e --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkHeaderVisitWalk.lean @@ -0,0 +1,85 @@ +import OAI.Computability.VPVNP.CompressorShrinkHeaderGreedyWindow +import OAI.Computability.VPVNP.CompressorWindowPackets +import OAI.Computability.VPVNP.CompressorShrinkHistoryDirectory + +/-! # Three chronological header packets for an actual shrinking level -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkHeaderGreedyPackets + +open BurstRAM Compression BlockPlanner DescriptorSpace BlockHeaderRun +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) + (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g : ℕ} + (X : State (ShrinkBlockInputs.a i) (packingLaneBits (ShrinkBlockInputs.a i) g)) + (sel : SelectedScore.Selection B X) (tape : List Bool) +local notation "v" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape +local notation "script₀" => BlockProgram.script B +variable {w : ℕ} (base : Word w) (positions blocks t : ℕ) +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pub" => Schedule.Ports.data (Workspace.ports (Schedule.arity (BlockPlanner.Script.catalog script₀)) base) +local notation "st" => (levelStart L (BlockPlanner.Script.levelsPerBlock script₀*t) : Word w) + +/-- Private-fuel bound for any of the three header calls, obtained from the lengths of both +scalar-row recipes and the descriptor-head publisher. -/ +def headerClock := (Scalars.advanceRow (.terminal (ShrinkBlockInputs.a i)) + (.shrink (ShrinkBlockInputs.a i) (ShrinkBlockInputs.b i))).recipe.code.length + + (Scalars.advanceRow (.shrink (ShrinkBlockInputs.a i) (ShrinkBlockInputs.b i)) + (.terminal (ShrinkBlockInputs.b i))).recipe.code.length + + (DescriptorHeads.publisher (BlockProgram.geometry B)).recipe.code.length + 1 + +set_option maxHeartbeats 600000 in +theorem header_walk (old new : Fin (L).levels) (hOld : (script₀).levelsPerBlock*t+i.val=old.val) + (hNew : (script₀).levelsPerBlock*t+(i.val+1)=new.val) (m : Memory w) + (run : Substep v L old new (by change 6 ≤ 54; decide) m) (fit : endAddress L < 2^w) + (entry : LevelFields.Entry L ((script₀).levelsPerBlock*t) pub st m) + (head : BlockHeaderPlan.firstHeader.eval pub st m=header w L 0) + (pitch : (pub 1-1).val < levelStart L old) (count : (pub 3).val < levelStart L old) + (bound : ℕ) (enough : headerClock B i ≤ bound) : + SourceWalk (Window.Raw (A:=script₀) L base t bound) (headers B i) m (reports v L old new m) := by + let mid := inputMemory v L old m + let next := outputMemory v L old new m + let r₀ := scalarReport (inputRow v) (header w L old) (header w L old) m + let r₁ := scalarReport (outputRow v) (header w L old) (header w L new) mid + let r₂ := headReport L new next + let q := headers B i + have qlen : q.length=3 := rfl + have hq₀ : 0 < q.length := by omega + have hq₁ : 1 < q.length := by omega + have hq₂ : 2 < q.length := by omega + obtain ⟨h₀,h₁,h₂⟩ := HeaderPacket.substep v run fit ((script₀).levelsPerBlock*t) i.val hOld hNew pub st entry head pitch count + have support (mem : Memory w) (j : Fin q.length) : + HeaderOperands.Supported (Window.operandRegion script₀ L base) pub st mem q[j.val] := + HeaderOperands.substep _ _ _ _ _ _ _ (.inl rfl) (.inr (.inl rfl)) _ (List.getElem_mem ..) + have c₀ : (inputRow v).recipe.code.length+1 ≤ bound := by + change (inputRow v).recipe.code.length+(outputRow v).recipe.code.length+ + (DescriptorHeads.publisher (L).shape).recipe.code.length+1 ≤ bound at enough + omega + have c₁ : (outputRow v).recipe.code.length+1 ≤ bound := by + change (inputRow v).recipe.code.length+(outputRow v).recipe.code.length+ + (DescriptorHeads.publisher (L).shape).recipe.code.length+1 ≤ bound at enough + omega + have c₂ : (DescriptorHeads.publisher (L).shape).recipe.code.length+1 ≤ bound := by + change (inputRow v).recipe.code.length+(outputRow v).recipe.code.length+ + (DescriptorHeads.publisher (L).shape).recipe.code.length+1 ≤ bound at enough + omega + change SourceWalk _ [q[0],q[1],q[2]] m ([r₀]++([r₁]++[r₂])) + refine SourceWalk.next (rs:=[r₀]) ⟨_,_,c₀,h₀,support m ⟨0,hq₀⟩⟩ ?_ + simp only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] + refine SourceWalk.next (rs:=[r₁]) ⟨_,_,c₁,h₁,support mid ⟨1,hq₁⟩⟩ ?_ + simp only [eventLog,List.flatMap_cons,List.flatMap_nil,List.append_nil] + exact SourceWalk.singleton ⟨_,_,c₂,h₂,support next ⟨2,hq₂⟩⟩ + +end CompressorRecords.ShrinkHeaderGreedyPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkHistoryAccess.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkHistoryAccess.lean new file mode 100644 index 0000000000..0857ccde46 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkHistoryAccess.lean @@ -0,0 +1,194 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkHistoryTrace + +/-! # External read and write addresses of the selected shrinking rows -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkHistoryTrace + +open BurstRAM OrdinalRun SourceTransport PrimedStackRAM +open scoped Fin.CommRing Classical + +variable {w : ℕ} + +private theorem placement_events (p : Fin 14 → Word w) (m : Memory w) (i : Word w) : + Reads (fun x => ∃ c : Fin 4, x = ShrinkRAM.readAddr p c i) (ShrinkRAM.events p m i) ∧ + Writes (fun x => ∃ c : Fin 4, x = ShrinkRAM.outAddr p c i) (ShrinkRAM.events p m i) := by + constructor <;> intro a v ha + · simp [ShrinkRAM.events] at ha + rcases ha with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ + · exact ⟨0,rfl⟩ + · exact ⟨1,rfl⟩ + · exact ⟨2,rfl⟩ + · exact ⟨3,rfl⟩ + · simp [ShrinkRAM.events] at ha + rcases ha with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ + · exact ⟨0,rfl⟩ + · exact ⟨1,rfl⟩ + · exact ⟨2,rfl⟩ + · exact ⟨3,rfl⟩ + +private theorem role_events (p : Fin 11 → Word w) (m : Memory w) (i : Word w) : + Reads (fun x => ∃ c : Fin 6, x = DemandRAM.inputAddr p m i c) (DemandRAM.events p m i) ∧ + Writes (fun x => ∃ t : Fin 4, x = DemandRAM.fieldAddr p i t) (DemandRAM.events p m i) := by + constructor <;> intro a v ha + · simp [DemandRAM.events] at ha + rcases ha with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ + · exact ⟨0,rfl⟩ + · exact ⟨1,rfl⟩ + · exact ⟨2,rfl⟩ + · exact ⟨3,rfl⟩ + · exact ⟨4,rfl⟩ + · exact ⟨5,rfl⟩ + · simp [DemandRAM.events] at ha + rcases ha with ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ | ⟨rfl,_⟩ + · exact ⟨0,rfl⟩ + · exact ⟨1,rfl⟩ + · exact ⟨2,rfl⟩ + · exact ⟨3,rfl⟩ + +/-- The placement report group reads only the old color, offset, mate and +displacement addresses, and writes only the four new columns. -/ +theorem placement_access (p : Fin 14 → Word w) (n : ℕ) (m : Memory w) (rs : List (Report w)) + (run : runSegment ((template ShrinkRAM.visit 0).instantiate w p).program 65 (some 0) m + (List.replicate n []) = some rs) : + Reads (fun x => ∃ j < n, ∃ c : Fin 4, x = ShrinkRAM.readAddr p c (j : Word w)) (eventLog rs) ∧ + Writes (fun x => ∃ j < n, ∃ c : Fin 4, x = ShrinkRAM.outAddr p c (j : Word w)) (eventLog rs) := by + let M := (template ShrinkRAM.visit 0).instantiate w p + apply OrdinalRun.footprint M.program 65 (fun j => (j : Word w)) n (fun _ _ => True) _ _ _ 0 _ m rs + (by simp) trivial run + intro j hj mem _ bits rep h + have eqn := (execute_prefix_unique (ShrinkRAM.visit_native p mem (j : Word w)) + (show execute M.program 65 (M.program.start (j : Word w)) mem ([]++bits) = some rep from h)).2 + subst rep + obtain ⟨rd,wr⟩ := placement_events p mem (j : Word w) + exact ⟨by simp,trivial,fun a v ha => ⟨j,hj,rd a v ha⟩,fun a v ha => ⟨j,hj,wr a v ha⟩⟩ + +private theorem role_input_stable {p : Fin 11 → Word w} {old m : Memory w} {N : ℕ} {i : Word w} + (reg : DemandRAM.Regions p old N) (hi : i.val < N) (done : DemandRAM.Written p old m i.val) + (c : Fin 6) : DemandRAM.inputAddr p m i c = DemandRAM.inputAddr p old i c := by + have read (j : Fin 6) : m (DemandRAM.inputAddr p old i j) = old (DemandRAM.inputAddr p old i j) := + done.frame _ fun u t hu => reg.input i u j t hi (hu.trans hi) + have t : BundleRAM.targetSite p m i = BundleRAM.targetSite p old i := congrArg (fun v => ShrinkRAM.div v (p 0)) (read 0) + have a : m (p 6+BundleRAM.sourceSite p i).val = old (p 6+BundleRAM.sourceSite p i).val := read 1 + have ends : DemandRAM.endpoints p m i = DemandRAM.endpoints p old i := by simp only [DemandRAM.endpoints,t,a] + simp only [DemandRAM.inputAddr,t,ends] + +open private Written.step from OAI.Computability.VPVNP.CompressorRecordsDemandScan + +/-- Even the indirect role lookups refer to the addresses determined by the +original incidence columns at the start of this phase. -/ +theorem role_access (p : Fin 11 → Word w) (n : ℕ) (old : Memory w) (rs : List (Report w)) + (reg : DemandRAM.Regions p old n) + (run : runSegment ((template DemandRAM.visit 0).instantiate w p).program 65 (some 0) old + (List.replicate n []) = some rs) : + Reads (fun x => ∃ j < n, ∃ c : Fin 6, x = DemandRAM.inputAddr p old (j : Word w) c) (eventLog rs) ∧ + Writes (fun x => ∃ j < n, ∃ c : Fin 4, x = DemandRAM.fieldAddr p (j : Word w) c) (eventLog rs) := by + let M := (template DemandRAM.visit 0).instantiate w p + apply OrdinalRun.footprint M.program 65 (fun j => (j : Word w)) n (fun j mem => DemandRAM.Written p old mem j) + _ _ _ 0 _ old rs (by simp) (DemandRAM.Written.start p old) run + intro j hj mem inv bits rep h + let i : Word w := j + have val : i.val = j := Nat.mod_eq_of_lt (hj.trans_le reg.fits) + have hi : i.val < n := val ▸ hj + have atI : DemandRAM.Written p old mem i.val := val ▸ inv + have eqn := (execute_prefix_unique (DemandRAM.visit_native p mem i) + (show execute M.program 65 (M.program.start i) mem ([]++bits) = some rep from h)).2 + subst rep + obtain ⟨rd,wr⟩ := role_events p mem i + refine ⟨by simp [i],?_,?_,fun a v ha => ⟨j,hj,wr a v ha⟩⟩ + · rw [DemandRAM.visit_after] + exact val ▸ Written.step reg hi atI + · intro a v ha + obtain ⟨c,hc⟩ := rd a v ha + exact ⟨j,hj,c,hc.trans (role_input_stable reg hi atI c)⟩ + +open Compression SelectedArena +open private decoded_offsets from OAI.Computability.VPVNP.CompressorRecordsSelectedArena +open private demand_offsets from OAI.Computability.VPVNP.CompressorRecordsSelectedArenaDemand + +/-- Lowest address among the old color, offset, mate and displacement columns supplied to the +shrinking pass. -/ +def inputFloor (p : Fin 14 → Word w) := min (min (p 6).val (p 7).val) (min (p 8).val (p 9).val) + +/-- Every event of the chronological placement and role scans lies in +its physical source or output interval. These estimates hold after selecting +either layout. -/ +theorem selected_access {k : Type*} [_root_.Field k] {schedule : BlockSchedule k} (B : schedule.Templates) + {a g : ℕ} (X : State a (packingLaneBits a g)) (term stride selectors : Word w) + (p₀ : Fin 14 → Word w) (T : IncidenceDirectory w) (s : SelectedScore.Selection B X) + (m : Memory w) (p : SelectedStage.Passes w) (exec : SelectedStage.Execution X term stride selectors p₀ T m p) + (stored : SelectedStage.Stored B X term stride p₀ s m p) (old : OldInputs X term stride p₀ T) + {initialSide : Bool} (hp : ShrinkRAM.Params p₀ a (Shrink.colors a) (Shrink.J a) g initialSide) + (fit : Fits X term stride) : + Reads (fun x => inputFloor p₀ ≤ x ∧ x < origin X term stride) (eventLog p.positions) ∧ + Writes (fun x => placementBase X term stride ≤ x ∧ x < roleBase X term stride) (eventLog p.positions) ∧ + Reads (fun x => (T.actualOut.val ≤ x ∧ x < origin X term stride) ∨ + (placementBase X term stride ≤ x ∧ x < roleBase X term stride)) (eventLog p.roles) ∧ + Writes (fun x => roleBase X term stride ≤ x ∧ x < endAddr X term stride) (eventLog p.roles) := by + let sh := selectedWords X term stride p₀ (p.afterScores m) + let role := demandWords X term stride p₀ T + let bit := (p.afterScores m) (origin X term stride+2) + let chosen := X.packingData.shrinkTermLayout B.shrink X.shrinkNumber X.packingWidth s + have room : origin X term stride+3+4*positions X+4*DemandRAM.absoluteCount X < 2^w := fit + have eo := DemandRAM.count_eq X + have reg := demand_regions X term stride p₀ T bit (p.afterPositions m) chosen hp exec.incidenceBeforeRoles stored.placementBeforeRoles old fit + obtain ⟨pr,pw⟩ := placement_access sh (positions X) (p.afterScores m) _ exec.positions + obtain ⟨rr,rw'⟩ := role_access role (DemandRAM.oldCount X) (p.afterPositions m) _ reg exec.roles + obtain ⟨pRange,rRange⟩ := selected_ranges X term stride p₀ T (p.afterScores m) hp fit + have fbound (head off : Word w) {size : ℕ} (hold : head.val+size ≤ origin X term stride) (ho : off.val < size) : + head.val ≤ (head+off).val ∧ (head+off).val < origin X term stride := by + rw [Fin.val_add,Nat.mod_eq_of_lt (by omega)] + omega + refine ⟨?_,?_,?_,?_⟩ + · intro x v hx + obtain ⟨j,hj,c,eq⟩ := pr x v hx + rw [eq] + let i : Word w := j + have vi : i.val=j := Nat.mod_eq_of_lt (by omega) + obtain ⟨base,arc⟩ := decoded_offsets X p₀ hp i (vi ▸ hj) + have here (head off : Word w) {N : ℕ} (hl : inputFloor p₀ ≤ head.val) (hstart : head.val+N ≤ origin X term stride) + (hoff : off.val < N) : inputFloor p₀ ≤ (head+off).val ∧ (head+off).val < origin X term stride := by + obtain ⟨ha,hb⟩ := fbound head off hstart hoff + exact ⟨hl.trans ha,hb⟩ + fin_cases c + · exact here _ _ ((min_le_left ..).trans (min_le_left ..)) old.color base + · exact here _ _ ((min_le_left ..).trans (min_le_right ..)) old.offset base + · exact here _ _ ((min_le_right ..).trans (min_le_left ..)) old.mate arc + · exact here _ _ ((min_le_right ..).trans (min_le_right ..)) old.displacement arc + · intro x v hx + obtain ⟨j,hj,c,eq⟩ := pw x v hx + exact eq ▸ pRange j hj c + · intro x v hx + obtain ⟨j,hj,c,eq⟩ := rr x v hx + rw [eq] + let i : Word w := j + have vi : i.val=j := Nat.mod_eq_of_lt (by omega) + obtain ⟨src,dst,lo,hi⟩ := demand_offsets X role sh T (p.afterPositions m) chosen (inputs X term stride p₀ T bit) + hp.degree exec.incidenceBeforeRoles stored.placementBeforeRoles (by omega) i (vi ▸ hj) + have col (t : Fin 4) (off : Word w) (ho : off.val < positions X) : + placementBase X term stride ≤ (placementWord X term stride t+off).val ∧ + (placementWord X term stride t+off).val < roleBase X term stride := by + have ht := Nat.mul_le_mul_right (positions X) t.isLt + rw [Nat.succ_mul] at ht + change placementBase X term stride ≤ _ ∧ _ < placementBase X term stride + 4*positions X + rw [Fin.val_add,column_value X term stride fit,Nat.mod_eq_of_lt (by unfold placementBase; omega)] + omega + fin_cases c + · exact .inl (fbound T.actualOut i old.actualOut (vi ▸ hj)) + · exact .inr (col 1 _ src) + · exact .inr (col 1 _ dst) + · exact .inr (col 2 _ lo) + · exact .inr (col 3 _ lo) + · exact .inr (col 0 _ hi) + · intro x v hx + obtain ⟨j,hj,c,eq⟩ := rw' x v hx + exact eq ▸ rRange j hj c + +end CompressorRecords.ShrinkHistoryTrace + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkHistoryDirectory.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkHistoryDirectory.lean new file mode 100644 index 0000000000..c9cd10d16f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkHistoryDirectory.lean @@ -0,0 +1,85 @@ +import OAI.Computability.VPVNP.CompressorRecordsSelectedFinish +import OAI.Computability.VPVNP.PairTraversalLevelDirectories + +/-! +# The completed shrinking scan as a level of the actual DFS history + +The selected pass, its term, and both site orders come from the compressor +execution. Later native calls can retain this directory by preserving its +three physical regions. They may change other cells, including the scheduler +header below the raw tables. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace PairSimulation.TraversalRows + +open BurstRAM CompressorRecords NetworkKernel LocalHistory Compression + +variable {A : Type*} [CommRing A] {N : Network} {t : Term A N} {w limit : ℕ} +variable {old : Order N.Site} {next : Order t.output.Site} {m m' : Memory w} + +/-- Addresses occupied by the old-owner column, the new-site counts and the fixed-capacity +preimage rows of a DFS directory. -/ +def directoryCell (pub : Fin 6 → Word w) (x : ℕ) : Prop := + ((pub 1).val ≤ x ∧ x < (pub 1).val+(pub 0).val) ∨ + ((pub 3).val ≤ x ∧ x < (pub 3).val+(pub 2).val) ∨ + ((pub 5).val ≤ x ∧ x < (pub 5).val+(pub 2).val*(pub 4).val) + +open private countAt_val rowAt_val from OAI.Computability.VPVNP.CompressorRecordPreimageScan + +/-- Reuse a collected DFS directory at a larger limit in another memory that agrees on its +owner, count and preimage-row regions. -/ +def Directory.transfer (dir : Directory t old next m limit) (newLimit : ℕ) + (room : limit ≤ newLimit) (agree : ∀ x, directoryCell dir.pub x → m' x = m x) : + Directory t old next m' newLimit := by + refine {dir with inputEnd := dir.inputEnd.trans room, collected := ⟨?_,?_⟩} + · intro i hi + have bounds := dir.regions.ownersBeforeCounts + have hfit := (dir.pub 3).isLt + have hi' : i.val < (dir.pub 0).val := hi + have addr : (dir.pub 1+i).val = (dir.pub 1).val+i.val := by + rw [Fin.val_add,Nat.mod_eq_of_lt (by omega)] + change m' (dir.pub 1+i).val = _ + rw [agree _ (.inl (by rw [addr]; omega))] + exact dir.collected.owners i hi + · intro v hv + have row := dir.collected.rows v hv + have c := countAt_val dir.regions hv + have r := rowAt_val dir.regions hv + have hv' : v.val < (dir.pub 2).val := hv + constructor + · rw [agree _ (.inr (.inl (by rw [c]; omega)))] + exact row.1 + · intro j + have hc := j.isLt.trans_le (dir.capacity v hv) + have mul := Nat.mul_le_mul_right (dir.pub 4).val hv' + rw [Nat.succ_mul] at mul + rw [agree _ (.inr (.inr (by rw [r]; omega)))] + exact row.2 j + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (f : B.Entry → A) (hf : B.IsSolution f) +variable (i : Fin S.steps) {g : ℕ} (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) +variable (term stride selectors : Word w) (p₀ : Fin 14 → Word w) (s : SelectedScore.Selection B X) +variable (mem : Memory w) (p : SelectedStage.Passes w) (q : SelectedFinish.Passes w) + +/-- Any selector bit string indexing this selected pass yields the same +DFS directory for its native placement rows. -/ +noncomputable def shrinkLevel (selector : List Bool) : SelectedLevel B f hf := + ⟨_,_,_,_,X,B.shrinkPassAt f hf i rfl X,.shrink i rfl X,s,selector⟩ + +/-- The selected shrinking pass's old-site placement directory in the final report memory, +bounded by the end of the selected allocation. -/ +noncomputable def selectedShrinkDirectory (selector : List Bool) + (built : SelectedFinish.Built B X term stride selectors p₀ s mem p q) + (room : SelectedFinish.stop X term stride ≤ 2^w) : + LevelDirectory (shrinkLevel B f hf i X s selector) (q.final (p.final mem)) (SelectedFinish.stop X term stride) := + built.selectedDirectory B X term stride selectors p₀ s mem p (f ∘ Sum.inl) ((B.solution_iff f).mp hf).1 (S.shrink i) room + +end PairSimulation.TraversalRows + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkInputTerms.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkInputTerms.lean new file mode 100644 index 0000000000..66850e89b3 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkInputTerms.lean @@ -0,0 +1,152 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkInput +import OAI.Computability.VPVNP.CompressorShrinkTermAllocation + +/-! +# Selecting shrinking terms from a completed graph-input pass + +The first free cell of the input construction is the dense demand head. +The next two cells per motif hold the AB/CD pair, followed by one strided +term descriptor per motif. The reports consume exactly the original +shrinking choices. Every cell of the completed graph-input arena survives +both scans, including its incidence directory, colors, offsets and old +field starts. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkInput + +open BurstRAM Compression Compression.PackingData ShrinkRankSpace MotifGrid MotifBlocks ShrinkMotif +open scoped Classical + +variable {w a g : ℕ} (X : State a (packingLaneBits a g)) (T : IncidenceDirectory w) (start : ℕ) + +local notation "Z" => plan X start +local notation "q" => Shape.collectBank (plan X start) w +local notation "dest" => ShrinkRAM.word w (Shape.ranks (plan X start)) +local notation "wb" => widthBase X start +local notation "B" => ShrinkTermSelection.bundles X +local notation "Q" => ShrinkTermSelection.ranks a +local notation "N" => B*Q + +/-- Base address of the dense two-word demand pairs, immediately after the shrinking input +workspace. -/ +abbrev demandHead := ShrinkRAM.word w (stop X start) +/-- Base address of the term descriptors, immediately after one dense AB/CD demand pair per +motif. -/ +abbrev termHead := ShrinkRAM.word w (stop X start+2*N) +/-- Exclusive end of the descriptor array, allowing one row of the given stride after each +motif's demand pair has been allocated. -/ +def termEnd (stride : ℕ) := stop X start+2*N+N*stride +/-- Prefix-scan operand bank for the thick-wire width rows in the completed shrinking input +arena. -/ +abbrev thickBank := ShrinkWidthArena.prefixBank X T q dest wb false +/-- Prefix-scan operand bank for the CD width rows in the completed shrinking input arena. -/ +abbrev cdBank := ShrinkWidthArena.prefixBank X T q dest wb true +/-- Operand bank for splitting each bundle's width into its ordered AB pieces in the input +arena. -/ +abbrev piecesBank := ShrinkWidthArena.abBank X T q dest wb +/-- Six gather operands that pair the AB piece width with the CD width for each motif and +address the dense demand output. -/ +abbrev pairBank := ShrinkTermInputs.operands (cdBank X T start) (piecesBank X T start) (demandHead (w := w) X start) + +set_option maxHeartbeats 1200000 in +theorem termLayout (stride : ℕ) (room : termEnd X start stride < 2^w) : + ShrinkDemandGather.Layout B Q (pairBank X T start) ∧ + ShrinkDemandFrame.Before B (2^(Shrink.colors a)*2^a/4) Q (thickBank X T start) + (cdBank X T start) (piecesBank X T start) (demandHead (w := w) X start).val ∧ + (demandHead (w := w) X start).val+ShrinkTermInputs.motifCount X*2 ≤ (termHead (w := w) X start).val ∧ + (termHead (w := w) X start).val+ShrinkTermInputs.motifCount X*stride < 2^w := by + let s := ShrinkWidthArena.scatterBank T q dest wb + let first := ShrinkWidthArena.prefixBase X q wb + let abStart := ShrinkWidthArena.abBase X q wb + change stop X start+2*N+N*stride < 2^w at room + have endSpace : stop X start = wb+6*N+2*B := rfl + have hrank : (Z).stop < 2^w := by change wb < _; omega + have hv := (Z).values T (placementBank X T start) Fintype.card_pos hrank + have hs : (s 3).val = Q := hv.stride + have hs₄ : (s 4).val = wb := Nat.mod_eq_of_lt hrank + have hf : first = wb+2*N := by change wb+2*(B*(q 4).val) = _; rw [hv.stride] + have ha : abStart = first+2*(B*(s 3).val)+2*B := rfl + have hd : abStart+2*N = stop X start := by rw [ha,hf,hs,endSpace]; omega + have hAfter : (s 4).val+2*(B*(s 3).val) ≤ first := by rw [hs₄,hs,hf] + have hfit : first+2*(B*(s 3).val)+2*B+4*N+N*stride < 2^w := by rw [← ha]; omega + obtain ⟨lay,early,sep,cap⟩ := ShrinkTermSelection.packed_arena s B (2^a) (Shrink.colors a) first stride + hs.ge hAfter hfit + let d := Fin.ofNat (2^w) (abStart+2*N) + let t := Fin.ofNat (2^w) (abStart+2*N+2*N) + have ed : d = demandHead (w := w) X start := congrArg (Fin.ofNat (2^w)) hd + have et : t = termHead (w := w) X start := congrArg (fun j => Fin.ofNat (2^w) (j+2*N)) hd + change ShrinkDemandGather.Layout B Q (ShrinkTermInputs.operands (cdBank X T start) (piecesBank X T start) d) at lay + change ShrinkDemandFrame.Before B _ Q (thickBank X T start) (cdBank X T start) (piecesBank X T start) d.val at early + change d.val+N*2 ≤ t.val at sep + change t.val+N*stride < 2^w at cap + rw [ed] at lay early + rw [ed,et,← ShrinkTermSelection.motifCount_eq X] at sep + rw [et,← ShrinkTermSelection.motifCount_eq X] at cap + exact ⟨lay,early,sep,cap⟩ + +variable {k : Type*} [_root_.Field k] {factor : ℝ} +variable (F : FixedBlock k demandSource demandTarget supply + (realWidths demandMass) (realWidths supplyMass) (31/16) factor) + + +set_option maxHeartbeats 900000 in +theorem gather_select_from (before : Memory w) + (stored : ShrinkTermSelection.oldRows X (thickBank X T start) (cdBank X T start) (piecesBank X T start) before) + (stride : ℕ) (wide : 10 ≤ stride) (room : termEnd X start stride < 2^w) + (fit : ShrinkTermSelection.fitConstant F+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (cap : ℕ) (gatherCap : ShrinkDemandGather.cost < cap) (termCap : TermWorker.budget F 2 8 w X.maxWireWidth ≤ cap) : + ∃ gs, ShrinkDemandGather.Gathered B Q (pairBank X T start) cap before gs ∧ + let mid := after before (eventLog gs) + (∀ bs : Fin (ShrinkTermInputs.motifCount X) → List Bool, + (runSegment (ShrinkTermSelection.termProgram F (demandHead X start) (termHead X start) stride) + cap (some 0) mid (List.ofFn bs)).isSome ↔ + ∃! s : X.ShrinkSelection F, bs = ShrinkTermSelection.tapes F X s w) ∧ + ∀ s : X.ShrinkSelection F, ∃ ts, + ShrinkTermSelection.Written F X (demandHead X start) (termHead X start) stride cap s mid ts ∧ + ShrinkTermSelection.oldRows X (thickBank X T start) (cdBank X T start) (piecesBank X T start) + (after mid (eventLog ts)) ∧ + ∀ addr < stop X start, after mid (eventLog ts) addr = before addr := by + obtain ⟨layout,earlier,sep,termRoom⟩ := termLayout X T start stride room + obtain ⟨gs,scan,legal,full⟩ := ShrinkTermSelection.gather_select F X (thickBank X T start) (cdBank X T start) + (piecesBank X T start) (demandHead X start) (termHead X start) stride wide sep termRoom before + stored layout earlier fit cap gatherCap termCap + refine ⟨gs,scan,legal,fun s => ?_⟩ + obtain ⟨ts,hs,hrows⟩ := full s + refine ⟨ts,hs,hrows,fun addr h => ?_⟩ + have hd : (demandHead (w := w) X start).val = stop X start := + Nat.mod_eq_of_lt (by change stop X start+2*N+N*stride < 2^w at room; omega) + exact (hs.frame addr (.inl (by omega))).trans (scan.frame addr (.inl (hd ▸ h))) + + +namespace Run + +variable {X T start} {m : Memory w} (r : Run X T start m) + +set_option maxHeartbeats 900000 in +theorem gather_select (stride : ℕ) (wide : 10 ≤ stride) (room : termEnd X start stride < 2^w) + (fit : ShrinkTermSelection.fitConstant F+4*Nat.clog 2 (X.maxWireWidth+1) ≤ w) + (cap : ℕ) (gatherCap : ShrinkDemandGather.cost < cap) (termCap : TermWorker.budget F 2 8 w X.maxWireWidth ≤ cap) : + ∃ gs, ShrinkDemandGather.Gathered B Q (pairBank X T start) cap r.post gs ∧ + let mid := after r.post (eventLog gs) + (∀ bs : Fin (ShrinkTermInputs.motifCount X) → List Bool, + (runSegment (ShrinkTermSelection.termProgram F (demandHead X start) (termHead X start) stride) + cap (some 0) mid (List.ofFn bs)).isSome ↔ + ∃! s : X.ShrinkSelection F, bs = ShrinkTermSelection.tapes F X s w) ∧ + ∀ s : X.ShrinkSelection F, ∃ ts, + ShrinkTermSelection.Written F X (demandHead X start) (termHead X start) stride cap s mid ts ∧ + ShrinkTermSelection.oldRows X (thickBank X T start) (cdBank X T start) (piecesBank X T start) + (after mid (eventLog ts)) ∧ + ∀ addr < stop X start, after mid (eventLog ts) addr = r.post addr := + gather_select_from X T start F r.post r.stored stride wide room fit cap gatherCap termCap + +end Run + +end CompressorRecords.ShrinkInput + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkInputUpperFrame.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkInputUpperFrame.lean new file mode 100644 index 0000000000..d2b11853f6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkInputUpperFrame.lean @@ -0,0 +1,53 @@ +import OAI.Computability.VPVNP.CompressorGreedyPacketFootprints +import OAI.Computability.VPVNP.CompressorShrinkPreparationAccess +import OAI.Computability.VPVNP.CompressorShrinkBundleAccess + +/-! # The upper frame of the pre-selection input scans + +The complete greedy, placement, ranking and width scans access the old +incidence data and the freshly allocated input arena. Their stores preserve +every address at or above the arena's exclusive end. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkInput.Run + +open BurstRAM Compression SourceTransport + +variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ} +variable {m : Memory w} (r : ShrinkInput.Run X T start m) + +/-- Bounds on all sixteen deterministic input segments before the absolute-ID +scatter. The old width and incidence columns can be anywhere below the arena. -/ +theorem input_access (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) (room : stop X start < 2^w) : + LogAccess (fun x ↦ lo ≤ x ∧ x < stop X start) (fun x ↦ start ≤ x ∧ x < stop X start) r.reports := by + let rd := fun x ↦ lo ≤ x ∧ x < stop X start + let wr := fun x ↦ start ≤ x ∧ x < stop X start + have endGreedy : GreedyArena.greedyStop start (Fintype.card X.Base) a ≤ stop X start := by + obtain ⟨_,a,b,c⟩ := range_bounds X start + exact a.trans (b.trans c) + have g (s : GreedyVisit.Stage) : LogAccess rd wr (GreedyVisit.packetReports r.greedy s) := + (GreedyVisit.packet_access r.greedy lo low s).mono + (fun _ h ↦ ⟨h.1,h.2.trans_le endGreedy⟩) (fun _ h ↦ ⟨h.1,h.2.trans_le endGreedy⟩) + have greedy : LogAccess rd wr r.greedy.reports := (((((g .extract).append (g .zero)).append + (g .colorPrepare)).append (g .colorRead)).append (g .tagPrepare)).append (g .tagRead) + obtain ⟨sites,clear,cls,app,gather,rank⟩ := r.preparation_footprints lo low room + obtain ⟨_,abs⟩ := ShrinkBundlePlan.run_absolute r ((range_bounds X start).2.2.2.trans_lt room) + obtain ⟨scatter,thick,cd,pieces,_⟩ := ShrinkBundlePlan.Scheduled.width_footprints r abs lo (low 5) room + have classified := ((greedy.append sites.2).append clear.2).append cls.2 + have ranked := ((classified.append app.2).append gather.2).append rank.2 + exact (((ranked.append scatter.2).append thick.2).append cd.2).append pieces.2 + + +theorem post_upper (room : stop X start < 2^w) (addr : ℕ) (high : stop X start ≤ addr) : r.post addr = m addr := by + rw [← r.post_reports] + exact after_outside m (r.input_access 0 (fun _ ↦ Nat.zero_le _) room).2 (fun h ↦ high.not_gt h.2) + +end CompressorRecords.ShrinkInput.Run + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkKernelSlices.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkKernelSlices.lean new file mode 100644 index 0000000000..eefb8fd5af --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkKernelSlices.lean @@ -0,0 +1,320 @@ +import OAI.Computability.VPVNP.CompressorShrinkSliceArrays +import OAI.Computability.VPVNP.CompressorTermRecordScan +import OAI.Computability.VPVNP.CompressorSlotOwnerDecode +import OAI.Computability.VPVNP.PackedShrinkStep + +/-! +# Physical slice records of the six-party shrinking kernel + +AB reads use the two bundle numberings at both endpoints. Surviving wires +use the selected payload-plus-selector width and the fixed subdivision count +of their role edge. The live frame stores the source offset, target offset +and length used by the local kernel. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkSliceArrays + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.PackingData +open SliceSchedule + +variable {w : ℕ} + +theorem fieldAt_ordered {A : Type*} {n : ℕ} (order : A ≃ Fin n) (width : A → ℕ) (a : A) : + fieldAt (orderedWidths order width) (order a).val = numberedField order width a := by + simp [fieldAt,orderedWidths,numberedField,fieldStart,← Fin.ofFn_take_eq_take_ofFn (order a).isLt.le, + List.sum_ofFn,Fin.take] + +private theorem sliceAt_pair (old new : List ℕ) (i : ℕ) (j : Fin new.length) : + sliceAt old new (i*new.length+j.val) = + let s := fieldAt old i + let t := fieldAt new j.val + copySlice s.start s.width t.start t.width := by + have hd : (i*new.length+j.val) / new.length = i := by + rw [Nat.mul_comm i, Nat.mul_add_div (Nat.zero_lt_of_lt j.isLt), Nat.div_eq_of_lt j.isLt,Nat.add_zero] + simp [sliceAt,pairAt,hd,Nat.mul_add_mod_of_lt j.isLt] + +section Bundle + +variable {V H Tag L : Type} {d c : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] +variable (P : PackingData V H Tag L d c) +variable (number : P.BundleNumbering) (order : P.ThickNumbering) (width : Arc V H Tag L d c → ℕ) +variable (b : Site V Tag L × Fin d) + +/-- The old array uses the rank among thick wires, the new array the rank +among CD motifs assigned to this bundle. -/ +def thickWidths := orderedWidths (order b) (fun a : P.ThickFiber b => width a.1.1) +/-- AB piece widths of one bundle listed in its motif numbering, the order used to compute the +target offsets of the thick-wire slices. -/ +def abWidths := orderedWidths (number b) (fun m : P.MotifFiber b => P.abWidth number width m.1) + +theorem thickWidths_sum : (thickWidths P order width b).sum = P.bundleWidth width b := by + rw [thickWidths,orderedWidths,List.sum_ofFn,bundleWidth] + exact (order b).symm.sum_comp (fun a : P.ThickFiber b => width a.1.1) + +theorem abWidths_split : + abWidths P number width b = List.ofFn (splitWidth (P.bundleWidth width b) (pieceCount d c)) := by + unfold abWidths orderedWidths + congr 1 + funext i + let m := (number b).symm i + have he : P.abWidth number width m.1 = + splitWidth (P.bundleWidth width b) (pieceCount d c) (number b m) := by + obtain ⟨z,h⟩ := m + subst b + rfl + simpa only [m,Equiv.apply_symm_apply] using he + +/-- Consume both sorted width rows of a real packed bundle. -/ +theorem ab_build (hc : 2 ≤ c) (hd : 0 < d) (o t B : Word w) (mem : Memory w) + (space : Workspace o t B (2^c*d/4) (pieceCount d c)) (fit : P.bundleWidth width b < 2^w) + (thick : ∀ i, (mem (o.val+i.val)).val = width (((order b).symm i).1.1)) + (ab : ∀ j, (mem (t.val+j.val)).val = P.abWidth number width (((number b).symm j).1)) : + ∃ rs, Built o t B (thickWidths P order width b) (abWidths P number width b) mem rs := by + apply build_arrays + · simpa [thickWidths,abWidths,orderedWidths] using space + · rw [thickWidths_sum]; exact fit + · rw [abWidths,orderedWidths,List.sum_ofFn, (number b).symm.sum_comp (fun z : P.MotifFiber b => P.abWidth number width z.1), + P.sum_abWidth hc hd number width b]; exact fit + · intro i hi + simpa [thickWidths,orderedWidths] using thick ⟨i,by simpa [thickWidths,orderedWidths] using hi⟩ + · intro j hj + simpa [abWidths,orderedWidths] using ab ⟨j,by simpa [abWidths,orderedWidths] using hj⟩ + +/-- From only a sorted thick row and its computed total, construct the AB +pieces and both incidence directories, preserving the exact local cost. -/ +theorem ab_build_from_total (q total o t B : Word w) (mem : Memory w) + (count : q.val = pieceCount d c) (pos : 0 < q.val) + (space : Workspace o t B (2^c*d/4) q.val) + (apart : total.val < t.val ∨ t.val+q.val ≤ total.val) + (rowsApart : o.val+2^c*d/4 ≤ t.val ∨ t.val+q.val ≤ o.val) + (thick : ∀ i, (mem (o.val+i.val)).val = width (((order b).symm i).1.1)) + (sum : (mem total.val).val = P.bundleWidth width b) : + ∃ split desc, SplitPass total q t mem split ∧ + Built o t B (thickWidths P order width b) (abWidths P number width b) (after mem (eventLog split)) desc := by + let old := thickWidths P order width b + have len : old.length = 2^c*d/4 := List.length_ofFn + have src (i : ℕ) (hi : i < old.length) : (mem (o.val+i)).val = old[i] := by + simpa only [old,thickWidths,orderedWidths,List.getElem_ofFn] using thick ⟨i,len ▸ hi⟩ + obtain ⟨rs,ds,run,built⟩ := split_build o total q t B old mem (len ▸ space) pos apart (len ▸ rowsApart) + src (sum.trans (thickWidths_sum P order width b).symm) + refine ⟨rs,ds,run,?_⟩ + rw [congrArg (fun n => List.ofFn (splitWidth old.sum n)) count] at built + simpa only [old,thickWidths_sum,abWidths_split] using built + +/-- The frame selected by the rank pair is the typed AB copy slice. -/ +theorem ab_sliceAt (a : P.ThickFiber b) (m : P.MotifFiber b) : + sliceAt (thickWidths P order width b) (abWidths P number width b) + ((order b a).val * pieceCount d c + (number b m).val) = P.demandSlice number order width b a m := by + let old := thickWidths P order width b + let new := abWidths P number width b + have hn : new.length = pieceCount d c := List.length_ofFn + change sliceAt old new _ = _ + rw [congrArg (fun k => (order b a).val*k+(number b m).val) hn.symm] + have pair := sliceAt_pair old new (order b a).val ⟨(number b m).val,lt_of_lt_of_eq (number b m).isLt hn.symm⟩ + rw [pair] + simp only [old,new,thickWidths,abWidths,fieldAt_ordered,numberedField,demandSlice] + +/-- The physical offset and length words implement the AB demand-bit bijection. +This characterizes both local A and local B reads, even when a field is empty. -/ +theorem ab_stored_bits (hc : 2 ≤ c) (hd : 0 < d) {B : Word w} {prior mem : Memory w} + (s : Stored B (thickWidths P order width b) (abWidths P number width b) prior mem) + (a : P.ThickFiber b) (m : P.MotifFiber b) (i : Fin (width a.1.1)) + (j : Fin (P.abWidth number width m.1)) : + let id := (order b a).val * pieceCount d c + (number b m).val + let frame := frameHead B.val (2^c*d/4) (pieceCount d c) + 3*id + P.demandBitEquiv hc hd number order width b ⟨m,j⟩ = ⟨a,i⟩ ↔ + ∃ k < (mem (frame+2)).val, i.val = (mem frame).val+k ∧ j.val = (mem (frame+1)).val+k := by + intro id frame + have hm : (thickWidths P order width b).length = 2^c*d/4 := List.length_ofFn + have hn : (abWidths P number width b).length = pieceCount d c := List.length_ofFn + have hi : id < (thickWidths P order width b).length * (abWidths P number width b).length := by + rw [hm,hn] + dsimp only [id] + calc + _ < (order b a).val * pieceCount d c + pieceCount d c := + Nat.add_lt_add_left (number b m).isLt _ + _ = ((order b a).val+1) * pieceCount d c := by ring + _ ≤ _ := Nat.mul_le_mul_right _ (order b a).isLt + have eqn := ab_sliceAt P number order width b a m + have len := s.lengths id hi + rw [hm,hn,eqn] at len + change (mem (frame+2)).val = _ at len + rw [len,P.demandBitEquiv_eq_iff_slice number order width b hc hd] + dsimp only + by_cases hz : 0 < (P.demandSlice number order width b a m).length + · obtain ⟨src,dst⟩ := s.offsets id hi (eqn ▸ hz) + rw [hm,hn,eqn] at src dst + change (mem frame).val = _ at src + change (mem (frame+1)).val = _ at dst + rw [src,dst] + · have zero : (P.demandSlice number order width b a m).length = 0 := by omega + simp [zero] + +end Bundle + + +/-- A singleton supply word intersects each subdivision in that entire +subdivision. Its local source offset is the sum of preceding widths. -/ +theorem surviving_sliceAt (b q : ℕ) (hq : 0 < q) (j : Fin q) : + let ws := List.ofFn (splitWidth b q) + sliceAt [b] ws j.val = ⟨(ws.take j.val).sum,0,splitWidth b q j⟩ := by + intro ws + have hj : j.val < ws.length := by simp [ws] + have hn : ws.sum = b := List.sum_ofFn.trans (sum_splitWidth _ _ hq) + have hval : ws[j.val] = splitWidth b q j := List.getElem_ofFn .. + have hsum := congrArg List.sum (List.take_append_drop (j.val+1) ws) + rw [List.sum_append,List.sum_take_succ _ _ hj,hval,hn] at hsum + have hbound : (ws.take j.val).sum + splitWidth b q j ≤ b := by omega + have pair := sliceAt_pair [b] ws 0 ⟨j.val,hj⟩ + simp only [Nat.zero_mul,Nat.zero_add] at pair + rw [pair] + simp [fieldAt,copySlice,hj,hval,Nat.min_eq_right hbound] + +/-- The target width, copied length and offsets left by the descriptor builder +are the word sections consumed by the source and target role maps. -/ +theorem surviving_frame (b q : ℕ) (hq : 0 < q) {B : Word w} {prior mem : Memory w} + (stored : Stored B [b] (List.ofFn (splitWidth b q)) prior mem) (j : Fin q) : + let frame := frameHead B.val 1 q + 3*j.val + (mem (frame+2)).val = splitWidth b q j ∧ + ∀ k : Fin (splitWidth b q j), (mem (frame+1)).val = 0 ∧ + (mem frame).val+k.val = (ShrinkPayload.sliceBits b q hq ⟨j,k⟩).val := by + intro frame + let ws := List.ofFn (splitWidth b q) + have hj : j.val < [b].length*ws.length := by simp [ws] + have eqn := surviving_sliceAt b q hq j + have hlen := stored.lengths j.val hj + rw [eqn] at hlen + refine ⟨by simpa only [List.length_singleton,List.length_ofFn,frame] using hlen,?_⟩ + intro k + have hp : 0 < (sliceAt [b] ws j.val).length := by rw [eqn]; exact Nat.zero_lt_of_lt k.isLt + obtain ⟨h₁,h₂⟩ := stored.offsets j.val hj hp + rw [eqn] at h₁ h₂ + simp only [List.length_singleton,List.length_ofFn] at h₁ h₂ + refine ⟨h₂,?_⟩ + rw [show (mem frame).val = (ws.take j.val).sum from h₁,ShrinkPayload.sliceBits_offset] + simp [ws,← Fin.ofFn_take_eq_take_ofFn j.isLt.le,List.sum_ofFn,Fin.take] + +section Surviving + +open MotifGrid MotifBlocks MotifConversion MotifDemandPadding ShrinkMotif + +variable {V H Tag L : Type} {d c N J nL : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable [Fintype V] [Fintype H] [Fintype Tag] [Fintype L] +variable [DecidableEq V] [DecidableEq Tag] [DecidableEq L] +variable (P : PackingData V H Tag L d c) (vertices : V ≃ Fin N) (tags : Tag ≃ Fin J) (lanes : L ≃ Fin nL) +variable {K : Type*} [_root_.Field K] {factor : ℝ} +variable (F : FixedBlock K demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) + (31 / 16) factor) +variable (number : P.BundleNumbering) (old : Arc V H Tag L d c → ℕ) +variable (choice : ∀ m : P.Motif, P.ShrinkChoice number old F m) + +/-- The fixed order of the two groups of four supply roles, as in the term reader. -/ +def supplyRoles : Fin 8 ≃ Bool × Fin 4 := + (finProdFinEquiv (m := 2) (n := 4)).symm.trans (finTwoEquiv.prodCongr (Equiv.refl (Fin 4))) + +theorem supplyRoles_index (l : Bool) (t : Fin 4) : + (supplyRoles.symm (l,t)).val = l.toNat*4+t.val := by + change t.val + 4 * (finTwoEquiv.symm l).val = l.toNat*4+t.val + cases l <;> simp [Nat.add_comm] + +/-- Rectangular width rows indexed by absolute CD arc, role type and +subdivision. The larger common stride admits direct addressing for every role. -/ +def survivingRowBase (widthBase : ℕ) (subdiv : Fin 4 → ℕ) (m : P.Motif) (t : Fin 4) : ℕ := + widthBase + ((Slots.oldArcIndex P vertices tags lanes m.val).val * 4 + t.val) * ∑ e, subdiv e + +/-- The whole term scan supplies all fields needed to reconstruct its image in +one row; earlier input memories and the saved headers need not be retained. -/ +theorem fields_record {n : ℕ} {E : Type} (supply : Fin n ≃ E) (v : E → ℕ) + (m : Memory w) (base : Word w) (fit : base.val+2+n < 2^w) + (fields : ∀ i, (m (base.val+2+i.val)).val = v (supply i)) : + ∀ x, base.val ≤ x → x < base.val+2+n → m x = + TermRecord.recordMemory m base (m base.val) (m (base.val+1)) supply v x := by + obtain ⟨hr,hu,hv,_⟩ := TermRecord.recordMemory_fields m base (m base.val) (m (base.val+1)) supply v fit + intro x hlo hhi + by_cases h₀ : x = base.val + · simpa only [h₀] using hr.symm + by_cases h₁ : x = base.val+1 + · simpa only [h₁] using hu.symm + let i : Fin n := ⟨x-(base.val+2),by omega⟩ + have hi : x = base.val+2+i.val := by dsimp [i]; omega + rw [hi,hv i] + apply Fin.ext + rw [Fin.val_natCast,← fields i,Nat.mod_eq_of_lt (m _).isLt] + +/-- A row read from the selected six-party term is written at the physical +address decoded by the new-slot scan. Both lists of slice references and the +widths survive the descriptor pass. -/ +theorem surviving_build (subdiv : Fin 4 → ℕ) (m : P.Motif) (layout : Bool) (t : Fin 4) + (mem : Memory w) (term total B : Word w) (widthBase : ℕ) + (recFit : term.val+2+8 < 2^w) (cap : outerCap F (P.shrinkDemandWidths number old m) < 2^w) + (fields : TermRecordScan.Fields F supplyRoles demandMass_pos (P.shrinkDemandWidths number old m) + (choice m).val term mem) + (selectors : F.selectorBits < 2^w) (wf : P.termWidths F number old choice m layout t < 2^w) + (hc : 0 < subdiv t) (hcount : subdiv t < 2^w) + (hbase : survivingRowBase P vertices tags lanes widthBase subdiv m t < 2^w) + (space : Workspace total (Fin.ofNat _ (survivingRowBase P vertices tags lanes widthBase subdiv m t)) + B 1 (subdiv t)) + (apart : total.val < survivingRowBase P vertices tags lanes widthBase subdiv m t ∨ + survivingRowBase P vertices tags lanes widthBase subdiv m t + subdiv t ≤ total.val) : + let dst : Word w := Fin.ofNat _ (survivingRowBase P vertices tags lanes widthBase subdiv m t) + let q : Word w := Fin.ofNat _ (subdiv t) + let width := P.termWidths F number old choice m layout t + let pub := supplyData (Fin.ofNat _ (layout.toNat*4+t.val)) (Fin.ofNat _ F.selectorBits) total + let r := supplyReport pub term mem + let prog := (template supplyOps 0).instantiate w pub + let mid := after mem r.events + execute prog.program 16 (prog.program.start term) mem [] = some r ∧ (mid total.val).val = width ∧ + ∃ split desc, SplitPass total q dst mid split ∧ + Built total dst B [width] (List.ofFn (splitWidth width (subdiv t))) (after mid (eventLog split)) desc ∧ + let out := desc.result (after mid (eventLog split)) + (∀ j : Fin (subdiv t), (out (widthBase+((Slots.oldArcIndex P vertices tags lanes m.val).val*4+t.val) * + (∑ e, subdiv e)+j.val)).val = splitWidth width (subdiv t) j) ∧ + ∀ x, x ≠ total.val → (x < dst.val ∨ dst.val+subdiv t ≤ x) → + (x < B.val ∨ stop B.val 1 (subdiv t) ≤ x) → out x = mem x := by + intro dst q width pub r prog mid + let i := supplyRoles.symm (layout,t) + have hd : dst.val = survivingRowBase P vertices tags lanes widthBase subdiv m t := Nat.mod_eq_of_lt hbase + have hq : q.val = subdiv t := Nat.mod_eq_of_lt hcount + have hs : supplyRoles i = (layout,t) := supplyRoles.apply_symm_apply _ + have hwidth : supplyWidths F (P.shrinkDemandWidths number old m) (choice m).val (supplyRoles i) = width := by + rw [hs]; rfl + have hp : supplyData (Fin.ofNat _ i.val) (Fin.ofNat _ F.selectorBits) total = pub := by + rw [show i.val = _ from supplyRoles_index layout t] + obtain ⟨run,hw,_,_,split,desc,pass,built⟩ := supply_build F supplyRoles supplyMass_pos + (P.shrinkDemandWidths number old m) (choice m) i mem mem term (mem term.val) (mem (term.val+1)) q total dst B recFit cap fields.2.1 + (fields_record supplyRoles (choice m).val mem term recFit fields.2.2) selectors (hwidth ▸ wf) (hq ▸ space) (hq ▸ hc) (by simpa only [hd,hq] using apart) + simp only [hp,hwidth] at run hw pass built + have eqWidths := congrArg (fun n => List.ofFn (splitWidth width n)) hq + rw [eqWidths] at built + refine ⟨run,hw,split,desc,pass,built,?_,?_⟩ + · intro j + have hi : j.val < q.val := lt_of_lt_of_eq j.isLt hq.symm + have raw := pass.widths.rows ⟨j.val,hi⟩ hi + change (after mid (eventLog split) (dst.val+j.val)).val = splitWidth (mid total.val).val q.val ⟨j.val,hi⟩ at raw + have he : splitWidth width q.val ⟨j.val,hi⟩ = splitWidth width (subdiv t) j := by + simp only [splitWidth,hq] + rw [hw,he] at raw + have outside := space.newApart + have frame := built.stored.outside (dst.val+j.val) (by + simp only [List.length_singleton,List.length_ofFn]; change dst.val+subdiv t ≤ B.val ∨ stop B.val 1 (subdiv t) ≤ dst.val at outside + have := j.isLt; omega) + rw [← frame,hd] at raw + exact raw + · intro x ht hd' hb + rw [built.stored.outside x (by simpa only [List.length_singleton,List.length_ofFn] using hb), + pass.widths.frame x (show x < dst.val ∨ dst.val+q.val ≤ x by simpa only [hq] using hd')] + rw [(supply_native pub term mem).2.1,writeMemory,show pub 2 = total from rfl,ite_eq_right ht] + +end Surviving + +end CompressorRecords.ShrinkSliceArrays + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkLevelSpace.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkLevelSpace.lean new file mode 100644 index 0000000000..4995f3c6f2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkLevelSpace.lean @@ -0,0 +1,311 @@ +import OAI.Computability.VPVNP.CompressorShrinkInputTerms +import OAI.Computability.VPVNP.CompressorRecordsSelectedPreimages +import OAI.Computability.VPVNP.CompressorShrinkOutputAllocation +import OAI.Computability.VPVNP.CompressorSliceIndexedStarts +import OAI.Computability.VPVNP.CompressorShrinkResidentLayout + +/-! +# Linear external address ranges of a selected shrinking level + +Each coefficient uses the fixed input and output degree exponents. The areas +for demand slices, surviving slices, and sorted slots can be assigned their +own table heads. The bound for the contiguous construction starts the supply +and slot arrays after the selected child-preimage rows. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkLevelSpace + +open BurstRAM Compression Compression.PackingData Compression.ShrinkMotif +open SlotLevel ShrinkSlots + +variable {a b g w : ℕ} (X : State a (packingLaneBits a g)) + +private theorem positions_eq : + Fintype.card X.Base*2^(packingLaneBits a g) = X.positions := by + simp only [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv + (packingLaneBits a g)),Fintype.card_fin] + +private theorem packed_le : ShrinkPreimages.newCount X ≤ X.positions := by + rw [← positions_eq X] + change Fintype.card X.Base*(2^(Shrink.J a)*2^g) ≤ Fintype.card X.Base*2^(packingLaneBits a g) + apply Nat.mul_le_mul_left + rw [← Nat.pow_add] + exact Nat.pow_le_pow_right Nat.zero_lt_two (by unfold packingLaneBits Shrink.J; omega) + +private theorem absolute_eq : ShrinkOutput.absoluteCount X = X.positions*2^a := + (DemandRAM.count_eq X).symm.trans (congrArg (·*2^a) (positions_eq X)) + +private theorem motif_le : ShrinkOutput.motifCount X ≤ X.positions*(2^a*ShrinkRankSpace.cap a) := by + change ShrinkPreimages.newCount X*2^a*ShrinkRankSpace.cap a ≤ _ + rw [Nat.mul_assoc]; exact Nat.mul_le_mul_right _ (packed_le X) + +private theorem selected_motifs : SelectedArena.motifs X = ShrinkOutput.motifCount X := + (Fintype.card_congr (ShrinkMotifOrder.stateNumber X)).trans (Fintype.card_fin _) + +/-- Per-position words for the six greedy scans, old placement and both dense rank/width banks. -/ +def inputRate (a : ℕ) := + let d := 2^a + 11+10*d+4*Greedy.WalkLayout.tagCount d+10*d*ShrinkRankSpace.cap a + +theorem input_stop (start : ℕ) : ShrinkInput.stop X start ≤ start+X.positions*inputRate a := by + let d := 2^a + let Q := ShrinkRankSpace.cap a + let t := Greedy.WalkLayout.tagCount d + let P := X.positions + let V := Fintype.card X.Base + let B := ShrinkPreimages.newCount X*d + have hV : V ≤ P := by + change Fintype.card X.Base ≤ X.positions + rw [← positions_eq X] + exact Nat.le_mul_of_pos_right _ (Nat.two_pow_pos _) + have hb : B ≤ P*d := Nat.mul_le_mul_right _ (packed_le X) + have hbase : ShrinkInput.placementBase X start = start+V*(6+3*d+4*t)+1 := + GreedyArena.greedyStop_eq .. + have hrank : ShrinkInput.rankBase X start = ShrinkInput.placementBase X start+4*P := + congrArg (fun n => ShrinkInput.placementBase X start+4*n) (positions_eq X) + let r := ShrinkInput.plan X start + have ha : r.A = P*d := congrArg (·*d) (positions_eq X) + have eqn : ShrinkInput.stop X start = + ShrinkInput.rankBase X start + 3*r.A + 4*B + 10*B*Q := by + change (((((ShrinkInput.rankBase X start+2*r.A)+2*B)+(2*B)*Q)+(2*B)*Q)+r.A)+6*(B*Q)+2*B = _ + ring + rw [eqn,hrank,hbase,ha] + change _ ≤ start+P*(11+10*d+4*t+10*d*Q) + linarith only [Nat.mul_le_mul_right (6+3*d+4*t) hV,Nat.mul_le_mul_right Q hb,hb,X.positions_pos] + +/-- Per-old-position space bound through the term descriptors, allowing for the input +workspace, two demand words per motif and a descriptor of the given stride. -/ +def termRate (a stride : ℕ) := inputRate a + (2+stride)*(2^a*ShrinkRankSpace.cap a) + +theorem term_end (start stride : ℕ) : + ShrinkInput.termEnd X start stride ≤ start+X.positions*termRate a stride := by + let M := ShrinkOutput.motifCount X + change ShrinkInput.stop X start+2*M+M*stride ≤ _ + have hm : M ≤ X.positions*(2^a*ShrinkRankSpace.cap a) := motif_le X + unfold termRate + linarith only [input_stop X start,hm,Nat.mul_le_mul_right stride hm] + +/-- Selected scores, role columns and both child-preimage arrays after the term table. -/ +def selectedRate (a : ℕ) := 9+4*2^a + +theorem selected_stop (term stride : Word w) : + SelectedFinish.stop X term stride ≤ term.val+ShrinkOutput.motifCount + X*stride.val+X.positions*selectedRate a := by + change term.val+SelectedArena.motifs X*stride.val+3+4*(Fintype.card X.Base*2^(packingLaneBits + a g))+ + 4*ShrinkOutput.absoluteCount X+ShrinkPreimages.newCount + X+(Fintype.card X.Base*2^(packingLaneBits a g)) ≤ _ + rw [selected_motifs X,positions_eq X,absolute_eq X,selectedRate] + linarith only [X.positions_pos,packed_le X] + +/-- The end of table zero with the actual allocated word head. Modulo conversion of +the head or stride can only decrease its natural value. -/ +theorem table_zero (start stride : ℕ) : + SelectedFinish.stop X (ShrinkInput.termHead (w := w) X start) (Fin.ofNat (2^w) stride) ≤ + start+X.positions*(termRate a stride+selectedRate a) := by + let term := ShrinkInput.termHead (w := w) X start + let step := Fin.ofNat (2^w) stride + let M := ShrinkOutput.motifCount X + have ht : term.val ≤ ShrinkInput.stop X start+2*M := Nat.mod_le .. + have hs : step.val ≤ stride := Nat.mod_le .. + have he := term_end X start stride + change ShrinkInput.stop X start+2*M+M*stride ≤ _ at he + have hc := selected_stop X term step + change SelectedFinish.stop X term step ≤ term.val+M*step.val+X.positions*selectedRate a at hc + linarith only [he,hc,ht,Nat.mul_le_mul_left M hs] + +/-- Per-position capacity of the separate AB interval banks. -/ +def abRate (a : ℕ) := 2^a*IndexedStarts.capacity (2^(Shrink.colors a)*2^a/4) (ShrinkRankSpace.cap a) + +theorem ab_end (first : ℕ) : + first+ShrinkTermSelection.bundles X*IndexedStarts.capacity (2^(Shrink.colors a)*2^a/4) + (ShrinkRankSpace.cap a) + ≤ first+X.positions*abRate a := by + apply Nat.add_le_add_left + change (ShrinkPreimages.newCount X*2^a)*_ ≤ X.positions*(2^a*_) + rw [Nat.mul_assoc]; exact Nat.mul_le_mul_right _ (packed_le X) + +/-- Total number of subdivisions over the four supply types for a shrink from degree exponent +`a` to exponent `b`. -/ +def subdivisionSum (a b : ℕ) := + ∑ t, subdivisions (2^a) (Shrink.colors a) (2^b) t + +/-- Width and interval banks of the four surviving supply roles. -/ +def survivingRate (a b : ℕ) := + let d := 2^a + let S := subdivisionSum a b + 4*d*S+4*d*ShrinkRankSpace.cap a*(5+7*S) + +theorem surviving_end (width : ℕ) : + ShrinkOutput.slotsBase X width (levelShape (b := b) X) ≤ width+X.positions*survivingRate a + b := by + let S := subdivisionSum a b + change width+(ShrinkOutput.absoluteCount X*4)*S+(ShrinkOutput.motifCount X*4)*(5+7*S) ≤ _ + rw [absolute_eq X] + unfold survivingRate + change _ ≤ width+X.positions*(4*2^a*S+4*2^a*ShrinkRankSpace.cap a*(5+7*S)) + linarith only [Nat.mul_le_mul_right (4*(5+7*S)) (motif_le X)] + +/-- Slot inputs, counters, sorted owner rows, inversion and six output incidence columns. -/ +def slotRate (a b : ℕ) := + let d := 2^a + let c := Shrink.colors a + let k := 4*d*(2^c*d)*subdivisionSum a b + let pad := 2^b-survivingDegree d c (subdivisions d c (2^b)) + 15+6*(k+pad)+(8+2*(k+pad))*2^b + +theorem slot_end (role start : ℕ) : + let s := levelShape (b := b) X + finish s (ShrinkOutput.heads s role start) ≤ start+X.positions*slotRate a b := by + intro s + let P := sites s + let U := 4*s.oldDegree*(2^s.colors*s.oldDegree)*(∑ t,s.subdivisions t) + let J := U+pad s + have hg : genuineCount s = P*(2*U) := by dsimp [P,genuineCount,sites,Slots.keyCount,U]; ring + have hd : dummyCount s = P*(2*pad s) := by dsimp [P,dummyCount,sites]; ring + have hf : fields s = P*(2*J) := by rw [← counts_add,hg,hd]; dsimp [J]; ring + have ho : owners s = 2*P := Nat.mul_comm .. + have hl : 1 ≤ s.lanes := Nat.two_pow_pos g + have hb : baseArcs s ≤ P*s.newDegree := by + change s.bases*s.tags*s.newDegree ≤ s.bases*(s.tags*s.lanes)*s.newDegree + rw [← Nat.mul_assoc]; exact Nat.mul_le_mul_right _ (Nat.le_mul_of_pos_right _ hl) + have hp : 0 < P := Nat.mul_pos Fintype.card_pos (Nat.mul_pos (Nat.two_pow_pos _) + (Nat.two_pow_pos _)) + apply le_trans _ (Nat.add_le_add_left (Nat.mul_le_mul_right (slotRate a b) (packed_le X)) start) + change _ ≤ start+P*(15+6*J+(8+2*J)*s.newDegree) + change start+8+P+4+fields s+(owners s+fields s)+(owners s+fields s)*s.newDegree+fields s+ + baseArcs s+baseArcs s+baseArcs s+P*s.newDegree+P*s.newDegree+P*s.newDegree ≤ _ + rw [hf,ho] + linarith only [hb,hp] + +/-- The ordinary contiguous output build starts its new width arrays after every +retained input, then allocates its ordered slots. -/ +theorem output_end (term stride : Word w) : + let role := SelectedArena.roleBase X term stride + let retained := SelectedFinish.stop X term stride + ShrinkOutput.stop (b := b) X term.val stride.val role retained ≤ + retained+X.positions*(survivingRate a b+slotRate a b) := by + intro role retained + have hs : term.val+ShrinkOutput.motifCount X*stride.val ≤ role := by + change _ ≤ term.val+SelectedArena.motifs X*stride.val+3+4*SelectedArena.positions X + rw [selected_motifs X]; omega + have hr : role+4*ShrinkOutput.absoluteCount X ≤ retained := by + change _ ≤ role+4*ShrinkOutput.absoluteCount X+ShrinkPreimages.newCount + X+ShrinkPreimages.oldCount X + omega + have hmax : ShrinkOutput.widthBase X term.val stride.val role retained = retained := by + unfold ShrinkOutput.widthBase + rw [max_eq_right hr,max_eq_right ((hs.trans (Nat.le_add_right ..)).trans hr)] + let width := ShrinkOutput.widthBase X term.val stride.val role retained + let slot := ShrinkOutput.slotsBase X width (levelShape (b := b) X) + have hw := surviving_end (b := b) X width + have hc := slot_end (b := b) X role slot + change ShrinkOutput.stop (b := b) X term.val stride.val role retained ≤ + slot+X.positions*slotRate a b at hc + change slot ≤ width+X.positions*survivingRate a b at hw + change width = retained at hmax + linarith only [hc,hw,hmax] + +/-- Both resident directories, including their owner columns, counters and +bounded append rows for the four hidden wires and six local maps per motif. -/ +def residentRate (a : ℕ) := 2+20*2^a*ShrinkRankSpace.cap a + +theorem resident_end (first : ℕ) : + (ShrinkResidentLayout.layout X first).endAddr ≤ first+X.positions*residentRate a := by + let P := ShrinkPreimages.newCount X + change first+SelectedArena.motifs X*4+P+SelectedArena.motifs X*4+SelectedArena.motifs + X*6+P+SelectedArena.motifs X*6 ≤ _ + rw [selected_motifs X,residentRate] + dsimp only [P]; linarith only [packed_le X,motif_le X] + +/-- Capacity for all live shrinking arenas, chosen from the fixed transition. -/ +def levelRate (a b : ℕ) := + termRate a 10+selectedRate a+abRate a+survivingRate a b+slotRate a b+residentRate a + +variable {k : Type*} [_root_.Field k] + +/-- Uniform rate chosen before the input, the number of remaining lanes and the +selected term. It works for separate table arenas and the contiguous output layout. -/ +def tableFactor (S : BlockSchedule k) := + Finset.univ.sup fun i : Fin S.steps ↦ levelRate (S.degreeExponent i.castSucc) + (S.degreeExponent i.succ) + +theorem levelRate_le_tableFactor (S : BlockSchedule k) (i : Fin S.steps) : + levelRate (S.degreeExponent i.castSucc) (S.degreeExponent i.succ) ≤ tableFactor S := + Finset.le_sup (f := fun j : Fin S.steps => levelRate (S.degreeExponent j.castSucc) + (S.degreeExponent j.succ)) (Finset.mem_univ i) + +/-- The contiguous shrinking branch is housed in a single linear-capacity arena. +The same uniform factor also bounds each of the separate slice and slot tables. -/ +theorem packed_ends (S : BlockSchedule k) (i : Fin S.steps) {g : ℕ} + (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) + (start ab supply slots : ℕ) (w : ℕ) : + let a := S.degreeExponent i.castSucc + let b := S.degreeExponent i.succ + let s := levelShape (b := b) X + let term := ShrinkInput.termHead (w := w) X start + let stride := Fin.ofNat (2^w) 10 + let role := SelectedArena.roleBase X term stride + let selected := SelectedFinish.stop X term stride + let size := X.positions*tableFactor S + ShrinkInput.stop X start ≤ start+size ∧ ShrinkInput.termEnd X start 10 ≤ start+size ∧ + selected ≤ start+size ∧ ShrinkOutput.stop (b := b) X term.val stride.val role selected ≤ + start+size ∧ + ab+ShrinkTermSelection.bundles X*IndexedStarts.capacity (2^(Shrink.colors a)*2^a/4) + (ShrinkRankSpace.cap a) ≤ ab+size ∧ + ShrinkOutput.slotsBase X supply s ≤ supply+size ∧ finish s + (ShrinkOutput.heads s role slots) ≤ slots+size := by + intro a b s term stride role selected size + have hi := input_stop X start + have ht := term_end X start 10 + have hp := table_zero (w := w) X start 10 + have ho := output_end (b := b) X term stride + have ha := ab_end X ab + have hs := surviving_end (b := b) X supply + have hw := slot_end (b := b) X role slots + have hf : X.positions*levelRate a b ≤ size := Nat.mul_le_mul_left _ (levelRate_le_tableFactor S i) + change selected ≤ start+X.positions*(termRate a 10+selectedRate a) at hp + change ShrinkOutput.stop (b := b) X term.val stride.val role selected ≤ + selected+X.positions*(survivingRate a b+slotRate a b) at ho + unfold levelRate at hf + have input : inputRate a ≤ termRate a 10 := Nat.le_add_right .. + have inputWords := Nat.mul_le_mul_left X.positions input + dsimp only [a,b,s] at * + simp only [Nat.mul_add] at hf hp ho + exact ⟨by omega,by omega,by omega,by omega,by omega,by omega,by omega⟩ + +/-- The resident arrays may follow the chosen preimage rows in table zero or +occupy their own table. The fixed schedule rate covers either address convention. -/ +theorem resident_table (S : BlockSchedule k) (i : Fin S.steps) {g : ℕ} + (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) + (start separate w : ℕ) : + let term := ShrinkInput.termHead (w := w) X start + let stride := Fin.ofNat (2^w) 10 + let next := SelectedFinish.stop X term stride + let size := X.positions*tableFactor S + (ShrinkResidentLayout.layout X next).endAddr ≤ start+size ∧ + (ShrinkResidentLayout.layout X separate).endAddr ≤ separate+size := by + intro term stride next size + have h := table_zero (w := w) X start 10 + change next ≤ _ at h + have hr := resident_end X next + have hs := resident_end X separate + have hf := Nat.mul_le_mul_left X.positions (levelRate_le_tableFactor S i) + unfold levelRate at hf + change _ ≤ size at hf + simp only [Nat.mul_add] at hf h + exact ⟨by omega,by omega⟩ + +end CompressorRecords.ShrinkLevelSpace + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkMotifAbsolute.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkMotifAbsolute.lean new file mode 100644 index 0000000000..370cff817d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkMotifAbsolute.lean @@ -0,0 +1,211 @@ +import OAI.Computability.VPVNP.CompressorRecordsBundleWidthScatter +import OAI.Computability.VPVNP.CompressorRecordsBundleRoleIndex + +/-! +# Absolute role-table identifiers in dense CD piece order + +A source port gives its residual lane by division by the old degree and +reduction modulo the lane radix. Append this lane to its normalized CD key +and scatter the resulting word by classified owner and sorted rank. The +preceding rectangle receives the thick wires' auxiliary words. The CD +rectangle has one entry for every motif and no holes. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.MotifAbsolute + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM Compression Compression.PackingData +open BundleLists BundleKeys BundleWidthScatter + +variable {w : ℕ} + +/-- The first five parameters use the shared scatter layout. The last two +are the old degree and the residual-lane radix. -/ +def columns (p : Fin 7 → Word w) : Fin 5 → Word w := fun t ↦ p (t.castAdd 2) + +/-- Encode an old port's absolute identifier by appending its residual-lane digit to the +normalized key, using the old degree and lane radix. -/ +def payload (p : Fin 7 → Word w) (i key : Word w) : Word w := + key*p 6 + BinaryOp.mod.eval (BinaryOp.div.eval i (p 5)) (p 6) + +/-- Native scatter visit that reads an old port's owner, sorted rank and key, writes its +lane-extended key at the owner and rank, and advances the cursor. -/ +def visit : List (Op 7 7) := + [.stateWord 0, .publicWord 1 0, .binary .add 1 1 0, .read 2 1, + .publicWord 1 1, .binary .add 1 1 0, .read 3 1, + .publicWord 1 2, .binary .add 1 1 0, .read 4 1, + .publicWord 1 3, .binary .mul 2 2 1, .publicWord 1 4, .binary .add 2 1 2, + .binary .add 2 2 3, .publicWord 5 5, .binary .div 5 0 5, .publicWord 6 6, + .binary .mod 5 5 6, .binary .mul 4 4 6, .binary .add 4 4 5, + .write 2 4, .constant 1 1, .binary .add 0 0 1] + +/-- Chronological trace for one absolute-identifier scatter, with the three observed source +words, the write to the classified row, and the intervening ticks. -/ +def events (p : Fin 7 → Word w) (m : Memory w) (i : Word w) : List (Event w) := + let q := columns p + let read (t : Fin 3) := Event.read (source q t i) (m (source q t i).val) + [.tick,.tick,.tick,read 0,.tick,.tick,read 1,.tick,.tick,read 2, + .tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick,.tick, + .write (outAddress q m i) (payload p i (width q m i)),.tick,.tick] + +theorem native (p : Fin 7 → Word w) (m : Memory w) (i : Word w) : + let M := (template visit 0).instantiate w p + execute M.program 25 (M.program.start i) m [] = some ⟨events p m i,some (i+1)⟩ := by + change execute ((template visit 0).instantiate w p).program (1+visit.length) + ⟨_,i,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + rw [execute_template, run_eq_trace] + rfl + +theorem run (p : Fin 7 → Word w) (initial : Memory w) (A : ℕ) (reg : Regions (columns p) initial A) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 25 (some 0) initial (List.replicate A []) = some rs ∧ + endState (some 0) rs = some (word A) ∧ Filled (columns p) initial (after initial (eventLog rs)) A (payload p) ∧ + rs.length = A ∧ (∀ r ∈ rs, r.events.length = 24 ∧ r.probes = 4) ∧ RAMBuckets.cost Report.probes rs = 5*A := by + apply scatter_values _ _ _ (columns p) initial A reg (payload p) + exact fun m i ↦ ⟨events p m i,native p m i,rfl,rfl,rfl⟩ + +variable {V H Tag L : Type} {d c n : ℕ} [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] + +/-- All dense addresses are used once. Recovering a motif from a dense index +recovers both its absolute bundle and its sorted piece number. -/ +def denseIndex (P : PackingData V H Tag L d c) (site : Site V Tag L ≃ Fin n) (cd : P.BundleNumbering) : + P.Motif ≃ Fin ((n*d)*pieceCount d c) := + ((Equiv.sigmaFiberEquiv P.bundle).symm.trans (Equiv.sigmaEquivProdOfEquiv cd)).trans + (((portIndex site).prodCongr (Equiv.refl _)).trans finProdFinEquiv) + +theorem denseIndex_val (P : PackingData V H Tag L d c) (site : Site V Tag L ≃ Fin n) + (cd : P.BundleNumbering) (b : Port V Tag L d) (x : P.MotifFiber b) : + (denseIndex P site cd x.1).val = (portIndex site b).val*pieceCount d c + (cd b x).val := by + rcases x with ⟨x,hx⟩ + subst b + change _ + _ * _ = _ * _ + _ + ac_rfl + +variable {a g N : ℕ} (G : LiftedSlots V (2^a) (BitWord (packingLaneBits a g))) (order : V ≃ Fin N) + +local notation "P" => orderedDyadicPacking G order +local notation "D" => 2^a +local notation "C" => Shrink.colors a +local notation "J" => Shrink.J a +local notation "A" => (N*2^(packingLaneBits a g))*D +local notation "B" => numBundles N a g +local notation "Q" => pieceCount D C +local notation "arcs" => oldArcOrder (a := a) (g := g) order +local notation "sites" => Shrink.packedIndex (a := a) (g := g) order + +/-- The compact role-table identifier in the exact order of the slot compiler. -/ +abbrev absoluteIndex := Slots.oldArcIndex P order (bitWordFinEquiv J) (bitWordFinEquiv g) + +private theorem lane_value (e : OldArc V a g) : + (arcs e).val / D % 2^g = (bitWordFinEquiv g e.1.1.2.2).val := by + rw [oldArcOrder_val, Nat.mul_comm, Nat.mul_add_div (Nat.two_pow_pos _), Nat.div_eq_of_lt e.1.2.isLt, Nat.add_zero] + let high := Shrink.join a (Shrink.join C (order e.1.1.1).val (bitWordFinEquiv C e.2.1).val) + (bitWordFinEquiv a e.2.2).val + let tag := (bitWordFinEquiv J e.1.1.2.1).val + let lane := (bitWordFinEquiv g e.1.1.2.2).val + change (high*2^(J+g) + (tag*2^g+lane)) % 2^g = lane + rw [pow_add, show high*(2^J*2^g)+(tag*2^g+lane) = (high*2^J+tag)*2^g+lane by ring, + Nat.mul_add_mod_of_lt (Fin.isLt _)] + +theorem payload_motif (p : Fin 7 → Word w) (hd : (p 5).val = D) (hl : (p 6).val = 2^g) + (ha : A ≤ 2^w) (e : (P).Motif) : + payload p (arcWord arcs e.1) (word (keyAt order false e.1)) = word ((absoluteIndex G order e.1).val) := by + let i := arcWord (w := w) arcs e.1 + have hi : i.val = (arcs e.1).val := Nat.mod_eq_of_lt ((arcs e.1).isLt.trans_le ha) + have divVal : (BinaryOp.div.eval i (p 5)).val = i.val/(p 5).val := Nat.mod_eq_of_lt ((Nat.div_le_self ..).trans_lt i.isLt) + have hmod : BinaryOp.mod.eval (BinaryOp.div.eval i (p 5)) (p 6) = + word (bitWordFinEquiv g e.1.1.1.2.2).val := by + change Fin.ofNat _ ((BinaryOp.div.eval i (p 5)).val % (p 6).val) = _ + rw [divVal,hi,hd,hl,lane_value order e.1] + have hr : p 6 = word (2^g) := Fin.ext (by rw [← hl]; exact (Nat.mod_eq_of_lt (p 6).isLt).symm) + change word _ * p 6 + BinaryOp.mod.eval (BinaryOp.div.eval i (p 5)) (p 6) = _ + rw [hmod,hr] + change _ = word (Slots.oldArcIndex P order (bitWordFinEquiv J) (bitWordFinEquiv g) e.1).val + rw [oldArcIndex_eq_key_lane G order] + apply Fin.ext + simp [word, Fin.val_add, Fin.val_mul, Nat.mul_mod_mod, Nat.mod_mul_mod, Nat.add_mod_mod, Nat.mod_add_mod] + +/-- Read all three columns at the physical port. The normalized key is needed +only on a CD port. Thick scratch words may have arbitrary values. -/ +structure Inputs (p : Fin 7 → Word w) (initial : Memory w) (cd : (P).BundleNumbering) (dd : (P).ThickNumbering) : Prop where + owners : ∀ e, initial (source (columns p) 0 (arcWord arcs e)).val = word (bucketIndex sites (bucketOf P e)).val + ranks : ∀ e, initial (source (columns p) 1 (arcWord arcs e)).val = word (rankOf P cd dd e) + keys : ∀ e : (P).Motif, initial (source (columns p) 2 (arcWord arcs e.1)).val = word (keyAt order false e.1) + +/-- The owner and rank cells coincide with the previously constructed width +scatter inputs. Only the third column is changed to the classifier's key. -/ +theorem Inputs.of_ranked {p : Fin 7 → Word w} {initial : Memory w} + {cd : (P).BundleNumbering} {dd : (P).ThickNumbering} + {s : Fin 5 → Word w} {old : OldArc V a g → ℕ} (h : RankedInput P cd dd arcs sites s initial old) + (ownerBase : (columns p) 0 = s 0) (rankBase : (columns p) 1 = s 1) + (fit : (p 2).val + A ≤ 2^w) + (keys : ∀ x : (P).Motif, initial ((p 2).val+(arcs x.val).val) = word (keyAt order false x.val)) : + Inputs G order p initial cd dd := by + refine ⟨fun e ↦ ?_,fun e ↦ ?_,fun x ↦ ?_⟩ + · change initial ((columns p) 0 + arcWord arcs e).val = _ + rw [ownerBase]; exact h.owners e + · change initial ((columns p) 1 + arcWord arcs e).val = _ + rw [rankBase]; exact h.ranks e + · change initial (p 2 + arcWord arcs x.val).val = _ + rw [Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt (by have := (arcs x.val).isLt; omega)] + exact keys x + +/-- Contents of every dense cell, including the complete inverse enumeration. -/ +def Directory (cd : (P).BundleNumbering) (denseBase : Word w) (final : Memory w) : Prop := + ∀ i, (final (denseBase.val+i.val)).val = + (absoluteIndex G order ((denseIndex P sites cd).symm i).1).val + +theorem Directory.atPiece {cd : (P).BundleNumbering} {denseBase : Word w} {final : Memory w} + (h : Directory G order cd denseBase final) (b : Port V (BitWord J) (BitWord g) D) (j : Fin Q) : + (final (denseBase.val + ((portIndex sites b).val*Q + j.val))).val = + (absoluteIndex G order ((cd b).symm j).1.1).val := by + let x := (cd b).symm j + have hv := denseIndex_val P sites cd b x + rw [show cd b x = j from (cd b).apply_symm_apply j] at hv + simpa only [Equiv.symm_apply_apply, hv] using h (denseIndex P sites cd x.1) + +/-- A single physical scan emits every requested absolute motif identifier +into its dense rank cell. Its frame preserves every address outside occupied +CD and thick scratch cells. -/ +theorem graph_run (p : Fin 7 → Word w) (initial : Memory w) (cd : (P).BundleNumbering) (dd : (P).ThickNumbering) + (denseBase : Word w) (layout : BundleWidthScatter.Layout (columns p) A (N*(2^J*2^g)) D C) + (hd : (p 5).val = D) (hl : (p 6).val = 2^g) (stride : ((columns p) 3).val = Q) + (dense : denseBase.val = ((columns p) 4).val + B*Q) (read : Inputs G order p initial cd dd) : + let M := (template visit 0).instantiate w p + ∃ rs, runSegment M.program 25 (some 0) initial (List.replicate A []) = some rs ∧ + endState (some 0) rs = some (word A) ∧ Filled (columns p) initial (after initial (eventLog rs)) A (payload p) ∧ + rs.length = A ∧ (∀ r ∈ rs, r.events.length = 24 ∧ r.probes = 4) ∧ RAMBuckets.cost Report.probes rs = 5*A ∧ + Directory G order cd denseBase (after initial (eventLog rs)) := by + let q := columns p + let old := fun e ↦ (width q initial (arcWord arcs e)).val + have hcols : RankedInput P cd dd arcs sites q initial old := ⟨read.owners,read.ranks,fun _ ↦ rfl⟩ + have ha : A ≤ 2^w := by have := layout.sourceFits 0; omega + have hcard := Fintype.card_congr ((arcs).symm.trans (absoluteIndex G order)) + simp only [Fintype.card_fin] at hcard + obtain ⟨rs,hr,he,hf,hln,hw,hc⟩ := run p initial A (regions_of_layout P cd dd arcs sites layout hcols) + refine ⟨rs,hr,he,hf,hln,hw,hc,fun i ↦ ?_⟩ + let m := (denseIndex P sites cd).symm i + let b := (P).bundle m + let x : (P).MotifFiber b := ⟨m,rfl⟩ + have hx : (denseIndex P sites cd x.1).val = i.val := congrArg Fin.val ((denseIndex P sites cd).apply_symm_apply i) + have hdense := (denseIndex_val P sites cd b x).symm.trans hx + have dest := output_eq P cd dd arcs sites layout hcols x.1.1 + change (outAddress q initial (arcWord arcs x.1.1)).val = (q 4).val + + ((bucketIndex sites (bucketOf P x.1.1)).val*(q 3).val + rankOf P cd dd x.1.1) at dest + rw [bucketOf_motif P x.1, rank_motif P cd dd x, show (bucketIndex sites (.inr ((P).bundle x.1))).val = B+ + (portIndex sites b).val from rfl, stride, Nat.add_mul, Nat.add_assoc, hdense, ← Nat.add_assoc, ← dense] at dest + have hs := hf.readback (arcs x.1.1).val (arcs x.1.1).isLt + change after initial (eventLog rs) (outAddress q initial (arcWord arcs x.1.1)).val = + payload p (arcWord arcs x.1.1) (initial (source q 2 (arcWord arcs x.1.1)).val) at hs + rw [dest, read.keys x.1, payload_motif G order p hd hl ha x.1] at hs + have fit := (absoluteIndex G order x.1.1).isLt.trans_le (hcard ▸ ha) + exact (congrArg Fin.val hs).trans (Nat.mod_eq_of_lt fit) + +end CompressorRecords.MotifAbsolute + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkMotifOrder.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkMotifOrder.lean new file mode 100644 index 0000000000..20da26323c --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkMotifOrder.lean @@ -0,0 +1,65 @@ +import OAI.Computability.VPVNP.ShrinkStatePass +import OAI.Computability.VPVNP.CompressorRecordsBundleLists +import OAI.Computability.VPVNP.CompressorRecordsShrink + +/-! +# The physical order of shrinking terms + +A CD occurrence is stored in the row of its assigned port, at the +lane-relative rank used to split the AB bundle. The product of the two +ordinals indexes the dense demand, term and score arrays. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkMotifOrder + +open Compression Compression.PackingData + +variable {V H Tag L : Type} {n d c : ℕ} +variable [AddCommGroup H] [AddCommGroup Tag] [AddCommGroup L] +variable (P : PackingData V H Tag L d c) (cd : P.BundleNumbering) (site : Site V Tag L ≃ Fin n) + +/-- Bundle ordinal followed by the CD rank inside that bundle. -/ +def number : P.Motif ≃ Fin ((n*d)*pieceCount d c) := + (((Equiv.sigmaFiberEquiv P.bundle).symm.trans (Equiv.sigmaEquivProdOfEquiv cd)).trans + ((BundleLists.portIndex site).prodCongr (Equiv.refl _))).trans finProdFinEquiv + +theorem number_val (m : P.Motif) : (number P cd site m).val = + (BundleLists.portIndex site (P.bundle m)).val * pieceCount d c + (cd (P.bundle m) ⟨m,rfl⟩).val := by + change _ + _ * _ = _ * _ + _ + ac_rfl + +theorem number_fiber (b : Site V Tag L × Fin d) (r : Fin (pieceCount d c)) : + (number P cd site ((cd b).symm r).1).val = + (BundleLists.portIndex site b).val * pieceCount d c + r.val := by + let m := (cd b).symm r + rw [number_val] + generalize he : (cd b).symm r = x + obtain ⟨x,hb⟩ := x + have hr := congrArg (cd b) he + rw [Equiv.apply_symm_apply] at hr + subst b + rw [← hr] + +/-- The dense order uses the same base, tag and lane numerals as the +shrinking graph scans. -/ +noncomputable abbrev stateNumber {a g : ℕ} (X : State a (packingLaneBits a g)) := + number X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) + +/-- The cardinal-length form can be used directly by history readers. -/ +noncomputable def entries {a g : ℕ} (X : State a (packingLaneBits a g)) : + Fin (Fintype.card X.packingData.Motif) ≃ X.packingData.Motif := + let e := stateNumber X + (finCongr ((Fintype.card_congr e).trans (Fintype.card_fin _))).trans e.symm + +theorem entries_ordinal {a g : ℕ} (X : State a (packingLaneBits a g)) (m : X.packingData.Motif) : + ((entries X).symm m).val = (stateNumber X m).val := rfl + +end CompressorRecords.ShrinkMotifOrder + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkOldFieldTransfer.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkOldFieldTransfer.lean new file mode 100644 index 0000000000..864bd21beb --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkOldFieldTransfer.lean @@ -0,0 +1,75 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentInterval +import OAI.Computability.VPVNP.CompressorRecordsShrinkBuild + +/-! # Reading the old shrinking tables after later writes + +The demand columns, motif IDs, ten term words, placement roles, selected bit +and preimage lists all lie in the interval from table zero's base through the +end of the preimage rows. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkOutput + +open Compression BurstRAM ShrinkBlockInputs ShrinkSliceSweep ShrinkSlots +open scoped Classical Fin.CommRing +open private absolute_room from OAI.Computability.VPVNP.CompressorRecordsShrinkBuild + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X) +variable (T : IncidenceDirectory w) (start : ℕ) +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "step" => (10 : Word w) +local notation "ids" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w +local notation "keepEnd" => SelectedFinish.stop X term step +local notation "role" => SelectedArena.roleBase X term step + +set_option maxHeartbeats 1200000 in +theorem Resident.below {width : ℕ} {m out : Memory w} (r : Resident B i X sel term step ids T start width m) + (room : ShrinkInput.termEnd X start 10 < 2^w) (ten : 10 < 2^w) + (same : ∀ x < keepEnd, out x = m x) : Resident B i X sel term step ids T start width out := by + have stepVal : (step).val = 10 := Nat.mod_eq_of_lt ten + have stepRoom : ShrinkInput.termEnd X start (step).val < 2^w := stepVal ▸ room + have lim := old_bounds i X term step + have prior := ShrinkInput.termLayout X T start 10 room + have termEarly : (term).val ≤ keepEnd := (Nat.le_add_right ..).trans lim.1 + have demandEarly : (ShrinkInput.demandHead (w := w) X start).val ≤ keepEnd := + ((Nat.le_add_right ..).trans prior.2.2.1).trans termEarly + have idEnd := absolute_room X start step stepRoom + have cell (arc) (j : ℕ) (hj : j<4) : out (role+4*(DemandRAM.absoluteIndex X arc).val+j) = m (role+4*(DemandRAM.absoluteIndex X arc).val+j) := by + have hi : (DemandRAM.absoluteIndex X arc).val < absoluteCount X := (DemandRAM.absoluteIndex X arc).isLt + exact same _ (by omega) + refine ⟨ShrinkDemandFrame.retain r.demand prior.2.1 (fun x hx => same x (hx.trans_le demandEarly)), + fun j => (congrArg Fin.val (same _ ((Nat.add_lt_add_left j.isLt _).trans_le idEnd))).trans (r.directory j), + ?_,⟨fun arc => (congrArg Fin.val (cell arc 3 (by decide))).trans (r.roles.cd arc), + fun arc e => (congrArg Fin.val (cell arc.val (SlotOwners.roleOffset e) (by cases e <;> decide))).trans (r.roles.packed arc e)⟩, + (same _ lim.2.2).trans r.chosen,preimages_retained X term step r.preimages same⟩ + apply terms_after B.shrink X term (step).val _ (levelShape (b := b i) X).subdivisions sel m out r.terms + intro j l hl ptr + have baseBound : ptr.val ≤ (term).val+j.val*(step).val := Nat.mod_le .. + have endBound := Nat.mul_le_mul_right (step).val j.isLt + rw [Nat.succ_mul] at endBound + change j.val*(step).val+(step).val ≤ motifCount X*(step).val at endBound + exact same _ (by omega) + +/-- A frame restricted to the allocated table suffices even when later +publications change cells in the old level header. -/ +theorem Resident.interval {width : ℕ} {m out : Memory w} (r : Resident B i X sel term step ids T start width m) + (room : ShrinkInput.termEnd X start 10 < 2^w) (ten : 10 < 2^w) (fit : keepEnd ≤ 2^w) + (same : ∀ x, start ≤ x → x < keepEnd → out x = m x) : Resident B i X sel term step ids T start width out := by + let staged : Memory w := fun x => if x < start then m x else out x + have keep (x : ℕ) (hx : x < keepEnd) : staged x = m x := by + by_cases early : x < start + · exact ite_eq_left early + · exact (ite_eq_right early).trans (same x (Nat.le_of_not_gt early) hx) + exact (r.below B i X sel T start room ten keep).above B i X sel T start room fit + (fun x hx => (ite_eq_right (Nat.not_lt.mpr hx)).symm) + +end CompressorRecords.ShrinkOutput + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkOutputAccess.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputAccess.lean new file mode 100644 index 0000000000..d55985cab5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputAccess.lean @@ -0,0 +1,138 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkOutputBuild +import OAI.Computability.VPVNP.CompressorSlotSelectedAccess + +/-! +# The bounded source walk on the actual shrinking allocation + +The selected width sweep precedes the chronological slot workers. Its +constructor supplies the old-arc role words in their physical memory, +so all slot phases and the six canonical copies have explicit access +bounds in the concrete consecutive allocation. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkOutput + +open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy +open MotifBlocks MotifGrid MotifConversion Slots SlotLevel ShrinkSlots BurstRAM + +variable {a b g w : ℕ} {k : Type*} [_root_.Field k] {factor δ : ℝ} +variable (X : State a (packingLaneBits a g)) +variable (F : FixedBlock k demandSource demandTarget Compression.ShrinkMotif.supply + (realWidths demandMass) (realWidths supplyMass) (31/16) factor) +variable (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (sel : X.ShrinkSelection F) +variable (term : Word w) (stride role retained : ℕ) + +local notation "s" => levelShape (b := b) X +local notation "h" => slotHeads (b := b) X term.val stride role retained +local notation "width" => widthBase X term.val stride role retained +local notation "last" => stop (b := b) X term.val stride role retained +local notation "side" => selectedLayout X F sel + +/-- Numeric bounds for either a consecutive or separately placed slot workspace. -/ +theorem FitsWords.slot_space_at (start : ℕ) (gap : (h).role ≤ start) + (room : finish s (heads s role start) < 2^w) (hw : FitsWords (b := b) X F term stride role retained) : + Build.Space s (heads s role start) width w := by + have old : role+4*absoluteCount X ≤ (h).role := + (role_room X term stride role retained).trans (width_le_slots X term stride role retained) + have splitRoom : width+(oldBaseArcCount (s).bases (s).tags (s).oldDegree (s).colors*(s).lanes)*4* + (∑ t,(s).subdivisions t) ≤ (h).role := Nat.le_add_right .. + exact ⟨old.trans gap,splitRoom.trans gap,le_rfl,le_rfl,le_rfl,room,hw.lanes,hw.tags,hw.profile,hw.degree⟩ + +theorem FitsWords.slot_space (hw : FitsWords (b := b) X F term stride role retained) : + Build.Space s h width w := hw.slot_space_at X F term stride role retained (h).role le_rfl hw.room + +/-- Both ways to look up any genuine or dummy field survive the selected physical slot output. -/ +theorem Constructed.retained_tables_at (start : ℕ) (gap : (h).role ≤ start) + (room : finish s (heads s role start) < 2^w) {initial out : Memory w} {r : Build.Construction w} + (c : Constructed X F ready sel term stride role retained initial out r start) + (hw : FitsWords (b := b) X F term stride role retained) : + Build.OrderedTables X ready side (heads s role start) (r.final out) := + Build.retained_tables X F ready sel (heads s role start) width out r (hw.slot_space_at X F term stride role retained start gap room) + c.inputRoles c.slots + +/-- Both ways to look up any genuine or dummy field survive the selected physical slot output. -/ +theorem Constructed.retained_tables {initial out : Memory w} {r : Build.Construction w} + (c : Constructed X F ready sel term stride role retained initial out r) + (hw : FitsWords (b := b) X F term stride role retained) : + Build.OrderedTables X ready side h (r.final out) := + Build.retained_tables X F ready sel h width out r (hw.slot_space X F term stride role retained) + c.inputRoles c.slots + +/-- Each of the 22 physical stages reads within the current allocation and +writes only in the slot workspace or the next canonical incidence block. -/ +theorem Constructed.sources_of_space (slotStart : ℕ) {initial out : Memory w} {r : Build.Construction w} + (c : Constructed X F ready sel term stride role retained initial out r slotStart) + (sp : Build.Space s (heads s role slotStart) width w) + (P : ShrinkSlotPlan.Scheduled.Plan) (L : DescriptorSpace.Layout) (level : Fin L.levels) : + let h₀ := heads s role slotStart + let end₀ := finish s h₀ + let Y := X.shrinkNext F ready sel + let start := DescriptorSpace.incidenceStart L level + let U := DescriptorSpace.packedIncidence L w level (actualCount s) + let copies := CopyIncidence.reports Y (directory s h₀ w) U CopyIncidence.allColumns (after out (eventLog r.all)) + DescriptorSpace.endAddress L < 2^w → actualCount s ≤ DescriptorSpace.slotCapacity L → + (end₀ ≤ start ∨ start+6*actualCount s ≤ targetsHead s h₀) → + SourceWalk (fun j m rs ↦ ShrinkSlotPlan.Scheduled.Source P s h₀ side width U j m rs ∧ + LogAccess (fun x ↦ role ≤ x ∧ x < end₀) + (fun x ↦ (slotStart ≤ x ∧ x < end₀) ∨ start ≤ x ∧ x < start+6*actualCount s) rs) + ShrinkSlotPlan.Scheduled.order out (r.all++copies) ∧ U.Represents Y (after out (eventLog (r.all++copies))) := by + intro h₀ end₀ Y start U copies room cap apart + have readHead : min h₀.oldArc width = role := min_eq_left (by + change role ≤ width + exact (Nat.le_add_right ..).trans (role_room X term stride role retained)) + have run := ShrinkSlotPlan.Scheduled.selected_sources X F ready sel P h₀ width out r L level + sp c.inputRoles c.slots c.incidence room cap apart + have rd : Build.readRegion s h₀ width = fun x ↦ role ≤ x ∧ x < end₀ := by + funext x; simp only [Build.readRegion,readHead]; rfl + rw [rd] at run + exact run + +/-- Each of the 22 physical stages reads within the current allocation and +writes only in the slot workspace or the next canonical incidence block. -/ +theorem Constructed.sources_at (slotStart : ℕ) (gap : (h).role ≤ slotStart) + (endFit : finish s (heads s role slotStart) < 2^w) {initial out : Memory w} {r : Build.Construction w} + (c : Constructed X F ready sel term stride role retained initial out r slotStart) + (hw : FitsWords (b := b) X F term stride role retained) + (P : ShrinkSlotPlan.Scheduled.Plan) (L : DescriptorSpace.Layout) (level : Fin L.levels) : + let h₀ := heads s role slotStart + let end₀ := finish s h₀ + let Y := X.shrinkNext F ready sel + let start := DescriptorSpace.incidenceStart L level + let U := DescriptorSpace.packedIncidence L w level (actualCount s) + let copies := CopyIncidence.reports Y (directory s h₀ w) U CopyIncidence.allColumns (after out (eventLog r.all)) + DescriptorSpace.endAddress L < 2^w → actualCount s ≤ DescriptorSpace.slotCapacity L → + (end₀ ≤ start ∨ start+6*actualCount s ≤ targetsHead s h₀) → + SourceWalk (fun j m rs ↦ ShrinkSlotPlan.Scheduled.Source P s h₀ side width U j m rs ∧ + LogAccess (fun x ↦ role ≤ x ∧ x < end₀) + (fun x ↦ (slotStart ≤ x ∧ x < end₀) ∨ start ≤ x ∧ x < start+6*actualCount s) rs) + ShrinkSlotPlan.Scheduled.order out (r.all++copies) ∧ U.Represents Y (after out (eventLog (r.all++copies))) := + c.sources_of_space X F ready sel term stride role retained slotStart + (hw.slot_space_at X F term stride role retained slotStart gap endFit) P L level + +/-- Each of the 22 physical stages reads within the current allocation and +writes only in the slot workspace or the next canonical incidence block. -/ +theorem Constructed.sources {initial out : Memory w} {r : Build.Construction w} + (c : Constructed X F ready sel term stride role retained initial out r) + (hw : FitsWords (b := b) X F term stride role retained) + (P : ShrinkSlotPlan.Scheduled.Plan) (L : DescriptorSpace.Layout) (level : Fin L.levels) : + let Y := X.shrinkNext F ready sel + let start := DescriptorSpace.incidenceStart L level + let U := DescriptorSpace.packedIncidence L w level (actualCount s) + let copies := CopyIncidence.reports Y (directory s h w) U CopyIncidence.allColumns (after out (eventLog r.all)) + DescriptorSpace.endAddress L < 2^w → actualCount s ≤ DescriptorSpace.slotCapacity L → + (last ≤ start ∨ start+6*actualCount s ≤ targetsHead s h) → + SourceWalk (fun j m rs ↦ ShrinkSlotPlan.Scheduled.Source P s h side width U j m rs ∧ + LogAccess (fun x ↦ role ≤ x ∧ x < last) + (fun x ↦ ((h).role ≤ x ∧ x < last) ∨ start ≤ x ∧ x < start+6*actualCount s) rs) + ShrinkSlotPlan.Scheduled.order out (r.all++copies) ∧ U.Represents Y (after out (eventLog (r.all++copies))) := + c.sources_at X F ready sel term stride role retained (h).role le_rfl hw.room hw P L level + +end CompressorRecords.ShrinkOutput + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkOutputAllocation.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputAllocation.lean new file mode 100644 index 0000000000..9c13c354dd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputAllocation.lean @@ -0,0 +1,109 @@ +import OAI.Computability.VPVNP.CompressorShrinkSelectedSlices +import OAI.Computability.VPVNP.CompressorSlotBuild + +/-! # Allocation of a selected shrinking pass + +Place the surviving width rectangle beyond the current role table, term +rows and retained directories. Dense interval records follow that rectangle. +The slot constructor then uses fresh consecutive heads for roles, cyclic +successors, subdivision counts and the ordered-slot workspace. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkOutput + +open Compression Compression.PackingData Compression.ShrinkMotif Compression.ShrinkEnergy +open MotifBlocks MotifGrid MotifConversion SlotLevel ShrinkSlots +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM ShrinkSliceSweep + +variable {a b g w : ℕ} (X : State a (packingLaneBits a g)) + +/-- Number of motif descriptors in the shrinking output allocation, one per numbered piece of +each packed-site bundle. -/ +abbrev motifCount := ((Fintype.card X.Base*(2^(Shrink.J a)*2^g))*2^a)*pieceCount (2^a) (Shrink.colors a) +/-- Number of old arcs in absolute role-table order, used to size the four-word role records. -/ +abbrev absoluteCount := DemandRAM.absoluteCount X + +/-- First address available for surviving width data, taken after the term rows, old-arc role +records and all retained directories. -/ +def widthBase (term stride role retained : ℕ) := + max (term+motifCount X*stride) (max (role+4*absoluteCount X) retained) + +/-- Start of the ordered-slot allocation after reserving the surviving width rectangle and the +per-motif interval records for every subdivision. -/ +def slotsBase (width : ℕ) (s : Shape) := + let sum := ∑ i, s.subdivisions i + width+(absoluteCount X*4)*sum+(motifCount X*4)*(5+7*sum) + +/-- Place the role, next-site, subdivision and scratch tables for slot construction from the +given start, using the existing old-arc role records. -/ +def heads (s : Shape) (role start : ℕ) : Heads := + ⟨role,start,start+8+sites s,start+8,start+8+sites s+4⟩ + +/-- Compute the slot-constructor table bases for this level after allocating its surviving +width and interval records. -/ +def slotHeads (term stride role retained : ℕ) := + let s := levelShape (b := b) X + heads s role (slotsBase X (widthBase X term stride role retained) s) + +/-- Exclusive end of the shrinking output allocation, including the slot constructor's +workspace at this level. -/ +def stop (term stride role retained : ℕ) := + finish (levelShape (b := b) X) (slotHeads (b := b) X term stride role retained) + +private theorem scratch_le_finish (s : Shape) (h : Heads) : h.scratch ≤ finish s h := by + unfold finish widthHead inHead outHead inverseBaseHead stopAddress shiftsHead targetsHead inverseHead rowsHead + omega + +variable {k : Type*} [_root_.Field k] {factor δ : ℝ} +variable (F : FixedBlock k demandSource demandTarget supply (realWidths demandMass) (realWidths supplyMass) (31/16) factor) +variable (sel : X.ShrinkSelection F) (term : Word w) (stride role retained : ℕ) + +/-- Allocate the selected term's surviving widths and slice records using its actual +subdivision counts and the space after the retained data. -/ +abbrev splitBank := + selectedAllocation F X sel term stride (widthBase X term.val stride role retained) (levelShape (b := b) X).subdivisions + +theorem splitBank_last : + (splitBank (b := b) X F sel term stride role retained).last = + (slotHeads (b := b) X term.val stride role retained).role := rfl + +theorem width_le_slots : + widthBase X term.val stride role retained ≤ (slotHeads (b := b) X term.val stride role retained).role := + (Nat.le_add_right _ _).trans (Nat.le_add_right _ _) + +theorem slots_le_stop : + (slotHeads (b := b) X term.val stride role retained).role ≤ stop (b := b) X term.val stride role retained := by + let s := levelShape (b := b) X + let h := slotHeads (b := b) X term.val stride role retained + have he : h.scratch = h.role+8+sites s+4 := rfl + exact (by omega : h.role ≤ h.scratch).trans (scratch_le_finish s h) + +theorem fits (ready : Ready (2^a) (2*2^a+1) (2^b) δ) (wide : 10 ≤ stride) + (room : stop (b := b) X term.val stride role retained < 2^w) : + (splitBank (b := b) X F sel term stride role retained).Fits := by + let h := slotHeads (b := b) X term.val stride role retained + have hstop := scratch_le_finish (levelShape (b := b) X) h + have he : h.scratch = h.role+8+sites (levelShape (b := b) X)+4 := rfl + change finish _ h < 2^w at room + refine ⟨wide,le_max_left ..,ready.count_pos,(slots_le_stop X term stride role retained).trans_lt room,?_⟩ + omega + +theorem role_room : role + 4*absoluteCount X ≤ widthBase X term.val stride role retained := + (le_max_left ..).trans (le_max_right ..) + +theorem retained_room : retained ≤ widthBase X term.val stride role retained := + (le_max_right ..).trans (le_max_right ..) + +end CompressorRecords.ShrinkOutput + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkOutputCharges.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputCharges.lean new file mode 100644 index 0000000000..6e43201303 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputCharges.lean @@ -0,0 +1,107 @@ +import OAI.Computability.VPVNP.CompressorShrinkScheduledOutput +import OAI.Computability.VPVNP.CompressorShrinkScheduledCharges + +/-! # Source traffic of the four post-selection shrinking windows + +The directory, AB, surviving-role and ordered-slot packets all use empty +choice tapes. Their combined call count depends only on the incoming shape +and fixed degrees. The cost includes copying the six actual incidence columns +into the next level. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ScheduledShrink + +open BurstRAM Compression ShrinkBlockInputs BlockPlanner DescriptorSpace SourceOnline +open SlotLevel ShrinkSlots ShrinkSlotPlan.Scheduled ShrinkOutput ShrinkScheduledCharges +open scoped Classical Fin.CommRing +open private positions_eq from OAI.Computability.VPVNP.CompressorShrinkLevelSpace + +/-- Calls plus external probes per incoming position for Parts 5–8. -/ +def outputRate (a b : ℕ) := 102*(2^a+1)+ShrinkScheduledCharges.rate a b + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} {B : S.Templates} {i : Fin S.steps} +variable {g w : ℕ} {X : State (a i) (packingLaneBits (a i) g)} +local notation "sh" => levelShape (b := b i) X + +/-- Native worker count including the resident publications and the three +base-port and three actual-port transfers. -/ +def outputCalls (i : Fin S.steps) {g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) := + let s := levelShape (b := b i) X + let q := ShrinkBundlePlan.cap (a i) + let t := ShrinkBundlePlan.thickCount (a i) + (ShrinkResidentLayout.layout X 0).calls + ShrinkTermSelection.bundles X*(t+q+2*(t*q)) + + motifCount X*ShrinkLevelSpace.subdivisionSum (a i) (b i) + + (constructionOrder.map (Stage.limit s)).sum + (3*baseArcs s+3*actualCount s) + +variable {sel : SelectedScore.Selection B X} {base : Word w} {positions blocks round cap : ℕ} +variable {input : Memory w} +local notation "A" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "old" => Script.levelsPerBlock A * round + i.val +local notation "tab" => (fun j : Fin 6 => tableBase L old j) +local notation "term" => ShrinkInput.termHead (w := w) X (tab (0 : Fin 6)) +local notation "ids" => ShrinkResidentPackets.absoluteWord (w := w) X (tab (0 : Fin 6)) +local notation "dst" => packedIncidence L w (old+1) (actualCount sh) +local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel +local notation "src" => directory sh (heads sh (SelectedArena.roleBase X term (10 : Word w)) (tab (3 : Fin 6))) w +variable {ps₅ ps₆ ps₇ ps₈ : List (SourceOnline.Packet (BlockProgram.script B) w)} {r : TablesRun w} +local notation "allPackets" => (((ps₅++ps₆)++ps₇)++ps₈) +local notation "cp" => CopyIncidence.reports Y src dst CopyIncidence.allColumns + (after r.remainder.postWidths (eventLog r.remainder.slots.all)) + +private theorem Output.account (out : Output (S := S) (w := w) (g := g) B i X sel base positions blocks round cap input ps₅ ps₆ ps₇ ps₈ r) : + Accounted B i X (S.shrink i) sel term 10 (tab 0) (tab 2) (tab 3) dst r := + accounted B i X (S.shrink i) sel term 10 ids (tab 0) (tab 2) (tab 3) dst r out.tables + +private theorem Output.reports (out : Output (S := S) (w := w) (g := g) B i X sel base positions blocks round cap input ps₅ ps₆ ps₇ ps₈ r) : + (allPackets).flatMap SourceWalk.Packet.reports = ps₅.flatMap SourceWalk.Packet.reports ++ (r.reports ++ cp) := by + simp only [List.flatMap_append,out.abReports,out.widthReports,out.slotReports,TablesRun.reports, + Passes.reports,List.append_assoc] + +/-- Every source packet of all four windows supplies exactly one empty tape +per native worker invocation. The count is independent of the selected terms. -/ +theorem Output.tapes (out : Output (S := S) (w := w) (g := g) B i X sel base positions blocks round cap input ps₅ ps₆ ps₇ ps₈ r) : + (allPackets).flatMap (fun p => p.stage.choices) = List.replicate (outputCalls i X) [] := by + have a := out.account + have resident := out.residents.tapes + rw [PublishedHeads.chronological_tapes input ps₅ out.residents.group.chronological] at resident + rw [PublishedHeads.chronological_tapes input allPackets out.group.chronological,out.reports] + have join (rs qs : List (Report w)) : branchPaths (rs++qs) = branchPaths rs++branchPaths qs := List.map_append + simp only [TablesRun.reports,Passes.reports,join,resident,a.abTapes,a.widthTapes,a.slotTapes,a.copyTapes] + obtain ⟨baseCount,actCount⟩ := next_counts X B.shrink (S.shrink i) sel + have actual : (Y).positions*2^(b i) = actualCount sh := by + simpa only [State.positions,Fintype.card_prod,Fintype.card_congr (bitWordFinEquiv g),Fintype.card_fin] using actCount + rw [baseCount,actual] + simp only [← List.replicate_add] + apply congrArg (fun n => List.replicate n ([] : List Bool)) + unfold outputCalls + simp only [Nat.add_assoc] + rfl + +/-- Calls plus probes of the original reports, with both resident and slot +publications charged to the current position count. -/ +theorem Output.charge (out : Output (S := S) (w := w) (g := g) B i X sel base positions blocks round cap input ps₅ ps₆ ps₇ ps₈ r) : + RAMBuckets.cost Report.probes ((allPackets).flatMap SourceWalk.Packet.reports) ≤ + X.positions*outputRate (a i) (b i) := by + have h := (ShrinkResidentLayout.cost_units X (tab (5 : Fin 6))).1 + change _ ≤ 102*(ShrinkPreimages.oldCount X*(2^(a i)+1)) at h + rw [show ShrinkPreimages.oldCount X = X.positions from positions_eq X] at h + rw [out.reports,RAMBuckets.cost_append,out.residents.cost] + calc + _ ≤ 102*(X.positions*(2^(a i)+1))+X.positions*ShrinkScheduledCharges.rate (a i) (b i) := + Nat.add_le_add h out.account.linear + _ = _ := by unfold outputRate; ring + +end CompressorRecords.ScheduledShrink + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkOutputHeaders.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputHeaders.lean new file mode 100644 index 0000000000..5dce83af12 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputHeaders.lean @@ -0,0 +1,105 @@ +import OAI.Computability.VPVNP.CompressorShrinkScheduledOutput + +/-! # Scalar inputs for the final shrinking publication groups + +The AB, surviving-width and slot visits preserve the controlling words and +both level headers. The final publishing calendar can therefore start from +the actual concatenation of Parts 5 through 8. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ScheduledShrink + +open BurstRAM Compression ShrinkBlockInputs DescriptorSpace SourceOnline BlockPlanner +open ShrinkOutput SlotLevel ShrinkSlots +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X) +variable (base : Word w) (positions blocks round : ℕ) +local notation "prog" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog prog)) base +local notation "first" => Script.levelsPerBlock prog*round +local notation "old" => first+i.val +local notation "next" => old+1 +local notation "tab" => (fun j : Fin 6 => tableBase L old j) +local notation "T" => packedIncidence L w old (DemandRAM.oldCount X) +local notation "term" => ShrinkInput.termHead (w := w) X (tab 0) +local notation "sh" => levelShape (b := b i) X +local notation "h" => ShrinkOutput.heads sh (SelectedArena.roleBase X term (10 : Word w)) (tab 3) +local notation "headBank" => PortRefresh.TraversalHeaders.HeadBank L +local notation "I" => BlockSlices.abInputs i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 1) + +/-- The old fields, old and new public column addresses and low controller +words required after the selected slot group. -/ +structure TailInputs (memory : Memory w) : Prop where + header : ShrinkHeaderReads.Header i X T (tab 0) L first memory + oldHeads : headBank old (DemandRAM.oldCount X) memory + nextHeads : headBank next (actualCount sh) memory + rows : memory (pt).rows.val = (directoryRows L : Word w) + pitch : memory ((pt).directory-1).val = (levelWords L : Word w) + +variable {B i X sel base positions blocks round} +variable {cap : ℕ} {m : Memory w} {ps₅ ps₆ ps₇ ps₈ : List (SourceOnline.Packet (BlockProgram.script B) w)} {r : TablesRun w} +local notation "out" => post m (((ps₅++ps₆)++ps₇)++ps₈) +local notation "mid" => post m ps₅ + +/-- Outside the slice and slot arenas and the copied successor incidence, +the appended four-part packet memory agrees with the output of Part 5. -/ +theorem Output.frame (run : Output B i X sel base positions blocks round cap m ps₅ ps₆ ps₇ ps₈ r) + (live : round < blocks) (sites : X.positions ≤ positions) (room : endAddress L < 2^w) + (x : ℕ) (tables : x < tab 1 ∨ finish sh h ≤ x) + (copy : x < incidenceStart L next ∨ incidenceStart L next+6*actualCount sh ≤ x) : out x = mid x := by + rw [post_append,run.postWidth] + exact scheduled_frame B i X sel base positions blocks round I mid mid cap r ps₈ live sites room run.tables + run.slotReports x tables copy + +set_option maxHeartbeats 1200000 in +theorem Output.tail_inputs (run : Output B i X sel base positions blocks round cap m ps₅ ps₆ ps₇ ps₈ r) + (live : round < blocks) (sites : X.positions ≤ positions) (room : endAddress L < 2^w) : + TailInputs B i X base positions blocks round out := by + have liveOld : old < (L).levels := by + change (S.steps+1)*round+i.val < 1+(S.steps+1)*blocks + have upper := Nat.mul_le_mul_left (S.steps+1) live + rw [Nat.mul_succ] at upper + have hi := i.isLt + omega + let level : Fin (L).levels := ⟨old,liveOld⟩ + have oldRoom := BlockLevelFit.shrink (w := w) B base.val positions blocks level rfl i X sites room + have slotBefore : finish sh h ≤ levelStart L next := oldRoom.2.2.2.2.2.2.1.next + have headerSize : levelHeaderWords L = 66 := rfl + have cut : levelStart L old+66 ≤ tab 0 := by + change levelStart L old+66 ≤ levelStart L old+66+6*slotCapacity L+0*tableWords L + omega + have order : tab 0 ≤ tab 1 := + (Nat.le_add_right _ _).trans (tableEnd_le_tableBase L old (show (0 : Fin 6) < 1 by decide)) + have nextStart : tab 1 ≤ incidenceStart L next := + (Nat.le_add_right _ _).trans ((tableEnd_le_nextLevel L old (1 : Fin 6)).trans (Nat.le_add_right _ _)) + have low (x : ℕ) (hx : x < tab 1) : out x = mid x := + run.frame live sites room x (.inl hx) (.inl (hx.trans_le nextStart)) + have oldHead (n : ℕ) (hn : n < levelHeaderWords L) : out (levelStart L old+n) = mid (levelStart L old+n) := + low _ ((Nat.add_lt_add_left (hn.trans_eq headerSize) _).trans_le (cut.trans order)) + have nextHead (n : ℕ) (hn : n < levelHeaderWords L) : out (levelStart L next+n) = mid (levelStart L next+n) := + run.frame live sites room _ (.inr (slotBefore.trans (Nat.le_add_right _ _))) (.inl (Nat.add_lt_add_left hn _)) + have cells := Window.lowCells (A := prog) L base (BlockProgram.layout_arity B ..).symm rfl + ((levelStart_mono L (Nat.zero_le (L).levels)).trans_lt room) + have floor := (levelStart_mono L (Nat.zero_le old)).trans ((Nat.le_add_right _ 66).trans (cut.trans order)) + have below : levelStart L old+60 < tab 0 := (Nat.add_lt_add_left (by decide : 60 < 66) _).trans_le cut + exact ⟨run.residents.header.keep_below below (fun x hx => low x (hx.trans_le order)), + run.residents.oldHeads.keep oldHead,run.residents.nextHeads.keep nextHead, + (low _ (cells.1.trans_le floor)).trans run.residents.rows, + (low _ (cells.2.trans_le floor)).trans run.residents.pitch⟩ + +end CompressorRecords.ScheduledShrink + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkOutputRate.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputRate.lean new file mode 100644 index 0000000000..e70febb503 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputRate.lean @@ -0,0 +1,63 @@ +import OAI.Computability.VPVNP.CompressorShrinkScheduledFinish +import OAI.Computability.VPVNP.CompressorShrinkOutputCharges +import OAI.Computability.VPVNP.CompressorShrinkGeometryCharge + +/-! # Scheduled traffic of the shrinking output and DFS publications + +The four output windows pay for the resident scans, rectangle intersections, +width rows, ordered-slot construction and the six incidence transfers. +The remaining twenty-one rows have fixed total traffic. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ScheduledShrink + +open BurstRAM Compression ShrinkBlockInputs DescriptorSpace SourceOnline BlockPlanner ShrinkOutput +open SlotLevel ShrinkSlots ShrinkSliceSweep ScheduledTrace +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X) +variable (base : Word w) (positions blocks round cap : ℕ) +local notation "prog" => BlockProgram.script B +local notation "Pkt" => SourceOnline.Packet prog w + +/-- The scheduled cost bound per incoming position for shrink output stages 5 through 8, +including scheduler overhead for their visits. -/ +def outputGroupRate := groupRate prog (outputRate (a i) (b i)) (ShrinkForward.visitsBefore B i 9) + +/-- The scheduled cost bound per incoming position for the shrink publication tail, using a +source charge of 53 and a packet count of 21. -/ +def tailGroupRate := groupRate prog 53 21 + +/-- The retained report lists of a completed output run determine its +entire scheduled charge, with a coefficient fixed before the input. -/ +theorem Output.rate {m : Memory w} {ps₅ ps₆ ps₇ ps₈ : List Pkt} {r : TablesRun w} + (out : Output B i X sel base positions blocks round cap m ps₅ ps₆ ps₇ ps₈ r) : + let all := ((ps₅++ps₆)++ps₇)++ps₈ + groupCost prog all ≤ X.positions * outputGroupRate B i := by + intro all + apply groupCost_le _ _ _ _ _ out.charge + have n := ShrinkScheduledFinish.output_length B i X sel base positions blocks round cap out + change 36+all.length = ShrinkForward.visitsBefore B i 9 at n + exact (show all.length ≤ ShrinkForward.visitsBefore B i 9 by omega).trans + (Nat.le_mul_of_pos_left _ X.positions_pos) + +theorem tail_rate {m : Memory w} {ms ps : List Pkt} (r : ShrinkScheduledTail.Result B base positions blocks round cap i X m ms ps) : + groupCost prog ps ≤ X.positions*tailGroupRate B := by + apply groupCost_le + · rw [r.charge]; exact Nat.le_mul_of_pos_left _ X.positions_pos + · rw [r.length]; exact Nat.le_mul_of_pos_left _ X.positions_pos + +end CompressorRecords.ScheduledShrink + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkOutputRetained.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputRetained.lean new file mode 100644 index 0000000000..c1e33c448b --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkOutputRetained.lean @@ -0,0 +1,49 @@ +import OAI.Computability.VPVNP.CompressorRecordsSelectedFinish + +/-! # Retaining the selected preimages below the output workspace + +Each packed site's child ordinal is strictly below the common capacity +of a preimage row. Preserving memory through the end of the contiguous +count and row tables therefore preserves the full preimage directory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkOutput + +open Compression BurstRAM +open scoped Classical + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) (term stride : Word w) + +theorem preimages_retained {layout : Bool} {before after : Memory w} + (h : ShrinkPreimages.Directory X layout (SelectedFinish.counts X term stride) (SelectedFinish.rows X term stride) before) + (frame : ∀ j < SelectedFinish.stop X term stride, after j = before j) : + ShrinkPreimages.Directory X layout (SelectedFinish.counts X term stride) (SelectedFinish.rows X term stride) after := by + have length (v : Shrink.Packed X.Base a g) : (ShrinkPreimages.children X layout v).length = ShrinkPreimages.capacity a := by + change Fintype.card {x : Shrink.Old X.Base a g // v = X.packingData.placement layout x} = _ + exact (Fintype.card_congr (Equiv.subtypeEquivRight (fun _ => eq_comm))).trans + (X.packingData.card_placement (by omega) layout v) + have hcount : (SelectedFinish.counts X term stride).val ≤ SelectedFinish.countStart X term stride := Nat.mod_le .. + have hrow : (SelectedFinish.rows X term stride).val ≤ SelectedFinish.rowStart X term stride := Nat.mod_le .. + constructor + · intro v + have idx : (Shrink.packedIndex X.baseIndex v).val < ShrinkPreimages.newCount X := (Shrink.packedIndex X.baseIndex v).isLt + rw [frame]; exact h.count v + unfold SelectedFinish.stop SelectedFinish.rowStart; omega + · intro v j + have hj := j.isLt.trans_le (length v).le + have hi := Nat.mul_le_mul_right (ShrinkPreimages.capacity a) (Shrink.packedIndex X.baseIndex v).isLt + rw [Nat.succ_mul] at hi + change _ ≤ ShrinkPreimages.newCount X * ShrinkPreimages.capacity a at hi + rw [← ShrinkPreimages.oldCount_eq X] at hi + rw [frame]; exact h.child v j + unfold SelectedFinish.stop; omega + +end CompressorRecords.ShrinkOutput + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkPassRun.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkPassRun.lean new file mode 100644 index 0000000000..6296a21701 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkPassRun.lean @@ -0,0 +1,78 @@ +import OAI.Computability.VPVNP.CompressorShrinkPassSegments + +/-! # Running the native shrinking pass from a reachable graph -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkScheduledRun + +open BurstRAM Compression ShrinkBlockInputs BlockPlanner DescriptorSpace SourceOnline +open PairSimulation.LocalHistory PairSimulation.TraversalRows PairSimulation.TraversalRoles +open ShrinkOutput ScheduledTrace PassTimeline Schedule +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} + (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) + {g w : ℕ} (X : GreedyArena.ShrinkingState (a i) g) (pub : Fin 11 → Word w) + (positions blocks round n : ℕ) (live : round < blocks) + (initial : TaggedLayer) (initialFrame : Fin 8 → Word w) + (fuel cap small refreshRate : ℕ) (past : List (SelectedLevel B f hf)) (m : Memory w) + (encode : SelectedScore.Selection B X → List Bool) +set_option quotPrecheck false +local notation "base" => pub 2 +local notation "layout" => BlockProgram.layout B (Fin.val (pub 2)) positions blocks +local notation "script" => BlockProgram.script B +local notation "loc" => (⟨round, .shrink i⟩ : Located S.steps) +local notation "o" => (PassOrigin.shrink i rfl X : PassOrigin B f hf (B.shrinkPassAt f hf i rfl X)) +local notation "src" => old B i (Fin.val (pub 2)) positions blocks round live +local notation "dst" => next B i (Fin.val (pub 2)) positions blocks round live +local notation "inc" => packedIncidence layout w src (DemandRAM.oldCount X) +local notation "begin" => tableBase layout src (0 : Fin 6) +local notation "total" => directoryRows layout +local notation "resident" => + CompiledResident.resident B f hf (pub 2) positions blocks n initial initialFrame +local notation "rawRate" => commonRawRate (fixedRate B) refreshRate +local notation "rate" => nativePassRate (BlockProgram.script B) rawRate * positions +local notation "pt" => Workspace.ports (arity (BlockProgram.script B).catalog) (pub 2) + +set_option maxHeartbeats 900000 in +-- Checking the ten packet families also checks their dependent native run certificates. +/-- Run the true geometry, selection, incidence and publication workers at each admitted term. -/ +theorem realize (common : ShrinkCurrentBranch.Common B f hf i X (Fin.val (pub 2)) + positions blocks src dst m fuel) + (fits : ShrinkBranch.PrefixFits B X inc begin (10 : Word w) fuel) + (index : past.length = (src).val) (size : X.positions ≤ positions) + (room : endAddress layout < 2 ^ w) (arith : TableArithmetic B i X w) + (width : SelectedTermWorker.fitConstant B + 4 * Nat.clog 2 (X.maxWireWidth + 1) ≤ w) + (h₁ : ShrinkHeaderGreedyPackets.clock B i ≤ small) + (h₂ : scanCap script (ShrinkBundlePackets.maxFuel B i) ≤ small) + (h₃ : scanCap script fuel ≤ small) (h₄ : scanCap script 95 ≤ small) + (clock : small ≤ cap) (large : Online.Run.ControlBounds (script).plan cap (w := w)) + (little : Online.Run.ControlBounds (script).plan small (w := w)) + (ready : ScheduledTrace.Boundary resident pub (levelWords layout : Word w) + total ((loc).first B) past X m) : + Nonempty (ScheduledTrace.PassRun resident pub (levelWords layout : Word w) total cap small rate + loc o encode past m) := by + have current : CurrentGraph.Current layout (src).val X n m := index ▸ ready.stored.1.2.1 + have headLow := column_lower B i positions blocks round live X base size room + have rows : m (pt).rows.val = (total : Word w) := Fin.ext (ready.totalValue.trans + (Nat.mod_eq_of_lt (ready.totalValue ▸ (m (pt).rows.val).isLt)).symm) + have build (s : SelectedScore.Selection B X) := + run B i positions blocks round live f hf X base m fuel small common s (encode s) fits + current.heads headLow size room rows ready.stride arith h₁ h₂ h₃ h₄ + choose pre marker geom p₅ p₆ p₇ p₈ ms tail tables result using build + exact ofSources B f hf i X pub positions blocks round n live initial initialFrame fuel cap small + refreshRate past m encode common fits index size room width clock large little ready pre marker + geom p₅ p₆ p₇ p₈ ms tail tables result + +end CompressorRecords.ShrinkScheduledRun + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkPassSegments.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkPassSegments.lean new file mode 100644 index 0000000000..eb4215210a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkPassSegments.lean @@ -0,0 +1,173 @@ +import OAI.Computability.VPVNP.CompressorPacketPassRun +import OAI.Computability.VPVNP.CompressorNativePassRates +import OAI.Computability.VPVNP.CompressorShrinkScheduledRunRate +import OAI.Computability.VPVNP.CompressorShrinkFinishedResident +import OAI.Computability.VPVNP.CompressorShrinkSourceWorker +import OAI.Computability.VPVNP.CompressorCanonicalNativeTapes +import OAI.Computability.VPVNP.CompressorScheduledPassCases +import OAI.Computability.VPVNP.CompressorPassWindowBounds + +/-! # A physical shrinking pass on the concrete resident graph + +The default term supplies the common deterministic prefix and its actual +post-gather input. Each selected term supplies its own source packet and +suffix, which publish the chosen preimage history and successor incidence +columns. The source and live executions have the same selected state. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkScheduledRun + +open BurstRAM Compression ShrinkBlockInputs BlockPlanner DescriptorSpace +open SourceOnline SourceTransport +open PairSimulation.LocalHistory PairSimulation.TraversalRows PairSimulation.TraversalRoles +open ShrinkOutput ScheduledTrace PassTimeline Schedule +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} + (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) + {g w : ℕ} (X : GreedyArena.ShrinkingState (a i) g) (pub : Fin 11 → Word w) + (positions blocks round n : ℕ) (live : round < blocks) (initial : TaggedLayer) + (initialFrame : Fin 8 → Word w) + (fuel cap small refreshRate : ℕ) (past : List (SelectedLevel B f hf)) (m : Memory w) + (encode : SelectedScore.Selection B X → List Bool) +set_option quotPrecheck false +local notation "base" => pub 2 +local notation "layout" => BlockProgram.layout B (Fin.val (pub 2)) positions blocks +local notation "script" => BlockProgram.script B +local notation "loc" => (⟨round, .shrink i⟩ : Located S.steps) +local notation "o" => (PassOrigin.shrink i rfl X : PassOrigin B f hf (B.shrinkPassAt f hf i rfl X)) +local notation "src" => old B i (Fin.val (pub 2)) positions blocks round live +local notation "dst" => next B i (Fin.val (pub 2)) positions blocks round live +local notation "inc" => packedIncidence layout w src (DemandRAM.oldCount X) +local notation "begin" => tableBase layout src (0 : Fin 6) +local notation "total" => directoryRows layout +local notation "resident" => + CompiledResident.resident B f hf (pub 2) positions blocks n initial initialFrame +local notation "rawRate" => commonRawRate (fixedRate B) refreshRate +local notation "rate" => nativePassRate (BlockProgram.script B) rawRate * positions +local notation "Choice" => SelectedScore.Selection B X +local notation "pkt" => SourceOnline.Packet script w +local notation "pt" => Workspace.ports (arity (BlockProgram.script B).catalog) (pub 2) + +private theorem slot_count_le {c h : ℕ} {Y : State c h} (bound : Y.positions ≤ positions) + (degree : 2 ^ c ≤ slotDegree S) : + IncidenceDirectory.slotCount Y ≤ + slotCapacity (BlockProgram.layout B (Fin.val (pub 2)) positions blocks) := by + have eqn : Y.positions = Fintype.card Y.Base * 2 ^ h := by + simp [State.positions, BitWord] + change Fintype.card Y.Base * 2 ^ h * 2 ^ c ≤ positions * slotDegree S + rw [← eqn] + exact Nat.mul_le_mul bound degree + +private theorem block_degree (j : Fin (S.steps + 1)) : 2 ^ S.degreeExponent j ≤ slotDegree S := + (Finset.le_sup (f := fun x : Fin (S.steps + 1) => 2 ^ S.degreeExponent x) + (Finset.mem_univ j)).trans (le_max_right ..) + +set_option maxHeartbeats 2400000 in +-- Checking the dependent source windows and both resident memories exceeds the default budget. +set_option maxRecDepth 5000 in +/-- The real selected packet groups, fixed inner clocks and word geometry +construct the shrinking case of the scheduled execution. -/ +theorem ofSources + (common : ShrinkCurrentBranch.Common B f hf i X base positions blocks src dst m fuel) + (fits : ShrinkBranch.PrefixFits B X inc begin (10 : Word w) fuel) + (index : past.length = (src).val) (size : X.positions ≤ positions) + (room : endAddress layout < 2 ^ w) + (width : SelectedTermWorker.fitConstant B + 4 * Nat.clog 2 (X.maxWireWidth + 1) ≤ w) + (clock : small ≤ cap) (large : Online.Run.ControlBounds (script).plan cap (w := w)) + (little : Online.Run.ControlBounds (script).plan small (w := w)) + (ready : ScheduledTrace.Boundary resident pub (levelWords layout : Word w) total + ((loc).first B) past X m) + (pre : Choice → List pkt) (marker : Choice → pkt) + (geom p₅ p₆ p₇ p₈ ms tail : Choice → List pkt) (tables : Choice → TablesRun w) + (result : ∀ s, Result B i positions blocks round live f hf X base m fuel small common s + (encode s) (pre s) (marker s) (geom s) (p₅ s) (p₆ s) (p₇ s) (p₈ s) (ms s) (tail s) + (tables s)) : + Nonempty (ScheduledTrace.PassRun resident pub (levelWords layout : Word w) total cap small rate + loc o encode past m) := by + classical + let d := defaultSelection o + let posts (s : SelectedScore.Selection B X) := + geom s ++ ((((p₅ s ++ p₆ s) ++ p₇ s) ++ p₈ s) ++ tail s) + let ord := ShrinkForward.first B i round + have hd := (result d).geometry + have hpre : (pre d).length = 21 := hd.prefixLength + have ordEq : (loc).first B = ord := rfl + have lastLen (s) : (loc).first B + (pre d).length + 1 + (posts s).length = (loc).finish B := by + rw [hpre] + have e := (result s).suffixLength + change 22 + (posts s).length = (BlockProgram.shrink B i).length at e + change _ = (loc).first B + (BlockProgram.shrink B i).length + omega + have endFits : (loc).finish B ≤ total := by + rw [BlockProgram.directory_rows] + exact (loc).finish_le_calendar B live + have preFits : (loc).first B + (pre d).length < total := by have e := lastLen d; omega + let worker := ShrinkCurrentBranch.workerInput B f hf i X inc begin fuel common.pre fits + have floor : levelStart layout 0 ≤ begin := by + have lower := levelStart_mono layout (Nat.zero_le (src).val) + unfold tableBase arrayBase incidenceStart; omega + have matchMarker : marker d = ShrinkTermOnline.packet B i X inc begin d fuel .select + common.pre.beforeTerm (marker d).reports := by + have inputEq : (marker d).input = common.pre.beforeTerm := hd.selectInput + rw [← inputEq] + simp only [ShrinkTermOnline.packet, ← hd.selectStage] + have physical : ScheduledTrace.SelectorSite.SourceWorker worker layout (marker d) := by + rw [matchMarker] + exact ShrinkCurrentBranch.sourceWorker B f hf i X inc begin fuel common.pre fits layout d + (marker d).reports floor width + refine ScheduledTrace.PassRun.ofPacketGroups (B := B) (f := f) (hf := hf) + (p := B.shrinkPassAt f hf i rfl X) + («o» := o) («resident» := resident) («loc» := loc) (L := layout) (pub := pub) + (past := past) (m := m) (raw := m) + (encode := encode) (cap := cap) (small := small) («total» := total) («rate» := rate) + (pre d) marker posts hd.prefixGroup + (fun s => ?_) (fun s => ?_) (fun q hq => List.eq_replicate_length.mpr (hd.prefixEmpty q hq)) + (fun s q hq => List.eq_replicate_length.mpr ((result s).quiet q hq)) + (fun s => ((result s).geometry.selectChoices).trans + (congrArg List.ofFn (CanonicalWorker.shrink_tapes B f hf i X s w))) + clock large little rfl rfl + (lt_of_le_of_lt (levelStart_mono layout (Nat.zero_le (layout).levels)) room) + preFits endFits lastLen le_rfl (fun _ _ => rfl) ready worker + physical + (fun s => ?_) (fun s u v agree stored => ?_) (fun s => ?_) + · rw [ordEq, hpre, hd.prefixPost] + dsimp only [ord, ShrinkForward.first] + exact (result s).geometry.selected + · rw [ordEq, hpre] + exact (result s).suffix + · dsimp only [posts] + rw [(result s).final] + exact (result s).finish.advance (Classical.choice (common.selected s)) live size room src dst + rfl rfl index + ready.stored (common.header s (encode s)) (result s).geometry.frame + · have ix : (past ++ [ScheduledTrace.level o encode s]).length < (layout).levels := by + simp only [List.length_append, List.length_singleton, index] + exact (dst).isLt + have outSize := ((o).next_positions_le s).trans size + exact DetailedResident.transfer stored ix room (by change 14 ≤ 54; decide) + (slot_count_le (B := B) (pub := pub) (positions := positions) (blocks := blocks) + outSize (block_degree i.succ)) agree + · have ch := Result.rate_shared (B := B) (common := common) (sel := s) (other := d) + (result s) (result d) + have coef := rawRate_le (PassTimeline.Pass.shrink i) (fixedRate B) refreshRate + have larger : rawRate ≤ nativePassRate script rawRate := by + unfold nativePassRate + have pos : 0 < arity (script).catalog + 3 := Nat.zero_lt_succ _ + exact (Nat.le_mul_of_pos_right _ pos).trans (Nat.le_add_right ..) + exact ch.trans ((Nat.mul_comm X.positions (fixedRate B i)).le.trans + (Nat.mul_le_mul (coef.trans larger) size)) + +end CompressorRecords.ShrinkScheduledRun + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkPhysicalWorkerInput.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkPhysicalWorkerInput.lean new file mode 100644 index 0000000000..9de2eaa64d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkPhysicalWorkerInput.lean @@ -0,0 +1,76 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch +import OAI.Computability.VPVNP.CompressorSelectedTermWorker + +/-! +# The selector input at the actual shrinking branch + +The AB and CD reads of the paired gather establish the exact demand +rows in its output memory. These rows and the packed term addresses +instantiate the physical worker input used by the reverse selector proof. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkCurrentBranch + +open BurstRAM Compression SelectedTerms PairSimulation.LocalHistory +open scoped Classical Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) +variable {g w : ℕ} (X : State (S.degreeExponent i.castSucc) (packingLaneBits (S.degreeExponent i.castSucc) g)) +variable (T : IncidenceDirectory w) (start fuel : ℕ) {m : Memory w} (p : ShrinkBranch.Prefix X T start fuel m) +local notation "o" => (PassOrigin.shrink i rfl X : PassOrigin B f hf (B.shrinkPassAt f hf i rfl X)) +local notation "dense" => ShrinkInput.demandHead (w := w) X start +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "thick" => ShrinkInput.thickBank X T start +local notation "cd" => ShrinkInput.cdBank X T start +local notation "ab" => ShrinkInput.piecesBank X T start + +theorem pairs (space : ShrinkInput.termEnd X start 10 < 2^w) (cost : ShrinkDemandGather.cost < fuel) : + ShrinkTermInputs.statePairs X dense p.beforeTerm := by + let ref := after p.input.post (eventLog p.absolute) + have fit : ShrinkInput.stop X start < 2^w := by unfold ShrinkInput.termEnd at space; omega + have rows := (p.input.keepAbsoluteFrame fit p.absoluteRun.frame).stored + obtain ⟨r,scan,data⟩ := ShrinkTermInputs.gather X.packingData (Shrink.packedIndex X.baseIndex) X.packingWidth + X.shrinkNumber X.shrinkOrder thick cd ab dense ref rows (ShrinkInput.termLayout X T start 10 space).1 cost + have eqn := Option.some.inj (scan.run.symm.trans p.gatherRun.run) + subst r; exact data + +set_option maxHeartbeats 1000000 in +/-- Build the motif term worker's input at the end of the actual gather prefix, with the stored +demand pairs, ten-word descriptor addresses and private-fuel bound. -/ +def workerInput (fit : ShrinkBranch.PrefixFits B X T start (10 : Word w) fuel) : WorkerInput o w := by + have ten : (10 : Word w).val = 10 := Nat.mod_eq_of_lt (fit.wide.trans_lt (10 : Word w).isLt) + have space := fit.termRoom + rw [ten] at space + let bounds := ShrinkInput.termLayout X T start 10 space + let sep := bounds.2.2.1 + let room := bounds.2.2.2 + let L := ShrinkTermInputs.termRows X dense term 10 le_rfl sep room + have data := ShrinkTermInputs.inputs X dense term 10 le_rfl sep room p.beforeTerm (pairs i X T start fuel p space fit.gatherClock) + exact ⟨L,ShrinkTermSelection.addr dense term 10, + TermWorker.addresses_strided (dense).val (term).val 2 10 le_rfl le_rfl sep room, + p.beforeTerm,data,fit.termWords,fuel,fit.termClock⟩ + +theorem workerInput_fields (fit : ShrinkBranch.PrefixFits B X T start (10 : Word w) fuel) : + let I := workerInput B f hf i X T start fuel p fit + I.addr = ShrinkTermSelection.addr dense term 10 ∧ I.fuel = fuel ∧ I.memory = p.beforeTerm := + ⟨rfl,rfl,rfl⟩ + +theorem workerInput_run (fit : ShrinkBranch.PrefixFits B X T start (10 : Word w) fuel) + (bs : Fin (ShrinkTermInputs.motifCount X) → List Bool) : + (workerInput B f hf i X T start fuel p fit).run bs = + runSegment (ShrinkTermSelection.termProgram B.shrink dense term 10) fuel (some 0) p.beforeTerm (List.ofFn bs) := rfl + +end CompressorRecords.ShrinkCurrentBranch + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkPrefixCharge.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkPrefixCharge.lean new file mode 100644 index 0000000000..a6a56f0fe0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkPrefixCharge.lean @@ -0,0 +1,143 @@ +import OAI.Computability.VPVNP.CompressorCompleteShrinkRates +import OAI.Computability.VPVNP.CompressorShrinkGeometryCharge +import OAI.Computability.VPVNP.CompressorShrinkScheduledPrefix + +/-! # Traffic of the first thirty-six scheduled shrinking rows + +The three header reports have a fixed charge. The greedy, placement, +bundle, term, and chosen-geometry workers use a bounded number of calls +and probes per old position. For the installed geometry group the two +score cursor conventions give the same events and number of calls. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkScheduledPrefix + +open BurstRAM DescriptorSpace BlockPlanner PhaseRecipe Schedule SourceOnline Compression +open BlockHeaderRun ShrinkBlockInputs ScheduledRates ScheduledTrace +open scoped Fin.CommRing +open private publisherCounts from OAI.Computability.VPVNP.CompressorScheduledGreedyRates + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} (B : S.Templates) +variable (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) {g w : ℕ} +variable (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X) (tape : List Bool) +variable (base : Word w) (positions blocks : ℕ) (old new : ℕ) (raw : Memory w) +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "v" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape +local notation "initialReports" => BlockHeaderRun.reports v L old new raw +local notation "pub₀" => BlockHeaderRun.scalarPorts (header w L old) +local notation "pub₁" => BlockHeaderRun.scalarPorts (header w L new) +local notation "pub₂" => BlockHeaderRun.headPorts (header w L new) (header w L 0) +local notation "inMem" => BlockHeaderRun.inputMemory v L old raw +local notation "outMem" => BlockHeaderRun.outputMemory v L old new raw + +/-- Total calls and probes for the three header publications of this shrinking substep. -/ +def fixedHeaderRate := headerRate (BlockProgram.geometry B) (.shrink (a i) (b i)) +/-- Bound on one header report's event count plus the final instruction, used for private fuel. -/ +def fixedHeaderCap := headerCap (BlockProgram.geometry B) (.shrink (a i) (b i)) +/-- Per-old-position traffic coefficient for the first 36 shrinking visits, combining header +publication with the selected graph, term and geometry scans. -/ +def prefixRate := fixedHeaderRate B i + selectedRate B (a i) + +set_option maxHeartbeats 1100000 in +private theorem headerCharge : + RAMBuckets.cost Report.probes initialReports = fixedHeaderRate B i ∧ + ∀ r ∈ initialReports, r.events.length+1 ≤ fixedHeaderCap B i := by + let r₀ := scalarReport (inputRow v) (header w L old) (header w L old) raw + let r₁ := scalarReport (outputRow v) (header w L old) (header w L new) inMem + let r₂ := headReport L new outMem + have h₀ := (publisherCounts (inputRow v) pub₀ (header w L old) raw).2 + have h₁ := (publisherCounts (outputRow v) pub₁ (header w L old) inMem).2 + have h₂ := (publisherCounts (DescriptorHeads.publisher (L).shape) pub₂ (0 : Word w) outMem).2 + change 1+r₀.probes = _ ∧ r₀.events.length+1 = _ at h₀ + change 1+r₁.probes = _ ∧ r₁.events.length+1 = _ at h₁ + change 1+r₂.probes = _ ∧ r₂.events.length+1 = _ at h₂ + constructor + · change (1+r₀.probes)+(1+r₁.probes+(1+r₂.probes+0)) = _ + rw [h₀.1,h₁.1,h₂.1,Nat.add_zero,← Nat.add_assoc] + rfl + · intro r hr + change r ∈ [r₀,r₁,r₂] at hr + simp only [List.mem_cons,List.not_mem_nil,or_false] at hr + rcases hr with rfl|rfl|rfl + · exact h₀.2.le.trans (le_max_left ..) + · exact h₁.2.le.trans ((le_max_left ..).trans (le_max_right ..)) + · exact h₂.2.le.trans ((le_max_right ..).trans (le_max_right ..)) + +variable (T : IncidenceDirectory w) (start : ℕ) (stride selectors : Word w) {fuel : ℕ} {m : Memory w} +variable {p : ShrinkBranch.Prefix X T start fuel m} + (chosen : ShrinkBranch.Selected B X T start stride selectors fuel m p sel) + +/-- Charge and clock of each actual source call, including all three +fixed header rows on the live input memories. -/ +theorem raw_charge : + RAMBuckets.cost Report.probes (initialReports++(p.reports++chosen.reports)) ≤ + fixedHeaderRate B i+X.positions*selectedRate B (a i) ∧ + ∀ r ∈ initialReports++(p.reports++chosen.reports), + r.events.length+1 ≤ max (fixedHeaderCap B i) (completeCap (a i) fuel) := by + obtain ⟨hc,ht⟩ := headerCharge B f hf i X sel tape base positions blocks old new raw + obtain ⟨sc,st⟩ := selectedReports B X T start stride selectors fuel chosen + refine ⟨?_,?_⟩ + · rw [RAMBuckets.cost_append,hc] + exact Nat.add_le_add_left sc _ + · intro r hr + exact (List.mem_append.mp hr).elim (fun hh ↦ (ht r hh).trans (le_max_left ..)) (fun hs ↦ (st r hs).trans (le_max_right ..)) + +local notation "scr" => BlockProgram.script B +local notation "Pkt₀" => SourceOnline.Packet scr w + +/-- Apply the exact report and tape identities returned by the twenty-two +preparation and selection rows and the fourteen chosen-geometry rows. -/ +theorem group_charge {pre geo : List Pkt₀} {last : Pkt₀} {mem : Memory w} + (before : pre.flatMap SourceWalk.Packet.reports = initialReports++p.reports) + (select : last.reports = chosen.terms) (preLen : pre.length=21) (geoLen : geo.length=14) + (geoRun : SourceWalk.Chronological Visit.Runs mem geo) + (events : eventLog (geo.flatMap SourceWalk.Packet.reports) = eventLog chosen.geometry.reports) + (tapes : geo.flatMap (fun q ↦ q.stage.choices) = List.replicate (SelectedTailPackets.selectedCalls X) []) : + let all := pre++last::geo + RAMBuckets.cost Report.probes (all.flatMap SourceWalk.Packet.reports) ≤ fixedHeaderRate B i+X.positions*selectedRate B (a i) ∧ + all.length=36 ∧ groupCost scr all ≤ X.positions*groupRate scr (prefixRate B i) 36 := by + intro all + have gCost := SelectedTailPackets.geometry_cost_eq B X T start stride selectors chosen geoRun events tapes + have sum := (raw_charge B f hf i X sel tape base positions blocks old new raw T start stride selectors chosen).1 + have data : RAMBuckets.cost Report.probes (all.flatMap SourceWalk.Packet.reports) ≤ fixedHeaderRate B i+X.positions*selectedRate B (a i) := by + simp only [all,List.flatMap_append,List.flatMap_cons,before,select,RAMBuckets.cost_append,gCost] + simp only [ShrinkBranch.Selected.reports,RAMBuckets.cost_append] at sum + omega + have len : all.length=36 := by simp only [all,List.length_append,List.length_cons,preLen,geoLen] + refine ⟨data,len,groupCost_le scr all _ _ _ ?_ ?_⟩ + · apply data.trans + rw [prefixRate,Nat.mul_add] + exact Nat.add_le_add_right (Nat.le_mul_of_pos_left _ X.positions_pos) _ + · rw [len] + exact Nat.le_mul_of_pos_left _ X.positions_pos + +/-- Each actual scheduled source report obeys the clock proved for its +catalog occurrence, including the redirected score reports. -/ +theorem group_tick_bound {ps : List Pkt₀} {cap ordinal total : ℕ} {mem : Memory w} + (group : Group scr L base cap ordinal total mem ps) (r : Report w) (hr : r ∈ ps.flatMap SourceWalk.Packet.reports) : + r.events.length+1 ≤ cap := by + obtain ⟨packet,hp,hreport⟩ := List.mem_flatMap.mp hr + have runs {A : Script} {raw : Memory w} {qs : List (SourceOnline.Packet A w)} (chron : SourceWalk.Chronological Visit.Runs raw qs) : + ∀ q ∈ qs, q.stage.Runs q.input q.reports := by + induction qs generalizing raw with + | nil => simp + | cons q qs ih => + intro b hb + exact (List.mem_cons.mp hb).elim (fun e ↦ e ▸ chron.2.1) (fun h ↦ ih chron.2.2 b h) + have length := localSegment_event_bound ((runSegment_iff ..).mp (runs group.chronological packet hp)).1 r hreport + have bound := (group.checked packet hp).dataClock + omega + +end CompressorRecords.ShrinkScheduledPrefix + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkPreparationAccess.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkPreparationAccess.lean new file mode 100644 index 0000000000..57636760ba --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkPreparationAccess.lean @@ -0,0 +1,101 @@ +import OAI.Computability.VPVNP.CompressorShrinkRankAccess + +/-! # Guarded source traces for the six bundle preparation visits + +Every report returns the next ordinal. Reads stay within the original +level's data and the allocated arena. Writes begin at the shrinking arena. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkInput.Run + +open BurstRAM PrimedStackRAM Compression SourceTransport ShrinkRankSpace +open scoped Fin.CommRing +open private collectPreimage_reject from OAI.Computability.VPVNP.CompressorSlotFrames + +variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ} +variable {m : Memory w} (r : Run X T start m) +local notation "Z" => plan X start +local notation "A" => Shape.A (plan X start) +local notation "B" => Shape.B (plan X start) +local notation "S" => Fintype.card X.Base * 2^(packingLaneBits a g) +local notation "sh" => placementBank X T start +local notation "p" => Shape.classifyBank (plan X start) T (placementBank X T start) +local notation "q" => Shape.collectBank (plan X start) w +local notation "K" => Shape.gatheredTable (plan X start) w T + +private theorem scanned {C : Type*} {P : BurstRAM.Program w C} {fuel : ℕ} + (step : ∀ m i rep, execute P fuel (P.start i) m [] = some rep → rep.result = some (i+1)) + (m : Memory w) (first count : ℕ) (rs : List (Report w)) + (run : runSegment P fuel (some (first : Word w)) m (List.replicate count []) = some rs) : + StageFrame.Scanned first (first+count) rs := by + induction count generalizing first rs m with + | zero => change some [] = some rs at run; cases Option.some.inj run; exact .done _ + | succ n ih => + rw [List.replicate_succ,runSegment] at run + cases hx : execute P fuel (P.start (first : Word w)) m [] with + | none => rw [hx] at run; contradiction + | some rep => + have inc := step m (first : Word w) rep hx + rw [show (first : Word w)+1 = ((first+1 : ℕ) : Word w) by simp] at inc + simp only [hx,inc,Option.map_eq_some_iff] at run + obtain ⟨tail,rt,rfl⟩ := run + exact .next (by omega) inc ((show first+1+n = first+(n+1) by omega) ▸ ih _ _ tail rt) + +private theorem next_of {C : Type*} {P : BurstRAM.Program w C} {fuel : ℕ} {m : Memory w} {i : Word w} + {rep : Report w} {es : List (Event w)} + (native : execute P fuel (P.start i) m [] = some ⟨es,some (i+1)⟩) + (actual : execute P fuel (P.start i) m [] = some rep) : rep.result = some (i+1) := + congrArg Report.result (Option.some.inj (actual.symm.trans native)) + +set_option maxHeartbeats 1500000 in +private theorem six_ordinals : + StageFrame.Scanned 0 S r.sites ∧ StageFrame.Scanned 0 (2*B) r.clear ∧ StageFrame.Scanned 0 A r.classify ∧ + StageFrame.Scanned 0 A r.append ∧ StageFrame.Scanned 0 A r.gather ∧ StageFrame.Scanned 0 A r.rank := by + have at_zero {C : Type} {P : BurstRAM.Program w C} {fuel n : ℕ} {mem : Memory w} {rs : List (Report w)} + (run : runSegment P fuel (some 0) mem (List.replicate n []) = some rs) + (step : ∀ m i rep, execute P fuel (P.start i) m [] = some rep → rep.result = some (i+1)) : StageFrame.Scanned 0 n rs := by + simpa only [Nat.zero_add] using scanned step mem 0 n rs run + refine ⟨at_zero r.positions (fun mem i _ ↦ next_of (ShrinkRAM.visit_native sh mem i)), + at_zero r.ranking.clear (fun mem i _ ↦ next_of (SliceRAM.clearVisit_native (q 3) i mem)), + at_zero r.ranking.ranked.classify (fun mem i _ ↦ next_of (BundleRAM.visit_native p mem i)), + at_zero r.ranking.ranked.append ?_, + at_zero r.ranking.ranked.gather (fun mem i _ ↦ next_of (BundleGather.Fixed.native (BundleGather.Fixed.parameters K) mem i)), + at_zero r.ranking.ranked.rank.executed ?_⟩ + · intro mem i rep run + by_cases h : i < q 0 ∧ ownerAt q mem i < q 2 ∧ mem (countAt q (ownerAt q mem i)).val < q 4 + · exact next_of (collectPreimage_native q mem i h.1 h.2.1 h.2.2) run + · rw [collectPreimage_reject q mem i h] at run; contradiction + · intro mem i rep run + obtain ⟨_,hn,_,_,_⟩ := PortRankRAM.run_one (BundleGather.rankPublic q (p 10) (Fin.ofNat _ (Z).gathered) (Fin.ofNat _ (Z).ranks)) mem i (Z).Q + exact next_of hn run + +/-- Each of the first six bundle segments is ready for source transport and +has the complete sequence of native successor cursors. -/ +theorem preparation_footprints (lo : ℕ) (low : ∀ c, lo ≤ (T.column c).val) (room : stop X start < 2^w) : + let checked := fun n (rs : List (Report w)) ↦ StageFrame.Scanned 0 n rs ∧ + LogAccess (fun z ↦ lo ≤ z ∧ z < stop X start) (fun z ↦ start ≤ z ∧ z < stop X start) rs + checked S r.sites ∧ checked (2*B) r.clear ∧ checked A r.classify ∧ checked A r.append ∧ + checked A r.gather ∧ checked A r.rank := by + intro checked + obtain ⟨s,c,k,l,g,rk⟩ := r.six_ordinals + have lowStart : lo ≤ start := (low 0).trans ((Nat.le_add_right ..).trans (r.greedy.old 0)) + obtain ⟨h₁,h₂,_,h₄⟩ := range_bounds X start + have chain : rankBase X start ≤ (Z).key ∧ (Z).key ≤ (Z).counts ∧ (Z).counts ≤ (Z).ids ∧ + (Z).ids ≤ (Z).gathered ∧ (Z).gathered ≤ (Z).ranks ∧ (Z).ranks ≤ widthBase X start := by + refine ⟨Nat.le_add_right ..,?_,Nat.le_add_right ..,Nat.le_add_right ..,Nat.le_add_right ..,Nat.le_add_right ..⟩ + change rankBase X start+A ≤ rankBase X start+2*A; omega + obtain ⟨hk,hc,hi,hg,hr,hw⟩ := chain + refine ⟨⟨s,(r.placement_access lo low room).mono ?_ ?_⟩,⟨c,(r.clear_access room).mono ?_ ?_⟩, + ⟨k,(r.classify_access lo low room).mono ?_ ?_⟩,⟨l,(r.append_access room).mono ?_ ?_⟩, + ⟨g,(r.gather_access room).mono ?_ ?_⟩,⟨rk,(r.rank_access room).mono ?_ ?_⟩⟩ + all_goals first | exact fun _ h ↦ h.elim | (rintro z ⟨a,b⟩; exact ⟨by omega,by omega⟩) + +end CompressorRecords.ShrinkInput.Run + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkPublishedHeader.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkPublishedHeader.lean new file mode 100644 index 0000000000..82dd06a57a --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkPublishedHeader.lean @@ -0,0 +1,76 @@ +import OAI.Computability.VPVNP.CompressorShrinkHeaderReads + +/-! +# Reading the shrinking term header from the tight block layout + +The physical scalar and pointer publishers supply the eight kinds of +metadata used by the shrinking term launches. The first scratch table +lies beyond the header, so writes to the shrinking arena preserve every +one of these cells. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkHeaderReads + +open BurstRAM Compression DescriptorSpace ShrinkBlockInputs +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {R : Type*} [CommRing R] (f : B.Entry → R) (hf : B.IsSolution f) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (s : X.ShrinkSelection B.shrink) +variable (T : IncidenceDirectory w) (base positions blocks iteration : ℕ) +local notation "L" => BlockProgram.layout B base positions blocks +local notation "first" => (S.steps+1)*iteration +local notation "level" => first+i.val +local notation "head" => levelStart L level +/-- Index zero among the six level tables, whose published pointer gives the first shrinking +scratch address. -/ +def firstTable : Fin (BlockProgram.layout B base positions blocks).shape.tables := + ⟨0,by change 0 < 6; decide⟩ + +local notation "firstIndex" => firstTable B base positions blocks +local notation "start" => tableBase L level firstIndex + +theorem table_after_header : head+60 < start := by + have hh : levelHeaderWords L = 66 := rfl + change head+60 < head + levelHeaderWords L + 6*slotCapacity L + 0*tableWords L + rw [hh,Nat.zero_mul] + omega + +set_option maxHeartbeats 1000000 in +theorem of_published (selector : List Bool) (dH : ℕ) (mem : Memory w) + (fit : endAddress L < 2^w) (it : iteration < blocks) + (published : let v : SelectedLevel B f hf := + ⟨_,_,_,_,X,B.shrinkPassAt f hf i rfl X,.shrink i rfl X,s,selector⟩ + LevelFields.Published L level v dH mem) + (incidence : ∀ c, mem (incidenceHead L level c) = T.column c) + (scratch : mem (tableHead L level firstIndex) = (start : Word w)) : + Header i X T start L first mem := by + have hl : level < (L).levels := by + have h := Nat.mul_le_mul_left (S.steps+1) it + rw [Nat.mul_succ] at h + change (S.steps+1)*iteration+i.val < 1+(S.steps+1)*blocks + have := i.isLt + omega + have hr := level_room L fit ⟨level,hl⟩ + have before := table_after_header B i base positions blocks iteration + have next : start ≤ levelStart L (level+1) := + (Nat.le_add_right _ _).trans (tableEnd_le_nextLevel L level firstIndex) + refine ⟨before.trans_le next |>.trans hr,published.vertices,published.degree,published.lanes,published.residual,?_,?_⟩ + · intro c + have eqn : incidenceHead L level c = head+(54+c.val) := by change head+54+c.val = _; omega + rw [← eqn]; exact incidence c + · exact scratch + +end CompressorRecords.ShrinkHeaderReads + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkRankAccess.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkRankAccess.lean new file mode 100644 index 0000000000..05953f2095 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkRankAccess.lean @@ -0,0 +1,144 @@ +import OAI.Computability.VPVNP.CompressorBundleGatherFootprint +import OAI.Computability.VPVNP.CompressorBundleRankFootprint +import OAI.Computability.VPVNP.CompressorShrinkSetupFootprint + +/-! # Physical read and write regions for bundle gather and rank + +The stored lists prove that every followed ID belongs to the old port range. +The rank scan's owner array is still readable after ranking, which identifies +each scanned key row before the rank was written. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkInput.Run + +open BurstRAM PrimedStackRAM Compression Compression.PackingData BundleKeys BundleGather +open ShrinkRankSpace BundleLists PortRankRAM +open private table_legal from OAI.Computability.VPVNP.CompressorBundleTableReadback +open scoped Classical + +variable {w a g : ℕ} {X : State a (packingLaneBits a g)} {T : IncidenceDirectory w} {start : ℕ} +variable {m : Memory w} (r : Run X T start m) + +local notation "Z" => plan X start +local notation "A" => Shape.A (plan X start) +local notation "B" => Shape.B (plan X start) +local notation "Q" => Shape.Q (plan X start) +local notation "sh" => placementBank X T start +local notation "q" => Shape.collectBank (plan X start) w +local notation "keyHead" => Fin.ofNat (2^w) (Shape.key (plan X start)) +local notation "out" => Fin.ofNat (2^w) (Shape.gathered (plan X start)) +local notation "dest" => Fin.ofNat (2^w) (Shape.ranks (plan X start)) +local notation "K" => Shape.gatheredTable (plan X start) w T +local notation "R" => BundleGather.rankPublic q keyHead out dest +local notation "P" => X.packingData +local notation "O" => oldArcOrder (a := a) (g := g) X.baseIndex +local notation "sites" => Shrink.packedIndex (a := a) (g := g) X.baseIndex +local notation "MS" => after r.greedy.post (eventLog r.sites) +local notation "ML" => after (after (after MS (eventLog r.clear)) (eventLog r.classify)) (eventLog r.append) +local notation "MG" => after ML (eventLog r.gather) + +theorem gather_access (room : stop X start < 2^w) : + LogAccess (fun z ↦ (Z).key ≤ z ∧ z < (Z).gathered) + (fun z ↦ (Z).gathered ≤ z ∧ z < (Z).ranks) r.gather := by + obtain ⟨h₁,h₂,_,h₄⟩ := range_bounds X start + have fit := h₄.trans_lt room + have val := (Z).values T sh Fintype.card_pos fit + have scalar := (Z).scalarFits Fintype.card_pos fit + obtain ⟨_,layout,_⟩ := (Z).regions T sh Fintype.card_pos ((r.greedy.old 5).trans (h₁.trans h₂)) fit + have hn : B+B ≤ 2^w := by have := scalar.2.1; omega + have stored : Stored P O sites q ML := by + intro b + exact r.ranking.ranked.lists.rows _ (show (bucketIndex sites b).val % (2^w) < (q 2).val by + rw [Nat.mod_eq_of_lt ((bucketIndex sites b).isLt.trans_le hn),val.buckets,two_mul] + exact (bucketIndex sites b).isLt) + have count : Fixed.entryCount K = A := by + change B*(2^(Shrink.colors a)*2^a/4+Q)=A + rw [Nat.mul_add]; exact bundle_rows_total .. + have legal := table_legal P O sites q keyHead out T.width (State.two_le_packingColors a) + scalar.1.le hn layout ML stored + have raw := Fixed.table_access K layout (count ▸ scalar.1) ML legal r.gather (count ▸ r.ranking.ranked.gather) + have hs : Fixed.slots K = (Z).rectangleSize := by + change (B+B)*(q 4).val = (2*B)*Q + rw [val.stride,two_mul] + have hg : (Z).ids+(Z).rectangleSize = (Z).gathered := rfl + have hr : (Z).gathered+(Z).rectangleSize = (Z).ranks := rfl + have hk : (Z).key+A ≤ (Z).ids := by + change rankBase X start+A+A ≤ rankBase X start+2*A+2*B; omega + have ids : (K).idsBase.val = (Z).ids := val.ids + have keys : (K).keyBase.val = (Z).key := val.key + have dst : (K).outputBase.val = (Z).gathered := val.gathered + apply LogAccess.mono raw + · intro z hz; rcases hz with ⟨lo,hi⟩ | ⟨lo,hi⟩ + · rw [ids] at lo hi; rw [hs,hg] at hi; exact ⟨by omega,hi⟩ + · change z < (K).keyBase.val+A at hi; rw [keys] at lo hi; exact ⟨lo,by omega⟩ + · intro z hz; rw [dst,hs,hr] at hz; exact hz + +theorem rank_access (room : stop X start < 2^w) : + LogAccess (fun z ↦ rankBase X start ≤ z ∧ z < (Z).ranks) + (fun z ↦ (Z).ranks ≤ z ∧ z < widthBase X start) r.rank := by + obtain ⟨h₁,h₂,_,h₄⟩ := range_bounds X start + have fit := h₄.trans_lt room + have val := (Z).values T sh Fintype.card_pos fit + have hA := ((Z).scalarFits Fintype.card_pos fit).1 + have ownHead : (R 0).val = rankBase X start := val.owner + have keyVal : (R 1).val = (Z).key := val.key + have rowHead : (R 2).val = (Z).gathered := val.gathered + have stride : (R 3).val = Q := val.stride + have countHead : (R 4).val = (Z).counts := val.counts + have rankHead : (R 5).val = (Z).ranks := val.ranks + have keyNat : rankBase X start+A = (Z).key := rfl + have countNat : rankBase X start+2*A = (Z).counts := rfl + have idNat : (Z).counts+2*B = (Z).ids := rfl + have gatheredNat : (Z).ids+(2*B)*Q = (Z).gathered := rfl + have rankNat : (Z).gathered+(2*B)*Q = (Z).ranks := rfl + have top : (Z).ranks+A < 2^w := fit + have ownerBound (j : ℕ) (hj : j < A) : (owner R MG (Fin.ofNat _ j)).val < 2*B := by + let x : Fin A := ⟨j,hj⟩ + let e := (O).symm x + have he : (O e).val = j := congrArg Fin.val ((O).apply_symm_apply x) + have stored := r.ranking.owners e + change r.rankPost ((R 0).val+(O e).val) = _ at stored + rw [he] at stored + have low := r.ranking.ranked.rank.frame ((R 0).val+j) (.inl (by change _ < (R 5).val; omega)) + change r.rankPost ((R 0).val+j) = MG ((R 0).val+j) at low + rw [PortRankRAM.owner,Fin.val_add,Fin.val_ofNat,Nat.add_mod_mod,Nat.mod_eq_of_lt (by omega),← low,stored] + have hb : (bucketIndex sites (bucketOf P e)).val < B+B := (bucketIndex sites _).isLt + exact (Nat.mod_le ..).trans_lt (by omega) + have rd (j : ℕ) (hj : j < A) (v : Word w) (hv : v ∈ inputs R MG (Fin.ofNat _ j) Q) : + rankBase X start ≤ v.val ∧ v.val < (Z).ranks := by + let i := Fin.ofNat (2^w) j + let u := owner R MG i + have hu : u.val < 2*B := ownerBound j hj + have hi : i.val = j := Nat.mod_eq_of_lt (hj.trans hA) + change v ∈ [R 0+i,R 1+i,R 4+u] ++ (List.range Q).map (fun z ↦ PortRankRAM.start R MG i + Fin.ofNat _ z) at hv + rcases List.mem_append.mp hv with h | h + · simp only [List.mem_cons,List.not_mem_nil,or_false] at h + rcases h with rfl | rfl | rfl + · rw [Fin.val_add,ownHead,hi,Nat.mod_eq_of_lt (by omega)]; exact ⟨by omega,by omega⟩ + · rw [Fin.val_add,keyVal,hi,Nat.mod_eq_of_lt (by omega)]; exact ⟨by omega,by omega⟩ + · rw [Fin.val_add,countHead,Nat.mod_eq_of_lt (by omega)]; exact ⟨by omega,by omega⟩ + · obtain ⟨z,hz,rfl⟩ := List.mem_map.mp h + have hz' := List.mem_range.mp hz + have hh := Nat.mul_le_mul_right Q hu + rw [Nat.succ_mul] at hh + have addr : (PortRankRAM.start R MG i+Fin.ofNat _ z).val = (Z).gathered+u.val*Q+z := by + change (R 2+u*R 3+Fin.ofNat _ z).val = _ + rw [Fin.val_add,Fin.val_add,Fin.val_mul,Fin.val_ofNat,rowHead,stride, + Nat.mod_eq_of_lt (by omega : u.val*Q < 2^w), + Nat.mod_eq_of_lt (by omega : (Z).gathered+u.val*Q < 2^w), + Nat.mod_eq_of_lt (by omega : z < 2^w),Nat.mod_eq_of_lt (by omega)] + rw [addr]; exact ⟨by omega,by omega⟩ + have reg : Regions R MG Q A := ⟨by rw [rankHead]; exact top.le, + fun j hj x hx ↦ .inl (by rw [rankHead]; exact (rd j hj x hx).2)⟩ + exact scan_access R MG Q A reg _ _ rd (fun j hj ↦ by rw [rankHead]; exact ⟨Nat.le_add_right ..,Nat.add_lt_add_left hj _⟩) + r.rank r.ranking.ranked.rank.executed + +end CompressorRecords.ShrinkInput.Run + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkReadbackTransfer.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkReadbackTransfer.lean new file mode 100644 index 0000000000..791a2f89cd --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkReadbackTransfer.lean @@ -0,0 +1,114 @@ +import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables + +/-! # Shrinking slice readbacks after later memory writes + +The AB endpoint lists, surviving interval descriptors and sparse subdivision +widths lie below the ordered-slot workspace. A subsequent pass that preserves those addresses can read them in its own +terminal memory. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkOutput + +open BurstRAM Compression Compression.PackingData ShrinkBlockInputs ShrinkSliceSweep SlotLevel ShrinkSlots +open Compression.ShrinkMotif MotifBlocks MotifGrid +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X) +variable (term stride : Word w) + +local notation "sh" => levelShape (b := b i) X +local notation "role" => SelectedArena.roleBase X term stride +local notation "bankAt" => splitBank (b := b i) X B.shrink sel term stride.val role +local notation "sitesOrd" => Shrink.packedIndex (a := a i) (g := g) X.baseIndex +local notation "ns" => ShrinkBundlePlan.thickCount (a i) +local notation "nt" => ShrinkBundlePlan.cap (a i) + +/-- The AB and surviving CD tables of a single selected block, as read from +one physical memory. -/ +structure SliceReadbacks (first width : ℕ) (post : Memory w) : Prop where + abFields : ABFields i X first post + intervals : ∀ j, Image ((bankAt width).row j) + (selected X.packingData X.shrinkNumber sitesOrd (bankAt width) B.shrink X.packingWidth sel j) post + sparseWidths : SlotWidthScan.SplitRows X.packingData (sh).subdivisions X.baseIndex + (bitWordFinEquiv (Shrink.J (a i))) (bitWordFinEquiv g) (branchWidth X B.shrink sel) + (widthBase X term.val stride.val role width) post + +variable {B i X sel term stride} + +/-- Transfer every AB frame and its two endpoint lists through a memory +frame covering the full bundle rectangle. -/ +theorem abFields_transfer_interval {T : IncidenceDirectory w} {start first limit : ℕ} {before post : Memory w} + (h : ABFields i X first before) {termStride : ℕ} (termRoom : ShrinkInput.termEnd X start termStride < 2^w) + (fresh : ShrinkInput.stop X start ≤ first) + (endBefore : first+(ShrinkInput.plan X start).B*IndexedStarts.capacity ns nt ≤ limit) + (fitsLimit : limit < 2^w) (frame : ∀ x, first ≤ x → x < limit → post x = before x) : ABFields i X first post := by + let layout := BlockSlices.ab_layout i X T start termRoom fresh (endBefore.trans_lt fitsLimit) + intro bundle + let ix := BundleLists.portIndex sitesOrd bundle + let oldRow := ShrinkSliceArrays.thickWidths X.packingData X.shrinkOrder X.packingWidth bundle + let newRow := ShrinkSliceArrays.abWidths X.packingData X.shrinkNumber X.packingWidth bundle + have olen : oldRow.length = ns := List.length_ofFn + have nlen : newRow.length = nt := List.length_ofFn + apply (h bundle).transfer (input := ShrinkABSliceTable.columns (ShrinkInput.thickBank X T start) + (ShrinkInput.piecesBank X T start) ix.val) + · change IndexedStarts.Space _ _ oldRow.length newRow.length + rw [olen,nlen] + exact ShrinkABSliceTable.space layout ix + · intro x hbase hx + change x < (ShrinkABSliceTable.bank first ns nt ix.val : Word w).val+IndexedStarts.capacity oldRow.length newRow.length at hx + have baseEq := ShrinkABSliceTable.bank_val layout ix + change (ShrinkABSliceTable.bank first ns nt ix.val : Word w).val ≤ x at hbase + rw [baseEq] at hbase + rw [olen,nlen,baseEq] at hx + have hi := Nat.mul_le_mul_right (IndexedStarts.capacity ns nt) ix.isLt + rw [Nat.succ_mul] at hi + change ix.val*IndexedStarts.capacity ns nt+IndexedStarts.capacity ns nt ≤ + (ShrinkInput.plan X start).B*IndexedStarts.capacity ns nt at hi + exact frame x (by omega) (by omega) + +/-- The prefix-frame form used immediately after the slot construction. -/ +theorem abFields_transfer {T : IncidenceDirectory w} {start first limit : ℕ} {before post : Memory w} + (h : ABFields i X first before) {termStride : ℕ} (termRoom : ShrinkInput.termEnd X start termStride < 2^w) + (fresh : ShrinkInput.stop X start ≤ first) + (endBefore : first+(ShrinkInput.plan X start).B*IndexedStarts.capacity ns nt ≤ limit) + (fitsLimit : limit < 2^w) (frame : ∀ x < limit, post x = before x) : ABFields i X first post := + abFields_transfer_interval (T := T) h termRoom fresh endBefore fitsLimit (fun x _ hx => frame x hx) + +set_option maxHeartbeats 900000 in +/-- Transfer both kinds of interval tables and the sparse widths from an actual +three-table run through a later copy preserving the addresses before the +ordered-slot workspace. -/ +theorem CompleteTables.slice_transfer {δ : ℝ} {ready : Ready (2^(a i)) (Shrink.colors (a i)) (2^(b i)) δ} + {abs : Word w} {T : IncidenceDirectory w} {start : ℕ} {I : ShrinkABSliceRecipe.Inputs} + {pub : Fin 5 → Word w} {state : Word w} {ref mem post : Memory w} {first width slotStart cap : ℕ} {r : TablesRun w} + (h : CompleteTables B i X ready sel term stride abs start I pub state ref first width slotStart cap mem r) + (termRoom : ShrinkInput.termEnd X start stride.val < 2^w) (fresh : ShrinkInput.stop X start ≤ first) + (widthAfter : first+(ShrinkInput.plan X start).B*IndexedStarts.capacity ns nt ≤ width) + (slotAfter : (bankAt width).last ≤ slotStart) (slotRoom : slotStart < 2^w) (wide : 10 ≤ stride.val) + (packedRoom : stop (b := b i) X term.val stride.val role width < 2^w) + (frame : ∀ x < slotStart, post x = r.final x) : SliceReadbacks B i X sel term stride first width post := by + have fit := fits X B.shrink sel term stride.val role width ready wide packedRoom + have widthRoom := (width_le_slots (b := b i) X term stride.val role width).trans slotAfter + have abEnd := widthAfter.trans ((retained_room X term stride.val role width).trans widthRoom) + have sparse := SlotWidthScan.SplitRows.congr_below _ _ _ _ _ h.remainder.construction.widths + ((Nat.le_add_right _ _).trans slotAfter) frame + refine ⟨abFields_transfer (T := T) h.abFields termRoom fresh abEnd slotRoom frame,?_,sparse⟩ + intro j + apply (h.remainder.construction.intervals j).keep + intro x hx + exact frame x (lt_of_not_ge fun beyond => hx ((bankAt width).rowOutside fit j x (.inr (slotAfter.trans beyond)))) + +end CompressorRecords.ShrinkOutput + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentCosts.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentCosts.lean new file mode 100644 index 0000000000..8c2012b9f2 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentCosts.lean @@ -0,0 +1,69 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentLayout + +/-! # Linear cost of the shrinking resident-directory phases -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkResidentLayout + +open Compression Compression.PackingData PairSimulation.LocalHistory + +namespace Layout + +/-- All native source calls, including the six published head words. -/ +def calls (L : Layout) := 20*L.motifs+2*L.sites+6 + +/-- Calls plus probes: four units per owner, five per append, two per +cleared counter and two per published head. -/ +def charge (L : Layout) := 90*L.motifs+4*L.sites+12 + +theorem end_eq (L : Layout) : L.endAddr = L.first+20*L.motifs+2*L.sites := by + dsimp [endAddr,rows,counts,owner,size,radix] + omega + +end Layout + +variable {a g : ℕ} (X : State a (packingLaneBits a g)) + +theorem motif_le_slots : + (shrinkMotifOrder X).length ≤ ShrinkPreimages.oldCount X * 2^a := by + let d := 2^a + let c := Shrink.colors a + have hQ : pieceCount d c ≤ ShrinkPreimages.capacity a := by + change 3*(2^c*d)/4 ≤ 2^c*d + omega + have count := Fintype.card_congr (ShrinkMotifOrder.stateNumber X) + rw [Fintype.card_fin] at count + change Fintype.card X.packingData.Motif ≤ _ + rw [count,ShrinkPreimages.oldCount_eq] + exact (Nat.mul_le_mul_left (ShrinkPreimages.newCount X*d) hQ).trans_eq (by dsimp only [d]; ac_rfl) + +/-- Source charge, total report count, arena size, and dispatcher surcharge +are bounded by the selected level's preexisting size unit. Every resident +worker has at most six public words, so eight extra probes per data report +cover the active dispatch-frame reads. -/ +theorem cost_units (first : ℕ) : + let L := layout X first + let units := ShrinkPreimages.oldCount X * (2^a+1) + L.charge ≤ 102*units ∧ L.calls ≤ 26*units ∧ + L.endAddr ≤ first + 20*units ∧ L.charge + 8*L.calls ≤ 310*units := by + intro L units + have oldPos : 0 < ShrinkPreimages.oldCount X := Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos _) + have newBound : L.sites ≤ ShrinkPreimages.oldCount X := by + rw [ShrinkPreimages.oldCount_eq X] + exact Nat.le_mul_of_pos_right _ (Nat.mul_pos (Nat.two_pow_pos _) (Nat.two_pow_pos _)) + have motif : L.motifs ≤ ShrinkPreimages.oldCount X*2^a := motif_le_slots X + have hunit : units = ShrinkPreimages.oldCount X*2^a + ShrinkPreimages.oldCount X := by + dsimp [units]; rw [Nat.mul_add,Nat.mul_one] + have hfirst : L.first = first := rfl + rw [L.end_eq,hfirst] + dsimp only [Layout.charge,Layout.calls] + omega + +end CompressorRecords.ShrinkResidentLayout + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentDirectory.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentDirectory.lean new file mode 100644 index 0000000000..48f233e0e6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentDirectory.lean @@ -0,0 +1,213 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentScan +import OAI.Computability.VPVNP.CompressorShrinkResidentFormula +import OAI.Computability.VPVNP.CompressorShrinkMotifAbsolute + +/-! +# Native owner columns for hidden and map residents of a shrinking node + +The dense CD array comes from the classified old-port scatter. The selected +layout supplies the absolute role rows. A scan over the motif-major order +uses exactly these two inputs to materialize each resident's packed owner. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +set_option maxHeartbeats 1500000 + +namespace CompressorRecords.ShrinkResidentDirectory + +open Compression Compression.SurvivingSlots BurstRAM BurstRAM.PrivateRAM +open PrimedStackRAM PairSimulation.LocalHistory ShrinkHistoryRows ResidentOwners +open scoped Fin.CommRing + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) + +/-- Motif-major scan order for resident occurrences, with four internal fields or six party +maps per motif according to `maps`. -/ +noncomputable abbrev oldOrder (maps : Bool) := (shrinkMotifOrder X).prod (Order.fin (arity maps)) + +/-- Select the packed role of an internal field or a party map from its local index and the +chosen shrink layout. -/ +def role : (maps : Bool) → Bool → Fin (arity maps) → PackedRole + | false => ShrinkMotif.internalRole + | true => ShrinkMotif.partyRole + +/-- Packed site owning a given motif's field or map occurrence, found from its surviving role +under the selected layout. -/ +noncomputable abbrev place (maps layout : Bool) (x : X.packingData.Motif × Fin (arity maps)) := + packedSiteEquiv (X.packingData.survivingRole layout (role maps layout x.2) x.1) + +/-- Encode the owner placement as RAM words using the motif-major occurrence order and the +numerical packed-site order. -/ +noncomputable abbrev physical (maps layout : Bool) := + encodedPlacement (w := w) (oldOrder X maps).entries.symm (packedOrder X).entries.symm (place X maps layout) + +/-- The dense CD directory in memory maps each motif index to its old arc's absolute role-table +index. -/ +abbrev Absolute (head : Word w) (mem : Memory w) := + MotifAbsolute.Directory X.slots X.baseIndex X.shrinkNumber head mem + +/-- The sorted scatter uses exactly the motif coordinate of the history cursor. -/ +theorem absolute_input {head : Word w} {mem : Memory w} (dir : Absolute X head mem) (m : X.packingData.Motif) : + (mem (head.val + (ShrinkMotifOrder.stateNumber X m).val)).val = (DemandRAM.absoluteIndex X m.val).val := by + let E := MotifAbsolute.denseIndex X.packingData (Shrink.packedIndex X.baseIndex) X.shrinkNumber + have read := dir (E m) + change (mem (head.val + (E m).val)).val = (DemandRAM.absoluteIndex X (E.symm (E m)).val).val at read + rw [E.symm_apply_apply] at read + exact read + +variable (maps : Bool) (p : Fin 4 → Word w) + +/-- The input rectangles may lie on either side of the fresh owner column. -/ +structure Areas : Prop where + absoluteRoom : (p 0).val + (shrinkMotifOrder X).length ≤ 2^w + roleRoom : (p 1).val + 4 * DemandRAM.absoluteCount X ≤ 2^w + ownerRoom : (p 3).val + (oldOrder X maps).length ≤ 2^w + absoluteApart : (p 0).val + (shrinkMotifOrder X).length ≤ (p 3).val ∨ + (p 3).val + (oldOrder X maps).length ≤ (p 0).val + roleApart : (p 1).val + 4 * DemandRAM.absoluteCount X ≤ (p 3).val ∨ + (p 3).val + (oldOrder X maps).length ≤ (p 1).val + radixFits : 6 < 2^w + +private theorem motif_lt (m : X.packingData.Motif) : (ShrinkMotifOrder.stateNumber X m).val < (shrinkMotifOrder X).length := + ((shrinkMotifOrder X).entries.symm m).isLt + +set_option maxHeartbeats 1300000 in +private theorem digits (j : Fin (oldOrder X maps).length) : + j.val / arity maps = (ShrinkMotifOrder.stateNumber X ((oldOrder X maps).entries j).1).val ∧ + j.val % arity maps = ((oldOrder X maps).entries j).2.val := by + cases maps with + | false => exact ShrinkResidentFormula.hiddenDigits X j + | true => exact ShrinkResidentFormula.mapDigits X j + +open private div_cast remainder_cast from OAI.Computability.VPVNP.CompressorShrinkResidentOwners + +private theorem cast_val (x : Word w) : (x.val : Word w) = x := Fin.ext (Nat.mod_eq_of_lt x.isLt) + +/-- The quotient in the running program reads the sorted absolute-ID cell. -/ +theorem absolute_address (areas : Areas X maps p) (j : Fin (oldOrder X maps).length) : + (absoluteAddr maps p (j.val : Word w)).val = + (p 0).val + (ShrinkMotifOrder.stateNumber X ((oldOrder X maps).entries j).1).val := by + let m := ((oldOrder X maps).entries j).1 + have hj : j.val < 2^w := j.isLt.trans_le ((Nat.le_add_left ..).trans areas.ownerRoom) + have hrad : arity maps < 2^w := (by cases maps <;> decide : arity maps ≤ 6).trans_lt areas.radixFits + let k := (ShrinkMotifOrder.stateNumber X m).val + have eqw : p 0+(k : Word w) = (((p 0).val+k : ℕ) : Word w) := by rw [Nat.cast_add,cast_val] + rw [absoluteAddr_eq,div_cast hj hrad,(digits X maps j).1,eqw] + exact Nat.mod_eq_of_lt ((Nat.add_lt_add_left (motif_lt X m) _).trans_le areas.absoluteRoom) + +private theorem tag_offset {layout : Bool} (side : p 2 = (layout.toNat : Word w)) + (areas : Areas X maps p) (j : Fin (oldOrder X maps).length) : + offset maps (p 2) (BinaryOp.mod.eval (j.val : Word w) (arity maps : Word w)) = + (SlotOwners.roleOffset (role maps layout ((oldOrder X maps).entries j).2) : Word w) := by + have hj : j.val < 2^w := j.isLt.trans_le ((Nat.le_add_left ..).trans areas.ownerRoom) + have hrad : arity maps < 2^w := (by cases maps <;> decide : arity maps ≤ 6).trans_lt areas.radixFits + rw [side,remainder_cast hj hrad,(digits X maps j).2] + cases maps with + | false => exact offset_hidden layout _ areas.radixFits + | true => exact offset_party layout _ areas.radixFits + +private theorem offset_lt (r : PackedRole) : SlotOwners.roleOffset r < 4 := by cases r <;> decide + +private theorem role_lt_end (m : X.packingData.Motif) (r : PackedRole) : + (p 1).val + 4*(DemandRAM.absoluteIndex X m.val).val + SlotOwners.roleOffset r < (p 1).val + 4 * DemandRAM.absoluteCount X := by + have bound {i n k : ℕ} (hi : i < n) (hk : k < 4) : 4*i+k < 4*n := by omega + rw [Nat.add_assoc] + exact Nat.add_lt_add_left (bound (DemandRAM.absoluteIndex X m.val).isLt (offset_lt r)) _ + +/-- Combining the scatter read and role digit identifies the actual role-word address. -/ +theorem role_address {layout : Bool} {mem : Memory w} (side : p 2 = (layout.toNat : Word w)) + (areas : Areas X maps p) (dir : Absolute X (p 0) mem) (j : Fin (oldOrder X maps).length) : + let x := (oldOrder X maps).entries j + (roleAddr maps p mem (j.val : Word w)).val = + (p 1).val + 4*(DemandRAM.absoluteIndex X x.1.val).val + SlotOwners.roleOffset (role maps layout x.2) := by + let x := (oldOrder X maps).entries j + let r := role maps layout x.2 + let abs := (DemandRAM.absoluteIndex X x.1.val).val + let addr := (absoluteAddr maps p (j.val : Word w)).val + have hv : (mem addr).val = abs := by + change (mem (absoluteAddr maps p (j.val : Word w)).val).val = _ + rw [absolute_address X maps p areas j] + exact absolute_input X dir x.1 + have value : mem addr = (abs : Word w) := by rw [← hv,cast_val] + rw [roleAddr_eq,tag_offset X maps p side areas j,show mem (absoluteAddr maps p (j.val : Word w)).val = (abs : Word w) from value] + have eqw : p 1 + 4*(abs : Word w) + (SlotOwners.roleOffset r : Word w) = + (((p 1).val + 4*abs + SlotOwners.roleOffset r : ℕ) : Word w) := by + rw [Nat.cast_add,Nat.cast_add,Nat.cast_mul,cast_val] + rfl + rw [eqw] + exact Nat.mod_eq_of_lt ((role_lt_end X p x.1 r).trans_le areas.roleRoom) + +private theorem role_read {layout : Bool} {mem : Memory w} (areas : Areas X maps p) + (newFit : (packedOrder X).length ≤ 2^w) (roles : DemandRAM.RoleColumns X layout (p 1).val mem) + (j : Fin (oldOrder X maps).length) : + let x := (oldOrder X maps).entries j + mem ((p 1).val + 4*(DemandRAM.absoluteIndex X x.1.val).val + SlotOwners.roleOffset (role maps layout x.2)) = + physical (w := w) X maps layout (j.val : Word w) := by + have oldFit : (oldOrder X maps).length ≤ 2^w := (Nat.le_add_left ..).trans areas.ownerRoom + cases maps with + | false => exact ShrinkResidentFormula.hidden_readback_at X roles oldFit newFit j + | true => exact ShrinkResidentFormula.map_readback_at X roles oldFit newFit j + +/-- Complete physical owner column and the native trace which generated it. -/ +structure Written (layout : Bool) (mem : Memory w) (rs : List (Report w)) : Prop where + native : runSegment ((worker maps).table.instantiate w p).program (1+(code maps).length) + (some 0) mem (List.replicate (oldOrder X maps).length []) = some rs + owner (j : Fin (oldOrder X maps).length) : + after mem (eventLog rs) ((p 3).val+j.val) = physical X maps layout (j.val : Word w) + frame (addr : ℕ) (outside : addr < (p 3).val ∨ (p 3).val+(oldOrder X maps).length ≤ addr) : + after mem (eventLog rs) addr = mem addr + cursor : endState (some 0) rs = some ((oldOrder X maps).length : Word w) + count : rs.length = (oldOrder X maps).length + work : ∀ r ∈ rs, r.events.length = (code maps).length ∧ countProbes r.events = 3 ∧ choiceBits r.events = [] + charge : RAMBuckets.cost Report.probes rs = 4*(oldOrder X maps).length + +/-- Each native owner word supplies the exact input read of the preimage collector. -/ +theorem Written.ownerAt {layout : Bool} {mem : Memory w} {rs : List (Report w)} + (written : Written X maps p layout mem rs) (areas : Areas X maps p) + (q : Fin 6 → Word w) (head : q 1 = p 3) (length : (q 0).val = (oldOrder X maps).length) + (i : Word w) (hi : i < q 0) : + CompressorRecords.ownerAt q (after mem (eventLog rs)) i = physical X maps layout i := by + let j : Fin (oldOrder X maps).length := ⟨i.val,(show i.val < (q 0).val from hi).trans_eq length⟩ + have fit : (p 3).val+i.val < 2^w := (Nat.add_lt_add_left j.isLt _).trans_le areas.ownerRoom + have word : (j.val : Word w) = i := cast_val i + change after mem (eventLog rs) (q 1+i).val = _ + rw [head,Fin.val_add,Nat.mod_eq_of_lt fit] + exact (written.owner j).trans (congrArg (physical X maps layout) word) + +/-- Scan the sorted absolute-CD input and selected role rows to form the +four-way hidden or six-way map owner column, preserving all other words. -/ +theorem run {layout : Bool} {mem : Memory w} (side : p 2 = (layout.toNat : Word w)) + (areas : Areas X maps p) (newFit : (packedOrder X).length ≤ 2^w) + (dir : Absolute X (p 0) mem) (roles : DemandRAM.RoleColumns X layout (p 1).val mem) : + ∃ rs, Written X maps p layout mem rs := by + let n := (oldOrder X maps).length + have input (i : Word w) (hi : i.val < n) : + ((absoluteAddr maps p i).val < (p 3).val ∨ (p 3).val+n ≤ (absoluteAddr maps p i).val) ∧ + ((roleAddr maps p mem i).val < (p 3).val ∨ (p 3).val+n ≤ (roleAddr maps p mem i).val) := by + let j : Fin n := ⟨i.val,hi⟩ + let x := (oldOrder X maps).entries j + have word : (j.val : Word w) = i := cast_val i + have absAddr := absolute_address X maps p areas j + have roleAddr := role_address X maps p side areas dir j + rw [word] at absAddr roleAddr + rw [absAddr,roleAddr] + constructor + · exact areas.absoluteApart.imp (fun h => (Nat.add_lt_add_left (motif_lt X x.1) _).trans_le h) + (fun h => h.trans (Nat.le_add_right ..)) + · exact areas.roleApart.imp (fun h => (role_lt_end X p x.1 (role maps layout x.2)).trans_le h) + (fun h => (h.trans (Nat.le_add_right ..)).trans (Nat.le_add_right ..)) + obtain ⟨rs,exec,read,frame,count,work,charge⟩ := + scan_separate maps p mem n areas.ownerRoom input + have cursor := endState_of_run maps p 0 mem n rs exec + refine ⟨rs,exec,fun j => ?_,frame,by simpa only [zero_add] using cursor,count,work,charge⟩ + rw [read j,role_address X maps p side areas dir j] + exact role_read X maps p areas newFit roles j + +end CompressorRecords.ShrinkResidentDirectory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentFinal.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentFinal.lean new file mode 100644 index 0000000000..a4cad54758 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentFinal.lean @@ -0,0 +1,113 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentRun +import OAI.Computability.VPVNP.CompressorShrinkResidentHeaders +import OAI.Computability.VPVNP.CompressorShrinkResidentCosts + +/-! # Resident directories in the memory after publication of all six heads -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkResidentRun + +open BurstRAM Compression ShrinkResidentLayout ShrinkHistoryRows ShrinkResidentsPlan +open scoped Fin.CommRing Classical + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) (first level : ℕ) (side : Bool) +local notation "L" => layout X first + +private theorem fiber_bound (maps : Bool) (v) : + (residents (ShrinkResidentDirectory.oldOrder X maps) (ShrinkResidentDirectory.place X maps side) v).length ≤ rowCapacity a maps := by + let f := ShrinkResidentDirectory.place X maps side + let e : {u // v=f u} ≃ {u // f u=v} := Equiv.subtypeEquivRight fun _ => eq_comm + apply (Fintype.card_congr e).le.trans + cases maps with + | false => exact (hidden_count X side v).le + | true => exact (map_count X side v).le + +/-- Every public count and ordered-ID read used by a local handler falls +inside the resident data allocation, including when several fields share one owner. -/ +theorem directory_addresses (maps : Bool) (fit : (L).endAddr < 2^w) : + let p := outputBank (w:=w) X first maps + (∀ v, let x := (p 3).val+((packedOrder X).entries.symm v).val + first≤x ∧ x<(L).endAddr) ∧ + (∀ v (j : Fin (residents (ShrinkResidentDirectory.oldOrder X maps) (ShrinkResidentDirectory.place X maps side) v).length), + let x := (p 5).val+((packedOrder X).entries.symm v).val*(p 4).val+j.val + first≤x ∧ x<(L).endAddr) := by + dsimp only + let p := outputBank (w:=w) X first maps + obtain ⟨_,_,_,hn,hc,hcap,hr⟩ := ShrinkResidentLayout.frame X first maps fit + change (p 2).val=(L).sites at hn + change (p 3).val=(L).counts maps at hc + change (p 4).val=rowCapacity a maps at hcap + change (p 5).val=(L).rows maps at hr + obtain ⟨lo,own,cnt,upper⟩ := (L).ranges maps + change first ≤ (L).owner maps at lo + have fits (v) : ((packedOrder X).entries.symm v).val < (L).sites := ((packedOrder X).entries.symm v).isLt + constructor + · intro v + let addr := (p 3).val + ((packedOrder X).entries.symm v).val + have range : first≤addr ∧ addr<(L).endAddr := by dsimp only [addr]; rw [hc]; have := fits v; omega + exact range + · intro v j + let row := ((packedOrder X).entries.symm v).val + let addr := (p 5).val+row*(p 4).val+j.val + have rowSize := Nat.mul_le_mul_right (rowCapacity a maps) (fits v) + change (row+1)*rowCapacity a maps ≤ (L).sites*rowCapacity a maps at rowSize + rw [Nat.succ_mul,← size_eq_rows X first maps] at rowSize + have col := j.isLt.trans_le (fiber_bound X side maps v) + have range : first≤addr ∧ addr<(L).endAddr := by dsimp only [addr]; rw [hr,hcap]; omega + exact range + +/-- Counts and ordered resident IDs depend only on the allocated data rectangle. -/ +theorem transfer (maps : Bool) {m m' : Memory w} + (dir : Directory (ShrinkResidentDirectory.oldOrder X maps) (packedOrder X) + (ShrinkResidentDirectory.place X maps side) (outputBank X first maps) m) + (fit : (L).endAddr < 2^w) (keep : ∀ x, first≤x → x<(L).endAddr → m' x=m x) : + Directory (ShrinkResidentDirectory.oldOrder X maps) (packedOrder X) + (ShrinkResidentDirectory.place X maps side) (outputBank X first maps) m' := by + obtain ⟨counts,ids⟩ := directory_addresses X first side maps fit + constructor + · intro v + rw [keep _ (counts v).1 (counts v).2]; exact dir.count v + · intro v j + rw [keep _ (ids v j).1 (ids v j).2]; exact dir.idAt v j + +/-- Memory after both the hidden-field and party-map scans and the six writes publishing their +directory heads in the old level header. -/ +def endMemory (m : Memory w) (h r : Passes w) := + after (r.final (h.final m)) (eventLog (List.ofFn (headerReport level L w))) + +/-- Executing both owner and row scans, followed by the six fixed publishers, +produces the typed resident directories and the public pointers to read them. -/ +theorem published_both (absolute roleHead : Word w) (m : Memory w) + (space : Areas X first absolute roleHead) (dir : ShrinkResidentDirectory.Absolute X absolute m) + (roles : DemandRAM.RoleColumns X side roleHead.val m) (headerRoom : level+36 ≤ 2^w) + (apart : level+36≤first ∨ (L).endAddr≤level+30) : + ∃ h r : Passes w, Built X first absolute roleHead side false m h ∧ + Built X first absolute roleHead side true (h.final m) r ∧ + (∀ i : Fin 6, endMemory X first level m h r (level+(30+i.val))=(headValues L i : Word w)) ∧ + (∀ maps : Bool, Directory (ShrinkResidentDirectory.oldOrder X maps) (packedOrder X) + (ShrinkResidentDirectory.place X maps side) (outputBank X first maps) (endMemory X first level m h r)) ∧ + RAMBuckets.cost Report.probes (h.all++r.all++List.ofFn (headerReport level L w))=(L).charge := by + obtain ⟨h,r,hb,rb,hidden,cost⟩ := both X first absolute roleHead side space m dir roles + obtain ⟨heads,frame⟩ := published level L headerRoom (r.final (h.final m)) + refine ⟨h,r,hb,rb,heads,fun maps => transfer X first side maps (m:=r.final (h.final m)) ?_ space.fit ?_,?_⟩ + · cases maps + · exact hidden + · exact rb.directory + · intro addr lo hi + exact frame addr (apart.elim (fun h => .inr (h.trans lo)) (fun h => .inl (hi.trans_le h))) + · rw [RAMBuckets.cost_append,cost] + have hh : RAMBuckets.cost Report.probes (List.ofFn (headerReport level L w)) = 12 := rfl + rw [hh]; rfl + +end CompressorRecords.ShrinkResidentRun + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentFootprint.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentFootprint.lean new file mode 100644 index 0000000000..a18cf07226 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentFootprint.lean @@ -0,0 +1,90 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentDirectory +import OAI.Computability.VPVNP.CompressorScanProgress + +/-! # Accesses and guard progress of the two native resident-owner scans -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkResidentDirectory + +open BurstRAM Compression SourceTransport ResidentOwners PairSimulation.LocalHistory +open scoped Fin.CommRing Classical + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) (maps : Bool) (p : Fin 4 → Word w) + +open private role_lt_end motif_lt from OAI.Computability.VPVNP.CompressorShrinkResidentDirectory + +/-- The two regions the owner scan may read, containing dense absolute CD identifiers and four +role words per absolute old arc. -/ +def readable (x : ℕ) := + ((p 0).val ≤ x ∧ x < (p 0).val + (shrinkMotifOrder X).length) ∨ + ((p 1).val ≤ x ∧ x < (p 1).val + 4*DemandRAM.absoluteCount X) + +/-- The owner column written by the scan, one word per motif occurrence in the chosen field or +map order. -/ +def writable (x : ℕ) := (p 3).val ≤ x ∧ x < (p 3).val+(oldOrder X maps).length + +set_option maxHeartbeats 1800000 in +/-- At each reset the absolute-CD word is still live, so the second +indirect read lies in the selected role rows. Each write advances through +the dense owner column. -/ +theorem Written.scanned {side : Bool} {m : Memory w} {rs : List (Report w)} + (written : Written X maps p side m rs) (hs : p 2 = (side.toNat : Word w)) + (areas : Areas X maps p) (dir : Absolute X (p 0) m) : + StageFrame.Scanned 0 (oldOrder X maps).length rs ∧ + Reads (readable X p) (eventLog rs) ∧ Writes (writable X maps p) (eventLog rs) := by + let n := (oldOrder X maps).length + let W := (worker maps).table.instantiate w p + let es := fun (mem : Memory w) (i : Word w) => (report maps p i mem).events + have step (j : ℕ) (_ : 0 ≤ j) (hj : j < n) (mem : Memory w) (hd : Absolute X (p 0) mem) : + Absolute X (p 0) (after mem (es mem (j : Word w))) ∧ + Reads (readable X p) (es mem (j : Word w)) ∧ Writes (writable X maps p) (es mem (j : Word w)) := by + let i : Fin n := ⟨j,hj⟩ + let u := (oldOrder X maps).entries i + let word := (j : Word w) + have room := areas.ownerRoom + change (p 3).val+n ≤ 2^w at room + have val : word.val=j := Nat.mod_eq_of_lt (by omega) + have ow : (p 3+word).val=(p 3).val+j := by rw [Fin.val_add,val,Nat.mod_eq_of_lt (by omega)] + have absRead : readable X p (absoluteAddr maps p word).val := by + change readable X p (absoluteAddr maps p (i.val : Word w)).val + rw [absolute_address X maps p areas i] + exact .inl ⟨Nat.le_add_right ..,Nat.add_lt_add_left (motif_lt X u.1) _⟩ + have roleRead : readable X p (roleAddr maps p mem word).val := by + change readable X p (roleAddr maps p mem (i.val : Word w)).val + rw [role_address X maps p hs areas hd i] + exact .inr ⟨(Nat.le_add_right ..).trans (Nat.le_add_right ..),role_lt_end X p u.1 _⟩ + have write : writable X maps p (p 3+word).val := by rw [ow]; exact ⟨Nat.le_add_right ..,Nat.add_lt_add_left hj _⟩ + refine ⟨?_,?_,?_⟩ + · intro b + have eqLen := Fintype.card_congr (ShrinkMotifOrder.stateNumber X) + rw [Fintype.card_fin] at eqLen + have hb : b.val < (shrinkMotifOrder X).length := b.isLt.trans_eq eqLen.symm + have neq : (p 0).val+b.val ≠ (p 3+word).val := by + rw [ow] + rcases areas.absoluteApart with h | h <;> dsimp only [n] at hj <;> omega + change (after mem (report maps p word mem).events ((p 0).val+b.val)).val = _ + rw [(ResidentOwners.native maps p word mem).2.1,writeMemory,ite_eq_right neq] + exact hd b + · intro a v hv + change Event.read a v ∈ (report maps p word mem).events at hv + simp [report] at hv + rcases hv with ⟨rfl,_⟩ | ⟨rfl,_⟩ + · exact absRead + · exact roleRead + · intro a v hv + change Event.write a v ∈ (report maps p word mem).events at hv + simp [report] at hv + exact hv.1 ▸ write + obtain ⟨shape,_,rd,wr⟩ := StageFrame.scan W.program (1+(code maps).length) 0 n + (fun _ mem => Absolute X (p 0) mem) es (readable X p) (writable X maps p) + (fun _ _ _ mem => (ResidentOwners.native maps p _ mem).1) step (Nat.zero_le _) m rs dir (by simpa only [Nat.sub_zero,Nat.cast_zero] using written.native) + exact ⟨shape,rd,wr⟩ + +end CompressorRecords.ShrinkResidentDirectory + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentFormula.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentFormula.lean new file mode 100644 index 0000000000..f767bd8bd0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentFormula.lean @@ -0,0 +1,124 @@ +import OAI.Computability.VPVNP.CompressorRecordsDemandOutput +import OAI.Computability.VPVNP.CompressorRecordsShrinkHistory + +/-! +# Reading resident owners in the selected shrinking layout + +A dense resident ordinal consists of a motif number followed by a four-way +absorbed-edge digit or a six-way map-party digit. Its owner word is the +corresponding role in the four-word row of the absolute CD arc. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkResidentFormula + +open Compression Compression.SurvivingSlots BurstRAM PairSimulation.LocalHistory ShrinkHistoryRows + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) + +private theorem productOrdinal {n : ℕ} (m : X.packingData.Motif) (t : Fin n) : + (((shrinkMotifOrder X).prod (Order.fin n)).entries.symm (m,t)).val = + (ShrinkMotifOrder.stateNumber X m).val * n + t.val := by + change t.val + n * (ShrinkMotifOrder.stateNumber X m).val = _ + ac_rfl + +theorem hiddenOrdinal (m : X.packingData.Motif) (t : Fin 4) : + ((hiddenOrder X).entries.symm (m,t)).val = (ShrinkMotifOrder.stateNumber X m).val * 4 + t.val := + productOrdinal X m t + +theorem mapOrdinal (m : X.packingData.Motif) (t : Fin 6) : + ((mapOrder X).entries.symm (m,t)).val = (ShrinkMotifOrder.stateNumber X m).val * 6 + t.val := + productOrdinal X m t + +private theorem digits_of_eq {j m n t : ℕ} (ht : t < n) (eq : j = m*n + t) : + j/n = m ∧ j%n = t := by + subst j + constructor + · rw [Nat.mul_comm, Nat.mul_add_div (Nat.zero_le t |>.trans_lt ht), Nat.div_eq_of_lt ht, Nat.add_zero] + · exact Nat.mul_add_mod_of_lt ht + +private theorem digits_at {M : Type*} {size n : ℕ} (order : Fin size ≃ M × Fin n) (number : M → ℕ) + (ordinal : ∀ (m : M) (t : Fin n), (order.symm (m,t)).val = number m*n + t.val) (j : Fin size) : + j.val/n = number (order j).1 ∧ j.val%n = (order j).2.val := + digits_of_eq (order j).2.isLt ((congrArg Fin.val (order.symm_apply_apply j)).symm.trans + (ordinal (order j).1 (order j).2)) + +set_option maxHeartbeats 1500000 in +theorem hiddenDigits (j : Fin (hiddenOrder X).length) : + j.val / 4 = (ShrinkMotifOrder.stateNumber X ((hiddenOrder X).entries j).1).val ∧ + j.val % 4 = ((hiddenOrder X).entries j).2.val := + digits_at (hiddenOrder X).entries (fun m => (ShrinkMotifOrder.stateNumber X m).val) (hiddenOrdinal X) j + +set_option maxHeartbeats 1500000 in +theorem mapDigits (j : Fin (mapOrder X).length) : + j.val / 6 = (ShrinkMotifOrder.stateNumber X ((mapOrder X).entries j).1).val ∧ + j.val % 6 = ((mapOrder X).entries j).2.val := + digits_at (mapOrder X).entries (fun m => (ShrinkMotifOrder.stateNumber X m).val) (mapOrdinal X) j + +variable {layout : Bool} {base : ℕ} {mem : Memory w} + +private theorem readback_at {n : ℕ} (role : Fin n → PackedRole) + (roles : DemandRAM.RoleColumns X layout base mem) + (oldFit : ((shrinkMotifOrder X).prod (Order.fin n)).length ≤ 2^w) + (newFit : (packedOrder X).length ≤ 2^w) + (j : Fin ((shrinkMotifOrder X).prod (Order.fin n)).length) : + let old := (shrinkMotifOrder X).prod (Order.fin n) + let p := old.entries j + mem (base + 4 * (DemandRAM.absoluteIndex X p.1.val).val + SlotOwners.roleOffset (role p.2)) = + encodedPlacement old.entries.symm (packedOrder X).entries.symm + (fun x => packedSiteEquiv (X.packingData.survivingRole layout (role x.2) x.1)) (Fin.ofNat _ j.val) := by + let old := (shrinkMotifOrder X).prod (Order.fin n) + apply Fin.ext + rw [encodedPlacement_eq _ _ _ oldFit newFit j] + exact roles.packed (old.entries j).1 (role (old.entries j).2) + +theorem hidden_readback_at (roles : DemandRAM.RoleColumns X layout base mem) + (oldFit : (hiddenOrder X).length ≤ 2^w) (newFit : (packedOrder X).length ≤ 2^w) + (j : Fin (hiddenOrder X).length) : + let p := (hiddenOrder X).entries j + mem (base + 4 * (DemandRAM.absoluteIndex X p.1.val).val + + SlotOwners.roleOffset (ShrinkMotif.internalRole layout p.2)) = + encodedPlacement (hiddenOrder X).entries.symm (packedOrder X).entries.symm + (X.packingData.shrinkInternalOwner layout) (Fin.ofNat _ j.val) := + readback_at X (ShrinkMotif.internalRole layout) roles oldFit newFit j + +theorem map_readback_at (roles : DemandRAM.RoleColumns X layout base mem) + (oldFit : (mapOrder X).length ≤ 2^w) (newFit : (packedOrder X).length ≤ 2^w) + (j : Fin (mapOrder X).length) : + let p := (mapOrder X).entries j + mem (base + 4 * (DemandRAM.absoluteIndex X p.1.val).val + + SlotOwners.roleOffset (ShrinkMotif.partyRole layout p.2)) = + encodedPlacement (mapOrder X).entries.symm (packedOrder X).entries.symm + (fun x => X.packingData.shrinkPartySite layout x.1 x.2) (Fin.ofNat _ j.val) := + readback_at X (ShrinkMotif.partyRole layout) roles oldFit newFit j + +theorem hidden_readback (roles : DemandRAM.RoleColumns X layout base mem) + (oldFit : (hiddenOrder X).length ≤ 2^w) (newFit : (packedOrder X).length ≤ 2^w) + (m : X.packingData.Motif) (t : Fin 4) : + (mem (base + 4 * (DemandRAM.absoluteIndex X m.val).val + + SlotOwners.roleOffset (ShrinkMotif.internalRole layout t))).val = + (encodedPlacement (w := w) (hiddenOrder X).entries.symm (packedOrder X).entries.symm + (X.packingData.shrinkInternalOwner layout) + (Fin.ofNat _ ((ShrinkMotifOrder.stateNumber X m).val * 4 + t.val))).val := by + have h := hidden_readback_at X roles oldFit newFit ((hiddenOrder X).entries.symm (m,t)) + simpa only [Equiv.apply_symm_apply,hiddenOrdinal] using congrArg Fin.val h + +theorem map_readback (roles : DemandRAM.RoleColumns X layout base mem) + (oldFit : (mapOrder X).length ≤ 2^w) (newFit : (packedOrder X).length ≤ 2^w) + (m : X.packingData.Motif) (t : Fin 6) : + (mem (base + 4 * (DemandRAM.absoluteIndex X m.val).val + + SlotOwners.roleOffset (ShrinkMotif.partyRole layout t))).val = + (encodedPlacement (w := w) (mapOrder X).entries.symm (packedOrder X).entries.symm + (fun x => X.packingData.shrinkPartySite layout x.1 x.2) + (Fin.ofNat _ ((ShrinkMotifOrder.stateNumber X m).val * 6 + t.val))).val := by + have h := map_readback_at X roles oldFit newFit ((mapOrder X).entries.symm (m,t)) + simpa only [Equiv.apply_symm_apply,mapOrdinal] using congrArg Fin.val h + +end CompressorRecords.ShrinkResidentFormula + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentHeaders.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentHeaders.lean new file mode 100644 index 0000000000..c82e4cfcb0 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentHeaders.lean @@ -0,0 +1,131 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentsPlan +import OAI.Computability.VPVNP.CompressorSourceWalk + +/-! # Publishing the six resident-directory heads of a shrinking level -/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkResidentsPlan + +open BurstRAM BlockPlanner PhaseRecipe ShrinkResidentLayout +open scoped Fin.CommRing + +variable {w : ℕ} + +/-- The six directory pointers in header order, owner, count and row bases for hidden fields +followed by the corresponding bases for party maps. -/ +def headValues (L : Layout) : Fin 6 → ℕ := + ![L.owner false,L.counts false,L.rows false,L.owner true,L.counts true,L.rows true] + +/-- The two publisher operands for head `i`, its destination at old-level offset `30 + i` and +the corresponding directory pointer. -/ +def headerBank (level : ℕ) (L : Layout) (w : ℕ) (i : Fin 6) : Fin 2 → Word w := + ![((level+(30+i.val) : ℕ) : Word w),(headValues L i : Word w)] + +/-- The single-head publication trace, including the pointer write at the designated header +offset and the return of cursor one. -/ +def headerReport (level : ℕ) (L : Layout) (w : ℕ) (i : Fin 6) : Report w := + ⟨[.tick,.tick,.tick,.write (headerBank level L w i 0) (headerBank level L w i 1),.tick,.tick],some 1⟩ + +/-- Plan the one-word publication of the chosen resident directory pointer at offset `30 + i` +of the old level. -/ +def headerVisit (I : SelectedPlan.Inputs) (first oldLevel : Expr) (i : Fin 6) := + publish (oldLevel.add (.lit (30+i.val))) (heads I first i) + +theorem header_bank_eq (I : SelectedPlan.Inputs) (first oldLevel : Expr) (pub : Fin 5 → Word w) + (st : Word w) (m : Memory w) (level : ℕ) (L : Layout) (h : Ready I first pub st m L) + (levelWord : Expr.eval pub st m oldLevel = (level : Word w)) (i : Fin 6) : + (fun j => Expr.eval pub st m ((headerVisit I first oldLevel i).params j)) = headerBank level L w i := by + funext j + fin_cases j + · change Expr.eval pub st m oldLevel + ((30+i.val : ℕ) : Word w) = ((level+(30+i.val) : ℕ) : Word w) + simp only [levelWord,Nat.cast_add] + · change Expr.eval pub st m (heads I first i) = (headValues L i : Word w) + fin_cases i + · exact owner_val I first pub st m L h false + · exact counts_val I first pub st m L h false + · exact rows_val I first pub st m L h false + · exact owner_val I first pub st m L h true + · exact counts_val I first pub st m L h true + · exact rows_val I first pub st m L h true + +/-- A successful single publication call from cursor zero with the concrete head operands, +seven units of fuel and an empty branch stream. -/ +def headerSource (I : SelectedPlan.Inputs) (first oldLevel : Expr) (level : ℕ) (L : Layout) + (i : Fin 6) (m : Memory w) (rs : List (Report w)) := + let M := ((headerVisit I first oldLevel i).worker.table.instantiate w (headerBank level L w i)).program + runSegment M 7 (some 0) m [[]] = some rs + +theorem header_source (I : SelectedPlan.Inputs) (first oldLevel : Expr) (level : ℕ) (L : Layout) + (i : Fin 6) (m : Memory w) : + headerSource I first oldLevel level L i m [headerReport level L w i] := by + have run := (publish_native (oldLevel.add (.lit (30+i.val))) (heads I first i) (headerBank level L w i) 0 m).1 + dsimp only [headerSource,runSegment,headerVisit] + rw [run,zero_add] + rfl + +theorem header_walk (I : SelectedPlan.Inputs) (first oldLevel : Expr) (level : ℕ) (L : Layout) + (m : Memory w) : + SourceWalk (headerSource I first oldLevel level L) (List.finRange 6) m (List.ofFn (headerReport level L w)) := by + have go (is : List (Fin 6)) (mem : Memory w) : + SourceWalk (headerSource I first oldLevel level L) is mem (is.map (headerReport level L w)) := by + induction is generalizing mem with + | nil => exact .done _ + | cons i is ih => exact SourceWalk.next (header_source I first oldLevel level L i mem) (ih _) + simpa only [List.ofFn_eq_map] using go (List.finRange 6) m + +private theorem addr_word (level : ℕ) (L : Layout) (fit : level+36 ≤ 2^w) (i : Fin 6) : + (headerBank level L w i 0).val = level+(30+i.val) := Nat.mod_eq_of_lt (by have := i.isLt; omega) + +/-- A list of successful publishers sets exactly its addressed head cells. -/ +private theorem publish_effect (level : ℕ) (L : Layout) (fit : level+36 ≤ 2^w) + (is : List (Fin 6)) (m : Memory w) : + let out := after m (eventLog (is.map (headerReport level L w))) + (∀ i ∈ is, out (level+(30+i.val)) = (headValues L i : Word w)) ∧ + (∀ x, (∀ i ∈ is, x ≠ level+(30+i.val)) → out x = m x) := by + induction is generalizing m with + | nil => exact ⟨fun _ hi => False.elim (List.not_mem_nil hi),fun _ _ => rfl⟩ + | cons i is ih => + let one := writeMemory m (headerBank level L w i 0) (headerBank level L w i 1) + have frame : after m (eventLog ((i::is).map (headerReport level L w))) = + after one (eventLog (is.map (headerReport level L w))) := by + change after m ((headerReport level L w i).events ++ eventLog _) = _ + rw [after,List.foldl_append]; rfl + obtain ⟨written,kept⟩ := ih one + dsimp only + rw [frame] + constructor + · intro j hj + by_cases found : j ∈ is + · exact written j found + · have same : j=i := (List.mem_cons.mp hj).resolve_right found + subst j + have unique (k : Fin 6) (hk : k ∈ is) : level+(30+i.val) ≠ level+(30+k.val) := by + intro eq + have same : i=k := Fin.ext (by omega) + exact found (same.symm ▸ hk) + rw [kept _ unique] + change (if _ then _ else _) = _ + rw [addr_word level L fit,ite_eq_left rfl]; rfl + · intro x hx + rw [kept x (fun j hj => hx j (List.mem_cons_of_mem _ hj))] + change (if _ then _ else _) = _ + rw [addr_word level L fit,ite_eq_right (hx i (List.mem_cons_self ..))] + +/-- The six heads are available at fixed offsets 30 through 35, and +other addresses retain their contents after these one-write calls. -/ +theorem published (level : ℕ) (L : Layout) (fit : level+36 ≤ 2^w) (m : Memory w) : + let out := after m (eventLog (List.ofFn (headerReport level L w))) + (∀ i : Fin 6, out (level+(30+i.val)) = (headValues L i : Word w)) ∧ + (∀ x, x stored i (List.mem_finRange i),fun x hx => frame x (fun i _ => by have := i.isLt; omega)⟩ + +end CompressorRecords.ShrinkResidentsPlan + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentInterval.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentInterval.lean new file mode 100644 index 0000000000..c136272df5 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentInterval.lean @@ -0,0 +1,122 @@ +import OAI.Computability.VPVNP.CompressorShrinkBranchResident +import OAI.Computability.VPVNP.CompressorShrinkScoreOperands +import OAI.Computability.VPVNP.CompressorBlockABSliceFootprint + +/-! # Inputs retained in table zero across the hidden and map publications + +Publishing six resident-directory heads changes cells in the old level header. +Every input of the two interval calendars is nevertheless in table zero, +from the sorted demand columns through the selected child-directory rows. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkOutput + +open Compression BurstRAM ShrinkBlockInputs ShrinkSliceSweep TermScores SlotLevel ShrinkSlots +open scoped Classical Fin.CommRing +open private columns_after before_width from OAI.Computability.VPVNP.CompressorBlockABSliceFootprint + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X) +variable (T : IncidenceDirectory w) (start : ℕ) +local notation "term" => ShrinkInput.termHead (w := w) X start +local notation "ids" => ShrinkBundlePlan.absoluteHead (ShrinkInput.plan X start) w +local notation "keepEnd" => SelectedFinish.stop X term (10 : Word w) +local notation "role" => SelectedArena.roleBase X term (10 : Word w) +local notation "wb" => ShrinkInput.widthBase X start +local notation "z" => ShrinkInput.plan X start +local notation "t" => ShrinkInput.thickBank X T start +local notation "cd" => ShrinkInput.cdBank X T start +local notation "ab" => ShrinkInput.piecesBank X T start + +set_option maxHeartbeats 1400000 in +theorem Resident.above {width : ℕ} {mem out : Memory w} + (h : Resident B i X sel term 10 ids T start width mem) + (room : ShrinkInput.termEnd X start 10 < 2^w) (selected : keepEnd ≤ 2^w) + (same : ∀ x, start ≤ x → out x = mem x) : + Resident B i X sel term 10 ids T start width out := by + have termLow := ScorePackets.start_le_term i X start room + have hwidth := before_width i X start + have col := columns_after i X T start room + have q := (z).values T (ShrinkInput.placementBank X T start) Fintype.card_pos + (show (z).stop < 2^w by change wb < 2^w; change wb+_+_+_+_ < 2^w at room; omega) + let block := (z).B*(ShrinkRankSpace.Shape.collectBank z w 4).val + have blockEq : block = (z).B*(z).Q := by dsimp [block]; rw [q.stride] + have inputFit : wb+6*((z).B*(z).Q)+2*(z).B < 2^w := by + change wb+6*((z).B*(z).Q)+2*(z).B+_+_ < 2^w at room; omega + have cd₂ : (cd 2).val = wb+block := by + change (wb%(2^w)+block)%(2^w) = _ + rw [Nat.mod_eq_of_lt (show wb<2^w by omega),Nat.mod_eq_of_lt (by omega)] + have cd₃ : (cd 3).val = wb+2*block+block := by + change (wb+2*block+block)%(2^w) = _ + exact Nat.mod_eq_of_lt (by omega) + have keep (p i j : ℕ) (hp : start ≤ p) : (out (p+i+j)).val = (mem (p+i+j)).val := + congrArg Fin.val (same _ (by omega)) + have rb := ShrinkInput.range_bounds X start + have gathered : ShrinkInput.rankBase X start ≤ (z).gathered := by + change ShrinkInput.rankBase X start ≤ ShrinkInput.rankBase X start+_+_+_; omega + have aEnd : (z).gathered+(z).B*(z).Q ≤ wb := by + change (z).gathered+(z).B*(z).Q ≤ (z).gathered+((2*(z).B)*(z).Q)+(z).A + rw [Nat.mul_assoc,two_mul]; omega + have absRoom : (z).gathered+(z).B*(z).Q < 2^w := by omega + have absLow : start ≤ (ids).val := by change start ≤ (_:ℕ)%(2^w); rw [Nat.mod_eq_of_lt absRoom]; omega + have hrole : start ≤ role := by unfold SelectedArena.roleBase SelectedArena.placementBase SelectedArena.origin; omega + have hcell : start ≤ SelectedArena.origin X term (10 : Word w)+2 := by unfold SelectedArena.origin; omega + refine ⟨⟨fun b j => (keep _ _ _ col.1).trans (h.demand.thickWidths b j), + fun b j => (keep _ _ _ (by omega : start ≤ (cd 2).val)).trans (h.demand.cdWidths b j), + fun b j => (keep _ _ _ col.2.1).trans (h.demand.thickStarts b j), + fun b j => (keep _ _ _ (by omega : start ≤ (cd 3).val)).trans (h.demand.cdStarts b j), + ⟨fun b j => (keep _ _ _ col.2.2.1).trans (h.demand.ab.widths b j), + fun b j => (keep _ _ _ col.2.2.2).trans (h.demand.ab.starts b j)⟩⟩, + fun j => (congrArg Fin.val (same _ (by omega))).trans (h.directory j),?_, + ⟨fun arc => (congrArg Fin.val (same _ (by omega))).trans (h.roles.cd arc), + fun arc r => (congrArg Fin.val (same _ (by omega))).trans (h.roles.packed arc r)⟩, + (same _ hcell).trans h.chosen,?_⟩ + · apply terms_after B.shrink X term (10 : Word w).val _ (levelShape (b := b i) X).subdivisions sel mem out h.terms + intro j k _ head + have rowFit := (ShrinkInput.termLayout X T start 10 room).2.2.2 + have hj : j.val ≤ ShrinkTermInputs.motifCount X := by + rw [← ShrinkTermRecipe.count_card X]; exact j.isLt.le + have le : j.val*(10 : Word w).val ≤ ShrinkTermInputs.motifCount X*10 := + Nat.mul_le_mul hj (Nat.mod_le 10 (2^w)) + have exactHead : head.val = (term).val+j.val*(10 : Word w).val := Nat.mod_eq_of_lt (by omega) + exact same _ (by omega) + · have hl : start ≤ SelectedFinish.countStart X term 10 := by + unfold SelectedFinish.countStart SelectedArena.endAddr; omega + have hc : (SelectedFinish.counts X term 10).val = SelectedFinish.countStart X term 10 := by + apply Nat.mod_eq_of_lt + have positive : 0 < ShrinkPreimages.newCount X := Nat.mul_pos Fintype.card_pos (Nat.mul_pos (Nat.two_pow_pos _) (Nat.two_pow_pos _)) + unfold SelectedFinish.stop SelectedFinish.rowStart at selected; omega + have hr : (SelectedFinish.rows X term 10).val = SelectedFinish.rowStart X term 10 := by + apply Nat.mod_eq_of_lt + have positive : 0 < ShrinkPreimages.oldCount X := Nat.mul_pos Fintype.card_pos (Nat.two_pow_pos _) + unfold SelectedFinish.stop at selected; omega + have rowLow : start ≤ (SelectedFinish.rows X term 10).val := by rw [hr]; unfold SelectedFinish.rowStart; omega + exact ⟨fun v => (congrArg Fin.val (same _ (by omega))).trans (h.preimages.count v), + fun v j => (congrArg Fin.val (same _ (by omega))).trans (h.preimages.child v j)⟩ + +/-- Intervening publications may update the header while preserving every +earlier field within the physical scratch table. -/ +theorem resident_of_branch_interval (selectors : Word w) (cap : ℕ) {m : Memory w} + (p : ShrinkBranch.Prefix X T start cap m) + (v : ShrinkBranch.Selected B X T start 10 selectors cap m p sel) + (fit : ShrinkBranch.PrefixFits B X T start 10 cap) (room : ShrinkInput.termEnd X start 10 < 2^w) + (selected : keepEnd ≤ 2^w) (width : ℕ) (input : Memory w) + (frame : ∀ x, start ≤ x → x < keepEnd → input x = v.beforeOutput x) : + Resident B i X sel term 10 ids T start width input := by + let staged : Memory w := fun x => if x < start then v.beforeOutput x else input x + have keep (x : ℕ) (hx : x < keepEnd) : staged x = v.beforeOutput x := by + by_cases early : x < start + · exact ite_eq_left early + · exact (ite_eq_right early).trans (frame x (Nat.le_of_not_gt early) hx) + have initial := resident_of_branch B i X sel T start 10 selectors cap p v fit width staged keep + exact initial.above B i X sel T start room selected (fun x hx => (ite_eq_right (Nat.not_lt.mpr hx)).symm) + +end CompressorRecords.ShrinkOutput + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentLayout.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentLayout.lean new file mode 100644 index 0000000000..ddffcc219f --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentLayout.lean @@ -0,0 +1,174 @@ +import OAI.Computability.VPVNP.CompressorRecordsShrinkHistory +import OAI.Computability.VPVNP.CompressorShrinkSelectedPlan + +/-! +# Workspace for the shrinking history's two resident directories + +The absorbed-field records start after the chosen placement's child rows. +The map records follow them. Each stores one owner word and one ordered +row word per occurrence, and one counter per packed site. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkResidentLayout + +open BurstRAM Compression Compression.PackingData PrimedStackRAM +open PairSimulation.LocalHistory ShrinkHistoryRows +open scoped Fin.CommRing Classical + +/-- Occurrences per motif in a resident scan, four for absorbed fields and six for party maps. -/ +def radix (maps : Bool) := if maps then 6 else 4 + +/-- Number of occurrence slots reserved per packed site in the selected field or map directory, +accounting for degree, pieces and occurrences per motif. -/ +def rowCapacity (a : ℕ) (maps : Bool) := radix maps*(2^a*pieceCount (2^a) (Shrink.colors a)) + +/-- Dimensions and starting address for two consecutive resident directories, each with an +owner column, per-site counts and ordered preimage rows. -/ +structure Layout where + /-- Number of packed output sites, each with its own count and preimage row in both + directories. -/ + sites : ℕ + /-- Number of shrinking motifs whose field and party-map occurrences must be assigned to + owners. -/ + motifs : ℕ + /-- Base of the hidden-field owner column, the first address of the combined resident + workspace. -/ + first : ℕ + +namespace Layout + +/-- Number of occurrences in the selected directory, the motif count times four hidden fields +or six party maps. -/ +def size (L : Layout) (maps : Bool) := L.motifs*radix maps + +/-- Start of the selected owner column. The hidden-field column comes first and the map column +follows the complete hidden-field directory. -/ +def owner (L : Layout) (maps : Bool) := + if maps then L.first + L.size false + L.sites + L.size false else L.first + +/-- Start of the per-site counts immediately following the selected occurrence-owner column. -/ +def counts (L : Layout) (maps : Bool) := L.owner maps + L.size maps + +/-- Start of the selected preimage rows, following one count word per packed site. -/ +def rows (L : Layout) (maps : Bool) := L.counts maps + L.sites + +/-- First free address following the party-map preimage rows and hence both resident +directories. -/ +def endAddr (L : Layout) := L.rows true + L.size true + +/-- Six public collector operands in order, occurrence count, owner base, site count, count +base, row capacity and row base. -/ +def params (L : Layout) (a : ℕ) (maps : Bool) (w : ℕ) : Fin 6 → Word w := + ![(L.size maps : Word w),(L.owner maps : Word w),(L.sites : Word w), + (L.counts maps : Word w),(rowCapacity a maps : Word w),(L.rows maps : Word w)] + +theorem ranges (L : Layout) (maps : Bool) : L.first ≤ L.owner maps ∧ + L.owner maps + L.size maps = L.counts maps ∧ L.counts maps+L.sites = L.rows maps ∧ + L.rows maps+L.size maps ≤ L.endAddr := by + cases maps <;> dsimp [endAddr,rows,counts,owner] <;> omega + +end Layout + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) + +/-- Instantiate the resident workspace at `first` using the actual number of packed sites and +the motif order of the shrinking state. -/ +def layout (first : ℕ) : Layout := ⟨ShrinkPreimages.newCount X,(shrinkMotifOrder X).length,first⟩ + +theorem size_eq_rows (first : ℕ) (maps : Bool) : + (layout X first).size maps = (layout X first).sites * rowCapacity a maps := by + have h := Fintype.card_congr (ShrinkMotifOrder.stateNumber X) + rw [Fintype.card_fin] at h + change Fintype.card X.packingData.Motif * radix maps = ShrinkPreimages.newCount X * _ + rw [h] + unfold rowCapacity + ring + +/-- No index is truncated when the next free address fits the word. -/ +theorem frame (first : ℕ) (maps : Bool) (fit : (layout X first).endAddr < 2^w) : + let L := layout X first + let p := L.params a maps w + RowRegions p ∧ (p 0).val = L.size maps ∧ (p 1).val = L.owner maps ∧ + (p 2).val = L.sites ∧ (p 3).val = L.counts maps ∧ (p 4).val = rowCapacity a maps ∧ + (p 5).val = L.rows maps := by + intro L p + change L.endAddr < 2^w at fit + obtain ⟨_,hc,hr,hend⟩ := L.ranges maps + have dim := size_eq_rows X first maps + change L.size maps = L.sites*rowCapacity a maps at dim + have hpos : 0 < L.sites := Nat.mul_pos Fintype.card_pos (Nat.mul_pos (Nat.two_pow_pos _) (Nat.two_pow_pos _)) + have hcap := Nat.le_mul_of_pos_left (rowCapacity a maps) hpos + have ok0 : (p 0).val = L.size maps := Nat.mod_eq_of_lt (by omega) + have ok1 : (p 1).val = L.owner maps := Nat.mod_eq_of_lt (by omega) + have ok2 : (p 2).val = L.sites := Nat.mod_eq_of_lt (by omega) + have ok3 : (p 3).val = L.counts maps := Nat.mod_eq_of_lt (by omega) + have ok4 : (p 4).val = rowCapacity a maps := Nat.mod_eq_of_lt (by omega) + have ok5 : (p 5).val = L.rows maps := Nat.mod_eq_of_lt (by omega) + exact ⟨⟨by rw [ok1,ok0,ok3,hc],by rw [ok3,ok2,ok5,hr], + by rw [ok5,ok2,ok4,←dim]; exact hend.trans fit.le⟩,ok0,ok1,ok2,ok3,ok4,ok5⟩ + +theorem hidden_id (m : X.packingData.Motif) (t : Fin 4) : + ((hiddenOrder X).entries.symm (m,t)).val = (ShrinkMotifOrder.stateNumber X m).val * 4 + t.val := by + change t.val + 4*(ShrinkMotifOrder.stateNumber X m).val = _ + omega + +theorem map_id (m : X.packingData.Motif) (t : Fin 6) : + ((mapOrder X).entries.symm (m,t)).val = (ShrinkMotifOrder.stateNumber X m).val * 6 + t.val := by + change t.val + 6*(ShrinkMotifOrder.stateNumber X m).val = _ + omega + +theorem hidden_build (first : ℕ) (fit : (layout X first).endAddr < 2^w) (side : Bool) + (mem : Memory w) : + let L := layout X first + let p := L.params a false w + let old := hiddenOrder X + let next := packedOrder X + let place := X.packingData.shrinkInternalOwner side + (∀ i : Word w, i

p 3)).program 8 (some 0) mem + (List.replicate L.sites []) = some cs ∧ + runSegment ((template collectPreimage 3).instantiate w p).program 23 (some 0) mid + (List.replicate (L.size false) []) = some rs ∧ + Directory old next place p out ∧ cs.length=L.sites ∧ rs.length=L.size false ∧ + (∀ r ∈ cs, r.probes=1 ∧ r.events.length+1=8) ∧ (∀ r ∈ rs, r.probes=4 ∧ r.events.length+1=23) ∧ + (∀ j, OutsidePreimageWrites p j → out j = mem j) := by + intro L p old next place owners + obtain ⟨regions,ho,_,hn,_,hc,_⟩ := frame X first false fit + exact build old next place p regions ho hn (fun v => (hidden_count X side v).le.trans hc.symm.le) mem owners + +theorem map_build (first : ℕ) (fit : (layout X first).endAddr < 2^w) (side : Bool) + (mem : Memory w) : + let L := layout X first + let p := L.params a true w + let old := mapOrder X + let next := packedOrder X + let place := fun (e : X.packingData.Motif × Fin 6) => X.packingData.shrinkPartySite side e.1 e.2 + (∀ i : Word w, i

p 3)).program 8 (some 0) mem + (List.replicate L.sites []) = some cs ∧ + runSegment ((template collectPreimage 3).instantiate w p).program 23 (some 0) mid + (List.replicate (L.size true) []) = some rs ∧ + Directory old next place p out ∧ cs.length=L.sites ∧ rs.length=L.size true ∧ + (∀ r ∈ cs, r.probes=1 ∧ r.events.length+1=8) ∧ (∀ r ∈ rs, r.probes=4 ∧ r.events.length+1=23) ∧ + (∀ j, OutsidePreimageWrites p j → out j = mem j) := by + intro L p old next place owners + obtain ⟨regions,ho,_,hn,_,hc,_⟩ := frame X first true fit + exact build old next place p regions ho hn (fun v => (map_count X side v).le.trans hc.symm.le) mem owners + +end CompressorRecords.ShrinkResidentLayout + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentOwners.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentOwners.lean new file mode 100644 index 0000000000..762e15360d --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentOwners.lean @@ -0,0 +1,170 @@ +import OAI.Computability.VPVNP.CompressorRecordsBlockPlanner +import OAI.Computability.VPVNP.CompressorSlotOwnerAgreement +import OAI.Computability.VPVNP.ShrinkRoles + +/-! +# Native generation of the shrinking resident owner columns + +A history cursor combines its motif number with either a party ordinal or an +absorbed edge type. The worker uses the sorted absolute-CD column and the +selected layout's A/B/D role words to write the owner at that cursor. It needs +two memory reads and one write. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ResidentOwners + +open Compression Compression.ShrinkMotif BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open PhaseRecipe BlockPlanner +open scoped Fin.CommRing + +/-- The six map parties or four absorbed edge types stored per motif. -/ +def arity (maps : Bool) := if maps then 6 else 4 + +variable {w : ℕ} + +private def four : Word w := 2*2 +private def radix (maps : Bool) : Word w := (if maps then 3 else 2)*2 + +private theorem four_eq : (four : Word w) = 4 := by unfold four; norm_num +private theorem radix_eq (maps : Bool) : (radix maps : Word w) = (arity maps : Word w) := by + cases maps <;> norm_num [radix,arity] + +private def mux (flag lo hi : Word w) := lo + flag*(hi-lo) + +private def chooseReg (flag lo hi dst : Fin 20) : List (Op 20 4) := + [.binary .sub 15 hi lo,.binary .mul 15 flag 15,.binary .add dst lo 15] + +/-- Registers 11, 12 and 13 carry the three bits of the within-motif tag. +Register 8 carries the layout, register 9 is two, and register 14 is the +resulting role offset. -/ +private def roleOps (maps : Bool) : List (Op 20 4) := if maps then + chooseReg 11 8 9 16 ++ chooseReg 12 11 16 14 ++ + [.binary .mul 16 9 8,.binary .sub 17 9 8] ++ chooseReg 11 16 17 18 ++ chooseReg 13 14 18 14 + else [.binary .mul 16 11 12] ++ chooseReg 16 8 9 14 + +/-- Native owner-scan instructions for a hidden field or party map. Decode the occurrence, read +its absolute CD identifier and role word, and write the packed owner. -/ +def code (maps : Bool) : List (Op 20 4) := + [.stateWord 0,.constant 9 2,.binary .mul 10 9 9, + .constant 3 (if maps then 3 else 2),.binary .mul 3 3 9,.binary .div 1 0 3,.binary .mod 2 0 3, + .publicWord 8 2, + .binary .mod 11 2 9,.binary .div 12 2 9,.binary .mod 12 12 9,.binary .div 13 2 10] ++ + roleOps maps ++ + [.publicWord 4 0,.binary .add 4 4 1,.read 5 4,.binary .mul 6 10 5,.publicWord 17 1, + .binary .add 6 17 6,.binary .add 6 6 14,.read 7 6,.publicWord 18 3,.binary .add 18 18 0, + .write 18 7,.constant 19 1,.binary .add 0 0 19] + +/-- Register the resident owner scan as a scheduler pass that returns its advanced occurrence +cursor. -/ +def worker (maps : Bool) : Schedule.Pass := ⟨_,_,_,template (code maps) 0⟩ + +/-- Schedule the owner scan from zero to the occurrence count with pointers to absolute CD +identifiers, role records and the owner output, plus the selected layout. -/ +def visit (maps : Bool) (count absoluteCD roleBase layout ownerBase : Expr) : Visit := + ⟨worker maps,.lit 0,count,![absoluteCD,roleBase,layout,ownerBase]⟩ + +/-- Compute the role-word offset within a four-word old-arc record from the selected layout and +the local field or party-map tag. -/ +def offset (maps : Bool) (layout tag : Word w) : Word w := + let lo := BinaryOp.mod.eval tag 2 + let mid := BinaryOp.mod.eval (BinaryOp.div.eval tag 2) 2 + let hi := BinaryOp.div.eval tag four + if maps then mux hi (mux mid lo (mux lo layout 2)) (mux lo (2*layout) (2-layout)) + else mux (lo*mid) layout 2 + +private theorem div_cast {x y : ℕ} (hx : x < 2^w) (hy : y < 2^w) : + BinaryOp.div.eval (x : Word w) (y : Word w) = ((x/y : ℕ) : Word w) := by + change Fin.ofNat _ ((x % 2^w)/(y % 2^w)) = _ + rw [Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hy] + rfl + +private theorem remainder_cast {x y : ℕ} (hx : x < 2^w) (hy : y < 2^w) : + BinaryOp.mod.eval (x : Word w) (y : Word w) = ((x%y : ℕ) : Word w) := by + change Fin.ofNat _ ((x % 2^w)%(y % 2^w)) = _ + rw [Nat.mod_eq_of_lt hx, Nat.mod_eq_of_lt hy] + rfl + +private theorem offset_nat (maps : Bool) (layout : Word w) (t : ℕ) (hw : 6 < 2^w) (ht : t < 6) : + offset maps layout (t : Word w) = + if maps then mux ((t/4 : ℕ) : Word w) + (mux ((t/2%2 : ℕ) : Word w) ((t%2 : ℕ) : Word w) (mux ((t%2 : ℕ) : Word w) layout 2)) + (mux ((t%2 : ℕ) : Word w) (2*layout) (2-layout)) + else mux (((t%2 : ℕ) : Word w)*((t/2%2 : ℕ) : Word w)) layout 2 := by + unfold offset + rw [four_eq] + have h₂ : 2 < 2^w := by omega + have h₄ : 4 < 2^w := by omega + have h := ht.trans hw + have hd : t/2 < 2^w := (Nat.div_le_self ..).trans_lt h + have r₂ := remainder_cast h h₂ + have d₂ := div_cast h h₂ + have dr := remainder_cast hd h₂ + have d₄ := div_cast h h₄ + simp only [Nat.cast_ofNat] at r₂ d₂ dr d₄ + rw [r₂,d₂,dr,d₄] + +/-- Bit decoding agrees with the party-role table in both layouts. -/ +theorem offset_party (layout : Bool) (t : Fin 6) (hw : 6 < 2^w) : + offset true (layout.toNat : Word w) (t.val : Word w) = (SlotOwners.roleOffset (partyRole layout t) : Word w) := by + rw [offset_nat true _ _ hw t.isLt] + cases layout <;> fin_cases t <;> simp [mux, partyRole, SlotOwners.roleOffset]; ring + +/-- Bit decoding agrees with the owner of each absorbed edge type. -/ +theorem offset_hidden (layout : Bool) (t : Fin 4) (hw : 6 < 2^w) : + offset false (layout.toNat : Word w) (t.val : Word w) = (SlotOwners.roleOffset (internalRole layout t) : Word w) := by + rw [offset_nat false _ _ hw (t.isLt.trans (by decide))] + cases layout <;> fin_cases t <;> simp [mux, internalRole, partyRole, supply, supplySource, SlotOwners.roleOffset] + +/-- Address of the occurrence's absolute CD identifier, using the quotient of its cursor by the +number of occurrences per motif. -/ +def absoluteAddr (maps : Bool) (p : Fin 4 → Word w) (s : Word w) := + p 0 + BinaryOp.div.eval s (radix maps) + +/-- Address of the packed-owner word in the old arc's four-word role record, using the stored +CD identifier and the occurrence's selected role. -/ +def roleAddr (maps : Bool) (p : Fin 4 → Word w) (m : Memory w) (s : Word w) := + p 1 + four*m (absoluteAddr maps p s).val + offset maps (p 2) (BinaryOp.mod.eval s (radix maps)) + +theorem absoluteAddr_eq (maps : Bool) (p : Fin 4 → Word w) (s : Word w) : + absoluteAddr maps p s = p 0 + BinaryOp.div.eval s (arity maps : Word w) := by + rw [absoluteAddr,radix_eq] + +theorem roleAddr_eq (maps : Bool) (p : Fin 4 → Word w) (m : Memory w) (s : Word w) : + roleAddr maps p m s = p 1 + 4*m (absoluteAddr maps p s).val + + offset maps (p 2) (BinaryOp.mod.eval s (arity maps : Word w)) := by rw [roleAddr,four_eq,radix_eq] + +/-- Trace of one owner visit, reading the motif identifier and selected role word, writing that +owner at the occurrence cursor, and returning the next cursor. -/ +def report (maps : Bool) (p : Fin 4 → Word w) (s : Word w) (m : Memory w) : Report w := + let abs := absoluteAddr maps p s + let role := roleAddr maps p m s + let value := m role.val + ⟨List.replicate (14+(roleOps maps).length) .tick ++ [.read abs (m abs.val)] ++ + List.replicate 4 .tick ++ [.read role value] ++ List.replicate 2 .tick ++ + [.write (p 3+s) value] ++ List.replicate 2 .tick, some (s+1)⟩ + +theorem length_code (maps : Bool) : (code maps).length = if maps then 39 else 29 := by cases maps <;> rfl + +theorem native (maps : Bool) (p : Fin 4 → Word w) (s : Word w) (m : Memory w) : + let M := (worker maps).table.instantiate w p + execute M.program (1+(code maps).length) (M.program.start s) m [] = some (report maps p s m) ∧ + after m (report maps p s m).events = writeMemory m (p 3+s) (m (roleAddr maps p m s).val) ∧ + countProbes (report maps p s m).events = 3 ∧ (report maps p s m).events.length = (code maps).length ∧ + choiceBits (report maps p s m).events = [] := by + intro M + refine ⟨?_,?_,?_,?_,?_⟩ + · change execute ((template (code maps) 0).instantiate w p).program (1+(code maps).length) + ⟨((template (code maps) 0).instantiate w p).entry,s,fun _ ↦ 0,fun _ ↦ 0⟩ m [] = _ + rw [execute_template,run_eq_trace] + cases maps <;> rfl + all_goals cases maps <;> rfl + +end CompressorRecords.ResidentOwners + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentPackets.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentPackets.lean new file mode 100644 index 0000000000..124892efbe --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentPackets.lean @@ -0,0 +1,235 @@ +import OAI.Computability.VPVNP.CompressorBlockIndex +import OAI.Computability.VPVNP.CompressorScriptWindow +import OAI.Computability.VPVNP.CompressorShrinkResidentHeaders +import OAI.Computability.VPVNP.CompressorShrinkResidentRun +import OAI.Computability.VPVNP.CompressorHeaderOperands + +/-! # The twelve resident-directory visits in the installed compressor script + +The old hidden and map directories each use an owner scan, a counter clear +and a guarded append. Six single-word publishers then install their heads +at offsets 30 through 35. The window starts after the 36 preceding visits +of the same shrinking substep. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkResidentPackets + +open Compression BurstRAM BlockPlanner PhaseRecipe DescriptorSpace PrimedStackRAM SourceTransport +open ShrinkResidentRun ShrinkResidentLayout +open scoped Fin.CommRing + +/-- Expressions and degree exponent used to plan the two resident directory builds and their +six header publications for a selected shrink. -/ +structure Plan where + /-- Selected-shrink input formulas supplying the site and motif counts, role-record base and + layout choice. -/ + chosen : SelectedPlan.Inputs + /-- Expression for the first workspace address assigned to the hidden-field and party-map + directories. -/ + first : Expr + /-- Expression for the old level header where the six completed directory heads are + published. -/ + oldLevel : Expr + /-- Expression for the dense motif-indexed array of absolute CD identifiers read by the owner + scans. -/ + absoluteCD : Expr + /-- Old degree exponent used to compute the preimage-row capacity for the collector's operand + bank. -/ + exponent : ℕ + +/-- A resident-directory operation, either writing owners, clearing counts, appending preimages +for one resident kind, or publishing one of the six heads. -/ +inductive Stage + | owners (maps : Bool) + | clear (maps : Bool) + | append (maps : Bool) + | header (i : Fin 6) + +/-- The three visits that build one resident directory, assigning owners, clearing site counts +and appending occurrence identifiers in order. -/ +def scans (maps : Bool) : List Stage := [.owners maps,.clear maps,.append maps] + +/-- Execution order of the twelve stages, building hidden-field rows, then party-map rows, then +publishing their six pointers. -/ +def order : List Stage := scans false ++ scans true ++ (List.finRange 6).map Stage.header + +/-- Translate one resident stage into its scheduled worker, cursor bounds and operand +expressions for this plan. -/ +def Stage.visit (P : Plan) : Stage → BlockPlanner.Visit + | .owners maps => ResidentOwners.visit maps (ShrinkResidentsPlan.size P.chosen maps) P.absoluteCD + (SelectedPlan.roleBase P.chosen) (SelectedPlan.layout P.chosen) (ShrinkResidentsPlan.owner P.chosen P.first maps) + | .clear maps => ops SliceRAM.clearOps 0 (.lit 0) P.chosen.newSites (fun _ => ShrinkResidentsPlan.counts P.chosen P.first maps) + | .append maps => ops collectPreimage 3 (.lit 0) (ShrinkResidentsPlan.size P.chosen maps) + (ShrinkResidentsPlan.bank P.chosen P.first P.exponent maps) + | .header i => ShrinkResidentsPlan.headerVisit P.chosen P.first P.oldLevel i + +/-- The ordered block-planner visits that execute both resident directory builds and publish +their heads using the plan's inputs. -/ +def Plan.visits (P : Plan) := ShrinkResidentsPlan.visits P.chosen P.first P.oldLevel P.absoluteCD P.exponent + +theorem Plan.ordered (P : Plan) : order.map (Stage.visit P) = P.visits := by + simp only [order,List.map_append,List.map_map,Plan.visits,ShrinkResidentsPlan.visits, + ShrinkResidentsPlan.publications,List.ofFn_eq_map] + rfl + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) + +/-- Recover the resident plan for a particular block substep from its selected inputs, old +level, directory arena, absolute CD table and old degree exponent. -/ +def plan : Plan := + let F := BlockProgram.geometry B + let origin := BlockProgram.arena B i.val 0 + ⟨ShrinkBlockInputs.selectedInputs B F i origin,BlockProgram.arena B i.val 5,LevelFields.atLevel i.val, + ShrinkBundlePlan.absoluteCD i.val (ShrinkBlockInputs.a i) origin,ShrinkBlockInputs.a i⟩ + +/-- The portion of this shrinking substep preceding its resident-directory window, comprising +the first 36 visits. -/ +def prior := ShrinkBlockInputs.beforeSlices B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0) + +private theorem tail_exists : ∃ tail, BlockProgram.shrink B i = prior B i ++ (plan B i).visits ++ tail := by + unfold BlockProgram.shrink + simp only [List.append_assoc] + exact ⟨_,rfl⟩ + +/-- Locate the twelve resident visits in the installed block script after the earlier substeps +and this substep's prefix. -/ +def window : Window (BlockProgram.script B) (plan B i).visits where + before := BlockIndex.earlier B i ++ prior B i + after := (tail_exists B i).choose ++ BlockIndex.later B i + block := by + change BlockProgram.block B = _ + conv_lhs => rw [BlockIndex.split_block,(tail_exists B i).choose_spec] + simp only [List.append_assoc] + +theorem window_offset : (window B i).before.length = (BlockIndex.earlier B i).length+36 := by + change (BlockIndex.earlier B i ++ prior B i).length = _ + rw [List.length_append,prior,ShrinkBlockInputs.beforeSlices_length] + +theorem window_phase (t : ℕ) (j : Fin (plan B i).visits.length) : + let A := BlockProgram.script B + let ordinal := A.initial.length+t*A.block.length+(BlockIndex.earlier B i).length+36+j.val + (Schedule.Online.calendar A.plan).phase ordinal = ((window B i).index j).val ∧ + (Schedule.Online.calendar A.plan).level ordinal = t := by + dsimp only + simpa only [Window.index,Window.position,window_offset,Fin.val_natAdd,Nat.add_assoc] using + (BlockProgram.script B).block_phase t ((window B i).position j) + +variable {w : ℕ} + +/-- Concrete resident workspace, header address, source pointers and layout choice used to +instantiate the planned scans at a given word width. -/ +structure Values (w : ℕ) where + /-- The concrete layout of both resident directories, determining their table addresses and + scan sizes. -/ + layout : ShrinkResidentLayout.Layout + /-- Address of the old level header receiving the six resident directory pointers. -/ + level : ℕ + /-- Machine-word pointer to the dense absolute CD identifiers, one per motif. -/ + absolute : Word w + /-- Machine-word pointer to the four-word role records indexed by absolute old arc. -/ + role : Word w + /-- The Boolean shrink layout used to select the resident's packed role when writing owners. -/ + side : Bool + +/-- Exclusive cursor bound for this stage, the occurrence count for owners and appends, the +site count for clearing, or one for a head publication. -/ +def Stage.limit (D : Values w) : Stage → ℕ + | .owners maps | .append maps => D.layout.size maps + | .clear _ => D.layout.sites + | .header _ => 1 + +/-- Private fuel allowed for one worker call of this stage, determined by its native owner, +clear, append or publication code. -/ +def Stage.fuel : Stage → ℕ + | .owners maps => 1+(ResidentOwners.code maps).length + | .clear _ => 8 + | .append _ => 23 + | .header _ => 7 + +theorem Stage.clock (j : Stage) : 0 < j.fuel ∧ j.fuel ≤ 40 := by + cases j with + | owners maps => cases maps <;> decide + | clear | append | header => simp [Stage.fuel] + +/-- Concrete public operand vector for the stage's worker, using the instantiated directory +addresses, source pointers and selected layout. -/ +def Stage.bank (P : Plan) (D : Values w) : (j : Stage) → Fin (Stage.visit P j).worker.params → Word w + | .owners maps => ![D.absolute,D.role,(D.side.toNat : Word w),(D.layout.owner maps : Word w)] + | .clear maps => fun _ => (D.layout.counts maps : Word w) + | .append maps => D.layout.params P.exponent maps w + | .header j => ShrinkResidentsPlan.headerBank D.level D.layout w j + +/-- The planned operands evaluate in the current public words, state and memory to the concrete +resident layout, header address, source pointers and selected side. -/ +structure OperandValues (P : Plan) (D : Values w) (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w) : Prop where + ready : ShrinkResidentsPlan.Ready P.chosen P.first pub st mem D.layout + oldLevel : P.oldLevel.eval pub st mem = (D.level : Word w) + absolute : P.absoluteCD.eval pub st mem = D.absolute + role : (SelectedPlan.roleBase P.chosen).eval pub st mem = D.role + side : (SelectedPlan.layout P.chosen).eval pub st mem = (D.side.toNat : Word w) + +theorem OperandValues.words {P : Plan} {D : Values w} {pub : Fin 5 → Word w} {st : Word w} {mem : Memory w} + (h : OperandValues P D pub st mem) (j : Stage) : + (j.visit P).initial.eval pub st mem = 0 ∧ (j.visit P).stop.eval pub st mem = (j.limit D : Word w) ∧ + (fun t => ((j.visit P).params t).eval pub st mem) = j.bank P D := by + have size := ShrinkResidentsPlan.size_val P.chosen P.first pub st mem D.layout h.ready + have owner := ShrinkResidentsPlan.owner_val P.chosen P.first pub st mem D.layout h.ready + have counts := ShrinkResidentsPlan.counts_val P.chosen P.first pub st mem D.layout h.ready + cases j with + | owners maps => + refine ⟨rfl,size maps,?_⟩ + funext t + fin_cases t <;> first | exact h.absolute | exact h.role | exact h.side | exact owner maps + | clear maps => exact ⟨rfl,h.ready.sites,funext fun _ => counts maps⟩ + | append maps => exact ⟨rfl,size maps,ShrinkResidentsPlan.bank_val P.chosen P.first pub st mem D.layout h.ready P.exponent maps⟩ + | header t => exact ⟨rfl,rfl,ShrinkResidentsPlan.header_bank_eq P.chosen P.first P.oldLevel pub st mem D.level D.layout h.ready h.oldLevel t⟩ + +/-- The only loaded expressions needed for all twelve visits. -/ +structure OperandReads (P : Plan) (data : ℕ → Prop) (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w) : Prop where + sites : P.chosen.newSites.ReadsFrom data pub st mem + motifs : P.chosen.motifs.ReadsFrom data pub st mem + first : P.first.ReadsFrom data pub st mem + role : (SelectedPlan.roleBase P.chosen).ReadsFrom data pub st mem + layout : (SelectedPlan.layout P.chosen).ReadsFrom data pub st mem + absolute : P.absoluteCD.ReadsFrom data pub st mem + level : P.oldLevel.ReadsFrom data pub st mem + +theorem OperandReads.supported {P : Plan} {data : ℕ → Prop} {pub : Fin 5 → Word w} {st : Word w} {mem : Memory w} + (h : OperandReads P data pub st mem) (j : Stage) : HeaderOperands.Supported data pub st mem (j.visit P) := by + let rd := fun x : Expr => x.ReadsFrom data pub st mem + have size (b) : rd (ShrinkResidentsPlan.size P.chosen b) := ⟨h.motifs,trivial⟩ + have owner (b) : rd (ShrinkResidentsPlan.owner P.chosen P.first b) := by + cases b + · exact h.first + · exact ⟨⟨⟨h.first,size false⟩,h.sites⟩,size false⟩ + have counts (b) : rd (ShrinkResidentsPlan.counts P.chosen P.first b) := ⟨owner b,size b⟩ + have rows (b) : rd (ShrinkResidentsPlan.rows P.chosen P.first b) := ⟨counts b,h.sites⟩ + cases j with + | owners b => + refine ⟨trivial,size b,?_⟩ + intro t; fin_cases t <;> first | exact h.absolute | exact h.role | exact h.layout | exact owner b + | clear b => exact ⟨trivial,h.sites,fun _ => counts b⟩ + | append b => + refine ⟨trivial,size b,?_⟩ + intro t; fin_cases t <;> first | exact size b | exact owner b | exact h.sites | exact counts b | exact rows b | trivial + | header i => + refine ⟨trivial,trivial,?_⟩ + intro t + fin_cases t + · exact ⟨h.level,trivial⟩ + · fin_cases i <;> first | exact owner false | exact counts false | exact rows false + | exact owner true | exact counts true | exact rows true + +end CompressorRecords.ShrinkResidentPackets + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentRun.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentRun.lean new file mode 100644 index 0000000000..218f216ef9 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentRun.lean @@ -0,0 +1,263 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentDirectory +import OAI.Computability.VPVNP.CompressorShrinkResidentsPlan + +/-! # Native construction of both local resident tables in chronological memory -/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkResidentRun + +open Compression BurstRAM PrimedStackRAM PairSimulation.LocalHistory +open ShrinkResidentLayout +open scoped Fin.CommRing Classical + +variable {a g w : ℕ} (X : State a (packingLaneBits a g)) (first : ℕ) +variable (absolute roleHead : Word w) (side : Bool) + +/-- The owner scan takes four words in order, the dense-to-absolute motif table base, the role +table base, the selected side bit, and the output base for hidden or map owners. -/ +def ownerBank (maps : Bool) : Fin 4 → Word w := + ![absolute,roleHead,(side.toNat : Word w),((layout X first).owner maps : Word w)] + +/-- The preimage collector takes six words for the chosen resident kind, giving its size and +owner base, the packed-site count and counter base, the row capacity, and the ID row base. -/ +def outputBank (maps : Bool) := (layout X first).params a maps w + +/-- The resident arena and both input tables fit the address space, each input table lies +outside the arena, and six is representable as a word. -/ +structure Areas : Prop where + fit : (layout X first).endAddr < 2^w + absoluteRoom : absolute.val+(shrinkMotifOrder X).length ≤ 2^w + roleRoom : roleHead.val+4*DemandRAM.absoluteCount X ≤ 2^w + absoluteApart : absolute.val+(shrinkMotifOrder X).length ≤ first ∨ (layout X first).endAddr ≤ absolute.val + roleApart : roleHead.val+4*DemandRAM.absoluteCount X ≤ first ∨ (layout X first).endAddr ≤ roleHead.val + tagFit : 6 < 2^w + +variable {X first absolute roleHead} (space : Areas X first absolute roleHead) + +include space in +theorem Areas.owner (maps : Bool) : ShrinkResidentDirectory.Areas X maps (ownerBank X first absolute roleHead side maps) := by + let L := layout X first + have dims : (ShrinkResidentDirectory.oldOrder X maps).length = L.size maps := rfl + obtain ⟨start,cnt,rows,stop⟩ := L.ranges maps + have fit : L.endAddr < 2^w := space.fit + have word : (ownerBank X first absolute roleHead side maps 3).val = L.owner maps := Nat.mod_eq_of_lt (show L.owner maps < 2^w by omega) + refine ⟨space.absoluteRoom,space.roleRoom,?_,?_,?_,space.tagFit⟩ + · rw [word,dims]; omega + · rw [word,dims]; exact space.absoluteApart.imp (fun h => h.trans start) (fun h => (show L.owner maps+L.size maps ≤ L.endAddr by omega).trans h) + · rw [word,dims]; exact space.roleApart.imp (fun h => h.trans start) (fun h => (show L.owner maps+L.size maps ≤ L.endAddr by omega).trans h) + +/-- Reports from the three successive scans that build a directory of hidden residents or map +residents at the packed sites. -/ +structure Passes (w : ℕ) where + /-- Reports from writing the packed owner of each resident in motif-major order. -/ + owners : List (Report w) + /-- Reports from setting each packed site’s resident counter to zero before collecting its + IDs. -/ + clear : List (Report w) + /-- Reports from appending each resident’s dense ID to its owner’s row and incrementing that + site’s counter. -/ + collect : List (Report w) + +/-- Memory after replaying the owner-column writes on the entry memory, ready for the +counter-clear scan. -/ +def Passes.mid (p : Passes w) (m : Memory w) := after m (eventLog p.owners) +/-- Memory after the owner scan and the counter-clear scan, where the ID collection starts. -/ +def Passes.cleared (p : Passes w) (m : Memory w) := after (p.mid m) (eventLog p.clear) +/-- Memory after collecting the resident IDs on top of the owner and counter scans. -/ +def Passes.final (p : Passes w) (m : Memory w) := after (p.cleared m) (eventLog p.collect) +/-- The complete directory trace in execution order, from the owner writes through counter +clearing to ID collection. -/ +def Passes.all (p : Passes w) := p.owners++p.clear++p.collect + +theorem Passes.after_all (p : Passes w) (m : Memory w) : after m (eventLog p.all) = p.final m := by + simp only [all,final,cleared,mid,eventLog,List.flatMap_append,after,List.foldl_append] + +variable (X first absolute roleHead) (maps : Bool) + +/-- Certifies the three native scans, their ordered per-site resident directory, and +preservation outside the resident tables. The total charge is nine per resident and two per +packed site. -/ +structure Built (m : Memory w) (p : Passes w) : Prop where + owners : ShrinkResidentDirectory.Written X maps (ownerBank X first absolute roleHead side maps) side m p.owners + clear : runSegment ((template SliceRAM.clearOps 0).instantiate w (fun _ => outputBank X first maps 3)).program 8 + (some 0) (p.mid m) (List.replicate (layout X first).sites []) = some p.clear + collect : runSegment ((template collectPreimage 3).instantiate w (outputBank X first maps)).program 23 + (some 0) (p.cleared m) (List.replicate ((layout X first).size maps) []) = some p.collect + directory : ShrinkHistoryRows.Directory (ShrinkResidentDirectory.oldOrder X maps) (ShrinkHistoryRows.packedOrder X) + (ShrinkResidentDirectory.place X maps side) (outputBank X first maps) (p.final m) + frame (x : ℕ) (hx : x < (layout X first).owner maps ∨ (layout X first).rows maps+(layout X first).size maps ≤ x) : + p.final m x = m x + charge : RAMBuckets.cost Report.probes p.all = 9*(layout X first).size maps + 2*(layout X first).sites + +private theorem clearCost (rs : List (Report w)) (h : ∀ r ∈ rs, r.probes = 1) : + RAMBuckets.cost Report.probes rs = 2*rs.length := by + induction rs with + | nil => rfl + | cons r rs ih => + rw [RAMBuckets.cost, h r (List.mem_cons_self ..), ih (fun _ hv => h _ (List.mem_cons_of_mem _ hv)), List.length_cons,Nat.mul_succ] + omega + +include space in +/-- Starting from actual CD and role data, this deterministic three-stage +scan gives precisely the ordered local hidden IDs or map IDs. -/ +theorem run (mem : Memory w) (dir : ShrinkResidentDirectory.Absolute X absolute mem) + (roles : DemandRAM.RoleColumns X side roleHead.val mem) : + ∃ p : Passes w, Built X first absolute roleHead side maps mem p := by + let L := layout X first + let bank := outputBank (w := w) X first maps + have ho : (ShrinkResidentDirectory.oldOrder X maps).length = L.size maps := rfl + have hn : (ShrinkHistoryRows.packedOrder X).length = L.sites := rfl + obtain ⟨areas,h0,h1,h2,h3,h4,h5⟩ := ShrinkResidentLayout.frame X first maps space.fit + change (bank 0).val=L.size maps at h0 + change (bank 1).val=L.owner maps at h1 + change (bank 2).val=L.sites at h2 + change (bank 3).val=L.counts maps at h3 + change (bank 4).val=rowCapacity a maps at h4 + change (bank 5).val=L.rows maps at h5 + have newFit : (ShrinkHistoryRows.packedOrder X).length ≤ 2^w := (h2 ▸ (bank 2).isLt).le + have allowed := space.owner side maps + obtain ⟨own,hw⟩ := ShrinkResidentDirectory.run X maps (ownerBank X first absolute roleHead side maps) rfl allowed newFit dir roles + have cap (v) : Fintype.card {x // ShrinkResidentDirectory.place X maps side x = v} ≤ (bank 4).val := by + exact (show Fintype.card {x // ShrinkResidentDirectory.place X maps side x = v} ≤ rowCapacity a maps from by + cases maps + · exact (ShrinkHistoryRows.hidden_count X side v).le + · exact (ShrinkHistoryRows.map_count X side v).le).trans h4.symm.le + obtain ⟨cs,rs,hc,hr,rows,clen,rlen,cwork,rwork,rf⟩ := ShrinkHistoryRows.build + (ShrinkResidentDirectory.oldOrder X maps) (ShrinkHistoryRows.packedOrder X) + (ShrinkResidentDirectory.place X maps side) bank areas h0 h2 cap (after mem (eventLog own)) + (hw.ownerAt X maps (ownerBank X first absolute roleHead side maps) allowed bank rfl h0) + let pass : Passes w := ⟨own,cs,rs⟩ + refine ⟨pass,hw,hc,hr,rows,?_,?_⟩ + · intro x hx + obtain ⟨_,oc,cr,_⟩ := L.ranges maps + have ss := size_eq_rows X first maps + change L.size maps=L.sites*rowCapacity a maps at ss + have other : OutsidePreimageWrites bank x := by + change (x < (bank 3).val ∨ (bank 3).val+(bank 2).val ≤ x) ∧ + (x < (bank 5).val ∨ (bank 5).val+(bank 2).val*(bank 4).val ≤ x) + rw [h3,h2,h5,h4,←ss] + change x < L.owner maps ∨ L.rows maps+L.size maps ≤ x at hx + omega + have wo : (ownerBank X first absolute roleHead side maps 3).val = L.owner maps := h1 + apply (rf x other).trans (hw.frame x ?_) + rw [wo,ho] + change x < L.owner maps ∨ L.rows maps+L.size maps ≤ x at hx + omega + · change RAMBuckets.cost Report.probes ((own++cs)++rs) = _ + have rc : RAMBuckets.cost Report.probes rs = 5*rs.length := preimagePass_cost (fun r h => (rwork r h).1) + rw [RAMBuckets.cost_append,RAMBuckets.cost_append,hw.charge,clearCost cs (fun r h => (cwork r h).1),rc,clen,rlen,ho,hn] + change 4*L.size maps+2*L.sites+5*L.size maps = 9*L.size maps+2*L.sites + omega + +/-- The entire resident workspace is disjoint from the two persistent +input arrays. A finished stage therefore leaves their typed readbacks live +for the next stage. -/ +theorem Built.inputs {m : Memory w} {r : Passes w} (h : Built X first absolute roleHead side maps m r) + (dir : ShrinkResidentDirectory.Absolute X absolute m) (roles : DemandRAM.RoleColumns X side roleHead.val m) + (sp : Areas X first absolute roleHead) : + ShrinkResidentDirectory.Absolute X absolute (r.final m) ∧ + DemandRAM.RoleColumns X side roleHead.val (r.final m) := by + let L := layout X first + obtain ⟨before,_,_,endBound⟩ := L.ranges maps + have same (x : ℕ) (hx : x < first ∨ L.endAddr ≤ x) : r.final m x = m x := + h.frame x (hx.imp (fun lo => lo.trans_le before) (fun hi => endBound.trans hi)) + have absSafe {i : ℕ} (hi : i < (shrinkMotifOrder X).length) : + absolute.val+i < first ∨ L.endAddr ≤ absolute.val+i := + sp.absoluteApart.imp (fun ha => (Nat.add_lt_add_left hi _).trans_le ha) (fun ha => ha.trans (Nat.le_add_right ..)) + have roleSafe {i j : ℕ} (hi : i (show _ < roleHead.val+4*DemandRAM.absoluteCount X by omega).trans_le ha) + (fun ha => (ha.trans (Nat.le_add_right ..)).trans (Nat.le_add_right ..)) + constructor + · intro i + have hc := Fintype.card_congr (ShrinkMotifOrder.stateNumber X) + rw [Fintype.card_fin] at hc + have hi : i.val < (shrinkMotifOrder X).length := i.isLt.trans_eq hc.symm + rw [same _ (absSafe hi)] + exact dir i + · constructor + · intro e + rw [same _ (roleSafe (DemandRAM.absoluteIndex X e).isLt (by decide : 3<4))] + exact roles.cd e + · intro e role + have small : SlotOwners.roleOffset role < 4 := by cases role <;> decide + rw [same _ (roleSafe (DemandRAM.absoluteIndex X e.val).isLt small)] + exact roles.packed e role + +private theorem hidden_length_le (v) : (ShrinkHistoryRows.residents (ShrinkHistoryRows.hiddenOrder X) + (X.packingData.shrinkInternalOwner side) v).length ≤ rowCapacity a false := by + let f := X.packingData.shrinkInternalOwner side + have changeFiber : {u // v=f u} ≃ {u // f u=v} := Equiv.subtypeEquivRight fun _ => eq_comm + exact (Fintype.card_congr changeFiber).le.trans (ShrinkHistoryRows.hidden_count X side v).le + +/-- The later map-directory calls retain both the earlier hidden counts +and every earlier hidden ID. -/ +theorem retained_hidden {m : Memory w} {h r : Passes w} + (hb : Built X first absolute roleHead side false m h) + (rb : Built X first absolute roleHead side true (h.final m) r) + (fit : (layout X first).endAddr < 2^w) : + ShrinkHistoryRows.Directory (ShrinkHistoryRows.hiddenOrder X) (ShrinkHistoryRows.packedOrder X) + (X.packingData.shrinkInternalOwner side) (outputBank X first false) (r.final (h.final m)) := by + let L := layout X first + let p := outputBank (w := w) X first false + obtain ⟨_,_,_,hSites,hCount,hCap,hRow⟩ := ShrinkResidentLayout.frame X first false fit + change (p 2).val=L.sites at hSites + change (p 3).val=L.counts false at hCount + change (p 4).val=rowCapacity a false at hCap + change (p 5).val=L.rows false at hRow + have order (v) : ((ShrinkHistoryRows.packedOrder X).entries.symm v).val < L.sites := + ((ShrinkHistoryRows.packedOrder X).entries.symm v).isLt + have next : L.owner true = L.rows false+L.size false := rfl + constructor + · intro v + have addr : (p 3).val+((ShrinkHistoryRows.packedOrder X).entries.symm v).val < L.owner true := by + rw [hCount,next] + have := order v + change L.counts false+_ < L.counts false+L.sites+L.size false + omega + rw [rb.frame _ (.inl addr)] + exact hb.directory.count v + · intro v j + have vv := Nat.mul_le_mul_right (rowCapacity a false) (order v) + rw [Nat.succ_mul] at vv + have hv := j.isLt.trans_le (hidden_length_le X side v) + have dim := size_eq_rows X first false + change L.size false=L.sites*rowCapacity a false at dim + have addr : (p 5).val+((ShrinkHistoryRows.packedOrder X).entries.symm v).val*(p 4).val+j.val < L.owner true := by + rw [hRow,hCap,next,dim] + omega + rw [rb.frame _ (.inl addr)] + exact hb.directory.idAt v j + +include space in +/-- Six deterministic native visits execute on the same memory image +as the two resident headers describe. No guessed bits are used to recover +the resident lists. -/ +theorem both (m : Memory w) (dir : ShrinkResidentDirectory.Absolute X absolute m) + (roles : DemandRAM.RoleColumns X side roleHead.val m) : + ∃ h r : Passes w, Built X first absolute roleHead side false m h ∧ + Built X first absolute roleHead side true (h.final m) r ∧ + ShrinkHistoryRows.Directory (ShrinkHistoryRows.hiddenOrder X) (ShrinkHistoryRows.packedOrder X) + (X.packingData.shrinkInternalOwner side) (outputBank X first false) (r.final (h.final m)) ∧ + RAMBuckets.cost Report.probes (h.all++r.all) = 90*(layout X first).motifs+4*(layout X first).sites := by + obtain ⟨h,hh⟩ := run X first absolute roleHead side space false m dir roles + obtain ⟨dir',roles'⟩ := hh.inputs X first absolute roleHead side false dir roles space + obtain ⟨r,hr⟩ := run X first absolute roleHead side space true (h.final m) dir' roles' + refine ⟨h,r,hh,hr,retained_hidden X first absolute roleHead side hh hr space.fit,?_⟩ + rw [RAMBuckets.cost_append,hh.charge,hr.charge] + change 9*((layout X first).motifs*4)+2*(layout X first).sites + + (9*((layout X first).motifs*6)+2*(layout X first).sites) = _ + omega + +end CompressorRecords.ShrinkResidentRun + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentScan.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentScan.lean new file mode 100644 index 0000000000..eebbf2b815 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentScan.lean @@ -0,0 +1,145 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentOwners + +/-! +# Executing the dense resident owner scan + +The role and absolute-CD input cells lie outside the fresh output column. +A pass preserves its source cells while writing exactly one owner for each +dense history index. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ResidentOwners + +open BurstRAM BurstRAM.PrivateRAM PrimedStackRAM +open scoped Fin.CommRing + +variable {w : ℕ} + +private def Written (maps : Bool) (p : Fin 4 → Word w) (old m : Memory w) (k : ℕ) : Prop := + (∀ j < k, m ((p 3).val+j) = old (roleAddr maps p old (j : Word w)).val) ∧ + ∀ a, a < (p 3).val ∨ (p 3).val+k ≤ a → m a = old a + +private theorem scan_from (maps : Bool) (p : Fin 4 → Word w) (old : Memory w) (N : ℕ) + (fits : (p 3).val+N ≤ 2^w) + (inputs : ∀ i : Word w, i.val < N → + ((absoluteAddr maps p i).val < (p 3).val ∨ (p 3).val+N ≤ (absoluteAddr maps p i).val) ∧ + ((roleAddr maps p old i).val < (p 3).val ∨ (p 3).val+N ≤ (roleAddr maps p old i).val)) + {k n : ℕ} {m : Memory w} (bound : k+n ≤ N) (done : Written maps p old m k) : + let W := (worker maps).table.instantiate w p + ∃ rs, runSegment W.program (1+(code maps).length) (some (k : Word w)) m (List.replicate n []) = some rs ∧ + Written maps p old (after m (eventLog rs)) (k+n) ∧ rs.length = n ∧ + (∀ r ∈ rs, r.events.length = (code maps).length ∧ countProbes r.events = 3 ∧ choiceBits r.events = []) ∧ + RAMBuckets.cost Report.probes rs = 4*n := by + intro W + induction n generalizing k m with + | zero => exact ⟨[],rfl,done,rfl,by simp,rfl⟩ + | succ n ih => + let i : Word w := (k : Word w) + have hk : k < N := by omega + have hi : i.val = k := Nat.mod_eq_of_lt (by omega) + have hr := inputs i (hi ▸ hk) + have keep (addr : ℕ) (ha : addr < (p 3).val ∨ (p 3).val+N ≤ addr) : m addr = old addr := + done.2 addr (by omega) + have hrole : roleAddr maps p m i = roleAddr maps p old i := by + unfold roleAddr + rw [keep _ hr.1] + have hval : m (roleAddr maps p m i).val = old (roleAddr maps p old i).val := by + rw [hrole]; exact keep _ hr.2 + have haddr : (p 3+i).val = (p 3).val+k := by + rw [Fin.val_add,hi,Nat.mod_eq_of_lt (by omega)] + let u := writeMemory m (p 3+i) (m (roleAddr maps p m i).val) + have step : Written maps p old u (k+1) := by + refine ⟨fun j hj ↦ ?_, fun a ha ↦ ?_⟩ + · by_cases eq : j = k + · subst j; simpa only [u,writeMemory,haddr,ite_true] using hval + · rw [show u ((p 3).val+j) = m ((p 3).val+j) by simp [u,writeMemory,haddr,eq]] + exact done.1 j (by omega) + · have hne : a ≠ (p 3).val+k := by omega + simp only [u,writeMemory,haddr,ite_eq_right hne] + exact done.2 _ (by omega) + obtain ⟨rs,run,stored,len,work,cost⟩ := ih (k := k+1) (m := u) (by omega) step + let head := report maps p i m + obtain ⟨call,update,reads,ticks,choices⟩ := native maps p i m + have next : head.result = some ((k+1 : ℕ) : Word w) := by + change some ((k : Word w)+1) = _; simp + have combined : after m (eventLog (head::rs)) = after u (eventLog rs) := by + change after m (head.events++eventLog rs) = _ + exact (List.foldl_append ..).trans (congrArg (fun s ↦ after s (eventLog rs)) update) + refine ⟨head::rs,?_,combined ▸ (by simpa only [Nat.add_assoc,Nat.add_comm 1 n] using stored), + by simp [len],?_,?_⟩ + · rw [List.replicate_succ,runSegment] + rw [call] + change (runSegment W.program _ head.result (after m head.events) _).map _ = _ + rw [next,update,run]; rfl + · intro r hr + rcases List.mem_cons.mp hr with rfl | hr + · exact ⟨ticks,reads,choices⟩ + · exact work r hr + · change 1+countProbes head.events+RAMBuckets.cost Report.probes rs = _ + rw [reads,cost]; omega + +/-- Exact terminal owner table, source-frame preservation and probe count on +the real fixed instruction sequence. -/ +theorem scan_separate (maps : Bool) (p : Fin 4 → Word w) (m : Memory w) (N : ℕ) + (fits : (p 3).val+N ≤ 2^w) + (inputs : ∀ i : Word w, i.val + change some [] = some rs at h + rw [← Option.some.inj h] + simp [endState] + | succ n ih => + rw [List.replicate_succ,runSegment,(native maps p start m).1] at h + cases eq : runSegment ((worker maps).table.instantiate w p).program (1+(code maps).length) + (some (start+1)) (after m (report maps p start m).events) (List.replicate n []) with + | none => + change Option.map _ (runSegment _ _ (some (start+1)) _ _) = _ at h + rw [eq] at h; contradiction + | some ts => + change Option.map _ (runSegment _ _ (some (start+1)) _ _) = _ at h + rw [eq] at h + rw [← Option.some.inj h] + change endState (some (start+1)) ts = _ + simpa [Nat.cast_succ,add_assoc,add_comm,add_left_comm] using ih (start+1) _ ts eq + +end CompressorRecords.ResidentOwners + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentTerms.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentTerms.lean new file mode 100644 index 0000000000..5d1fa455e6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentTerms.lean @@ -0,0 +1,52 @@ +import OAI.Computability.VPVNP.CompressorShrinkOutputAllocation +import OAI.Computability.VPVNP.CompressorRecordsSelectedFinish + +/-! # The selected shrinking rows in the allocated output pass + +The post-selection readback uses the cardinal-length motif order. The +split worker uses the state numbering of the same ordered motifs. Their +ten-word rows and all eight supply coordinates coincide. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkOutput + +open Compression Compression.PackingData Compression.ShrinkMotif MotifBlocks MotifGrid MotifConversion +open BurstRAM ShrinkSliceSweep +open scoped Classical + +variable {a b g w : ℕ} {k : Type*} [_root_.Field k] {S : BlockSchedule k} +variable (B : S.Templates) (X : State a (packingLaneBits a g)) +variable (term stride selectors : Word w) (role retained : ℕ) + +set_option maxHeartbeats 1200000 in +theorem resident_terms (sel : SelectedScore.Selection B X) (mem : Memory w) + (hs : SelectedScore.Stored B X sel (SelectedScore.headAt X (SelectedArena.scoreTables X term stride selectors)) mem) : + let T := splitBank (b := b) X B.shrink sel term stride.val role retained + Terms X.packingData X.shrinkNumber (Shrink.packedIndex X.baseIndex) T B.shrink X.packingWidth sel mem := by + intro T i + let m := (ShrinkMotifOrder.stateNumber X).symm i + let j := (SelectedScore.motifOrder X).entries.symm m + have hj : j.val = i.val := (ShrinkMotifOrder.entries_ordinal X m).trans (congrArg Fin.val ((ShrinkMotifOrder.stateNumber X).apply_symm_apply i)) + have h := hs j + change TermRecordScan.Fields _ _ _ _ (sel ((SelectedScore.motifOrder X).entries j)).val _ _ at h + rw [show (SelectedScore.motifOrder X).entries j = m from (SelectedScore.motifOrder X).entries.apply_symm_apply _] at h + have addr : SelectedScore.headAt X (SelectedArena.scoreTables X term stride selectors) j = Fin.ofNat (2^w) (term.val+i.val*stride.val) := by + apply Fin.ext + simp only [SelectedScore.headAt, TermScores.rowBase, TermScores.word, SelectedArena.scoreTables, Fin.val_add, Fin.val_mul, Fin.val_ofNat, hj] + simp [Nat.add_mod, Nat.mul_mod] + rw [addr] at h + exact h + +end CompressorRecords.ShrinkOutput + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkResidentsPlan.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentsPlan.lean new file mode 100644 index 0000000000..9e84b765c6 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkResidentsPlan.lean @@ -0,0 +1,124 @@ +import OAI.Computability.VPVNP.CompressorShrinkResidentLayout +import OAI.Computability.VPVNP.CompressorShrinkResidentOwners + +/-! +# Native planner rows for the six-party resident directories + +Build hidden and map owner columns, clear their counters, append the dense +ordinals, and publish the six absolute heads in level header cells 30–35. +The chosen layout is read from the score comparison's actual output cell. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +namespace CompressorRecords.ShrinkResidentsPlan + +open BurstRAM BlockPlanner PhaseRecipe PrimedStackRAM ShrinkResidentLayout +open scoped Fin.CommRing + +variable (I : SelectedPlan.Inputs) (first : Expr) + +/-- Number of dense resident IDs for the chosen kind, four per motif for hidden residents and +six per motif for maps. -/ +def size (maps : Bool) := I.motifs.mul (.lit (radix maps)) + +/-- Planner expression for the start of the owner column. Hidden owners start at `first`, and +map owners start just after the hidden ID rows. -/ +def owner (maps : Bool) := + if maps then ((first.add (size I false)).add I.newSites).add (size I false) else first + +/-- Planner address of the per-site counters, immediately after the owner column for this +resident kind. -/ +def counts (maps : Bool) := (owner I first maps).add (size I maps) + +/-- Planner address of the resident ID rows, immediately after the count word for the last +packed site. -/ +def rows (maps : Bool) := (counts I first maps).add I.newSites + +/-- First address after the map ID rows, which end the workspace for the two resident +directories. -/ +def endAddr := (rows I first true).add (size I true) + +/-- The six operand expressions for resident collection, giving the resident count, owner base, +site count, counter base, IDs per row, and ID row base. -/ +def bank (a : ℕ) (maps : Bool) : Fin 6 → Expr := + ![size I maps,owner I first maps,I.newSites,counts I first maps,.lit (rowCapacity a maps),rows I first maps] + +/-- The three visits for one resident kind write each ID’s packed owner using the chosen +layout, clear one counter per site, then append the IDs to their owners’ rows. -/ +def phases (absoluteCD : Expr) (a : ℕ) (maps : Bool) : List Visit := + [ResidentOwners.visit maps (size I maps) absoluteCD (SelectedPlan.roleBase I) (SelectedPlan.layout I) (owner I first maps), + ops SliceRAM.clearOps 0 (.lit 0) I.newSites (fun _ => counts I first maps), + ops collectPreimage 3 (.lit 0) (size I maps) (bank I first a maps)] + +/-- The six directory bases in publication order, with owner, count, and ID row bases for +hidden residents followed by the same three bases for maps. -/ +def heads : Fin 6 → Expr := + ![owner I first false,counts I first false,rows I first false,owner I first true,counts I first true,rows I first true] + +/-- Six visits that write the resident directory bases to offsets 30 through 35 of the old +level header. -/ +def publications (oldLevel : Expr) := + List.ofFn fun i : Fin 6 => publish (oldLevel.add (.lit (30+i.val))) (heads I first i) + +/-- The complete resident schedule builds the hidden directory, builds the map directory, then +publishes their six bases in the old level header. -/ +def visits (oldLevel absoluteCD : Expr) (a : ℕ) := + phases I first absoluteCD a false ++ phases I first absoluteCD a true ++ publications I first oldLevel + +theorem visits_length (oldLevel absoluteCD : Expr) (a : ℕ) : + (visits I first oldLevel absoluteCD a).length = 12 := by simp [visits,phases,publications] + +section Words + +variable {w : ℕ} (pub : Fin 5 → Word w) (st : Word w) (mem : Memory w) (L : Layout) +local notation "ev" => Expr.eval pub st mem + +/-- Only the site count, motif count and start of the allocated arena vary +across the linked levels. -/ +structure Ready : Prop where + sites : ev I.newSites = (L.sites : Word w) + motifs : ev I.motifs = (L.motifs : Word w) + arena : ev first = (L.first : Word w) + +variable (h : Ready I first pub st mem L) + +private theorem eval_add (a b : Expr) : ev (a.add b) = ev a + ev b := rfl +private theorem eval_mul (a b : Expr) : ev (a.mul b) = ev a * ev b := rfl +private theorem eval_lit (n : ℕ) : ev (.lit n) = (n : Word w) := rfl + +include h in +theorem size_val (maps : Bool) : ev (size I maps) = (L.size maps : Word w) := by + simp only [size,Layout.size,eval_mul,eval_lit,h.motifs,Nat.cast_mul] + +include h in +theorem owner_val (maps : Bool) : ev (owner I first maps) = (L.owner maps : Word w) := by + cases maps <;> simp [owner,Layout.owner,eval_add,h.arena,size_val I first pub st mem L h,h.sites,Nat.cast_add] + +include h in +theorem counts_val (maps : Bool) : ev (counts I first maps) = (L.counts maps : Word w) := by + simp only [counts,Layout.counts,eval_add,owner_val I first pub st mem L h,size_val I first pub st mem L h,Nat.cast_add] + +include h in +theorem rows_val (maps : Bool) : ev (rows I first maps) = (L.rows maps : Word w) := by + simp only [rows,Layout.rows,eval_add,counts_val I first pub st mem L h,h.sites,Nat.cast_add] + +include h in +theorem end_val : ev (endAddr I first) = (L.endAddr : Word w) := by + simp only [endAddr,Layout.endAddr,eval_add,rows_val I first pub st mem L h,size_val I first pub st mem L h,Nat.cast_add] + +include h in +theorem bank_val (a : ℕ) (maps : Bool) : + (fun i => ev (bank I first a maps i)) = L.params a maps w := by + funext i + fin_cases i <;> first | exact size_val I first pub st mem L h maps | exact owner_val I first pub st mem L h maps + | exact h.sites | exact counts_val I first pub st mem L h maps | rfl | exact rows_val I first pub st mem L h maps + +end Words +end CompressorRecords.ShrinkResidentsPlan + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledCharges.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledCharges.lean new file mode 100644 index 0000000000..a567546199 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledCharges.lean @@ -0,0 +1,177 @@ +import OAI.Computability.VPVNP.CompressorShrinkAllocatedTables +import OAI.Computability.VPVNP.CompressorShrinkSlotWindow +import OAI.Computability.VPVNP.CompressorScheduledSlotRates +import OAI.Computability.VPVNP.CompressorPublishedHeadWindows +import OAI.Computability.VPVNP.CompressorShrinkLevelSpace + +/-! # Tapes and traffic of the three shrinking output windows + +The native AB, surviving-width, ordered-slot and canonical-copy reports all +consume empty tapes. We count the calls of each scan and include the actual +copy reports in the bound per incoming wire position. The same statements +hold for the packet choices whenever the packets replay these reports. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkScheduledCharges + +open BurstRAM Compression ShrinkBlockInputs ShrinkOutput ShrinkSliceSweep +open SlotLevel ShrinkSlots ShrinkSlotPlan.Scheduled +open scoped Classical Fin.CommRing +open private motif_le packed_le from OAI.Computability.VPVNP.CompressorShrinkLevelSpace + +private theorem walk_tapes {J : Type*} {w : ℕ} {run : J → Memory w → List (Report w) → Prop} + {js : List J} {mem : Memory w} {rs : List (Report w)} (count : J → ℕ) + (walk : SourceWalk run js mem rs) + (one : ∀ j m log, run j m log → branchPaths log = List.replicate (count j) []) : + branchPaths rs = List.replicate ((js.map count).sum) [] := by + induction walk with + | done => rfl + | @next j js m head tail h _ ih => + rw [branchPaths,List.map_append,← branchPaths,← branchPaths,one j m head h,ih, + List.map_cons,List.sum_cons,List.replicate_add] + +/-- Incoming positions pay for the AB and width rectangles, and for the +ordered-slot scans and their physical transfers. All three rates depend +only on the fixed degrees and the subdivisions of the template. -/ +def rate (a b : ℕ) := + let d := 2^a + let q := ShrinkBundlePlan.cap a + let t := ShrinkBundlePlan.thickCount a + let u := ShrinkLevelSpace.subdivisionSum a b + let s : Shape := ⟨1,1,1,d,Shrink.colors a,Compression.ShrinkMotif.subdivisions d (Shrink.colors a) (2^b),2^b⟩ + d*(2*(t+q)+16*(t*q)) + 18*(d*q)*u + ScheduledRates.slotRate s + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {g w : ℕ} {δ : ℝ} (X : State (a i) (packingLaneBits (a i) g)) +variable (ready : ShrinkMotif.Ready (2^(a i)) (Shrink.colors (a i)) (2^(b i)) δ) (sel : SelectedScore.Selection B X) +variable (term stride abs : Word w) (start : ℕ) {I : ShrinkABSliceRecipe.Inputs} +variable {pub : Fin 5 → Word w} {st : Word w} {ref m : Memory w} {first cap : ℕ} (width slotStart : ℕ) +variable (dst : IncidenceDirectory w) (r : TablesRun w) + +local notation "sh" => levelShape (b := b i) X +local notation "role" => SelectedArena.roleBase X term stride +local notation "bank" => splitBank (b := b i) X B.shrink sel term (Fin.val stride) role width +local notation "slotHead" => heads sh role slotStart +local notation "Y" => X.shrinkNext B.shrink ready sel +local notation "src" => directory sh slotHead w +local notation "native" => r.remainder.slots +local notation "raw" => r.remainder.postWidths +local notation "copies" => CopyIncidence.reports Y src dst CopyIncidence.allColumns (after raw (eventLog (Build.Construction.all native))) +local notation "bs" => ShrinkRankSpace.Shape.B (ShrinkInput.plan X start) +local notation "ns" => ShrinkBundlePlan.thickCount (a i) +local notation "nt" => ShrinkBundlePlan.cap (a i) +local notation "nAB" => bs*(ns+nt+2*(ns*nt)) +local notation "nWidth" => motifCount X*Allocation.stride bank +local notation "nSlot" => List.sum (List.map (Stage.limit sh) constructionOrder) +local notation "nCopy" => 3*(Fintype.card (State.Base Y)*2^(b i))+3*(State.positions Y*2^(b i)) +local notation "allLogs" => r.reports++copies + +/-- Counts, costs and choice tapes for the four report lists in Parts 6–8. -/ +structure Accounted : Prop where + abCount : r.intersections.length = nAB + widthCount : r.remainder.widthRows.flatten.length = nWidth + slotCount : (native).all.length = nSlot + copyCount : (copies).length = nCopy + abTapes : branchPaths r.intersections = List.replicate nAB [] + widthTapes : branchPaths r.remainder.widthRows.flatten = List.replicate nWidth [] + slotTapes : branchPaths (native).all = List.replicate nSlot [] + copyTapes : branchPaths copies = List.replicate nCopy [] + abCost : RAMBuckets.cost Report.probes r.intersections ≤ bs*(2*(ns+nt)+16*(ns*nt)) + widthCost : RAMBuckets.cost Report.probes r.remainder.widthRows.flatten = 18*nWidth + slotCost : RAMBuckets.cost Report.probes (native).all = slotProbes sh + copyCost : RAMBuckets.cost Report.probes copies = 9*(Fintype.card (State.Base Y)*2^(b i))+9*(State.positions Y*2^(b i)) + linear : RAMBuckets.cost Report.probes allLogs ≤ X.positions*rate (a i) (b i) + +set_option maxHeartbeats 1400000 in +/-- Account for the reports of a completed three-table run and the six copies +which follow it in the ordered-slot window. -/ +theorem accounted (run : CompleteTables B i X ready sel term stride abs start I pub st ref first width slotStart cap m r) : + Accounted B i X ready sel term stride start width slotStart dst r := by + have ab := ScheduledRates.scheduledABCounts I pub st ref run.abRun + have abTapes := walk_tapes (fun _ ↦ bs) run.abRun (fun _ _ _ h ↦ ((runSegment_iff ..).mp h).2.2) + have abNumber : ((ShrinkABSliceRecipe.phases ns nt).map (fun _ ↦ bs)).sum = nAB := by + have eq := congrArg List.length abTapes + simpa only [branchPaths,List.length_map,List.length_replicate,ab.1] using eq.symm + rw [abNumber] at abTapes + have wc := run.remainder.sweep.calls + have widthBits : branchPaths r.remainder.widthRows.flatten = List.replicate nWidth [] := by + rw [← wc] + apply List.eq_replicate_iff.mpr + refine ⟨List.length_map _,?_⟩ + intro tape ht + obtain ⟨rep,hr,rfl⟩ := List.mem_map.mp ht + obtain ⟨_,_,site⟩ := run.remainder.sweep.sites hr + exact site.bits + have slot := run.remainder.construction + have phases := construction_sources (ShrinkSlotCalendar.plan B i) sh slotHead (selectedLayout X B.shrink sel) + (bank).widthBase dst native raw slot.slots + have slotTapes := walk_tapes (Stage.limit sh) phases (fun _ _ _ h ↦ ((runSegment_iff ..).mp h).2.2) + have slotCount : (native).all.length = nSlot := by + simpa only [branchPaths,List.length_map,List.length_replicate] using congrArg List.length slotTapes + have cp := ScheduledRates.copyColumns Y src dst (after raw (eventLog (Build.Construction.all native))) + have copyBits : branchPaths copies = List.replicate nCopy [] := by + apply List.eq_replicate_iff.mpr + refine ⟨(List.length_map _).trans cp.2.1,?_⟩ + intro tape ht + obtain ⟨rep,hr,rfl⟩ := List.mem_map.mp ht + exact (CopyIncidence.reports_work Y src dst CopyIncidence.allColumns _).2.2 rep hr |>.2.2 + have widthCost : RAMBuckets.cost Report.probes r.remainder.widthRows.flatten = 18*nWidth := by + have c := run.remainder.probes + rw [Passes.reports,RAMBuckets.cost_append,← slot.probes] at c + exact Nat.add_right_cancel c + refine ⟨ab.1,wc,slotCount,cp.2.1,abTapes,widthBits,slotTapes,copyBits,ab.2.1,widthCost, + slot.probes,cp.2.2.1,?_⟩ + have slotTotal := (ScheduledRates.selectedSlotProgram X B.shrink ready sel slotHead (bank).widthBase + dst raw native slot.slots).2.1 + rw [Build.Construction.final_eq] at slotTotal + let d := 2^(a i) + let u := ShrinkLevelSpace.subdivisionSum (a i) (b i) + let abWeight := 2*(ns+nt)+16*(ns*nt) + have bFit : bs ≤ X.positions*d := Nat.mul_le_mul_right d (packed_le X) + have mFit : motifCount X ≤ X.positions*(d*nt) := motif_le X + have cAB := ab.2.1.trans (Nat.mul_le_mul_right abWeight bFit) + have cWidth : RAMBuckets.cost Report.probes r.remainder.widthRows.flatten ≤ 18*((X.positions*(d*nt))*u) := + widthCost.le.trans (Nat.mul_le_mul_left 18 (Nat.mul_le_mul_right u mFit)) + change RAMBuckets.cost Report.probes ((r.intersections++(r.remainder.widthRows.flatten++(native).all))++copies) ≤ + X.positions*(d*abWeight+18*(d*nt)*u+ScheduledRates.slotRate sh) + rw [List.append_assoc,List.append_assoc,RAMBuckets.cost_append,RAMBuckets.cost_append] + calc + _ ≤ (X.positions*d)*abWeight+(18*((X.positions*(d*nt))*u)+X.positions*ScheduledRates.slotRate sh) := + Nat.add_le_add cAB (Nat.add_le_add cWidth slotTotal) + _ = _ := by ring + +/-- The AB intersection probes depend on the widths. Once that observed charge +is fixed, the remaining three scans have the following exact charge. -/ +theorem Accounted.exact_cost (h : Accounted B i X ready sel term stride start width slotStart dst r) : + RAMBuckets.cost Report.probes allLogs = RAMBuckets.cost Report.probes r.intersections + + (18*nWidth + slotProbes sh) + (9*(Fintype.card (State.Base Y)*2^(b i)) + 9*(State.positions Y*2^(b i))) := by + simp only [TablesRun.reports,Passes.reports,RAMBuckets.cost_append,h.widthCost,h.slotCost,h.copyCost] + +/-- The actual packet tapes and their source charge for the concatenation of +all three windows. The only input about the packets is their verified native +chronology and the equality of the four flattened report lists. -/ +theorem Accounted.packets (h : Accounted B i X ready sel term stride start width slotStart dst r) + {A : BlockPlanner.Script} (input : Memory w) (ps : List (SourceOnline.Packet A w)) + (chron : SourceWalk.Chronological SourceOnline.Visit.Runs input ps) + (reports : ps.flatMap SourceWalk.Packet.reports = allLogs) : + ps.flatMap (fun p => p.stage.choices) = List.replicate (nAB+nWidth+nSlot+nCopy) [] ∧ + RAMBuckets.cost Report.probes (ps.flatMap SourceWalk.Packet.reports) ≤ X.positions*rate (a i) (b i) := by + rw [PublishedHeads.chronological_tapes input ps chron,reports] + refine ⟨?_,h.linear⟩ + have join (xs ys : List (Report w)) : branchPaths (xs++ys) = branchPaths xs++branchPaths ys := List.map_append + simp only [TablesRun.reports,Passes.reports,join,h.abTapes,h.widthTapes,h.slotTapes,h.copyTapes] + simp only [List.replicate_add,List.append_assoc] + +end CompressorRecords.ShrinkScheduledCharges + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledFinish.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledFinish.lean new file mode 100644 index 0000000000..6aefed2465 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledFinish.lean @@ -0,0 +1,108 @@ +import OAI.Computability.VPVNP.CompressorShrinkScheduledOutput +import OAI.Computability.VPVNP.CompressorShrinkScheduledTail + +/-! # The output graph and final history records of a scheduled shrinking step + +The selected geometry feeds the resident-directory builders, interval scans and +canonical slot copies. The three final publications then run in the memory +produced by those copies. Their endpoint is the exact last visit of the +shrinking substep, including all static rectangle subdivisions. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkScheduledFinish + +open BurstRAM Compression BlockPlanner DescriptorSpace SourceOnline +open ShrinkBlockInputs ShrinkOutput +open scoped Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X) +variable (base : Word w) (positions blocks round cap : ℕ) +local notation "prog" => BlockProgram.script B +local notation "space" => BlockProgram.layout B (Fin.val base) positions blocks +local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog prog)) base +local notation "fst" => Script.levelsPerBlock prog * round +local notation "idx" => fst+i.val +local notation "tab₀" => tableBase space idx (0 : Fin 6) +local notation "oldInc" => packedIncidence space w idx (DemandRAM.oldCount X) +local notation "P₀" => SourceOnline.Packet prog w +local notation "ord" => ShrinkForward.first B i round + +/-- The four output windows occupy precisely the interval between the end +of selected geometry and the first metadata publication. -/ +theorem output_length {m : Memory w} {a₅ a₆ a₇ a₈ : List P₀} {r : TablesRun w} + (out : ScheduledShrink.Output B i X sel base positions blocks round cap m a₅ a₆ a₇ a₈ r) : + 36 + (((a₅++a₆)++a₇)++a₈).length = ShrinkForward.visitsBefore B i 9 := by + let parts := BlockGroups.parts B i + have sizes := congrArg List.length out.indices + simp only [List.length_map,List.length_append] at sizes + have first : ShrinkForward.visitsBefore B i 5 = 36 := by + change ((BlockGroups.parts B i).take 5).flatten.length = 36 + rw [show ((BlockGroups.parts B i).take 5).flatten = ShrinkBlockInputs.beforeSlices B + (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0) by + simp only [BlockGroups.parts,ShrinkBlockInputs.beforeSlices,List.take_succ_cons, + List.take_zero,List.flatten_cons,List.flatten_nil,List.append_nil,List.append_assoc]] + exact ShrinkBlockInputs.beforeSlices_length .. + have offset (j : ℕ) (live : j < 12) : + ShrinkForward.visitsBefore B i (j+1) = ShrinkForward.visitsBefore B i j + + (parts[j]'(by change j < 12; exact live)).length := by + simp only [ShrinkForward.visitsBefore,List.take_succ_eq_append_getElem + (show j < (BlockGroups.parts B i).length by change j<12; exact live),List.flatten_append, + List.flatten_cons,List.flatten_nil,List.append_nil,List.length_append,parts] + have h₅ : (ShrinkResidentPackets.window B i).indices.length = (parts[5]'(by change 5<12; decide)).length := List.length_ofFn + have h₆ : (BlockSlices.abWindow B i).indices.length = (parts[6]'(by change 6<12; decide)).length := List.length_ofFn + have h₇ : (SurvivingPackets.window B i).indices.length = (parts[7]'(by change 7<12; decide)).length := List.length_ofFn + have h₈ : (BlockGroups.shrink B i 8).indices.length = (parts[8]'(by change 8<12; decide)).length := List.length_ofFn + rw [h₅,h₆,h₇,h₈] at sizes + have e₅ := offset 5 (by decide) + have e₆ := offset 6 (by decide) + have e₇ := offset 7 (by decide) + have e₈ := offset 8 (by decide) + norm_num1 at e₅ e₆ e₇ e₈ + simp only [List.length_append] + omega + +/-- The twenty-one final deterministic calls close the substep. -/ +theorem tail_length : + ShrinkForward.visitsBefore B i 9 + 21 = (BlockProgram.shrink B i).length := by + rw [← BlockGroups.parts_flatten] + rw [← List.take_append_drop 9 (BlockGroups.parts B i),List.flatten_append,List.length_append] + change ShrinkForward.visitsBefore B i 9 + 21 = ShrinkForward.visitsBefore B i 9 + _ + apply congrArg (ShrinkForward.visitsBefore B i 9 + ·) + change 21 = 3+4+14 + decide + +/-- All six output and publication lists retain their actual native executions. +The metadata subgroup is a prefix of the three final publication groups. -/ +structure Finish (input : Memory w) (a₅ a₆ a₇ a₈ ms tail : List P₀) (r : TablesRun w) : Prop where + output : ScheduledShrink.Output B i X sel base positions blocks round cap input a₅ a₆ a₇ a₈ r + published : ShrinkScheduledTail.Result B base positions blocks round cap i X + (post input (((a₅++a₆)++a₇)++a₈)) ms tail + group : Group prog space base cap (ord+36) (directoryRows space) input ((((a₅++a₆)++a₇)++a₈)++tail) + length : 36 + ((((a₅++a₆)++a₇)++a₈)++tail).length = (BlockProgram.shrink B i).length + +theorem join {input : Memory w} {a₅ a₆ a₇ a₈ ms tail : List P₀} {r : TablesRun w} + (out : ScheduledShrink.Output B i X sel base positions blocks round cap input a₅ a₆ a₇ a₈ r) + (pubs : ShrinkScheduledTail.Result B base positions blocks round cap i X + (post input (((a₅++a₆)++a₇)++a₈)) ms tail) : + Finish B i X sel base positions blocks round cap input a₅ a₆ a₇ a₈ ms tail r := by + have sizes := output_length B i X sel base positions blocks round cap out + refine ⟨out,pubs,out.group.append ?_,?_⟩ + · have h := pubs.group + change Group prog space base cap ((ord+36)+_) _ _ _ + rw [Nat.add_assoc,sizes]; exact h + · rw [List.length_append,← Nat.add_assoc,sizes,pubs.length,tail_length] + +end CompressorRecords.ShrinkScheduledFinish + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledGeometry.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledGeometry.lean new file mode 100644 index 0000000000..e587b77985 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledGeometry.lean @@ -0,0 +1,174 @@ +import OAI.Computability.VPVNP.CompressorShrinkScheduledPrefix +import OAI.Computability.VPVNP.CompressorShrinkSelectedGroup +import OAI.Computability.VPVNP.CompressorShrinkGeometryHeadRetention +import OAI.Computability.VPVNP.CompressorSourceGroupSplit +import OAI.Computability.VPVNP.CompressorBlockShrinkPrefixFits + +/-! +# The shrinking calendar through the selected geometry + +The first twenty-one visits prepare the physical selector input. One visit +runs the prescribed selection. The following fourteen visits score its +terms and build the selected placement, role, and child directories. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkScheduledGeometry + +open BurstRAM BlockPlanner DescriptorSpace Compression BlockHeaderRun SourceOnline SourceTransport +open ShrinkSlots SlotLevel +open scoped Fin.CommRing + +variable {w : ℕ} + +private theorem below_data {A : Script} {L : Layout} {base : Word w} {cap ord total : ℕ} + {m : Memory w} {ps : List (Packet A w)} (run : Group A L base cap ord total m ps) + {x : ℕ} (hx : x < levelStart L 0) : post m ps x = m x := by + apply after_outside m (data := (levelStart L 0 ≤ ·)) _ (Nat.not_le_of_gt hx) + intro a value ha + change Event.write a value ∈ (ps.flatMap SourceWalk.Packet.reports).flatMap Report.events at ha + obtain ⟨r,hr,ev⟩ := List.mem_flatMap.mp ha + obtain ⟨q,hq,hr⟩ := List.mem_flatMap.mp hr + exact (run.checked q hq).write a value (List.mem_flatMap.mpr ⟨r,hr,ev⟩) + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) +variable {g w : ℕ} (X : GreedyArena.ShrinkingState (ShrinkBlockInputs.a i) g) +variable (sel : SelectedScore.Selection B X) (tape : List Bool) (base : Word w) (positions blocks t : ℕ) +local notation "prog" => BlockProgram.script B +local notation "L" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog (BlockProgram.script B))) base +local notation "first" => (S.steps+1)*t +local notation "level" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape +local notation "offset" => List.length (Script.initial prog)+t*List.length (Script.block prog)+List.length (BlockIndex.earlier B i) +local notation "total" => directoryRows L +local notation "H" => levelStart L 0 +local notation "Pkt" => SourceOnline.Packet prog w +variable (old new : Fin (BlockProgram.layout B base.val positions blocks).levels) (m : Memory w) +local notation "start" => tableBase L old (0 : Fin 6) +local notation "T" => packedIncidence L w old (DemandRAM.oldCount X) +local notation "initial" => finalMemory level L old new m +local notation "headers" => BlockHeaderRun.reports level L old new m +local notation "s" => levelShape (b := ShrinkBlockInputs.b i) X +local notation "rawHeader" => ShrinkHeaderReads.Header i X T start L first +local notation "headBank" => PortRefresh.TraversalHeaders.HeadBank L + +set_option maxHeartbeats 1800000 + +/-- A scheduled execution of shrink geometry in 36 packets. The 21 prefix packets, selector and +14 suffix packets reproduce the branch events and leave the required headers and head banks +in memory before output. -/ +structure Result (fuel : ℕ) (p : ShrinkBranch.Prefix X T start fuel initial) + (v : ShrinkBranch.Selected B X T start (10 : Word w) (B.shrink.selectorBits : Word w) fuel initial p sel) (cap : ℕ) (pre : List Pkt) (selector : Pkt) (tail : List Pkt) : Prop where + prefixGroup : Group prog L base cap offset total m pre + prefixLength : pre.length = 21 + prefixEmpty : ∀ q ∈ pre, ∀ bs ∈ q.stage.choices, bs = [] + prefixReports : pre.flatMap SourceWalk.Packet.reports = headers++p.reports + prefixPost : post m pre = p.beforeTerm + selected : Group prog L base cap (offset+21) total p.beforeTerm [selector] + selectInput : selector.input = p.beforeTerm + selectStage : selector.stage = ShrinkTermOnline.globalVisit B i X T start sel fuel .select + selectChoices : selector.stage.choices = List.ofFn (ShrinkTermSelection.tapes B.shrink X sel w) + selectReports : selector.reports = v.terms + selectOutput : selector.output = after p.beforeTerm (eventLog v.terms) + suffix : Group prog L base cap (offset+22) total selector.output tail + suffixLength : tail.length = 14 + suffixEmpty : ∀ q ∈ tail, ∀ bs ∈ q.stage.choices, bs = [] + suffixTapes : tail.flatMap (fun q => q.stage.choices) = List.replicate (SelectedTailPackets.selectedCalls X) [] + suffixEvents : eventLog (tail.flatMap SourceWalk.Packet.reports) = eventLog v.geometry.reports + whole : Group prog L base cap offset total m (pre++selector::tail) + length : (pre++selector::tail).length = 36 + events : eventLog ((pre++selector::tail).flatMap SourceWalk.Packet.reports) = + eventLog ((headers++p.reports)++v.reports) + final : post m (pre++selector::tail) = v.beforeOutput + beforeHeader : rawHeader p.beforeTerm + beforeRows : p.beforeTerm (pt).rows.val = (total : Word w) + beforePitch : p.beforeTerm ((pt).directory-1).val = (levelWords L : Word w) + header : rawHeader v.beforeOutput + rows : v.beforeOutput (pt).rows.val = (total : Word w) + pitch : v.beforeOutput ((pt).directory-1).val = (levelWords L : Word w) + oldHeads : headBank old (DemandRAM.oldCount X) v.beforeOutput + nextHeads : headBank new (actualCount s) v.beforeOutput + frame : ∀ x, x < start ∨ levelStart L new ≤ x → v.beforeOutput x = initial x + +/-- Join the deterministic prefix, prescribed selector and deterministic +geometry at their exact calendar ordinals and machine memories. -/ +theorem run (fuel : ℕ) (p : ShrinkBranch.Prefix X T start fuel initial) + (v : ShrinkBranch.Selected B X T start (10 : Word w) (B.shrink.selectorBits : Word w) fuel initial p sel) (oldAt : first+i.val=old.val) (next : old.val+1=new.val) + (sub : Substep level L old new (by change 6 ≤ 54; decide) m) + (fits : ShrinkBranch.PrefixFits B X T start (10 : Word w) fuel) + (oldHeads : headBank old (DemandRAM.oldCount X) m) + (low : ∀ c, H ≤ ((T).column c).val) (room : endAddress L < 2^w) + (sitesFit : X.positions ≤ positions) (within : t < blocks) + (rows : m (pt).rows.val = (total : Word w)) (pitch : m ((pt).directory-1).val = (levelWords L : Word w)) + (cap : ℕ) (headerClock : ShrinkHeaderGreedyPackets.clock B i ≤ cap) + (denseClock : scanCap prog (ShrinkBundlePackets.maxFuel B i) ≤ cap) + (termClock : scanCap prog fuel ≤ cap) (geometryClock : scanCap prog 65 ≤ cap) : + ∃ pre selector tail, Result B f hf i X sel tape base positions blocks t old new m fuel p v cap pre selector tail := by + have stride : (10 : Word w).val = 10 := Nat.le_antisymm (Nat.mod_le ..) fits.wide + have termRoom := fits.termRoom + rw [stride] at termRoom + have heads (c : Fin 6) : m (incidenceHead L old c) = (T).column c := by + rw [packed_column]; exact oldHeads.incidence c + obtain ⟨pre,selector,gp,npre,empty,plogs,ppost,hin,stage,choices,logs,gs,spost,before⟩ := + ShrinkScheduledPrefix.through_selection B f hf i X sel tape base positions blocks t old new m T + oldAt next sub fuel p v heads (oldHeads.tables (0 : Fin 6)) low room termRoom rows pitch within cap headerClock + denseClock fits.gatherClock termClock + have hH := (levelStart_mono L (Nat.zero_le (L).levels)).trans_lt room + have cells := Window.lowCells (A := prog) L base rfl rfl hH + have beforeRows : p.beforeTerm (pt).rows.val = (total : Word w) := by + exact (congrFun ppost _).symm.trans ((below_data gp cells.1).trans rows) + have beforePitch := before.entry.pitch + have geomRoom := ShrinkBranch.selected_geometry_fit B i X base.val positions blocks old sitesFit room + obtain ⟨tail,gt,ntail,tailEvents,tailPost,tailChoices⟩ := + SelectedTailPackets.selected_group B i X T start base positions blocks t sel initial fuel cap + p v fits geomRoom before.raw before.fieldsBelow low beforeRows beforePitch within room geometryClock + have selectGroup := gs.split.2 + rw [npre,ppost] at selectGroup + have selectOut : selector.output = after p.beforeTerm (eventLog v.terms) := by + simp only [SourceWalk.Packet.output,hin,logs] + have full := gs.append (by + rw [spost,List.length_append,List.length_singleton,npre]; exact gt) + have postFull : post m (pre++selector::tail) = v.beforeOutput := by + have joined := (post_append m (pre++[selector]) tail).trans + ((congrArg (fun z => post z tail) spost).trans tailPost) + simpa only [List.append_assoc,List.singleton_append] using joined + have gfull : Group prog L base cap offset total m (pre++selector::tail) := by + simpa only [List.append_assoc,List.singleton_append] using full + have keep (x : ℕ) (hx : x < start) : v.beforeOutput x = p.beforeTerm x := by + have ranges := ShrinkInput.range_bounds X start + have oldLimit := hx.trans_le (ranges.1.trans (ranges.2.1.trans (ranges.2.2.1.trans ranges.2.2.2))) + have stopFit : ShrinkInput.stop X start < 2^w := by unfold ShrinkInput.termEnd at termRoom; omega + have daddr : (ShrinkInput.demandHead (w := w) X start).val = ShrinkInput.stop X start := Nat.mod_eq_of_lt stopFit + exact (v.lowerFrame x oldLimit).trans (p.gatherRun.frame x (.inl (by + change x < (ShrinkInput.demandHead (w := w) X start).val; rwa [daddr]))).symm + have afterHeader := before.keep_below keep + have banks := ShrinkGeometryHeadBanks.beforeOutput_heads B i X sel base.val positions blocks old new + f hf tape next m sub p v oldHeads sitesFit room + have frame := ShrinkGeometryHeadBanks.beforeOutput_frame B i X sel base.val positions blocks old new + next p v sitesFit room + refine ⟨pre,selector,tail,gp,npre,empty,plogs,ppost,selectGroup,hin,stage,choices,logs,selectOut, + selectOut.symm ▸ gt,ntail,?_,tailChoices,tailEvents,gfull,?_,?_,postFull,before.raw,beforeRows,beforePitch, + afterHeader.raw,?_,afterHeader.entry.pitch,banks.1,banks.2,frame⟩ + · intro q hq bs hb + have hmem : bs ∈ tail.flatMap (fun q => q.stage.choices) := List.mem_flatMap.mpr ⟨q,hq,hb⟩ + rw [tailChoices] at hmem + exact (List.mem_replicate.mp hmem).2 + · rw [List.length_append,List.length_cons,npre,ntail] + · simp only [List.flatMap_append,List.flatMap_cons,plogs,logs,ShrinkBranch.Selected.reports, + eventLog,List.append_assoc] at tailEvents ⊢ + rw [tailEvents] + · rw [← postFull]; exact (below_data gfull cells.1).trans rows + +end CompressorRecords.ShrinkScheduledGeometry + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledOutput.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledOutput.lean new file mode 100644 index 0000000000..21700e2268 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledOutput.lean @@ -0,0 +1,149 @@ +import OAI.Computability.VPVNP.CompressorShrinkScheduledResidents +import OAI.Computability.VPVNP.CompressorShrinkTablesPhysical +import OAI.Computability.VPVNP.CompressorShrinkABSliceGroup +import OAI.Computability.VPVNP.CompressorShrinkSurvivingPackets +import OAI.Computability.VPVNP.CompressorShrinkSlotPhysicalGroup +import OAI.Computability.VPVNP.CompressorShrinkScheduledRetention + +/-! # The four post-selection groups of a physical shrinking substep + +On each admitted branch the hidden/map directory visits precede the AB +intervals, the four surviving-role scans and the ordered-slot/copy visits. +The AB and surviving packets use the actual reports of the same three-table +construction. The final memory carries the new canonical incidence directory +and all old-level data read by the backward traversal. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ScheduledShrink + +open BurstRAM Compression ShrinkBlockInputs DescriptorSpace SourceOnline BlockPlanner ShrinkOutput +open SlotLevel ShrinkSlots ShrinkSliceSweep +open scoped Classical Fin.CommRing + +variable {k : Type*} [_root_.Field k] {S : BlockSchedule k} (B : S.Templates) (i : Fin S.steps) +variable {w g : ℕ} (X : State (a i) (packingLaneBits (a i) g)) (sel : SelectedScore.Selection B X) +variable (base : Word w) (positions blocks round : ℕ) +local notation "prog" => BlockProgram.script B +local notation "space" => BlockProgram.layout B base.val positions blocks +local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog prog)) base +local notation "pub" => Schedule.Ports.data pt +local notation "first₀" => Script.levelsPerBlock prog * round +local notation "old₀" => first₀+i.val +local notation "next₀" => old₀+1 +local notation "tab" => (fun j : Fin 6 => tableBase space old₀ j) +local notation "st₀" => (levelStart space first₀ : Word w) +local notation "term" => ShrinkInput.termHead (w := w) X (tab 0) +local notation "abs₀" => ShrinkResidentPackets.absoluteWord (w := w) X (tab 0) +local notation "T" => packedIncidence space w old₀ (DemandRAM.oldCount X) +local notation "sh" => levelShape (b := b i) X +local notation "Pkt" => SourceOnline.Packet prog w +local notation "headWords" => PortRefresh.TraversalHeaders.HeadBank space +local notation "I" => BlockSlices.abInputs i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 1) +local notation "part₅" => ShrinkResidentPackets.window B i +local notation "part₆" => BlockSlices.abWindow B i +local notation "part₇" => SurvivingPackets.window B i +local notation "part₈" => BlockGroups.shrink B i 8 +local notation "h" => ShrinkOutput.heads sh (SelectedArena.roleBase X term (10 : Word w)) (tab 3) +local notation "Y" => X.shrinkNext B.shrink (S.shrink i) sel +local notation "dst" => packedIncidence space w next₀ (actualCount sh) + +private theorem offset_succ {j : ℕ} (hj : j+1 < 12) : + (BlockGroups.shrink B i ⟨j+1,hj⟩).before.length = + (BlockGroups.shrink B i ⟨j,by omega⟩).before.length+ + ((BlockGroups.parts B i)[j]'(by change j < 12; omega)).length := by + rw [BlockGroups.shrink_offset,BlockGroups.shrink_offset] + simp only [List.take_succ_eq_append_getElem (show j < (BlockGroups.parts B i).length by change j < 12; omega), + List.flatten_append,List.flatten_cons,List.flatten_nil,List.append_nil,List.length_append,Nat.add_assoc] + +/-- A consecutive trace and the native reports consumed by its calendar windows. -/ +structure Output (cap : ℕ) (input : Memory w) (ps₅ ps₆ ps₇ ps₈ : List Pkt) (r : TablesRun w) : Prop where + residents : Residents B i X sel base positions blocks round cap input ps₅ + tables : CompleteTables B i X (S.shrink i) sel term 10 abs₀ (tab 0) I pub st₀ (post input ps₅) + (tab 1) (tab 2) (tab 3) cap (post input ps₅) r + abReports : ps₆.flatMap SourceWalk.Packet.reports = r.intersections + widthReports : ps₇.flatMap SourceWalk.Packet.reports = r.remainder.widthRows.flatten + slotReports : ps₈.flatMap SourceWalk.Packet.reports = r.remainder.slots.all ++ + CopyIncidence.reports Y (directory sh h w) dst CopyIncidence.allColumns + (after r.remainder.postWidths (eventLog r.remainder.slots.all)) + group : Group prog space base cap ((prog).initial.length+round*(prog).block.length+(BlockIndex.earlier B i).length+36) + (directoryRows space) input (((ps₅++ps₆)++ps₇)++ps₈) + indices : (((ps₅++ps₆)++ps₇)++ps₈).map (fun p => p.stage.phase) = + (((part₅).indices++(part₆).indices)++(part₇).indices)++(part₈).indices + postWidth : post input ((ps₅++ps₆)++ps₇) = r.remainder.postWidths + readbacks : ScheduledReadbacks B i X sel base positions blocks round T (post input (((ps₅++ps₆)++ps₇)++ps₈)) + +set_option maxHeartbeats 2600000 in +theorem output (fuel cap : ℕ) {initial : Memory w} (p : ShrinkBranch.Prefix X T (tab 0) fuel initial) + (v : ShrinkBranch.Selected B X T (tab 0) 10 (B.shrink.selectorBits : Word w) fuel initial p sel) + (hp : ShrinkBranch.PrefixFits B X T (tab 0) 10 fuel) + (header : ShrinkHeaderReads.Header i X T (tab 0) space first₀ v.beforeOutput) + (oldHeads : headWords old₀ (DemandRAM.oldCount X) v.beforeOutput) + (nextHeads : headWords next₀ (actualCount sh) v.beforeOutput) + (rows : v.beforeOutput (pt).rows.val = (directoryRows space : Word w)) + (pitch : v.beforeOutput ((pt).directory-1).val = (levelWords space : Word w)) + (live : round < blocks) (sites : X.positions ≤ positions) (room : endAddress space < 2^w) + (arithmetic : TableArithmetic B i X w) (clock : scanCap prog 95 ≤ cap) : + ∃ ps₅ ps₆ ps₇ ps₈ r, Output B i X sel base positions blocks round cap v.beforeOutput ps₅ ps₆ ps₇ ps₈ r := by + have clockAt (n : ℕ) (hn : n ≤ 95) : scanCap prog n ≤ cap := by unfold scanCap at *; omega + have sourceCap : 95 ≤ cap := by unfold scanCap at clock; omega + obtain ⟨ps₅,res⟩ := residents B i X sel base positions blocks round fuel cap p v hp header oldHeads nextHeads + rows pitch sites room live (clockAt 40 (by decide)) + let m := post v.beforeOutput ps₅ + obtain ⟨r,native,abArgs⟩ := withAB_physical B i X base positions blocks round T m (S.shrink i) sel + live sites room arithmetic res.header res.pitch (res.oldHeads.tables (1 : Fin 6)) res.tables cap sourceCap + (lt_of_lt_of_le (by decide : SurvivingNative.ops.length < 95) sourceCap) + have entry : LevelFields.Entry space first₀ pub st₀ m := ⟨rfl,res.pitch⟩ + obtain ⟨ps₆,logs₆,g₆,ids₆,_⟩ := BlockSlices.build_packets_of_run B i X base positions blocks round + m live sites room arithmetic.widthRoom res.rows res.pitch (res.header.reads B entry) + (res.oldHeads.tables (1 : Fin 6)) res.tables.demand m cap r.intersections abArgs native.abRun cap clock + have post₆ : post m ps₆ = r.postAB m := by rw [post,logs₆]; rfl + obtain ⟨ps₇,g₇,ids₇,logs₇,post₇⟩ := SurvivingPackets.group B i X T base positions blocks round sel + (S.shrink i) m m cap cap r native live sites room res.header (res.oldHeads.tables (2 : Fin 6)) + res.rows res.pitch (clockAt _ (by decide)) + obtain ⟨ps₈,g₈,ids₈,logs₈,incidence,_⟩ := ShrinkSlotCalendar.physical_group B i X base positions blocks round + T sel abs₀ I m m cap r live sites room res.rows res.pitch res.header (DemandRAM.oldCount X) + res.oldHeads res.nextHeads res.tables native cap (clockAt 49 (by decide)) + have abLength : ps₆.length = ((BlockGroups.parts B i)[6]'(by change 6 < 12; decide)).length := by + change ps₆.length = (BlockSlices.intersections i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 1)).length + simpa only [List.length_map,Window.indices,List.length_ofFn] using congrArg List.length ids₆ + have widthLength : ps₇.length = ((BlockGroups.parts B i)[7]'(by change 7 < 12; decide)).length := by + change ps₇.length = (BlockSlices.surviving B (BlockProgram.geometry B) i (BlockProgram.arena B i.val 0) (BlockProgram.arena B i.val 2)).length + simpa only [List.length_map,Window.indices,List.length_ofFn] using congrArg List.length ids₇ + have e₆ := BlockSlices.abWindow_offset B i + have e₇ : (part₇).before.length = (part₆).before.length+ps₆.length := by rw [abLength]; exact offset_succ B i (j := 6) (by decide) + have e₈ : (part₈).before.length = (part₇).before.length+ps₇.length := by rw [widthLength]; exact offset_succ B i (j := 7) (by decide) + have g₅₆ := res.group.append (show Group prog space base cap + ((prog).initial.length+round*(prog).block.length+(BlockIndex.earlier B i).length+36+ps₅.length) + (directoryRows space) m ps₆ by convert g₆ using 1; rw [e₆,res.length]; omega) + have after₆ : post v.beforeOutput (ps₅++ps₆) = r.postAB m := (post_append ..).trans post₆ + have g₅₆₇ := g₅₆.append (show Group prog space base cap + ((prog).initial.length+round*(prog).block.length+(BlockIndex.earlier B i).length+36+(ps₅++ps₆).length) + (directoryRows space) (post v.beforeOutput (ps₅++ps₆)) ps₇ by + rw [after₆]; convert g₇ using 1 + rw [List.length_append,res.length,e₇,e₆]; omega) + have after₇ : post v.beforeOutput ((ps₅++ps₆)++ps₇) = r.remainder.postWidths := by + rw [post_append,after₆,post₇] + have all := g₅₆₇.append (show Group prog space base cap + ((prog).initial.length+round*(prog).block.length+(BlockIndex.earlier B i).length+36+((ps₅++ps₆)++ps₇).length) + (directoryRows space) (post v.beforeOutput ((ps₅++ps₆)++ps₇)) ps₈ by + rw [after₇]; convert g₈ using 1 + rw [List.length_append,List.length_append,res.length,e₈,e₇,e₆]; omega) + refine ⟨ps₅,ps₆,ps₇,ps₈,r,res,native,logs₆,logs₇,logs₈,all,?_,after₇,?_⟩ + · simp only [List.map_append,res.indices,ids₆,ids₇,ids₈] + · rw [post_append,after₇] + exact scheduled_readbacks B i X sel base positions blocks round T I m m cap r ps₈ live sites room res.tables + ⟨res.published,res.directories⟩ native logs₈ incidence + +end CompressorRecords.ScheduledShrink + +end + +end VPVNP +end Computability +end OAI diff --git a/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledPrefix.lean b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledPrefix.lean new file mode 100644 index 0000000000..33ea755104 --- /dev/null +++ b/lean/OAI/Computability/VPVNP/CompressorShrinkScheduledPrefix.lean @@ -0,0 +1,181 @@ +import OAI.Computability.VPVNP.CompressorShrinkHeaderGreedyPackets +import OAI.Computability.VPVNP.CompressorShrinkHeaderGreedyTapes +import OAI.Computability.VPVNP.CompressorShrinkBundlePrepared +import OAI.Computability.VPVNP.CompressorShrinkTermGroup +import OAI.Computability.VPVNP.CompressorRecordsShrinkBranch + +/-! # The actual shrinking calendar up to the selected term rows + +The same memory that receives the three header publications feeds the greedy, +placement, bundle, and absolute-ID workers. The gather and the term selection +then use the demand widths computed by those workers. The complete prefix +has twenty-two visits at their concrete global ordinals. +-/ + +namespace OAI +namespace Computability +namespace VPVNP + +noncomputable section + +namespace CompressorRecords.ShrinkScheduledPrefix + +open BurstRAM BlockPlanner DescriptorSpace Compression BlockHeaderRun SourceOnline +open scoped Fin.CommRing + +variable {k R : Type*} [_root_.Field k] [CommRing R] {S : BlockSchedule k} +variable (B : S.Templates) (f : B.Entry → R) (hf : B.IsSolution f) (i : Fin S.steps) +variable {g w : ℕ} (X : GreedyArena.ShrinkingState (ShrinkBlockInputs.a i) g) +variable (sel : SelectedScore.Selection B X) (tape : List Bool) (base : Word w) +variable (positions blocks t : ℕ) +local notation "scr" => BlockProgram.script B +local notation "L" => BlockProgram.layout B (Fin.val base) positions blocks +local notation "pt" => Workspace.ports (Schedule.arity (Script.catalog (BlockProgram.script B))) base +local notation "H" => levelStart L 0 +local notation "first" => (S.steps+1)*t +local notation "v" => PairSimulation.TraversalRows.shrinkLevel B f hf i X sel tape +local notation "atStart" => List.length (Script.initial scr)+t*List.length (Script.block scr)+List.length (BlockIndex.earlier B i) + +variable (old new : Fin (BlockProgram.layout B (Fin.val base) positions blocks).levels) (m : Memory w) (T : IncidenceDirectory w) +local notation "start" => tableBase L old (0 : Fin 6) +local notation "headPost" => finalMemory v L old new m +local notation "hdr" => ShrinkGreedyHeaderValues.Header i X T L first start (Schedule.Ports.data pt) (levelStart L first : Word w) +local notation "Pkt" => SourceOnline.Packet scr w + +set_option maxHeartbeats 1200000 in +/-- The physical reports and memory before the first gather, together with the +published fields the term planner will read in that memory. -/ +theorem before_gather (oldAt : first+i.val=old.val) (next : old.val+1=new.val) + (sub : Substep v L old new (by change 6 ≤ 54; decide) m) (fuel : ℕ) + (p : ShrinkBranch.Prefix X T start fuel headPost) + (heads : ∀ c : Fin 6, m (incidenceHead L old c)=T.column c) + (scratch : m (tableHead L old (0 : Fin 6))=(start : Word w)) + (low : ∀ c, H ≤ (T.column c).val) + (fit : endAddress L < 2^w) (room : ShrinkInput.stop X start < 2^w) + (rows : m (pt).rows.val=(directoryRows L : Word w)) + (pitch : m ((pt).directory-1).val=(levelWords L : Word w)) + (within : t < blocks) (cap : ℕ) (headClock : ShrinkHeaderGreedyPackets.clock B i ≤ cap) + (denseClock : scanCap scr (ShrinkBundlePackets.maxFuel B i) ≤ cap) : + ∃ ps : List Pkt, Group scr L base cap atStart (directoryRows L) m ps ∧ ps.length=20 ∧ + ps.flatMap SourceWalk.Packet.reports = + (BlockHeaderRun.reports v L old new m ++ p.input.reports) ++ p.absolute ∧ + post m ps = after p.input.post (eventLog p.absolute) ∧ + hdr headPost ∧ hdr (after p.input.post (eventLog p.absolute)) ∧ + (∀ q ∈ ps, ∀ bs ∈ q.stage.choices, bs = []) := by + let absMem := after p.input.post (eventLog p.absolute) + have hH : H < 2^w := (levelStart_mono L (Nat.zero_le (L).levels)).trans_lt fit + have cells := Window.lowCells (A:=scr) L base (BlockProgram.layout_arity B ..).symm rfl hH + have here := levelStart_mono L (Nat.zero_le old.val) + have entry : LevelFields.Entry L first (pt).data (levelStart L first : Word w) m := ⟨rfl,pitch⟩ + have header : hdr headPost := ShrinkGreedyHeaderValues.post_header B i X f hf sel tape base positions blocks + T first old new oldAt.symm next.symm m sub fit _ _ entry (cells.2.trans_le here) heads scratch + have postRows := (sub.before v next (pt).rows.val (cells.1.trans_le here)).trans rows + obtain ⟨hs,hg,phases,hlogs,hpost⟩ := ShrinkHeaderGreedyPackets.group B f hf i X sel tape base + positions blocks t old new oldAt next m sub T p.input.greedy heads scratch low fit rows pitch within cap headClock + obtain ⟨ds,dg,labels,dlogs,dpost⟩ := ShrinkBundlePackets.group B i X T start base positions blocks t + p.input p.absolute p.absoluteRun room low within header postRows cap denseClock + have hlen : hs.length=9 := by + calc + hs.length = (ShrinkHeaderGreedyPackets.window B i).indices.length := by + simpa only [List.length_map] using congrArg List.length phases + _ = (ShrinkHeaderGreedyPackets.visits B i).length := List.length_ofFn + _ = 9 := ShrinkHeaderGreedyPackets.visits_length B i + have dlen : ds.length=11 := by + calc + ds.length = ShrinkBundlePackets.stages.length := by + simpa only [List.length_map,List.length_ofFn] using congrArg List.length labels + _ = 11 := by decide + rw [ShrinkBundlePackets.startOrdinal_eq] at dg + have together := hg.append (by rw [hpost,hlen]; exact dg) + have floor : start ≤ (ShrinkInput.plan X start).gathered := by + have pre := (ShrinkInput.range_bounds X start).1.trans (ShrinkInput.range_bounds X start).2.1 + apply pre.trans + change ShrinkInput.rankBase X start ≤ ((ShrinkInput.rankBase X start + 2*(ShrinkInput.plan X start).A) + + 2*(ShrinkInput.plan X start).B) + (ShrinkInput.plan X start).rectangleSize + omega + have keep (x : ℕ) (hx : x < start) : absMem x = headPost x := + (p.absoluteRun.frame x (.inl (hx.trans_le floor))).trans (p.input.below x hx) + have hempty := ShrinkHeaderGreedyPackets.empty_choices v sub p.input.greedy hg.chronological hlogs + have dempty (q : Pkt) (hq : q ∈ ds) (bits : List Bool) (hb : bits ∈ q.stage.choices) : bits = [] := by + have mem : q.stage ∈ ds.map SourceWalk.Packet.stage := List.mem_map_of_mem hq + rw [labels,List.mem_ofFn] at mem + obtain ⟨j,hj⟩ := mem + rw [← hj] at hb + exact (List.mem_replicate.mp hb).2 + refine ⟨hs++ds,together,by rw [List.length_append,hlen,dlen],?_,?_,header,header.keep_below keep,?_⟩ + · rw [List.flatMap_append,hlogs,dlogs] + simp only [ShrinkInput.Run.reports,ShrinkBundlePlan.Scheduled.preparationReports,List.append_assoc] + · rw [post_append,hpost,dpost] + · intro q hq bs hb + exact (List.mem_append.mp hq).elim (fun h => hempty q h bs hb) (fun h => dempty q h bs hb) + +set_option maxHeartbeats 1200000 in +/-- The first twenty-one visits are deterministic. The final packet runs the +true term worker on the memory built by the preceding gather, and its tapes +are the ordered words of the prescribed shrinking selection. -/ +theorem through_selection (oldAt : first+i.val=old.val) (next : old.val+1=new.val) + (sub : Substep v L old new (by change 6 ≤ 54; decide) m) (fuel : ℕ) + (p : ShrinkBranch.Prefix X T start fuel headPost) + (chosen : ShrinkBranch.Selected B X T start (10 : Word w) (B.shrink.selectorBits : Word w) + fuel headPost p sel) + (heads : ∀ c : Fin 6, m (incidenceHead L old c)=T.column c) + (scratch : m (tableHead L old (0 : Fin 6))=(start : Word w)) (low : ∀ c, H ≤ (T.column c).val) + (fit : endAddress L < 2^w) (room : ShrinkInput.termEnd X start 10 < 2^w) + (rows : m (pt).rows.val=(directoryRows L : Word w)) (pitch : m ((pt).directory-1).val=(levelWords L : Word w)) + (within : t < blocks) (cap : ℕ) (headClock : ShrinkHeaderGreedyPackets.clock B i ≤ cap) + (denseClock : scanCap scr (ShrinkBundlePackets.maxFuel B i) ≤ cap) + (gatherClock : ShrinkDemandGather.cost < fuel) (termClock : scanCap scr fuel ≤ cap) : + ∃ pre : List Pkt, ∃ last : Pkt, + Group scr L base cap atStart (directoryRows L) m pre ∧ pre.length=21 ∧ + (∀ q ∈ pre, ∀ bs ∈ q.stage.choices, bs = []) ∧ + pre.flatMap SourceWalk.Packet.reports = BlockHeaderRun.reports v L old new m ++ p.reports ∧ + post m pre = p.beforeTerm ∧ last.input = p.beforeTerm ∧ + last.stage = ShrinkTermOnline.globalVisit B i X T start sel fuel .select ∧ + last.stage.choices = List.ofFn (ShrinkTermSelection.tapes B.shrink X sel w) ∧ last.reports=chosen.terms ∧ + Group scr L base cap atStart (directoryRows L) m (pre++[last]) ∧ + post m (pre++[last]) = after p.beforeTerm (eventLog chosen.terms) ∧ + hdr p.beforeTerm := by + have stopFit : ShrinkInput.stop X start < 2^w := by unfold ShrinkInput.termEnd at room; omega + obtain ⟨ps,gp,nps,reports,post₀,hbefore,habs,empty⟩ := before_gather B f hf i X sel tape base + positions blocks t old new m T oldAt next sub fuel p heads scratch low fit stopFit rows pitch within cap headClock denseClock + let absMem := after p.input.post (eventLog p.absolute) + let ga := ShrinkTermOnline.packet B i X T start sel fuel .gather absMem p.gather + let te := ShrinkTermOnline.packet B i X T start sel fuel .select p.beforeTerm chosen.terms + have cert := ShrinkTermOnline.branch_group B i X T start sel fuel base positions blocks t cap headPost p chosen + gatherClock room hbefore.raw hbefore.fieldsBelow within termClock + have two : Group scr L base cap (atStart+20) (directoryRows L) absMem [ga,te] := cert.1 + have g := Group.singleton ga rfl two.chronological.2.1 (two.checked ga (by simp)) + (show Prepared scr L base (atStart+20) (directoryRows L) ga by simpa using two.prepared 0) + have before := gp.append (by rw [post₀,nps]; exact g) + have all := gp.append (by rw [post₀,nps]; exact two) + have preg : post m (ps++[ga]) = p.beforeTerm := by + rw [post_append,post₀] + simp only [post,List.flatMap_cons,List.flatMap_nil,List.append_nil,ga,ShrinkTermOnline.packet, + ShrinkBranch.Prefix.beforeTerm,absMem] + have daddr : (ShrinkInput.demandHead (w:=w) X start).val = ShrinkInput.stop X start := + Nat.mod_eq_of_lt stopFit + have stLe := ShrinkInput.range_bounds X start + have keep (x : ℕ) (hx : x