diff --git a/research/mixed-rank-uniform-composition/ASSEMBLY.md b/research/mixed-rank-uniform-composition/ASSEMBLY.md new file mode 100644 index 0000000000..9d0548c2d2 --- /dev/null +++ b/research/mixed-rank-uniform-composition/ASSEMBLY.md @@ -0,0 +1,54 @@ +# From two bit strings to their product + +Fix the price at κ = 0.00387992803556 and put g = 10⁻¹⁴. The fixed source word, transcript and compiler are part of the algorithm. Input data never select a different word. Use the operator and layout constructions in [COMPILER.md](COMPILER.md), [ORDINARY.md](ORDINARY.md) and [FRAMES.md](FRAMES.md). This section connects their outputs to a single fixed multitape integer machine. The resource unit V includes all bits in one complete external array, before a constant number of buffers or tapes. + +## Layout, parameters and sources + +Read two nonnegative binary integers of length at most n. Take the larger length including given leading zeros, and pad the shorter input. Treat empty or small operands by elementary multiplication. For the large branch set b = ceil(log₂ n), p = 6b, B = 2ᵇ. Obtain the unique power of two T in [4n/b,8n/b). Let ε = 1−g and β = 1−3g. Choose a power-of-two d within a factor two of p^ε, and partition it into power-of-two groups of m axes within a factor two of p^β. Choose integer powers and floors by exact power comparisons after clearing the fixed rational exponents. Use width ℓ or ℓ−1 on each of the d target axes so that their sum is log₂ T. Give axis zero maximum width. It is the contiguous suffix. Thus V = Tp satisfies 24n ≤ V < 48n. Also ℓ = Θ(p^(1−ε)), dℓ = Θ(p) and 2^O(ℓ) poly(p) = 2^o(p). All constants below are fixed before n varies. + +For signed magnitudes, retain the XOR of the sign bits and apply it to the magnitude output, giving zero its canonical sign. A fixed-width two's-complement input or output uses a single inversion-and-add-one scan on a negative value. Both conventions add O(n) time and backing. The core theorem below is stated on the unsigned digit streams. + +For each dyadic side t_i select a different odd prime r_i in ((1−1/(2p²))t_i,(1−1/(4p²))t_i]. Scan the intervals deterministically and use trial division. Trudgian's explicit bound for π(x) differs from li(x) by at most 0.2795 x (log x)^(−3/4) exp(−sqrt(log(x)/6.455)) for x ≥ 229. The main term between the two endpoints is at least t_i/(4p² log t_i). The ratio of the two errors to this term is O(p²(log t_i)^(1/4) exp(−c sqrt(log t_i))). It tends to zero because ℓ grows as a fixed positive power of p. The resulting count exceeds d. The two distinct target sizes have disjoint intervals. Full scans, trial divisions and reversals cost d·2^O(ℓ) poly(p) = o(n). This is the only large-prime counting input. [Primary theorem 2](https://arxiv.org/html/1401.2689v2#S2) · [Fine-prime construction](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/native-kappa-30201655/modern-sources/FINE-PRIME-PADDING.md) + +Set S = product r_i. Then T/2 < S < T, since the relative loss is at most d/(2p²). For b ≥ 8, S ≤ B. Each operand has at most l = ceil(n/b) digits, 2l−2 < 2n/b ≤ T/2. Allocate S cyclic coordinates with zeros past the last digit. The raw radix-B digits are less than B. Their linear convolution is also their cyclic convolution. Its coefficients are bounded by l(B−1)² < B³. These tests depend only on the input length. Reading and padding costs O(V), including exactly representing each digit divided by 4B on the p-bit fractional grid. + +## An actual router for three CRT conversions + +Set P_i = product of r_j for jn. In this case A s=r_j A c_parent>n. For a root port, the same strict inequality follows from the definition of G applied to the extended target list. The rank interval is therefore n/A1/A and 0249/250. These inequalities give both base and η bounds from integer comparisons in Funding.lean. At the source carriers n=2^H the same file checks (H+1)^p<2^(Hδ) for H=1285200000000000, δ=1/400000000000 on BIT, and H=15171300000000000000, δ=1/10^14 on the complex side. Thus each actual finite word has P_n/B_nd^g. Since e_{j−1}≤d/N^(j−1), N^j3 ensures the h^(1/250) term is o(h) on this range. [Depth and product stock in the complete support argument](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/kappa-rebuild/transfer-audit/OUTER-TRANSFER-AUDIT.md) + +Reserve these chunks before transforming their selected bits. Complete the active tensor layer on the other true axes. The compact controls, all prefix rows and every other spectator are restored for arbitrary original contents, so the selected bits inside reserved chunks can be processed in the next phase. Pad a complete leading row block once to a stock multiple. Remove that padding after the whole phase returns and before exposing another group. The total number of unfinished selected bits shrinks by at least 16, and a geometric sum of every positive power of the phase widths costs a fixed multiple of its first term. Add one polylogarithmic sequential tail and the cost of at most O(log(d+1)) phase setups. Each phase's complete exposure and inverse, arithmetic, cleanup and full-field return are included. The number of complex denominators created by finished disjoint layers sums over the d selected bits. Only one currently active phase requires unfinished guard precision. The remaining numerical height and layout proof is a property of the actual primitive frame. A product caller still needs to produce the required complete global tensor on the proved precision grid and to recover its integer output. The complete-width supplier result alone does not prove those implications. diff --git a/research/mixed-rank-uniform-composition/EVIDENCE.json b/research/mixed-rank-uniform-composition/EVIDENCE.json new file mode 100644 index 0000000000..dfb769b4d5 --- /dev/null +++ b/research/mixed-rank-uniform-composition/EVIDENCE.json @@ -0,0 +1,129 @@ +{ + "base": "e54523517d0f03e58352e647c403a5af3e525a57", + "mixed": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "native": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "submitted_kappa": "0.00387992803556", + "ordinary_bit": "0.003879928035646", + "complex_trial": "0.00387992803563", + "balanced_crt_saving": "0.003879928035626", + "pinned_replays": { + "RESULT.json": "036eb36b24467b6842e1348a49ec6ca7ac87d3e66c5856cfadf6d387189ea360", + "BIT.json": "8744587b49787bd9bfaed28a2595069d91afa45274284049bbba9764bc704a7d", + "AUDIT.json": "a4f318b83a810758bc9dc80eec15326e2794441f36d872aa24811b61c5d9f376", + "APPLICATION.json": "2bf9baed27a0b26fded815b061466ee6ceba4c05549818604b3d5bdcbcd8e50b" + }, + "independent_byte_comparisons": [ + "AUDIT.json", + "APPLICATION.json" + ], + "producer_input_pins": { + "direct": 21, + "inherited": 127 + }, + "original_atlas_sha256": "c7173d46c95d1311b8b18a92c874fb7013c6e694aa8e9c0c256f0f1eaf1ede74", + "source_markers": [ + "root c, exact context product bit length, compiler H 856 14083 15171300000000000000", + "live wide row/return occurrences 133360", + "complete radix-padded opaque records 877896", + "ordered ordinary wrapper checks 192", + "PASS_GRADE14_ALL_COLUMN_COMPLEX", + "PASS_GRADE14_ALL_COLUMN_BIT", + "PASS_GRADE14_COMPLETE_LOCAL_RING", + "PASS_NATIVE_ATLAS_BUILD c7173d46c95d1311b8b18a92c874fb7013c6e694aa8e9c0c256f0f1eaf1ede74", + "PASS_MIXED_CUTOFF_BIT_FINITE 0.003879928035646", + "PASS_COMPLETE_CONDITIONAL_APPLICATION 0.00387992803556", + "PASS_INDEPENDENT_MIXED_CUTOFF_CONDITIONAL_APPLICATION 0.00387992803556", + "PASS_PINNED_COMPLETE_APPLICATION_AND_NATIVE_REPLAYS" + ], + "finite_probe_outputs": [ + "PASS 10404 frame returns, depth 1000, 49 literal transitions", + "exact power margins {'hadamard': '398836021589323/10000000000000000000000000000', 'support': '12470900539733/250000000000000000000000000', 'group_scan': '49806003598221/50000000000000', 'boundary': '399612007196441/10000000000000000000000000000', 'union': '4062500000000399612007196441/10000000000000000000000000000', 'shrinking_halo': '228112875224889/3125000000000', 'physical_crt_if_admitted': '1/50000000000000'}", + "finite structural axis test reports (64, 20, 12, '1.8052171415990367e-09') (64, 20, 12, '0.001273014847014439')", + "sparse tag classes, smallest RHS count, total visits (10, 12, 2373)", + "Common complete Hadamard calls and exact matrix entries (18, 8192)", + "Exact signed Gaussian/ring coordinates in three fixtures 1152", + "r, t, max mass, left/right wrap, repeated slots, independent entries = (1013, 1024, 36164157998, 36, 36, 0, 387)", + "r, t, max mass, left/right wrap, repeated slots, independent entries = (2029, 2048, 39907467270, 36, 36, 0, 761)", + "r, t, max mass, left/right wrap, repeated slots, independent entries = (3, 4, 0, 27, 28, 55, 88)", + "PASS_PHYSICAL_GAUSSIAN_ADMISSION", + "741503 x 466013 = 345550037539 coefficients [11811, 10996, 4152, 868, 77]", + "PASS_JOINED_SMALL_GEOMETRY", + "PASS_REGISTERED_RESEARCH_PACKAGE research/mixed-rank-uniform-composition outcome=completed" + ], + "lean": { + "version": "4.34.1", + "mathlib": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "toolchain": "5045d0056413266e57c625dcd7c365b10e377c52", + "source_sha256_by_replayed_module": { + "CertifiedPrices": "83b63bd13bdaf420341f0d6f07b67ee54679816afa7f6aaa328dcaa8f4a3fb31", + "CompilerFlow": "ff57d08eb6c23c67feb4c1d657281e22a26cbb0de0a4f7d3e7cfdfd2e7d18bb6", + "Coordinates": "c0601a69c99000d5cbee65d96d1f39d31b6fe0010cc4c778e0fc416e54055d71", + "CoverRows": "ed0d031fd2a01a2ceaf5c18ad5f30616371b72e4c9697855736423123a0f0a61", + "DyadicRoot": "57dc67c7f0e8932816aec23c9990a216f6436439058384f34d50cc32f4e85ec0", + "Funding": "803b8df70ae71c2b762d381eb39f015553830fcdbaa639ec0183480f9d087b59", + "HaloRadius": "8c3096925a17d734340b660575f649651e56f150cf6fb9cd69078c0bd4712cd1", + "Integrated": "6e0e9b8d8911f1472df65fbd55e729da124c7302e284e7aaea2c9f0f98f9c270", + "OuterPrices": "f95f1629093a62b2217acbcc8eec8b7d2145a4963fcf43a9d9e8437f00bcfdac", + "PhaseBudget": "ec65e92658f2760b74de0c0027ac41e8fcdc2b34ace91378da691eb42b2c1d06", + "PhysicalFrames": "2731fc91cd4ba80806582d15bbd277c627ead764a6f69cf850ef73c7980948be", + "PublicGrid": "6ed96159ceee72d1660aebe74043a7ddf9dd450cd7aff8629f2fc9949495704b", + "RankMoments": "fdb68804f855c06afbbfb7126ddf9eeb042b2233b257c4b801bedbf7751a89d0", + "RankOneBridge": "9f2cb7f66e003aecc3b4cf2ada4b1afbd5eb3e8eaa0be0d123383e02da3971fd", + "RationalInverse": "c9d2f0ae1eedd7c1865106de85d019ca59b731320bcfa0a2e0fc72a38a5b79f2", + "Recovery": "96512c735c35f62c609ca4e6e08f0b3343d7f40aeba6985fc0e0b4c9cb428b8e", + "SyntheticBridge": "83baaf76d4827e7a903fd6fa7bcfd02cffdc31f9f7917bbeb582ca7753cffc09" + }, + "printed_theorems": 103, + "axiom_union": [ + "Classical.choice", + "Quot.sound", + "propext" + ], + "central_declarations": { + "CertifiedPrices.mixed_prices": [ + "propext", + "Classical.choice", + "Quot.sound" + ], + "MixedCompiler.admitted_source": [ + "propext", + "Quot.sound" + ], + "MixedRankIntegrated.physical_character": [ + "propext", + "Classical.choice", + "Quot.sound" + ], + "MixedRankPrices.costs_fit": [ + "propext", + "Classical.choice", + "Quot.sound" + ], + "MixedRankPublicGrid.grid_product_at_physical_coordinates": [ + "propext", + "Classical.choice", + "Quot.sound" + ], + "PhysicalFrames.leave_correct": [ + "propext", + "Quot.sound" + ], + "RankOneBridge.covered_good": [ + "propext", + "Classical.choice", + "Quot.sound" + ], + "RationalInverse.fineGaussianInverse": [ + "propext", + "Classical.choice", + "Quot.sound" + ], + "SyntheticBridge.clearedCharacter": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + } + }, + "scope": "Written all-size time and construction proof with partial Lean formalization and finite source-binding checks. No practical complete-carrier execution or independent scientific acceptance." +} diff --git a/research/mixed-rank-uniform-composition/FRAMES.md b/research/mixed-rank-uniform-composition/FRAMES.md new file mode 100644 index 0000000000..c4fc29a6e2 --- /dev/null +++ b/research/mixed-rank-uniform-composition/FRAMES.md @@ -0,0 +1,53 @@ +# Physical frames and exact phase changes for the mixed-cut supplier + +This note concerns the two suppliers of the [mixed-cut multiplication claim](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-mixed-rank-supplier/PROOF.md) at κ = 0.00387992803556. It describes a fixed-tape realization of the ownership boundary and a common-format invariant across the deferred complex phases. All quantities denoted by a fixed constant can depend on the compiled finite word and its prime. They cannot depend on input length. + +## A physical recursive call + +Use a finite number of physical one-head tapes. Each private work tape holds a stack of adjacent intervals. One interval has a beginning marker, at least one data cell, and a terminal marker. Data cells represent a symbol of the working alphabet, including its blank symbol. One additional bit can hold a suspended-head mark. The right terminal is one cell beyond the largest coordinate visited in this frame. Use one physical outside blank for unused tape. Two tracks and a sign bit simulate a two-sided logical tape with a half-line of cells: fold position -1-j over j for j≥0. Switching across the origin changes the sign and keeps the head stationary. The larger alphabet and table are finite. Alternatively the stream algorithms in the present suppliers operate on marked half-lines directly. + +Installation at the top of a blank tape writes beginning, data-blank and terminal and returns to the data cell. A move to the right at the terminal replaces that marker by data-blank, writes a new terminal on its right and returns to the new data cell. A left move at the beginning stays at the first data cell, or uses the sign track for a two-sided logical tape. Each ordinary local step takes a fixed number of physical one-cell transitions. Eager clearing rewrites to physical outside blanks. No position, extent, free list or depth is a selection key for these transitions. + +On suspension, mark the actual parent head, walk right to the terminal and install the next frame immediately after the terminal. After the child has delivered its arguments for return, walk right to its terminal, erase it, walk left erasing all child cells, erase its beginning, pass the parent terminal, and walk left to the first saved head. Unmark it. All saved data closer than any older suspended head are in the immediate parent. An older frame is never scanned. Lengths can exceed or fall below every prior length. A previous wider sibling leaves real blank tape to the right. + +At an arbitrary parent head with a data cells to its right, push takes a+5 transitions. At an arbitrary child head with b data cells to its right and m≥1 child data cells in all, pop takes (1+b)+1+m+2+a+1 transitions. These formulas include erasing every physical cell of a dirty child. The Lean theorems `push_correct` and `leave_correct` derive the final tape and these iteration counts from the one-head table. They quantify over both outer pieces of the tape. No admissibility assumption on their contents is used, apart from the three fresh physical cells written by a push. Their existence follows from the initial blank work tapes, closest-first extension, serial nesting and the pop restoring its entire historical interval. At any instant no currently active frame can have a live descendant to the right of its terminal. Prior siblings have been physically cleaned. This is an induction on the actual execution, not a semantic promise that the allocator grants blank space. + +Pass arguments through a fixed set of initially empty transfer tapes. A fixed site selects its actual complete argument banks. Copy the selected arguments and their shape descriptors to the transfer tapes by full signed or binary payload scans. Mark-and-rewind restores each borrowed head. Select the fixed number of work tapes used by the callees and suspend each as above. Install the arguments in the child and clear the transfer tapes through their terminal. Empty the transfer tapes before calling any recursive subroutine. At return perform these transfers in the opposite order, install every completed result into its designated held owner and clear the transfer buffers. A primitive that overwrites an output physically writes the whole output before exposing it to its consumer. A local numerical transducer used per scalar or per row is inlined in the current frame, or uses its private numerical tapes while leaving the large data tapes stationary. It does not suspend and copy the entire parent array per scalar. + +All possible argument lists are finite for the fixed precompiled templates. Cases whose choice depends on a low matrix select from a fixed finite list. Record lengths vary. A split side with no numerical payload emits its delimiter and performs no data iterations. The template uses no tape per axis, recursion depth, high matrix, operand digit or logical copy at runtime. The mathematical machine may have an enormous fixed number of tapes and a large finite-state control. This is the upstream machine model. + +If the total private extent at a node is at most K V, where V includes the full positive bit volume of the presented call, one suspend/return pair costs O(K V) plus O(child extent). Budget the child's final reverse sweep also to the child. The number of sites is fixed at a compiled word and can multiply that local cost. Repeated slot sweeps with a number of occurrences proportional to the local width charge that number explicitly. A transfer tape is only live at one edge and only until its handoff is complete. At any time the historical extent reached so far on a physical tape is bounded by the **maximum** over earlier active chains of the sum of their frame extents inclusive of delimiters. Each new interval begins immediately after its live parent. A completed sibling never shifts the next interval farther away. For one recursion with V(child)≤V(parent)/2, the sum including the root is at most 2 V(root). The induction in `chain_space` proves the bound for every finite chain. This bound applies to the previously visited cells as well as to current nonblank payloads. Distinct component tapes may reach their maxima at different times. Their count is fixed. At a call to an earlier ordinary stage the volume can be comparable to the parent and its radial padding can introduce a fixed factor. There are at most six nontrivial ordinary stage indices on a chain, plus the elementary stage. Multiplying their constants retains O(V) storage. Repeated outer phases are sequential with all temporary frames released between phases. + +The [earlier parking table](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/finite-parking-frames/PROOF.md) proves matched serial transfer to a dedicated parking stack. The [complete-row caller](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/literal-complete-row-parking-caller/PROOF.md) reserves eight supplied ports and explicitly leaves recursive reuse of their complete backing open. The machine here instead grows adjacent intervals on each fixed tape and preserves arbitrary interior parent heads. + +## Source owners and physical row selection + +The pinned complex graph has 1,289 immutable public entrances, 5,707 paid return rows, 1,289 deferred terminal outputs, and 220,217 donor terms. Schedule each row only after every donor is materialized. Keep the entrance and every paid return in separate, immutable slots until all outputs have been computed. Each paid row stages the combined donors on its own active sender, passes it to the child, installs the return and resumes only afterward. The source uses at most one outstanding sender per raw invocation. Keep the 8,290 numerical homes and its four extra guarded streams per native invocation. Staging two sources with equal values never aliases their owners. The explicit incidence check in `check_binding.py` inspects all actual donors in schedule order. It does not certify the numerical equivalence of that graph. + +The exact binary word has 680 public slots and 3,554 private names. Its 32,296 ADDs, 3,554 INITs, 3,554 CLEARs, 2,874 MOVEs and 680 SWAPs access actual currently live addresses. Reversing the word exchanges INIT and CLEAR and the read/write directions. All 3,554 opens and closes are legal in that direction too. The measured peak of live slots is 4,234 in both directions. Implement INIT by an explicitly sized scan writing zeros, COPY by ADD into a proved initialized zero, SWAP by moving or exchanging the two staged values, and CLEAR by overwriting the entire private slot. Dirty clear on an ordinary irreversible multitape machine does not require bottom-up uncomputation. The completed arbitrary-input endpoints and their independence remain mathematical obligations of the native and compiler proofs. No result is inferred from erasing a row before its last prescribed access. + +At each of the 36 binary or 48 complex caller invocations allocate fresh helper tags and distinct owned banks for all simultaneous suspended raw instances. At every finite product or completion use its full literal occurrence label as the bank tag. In particular #7830 composes 480 copies. Its classes are determined by the first raw paid label. Its two block sizes are 10^480 and 11^480 and the productive cutoff is 16^480. A complement or split executes complete subjobs in order on the same held owner. When a productive target is dropped, allocate a private field, initialize the entire field to zero, carry its genuine work to the completed zero endpoint, then retire it. It contributes zero units of productive width. With b=20706, p=107460, all U=sum_{i=0}^{479} b^(479-i) p^i raw occurrences get their own fixed allocations. The previously charged 6,998,544 U is a raw backing count. Additional split, complement, lift and compiler-held buffers need their own finite auxiliary counts. The allocated extents and extra full scans can increase the implementation constants. No child or productive count changes. Fixed layouts can use one physical role per emitted slot, or the old paid selector for a serial bank. In both cases a child runs only after the prior layout operation returned from all its complete scans. + +For the BIT stopped recursion set L=B |GL_N(F_q)| and H=q^(N²(w-1)). The fresh row range is L H. In the exact [batch-allocation map](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/delayed-cover-batch-allocation/PROOF.md) a local address is ordered as (unused prefix, low, high, earlier high tuple, body). For each unused prefix, stream one complete high-by-earlier-high-by-body slab to each of the L fixed low streams, in order. The inverse emits the slabs back in the same order. Keep the low selector in fixed control. The number of bits in one slab is s=H^(j+1)R at depth j. A ripple block counter resets in O(log(s+1)) per slab and advances in amortized constant time per bit. Compute s once per split/merge from the current descriptor. Do not recompute log-volume metadata on each tiny slab. The split and inverse each scan O(V) bits and preserve every old high index and spectator. Each child receives V/L, including *all* high rows. Only its future independent stock is divided by L H. Split the current positive q-digit reserve once and pad to the next multiple before starting. Inverse restoration and deletion take place only after the completed coordinate action. All padding must stay live in each child. A fixed low type is one physical branch. There is no call per high matrix. The paid right routes and weighted fallback are the earlier [full constructions](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/ROUTES.md), with the dimension, prime and schedule supplied by #7830. The [independent matching review](https://github.com/CrocSwap/integer-mult-bounds/pull/7840) requires consistent matchers on coupled completed blocks. Only the allowed generated weights can use this descriptor tariff. + +Mutually simultaneous complex and ordinary stock factors multiply. At a single stage depth D, the BIT stock is (LH)^D times the previous backend's internal stock. Across six fixed stages its logarithm is O_fixed(w log(e+1)). At each downgrade the called width is at most w. Thus the bound is conservative even if all six are live. On true cold entry the elementary backend exchanges corresponding digits via fixed q² buckets for each position. The [mixed-cut budget](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-mixed-rank-supplier/BIT.json) has covered saving C=60623875557/15625000000000 and rho=1/250. Applied once from b=0 its envelope (1-rho) C exceeds the required seed 12039/3125000 by 46595013693/3906250000000000. Five more strict stages reach the recorded 0.003879928035646. Within each stage ordinary right matches, peeling, base swaps, fallback and restoring the borrowed high pieces use only the previous stage or elementary digit operations. The retained three root terms, all stopped-leaf multiplicities and the exact real stage gaps are unaffected by the extra constant-factor frame scans. The same fixed template and an effective single prime can be used from the cold start. + +At the complex uniform word, one productive role receives V/B and B≥2. Every private field has the same complete positive shape as its corresponding productive slot. The active route and record buffer sizes are O_fixed(V). Inactive banks remain whole. A staged address monomial consists of its finite elementary basis changes, phase evaluations, ordered rotations and existing positive intertwines. The compact movement proof bills O(V+M A³+δ M A(R+A)) for rare carry repairs, where V=M R. A≥1 and the actual untouched fibre R≥2^(c log² p) absorb fixed polynomial preparation for large p. The bound δ≤5/(128p³) and A=O(p) give repair O(V). Keys and any second streamed copy of payloads occupy O(V) cells. Its large nonlocal swaps invoke the completed ordinary service on whole suffix records. They are not priced as linear movement. The [actual symbolic tariff and complete compact guards](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/APPLICATION.md) include fixed selected-address elementary records, the four guarded streams, guide preparation and every head return. The numeric scalar envelope and the movement tariff have different units. This note allows larger fixed constants for physical frame transfer and marker simulation. It does not claim the old numeric transition count unchanged. + +## Precision at the actual phase cuts + +Use the source-bound root grid from the [expanded complex application](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-chart306-chain/DOUBLE-APPLICATION.json). The two words have hashes 7660985e…19b48 (complex raw bytes) and d3aa4426…a27d (binary canonical JSON). No mixed-class decision changes the complex word. Its exact binary exterior denominator increment per open context is at most 140 and its coefficient-mass exponent is at most 428. In particular c=856. The caller odd scale is 2025 and the native scale 763745901562474065860625 is installed as factors 15658669, 13190315, 15217125 and 243. Every factor has at most 24 bits. Removal reverses their order. The expanded scalar plans first exact-divide a reduced denominator (it divides the donor whenever the reduced product is integral), then use same-sign radix-Horner accumulation. Partial magnitudes never exceed the larger of the donor and its final product. A preproduct and complete row fit the advertised 26 guard bits. The expanded [scalar compiler](https://github.com/CrocSwap/integer-mult-bounds/blob/89a67c404226d51028e135de2b9169e9020d57af/research/p104-iterated-returns/continuation/compiler.py) checks its exact symbolic identity and restricted primitives for every compiled coefficient. An interchange of signed components or a partial write is exposed only at completed instruction boundaries. No intermediate quantum measurement or early numerical rounding is used. + +H_C=15171300000000000000. The exact positive integer 856·1920·153^1920·(H_C+1)^2 has 14,083 bits, hence is less than 2^H_C. For D active axes and ℓ=floor(log_(2^H_C)D), at most t=1920·153^1920·(H_C+1)^2·ℓ contexts can lie on a single open source path by the finite compiler's shrink/divisor argument. For ℓ≥1, 2^H_C ℓ≤(2^H_C)^ℓ≤D. Thus 856 t < D whenever a nontrivial root recursion is open. Complete Clifford returns on the original root coordinates absorb completed children. Scaled dyadic coefficient expansions, actual unit phases and intermediate scalar bounds then give F=p+D, W=p+h+2D+3, temporary W+26 as in the [common-grid proof](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/odd-native-common-grid/PROOF.md). The noncommutative temporal structure matters: no numerator certificate on one column alone proves the all-column chart identities, and no rounded physical child may be inserted into this induction. + +There is a distinction between the old selected preprocessing, which describes paying individually for prior reserved axes, and the deferred shrinking phases required by the present movement bill. Suppose m axes have been completed and the next phase will process a active axes, with m+a≤d. Start on signed complex components with fractional precision p and magnitude exponent h. On each actual one-axis kernel the two output numerators at a doubled denominator are the components of x+i x+y-i y, where y is the input at the partner obtained by flipping this axis bit. If all incoming numerators are componentwise bounded by M, the next numerators are bounded by 4 M. Thus m completed axes have increased the dyadic grid exponent by at most m and each component's actual magnitude by at most 2^m. This uses arbitrary independent operand arrays. The exact ordered phases are disjoint C tensor factors, and the incoming S phases are signed quarter-turns. + +At that completed cut, re-anchor the proof on the whole *new* values with parameters p+m and h+m, including complete now-reserved external labels. Every interior local bound uses fractional precision at most (p+m)+a≤p+d, magnitude exponent at most (h+m)+a+2≤h+d+2, and signed width at most (p+m)+(h+m)+2a+3≤p+h+2d+3. A single global format with these maxima therefore suffices. This change of proof reference requires no truncation, repack or additional kernel. It does not assume that a projection onto a changing exterior prefix is itself a Clifford operator. The remaining h/16 or smaller reservation subtree receives its next ordinary phase. Only the final polylogarithmic regime is processed one axis per scan. The terminal b₀^d S C S conversion and any 2^d normalization of H are included at their actual final boundary, with O(d) more guard bits as in the upstream layer. Since d=O(p^ε), ε<1, all these widths are O(p). `PhaseBudget.kernel_numerators` and `same_guard` check the Gaussian recurrence and the common physical format. They do not prove the internal noncommutative Clifford common-grid theorem. + +## What the evidence closes + +The two kernel-checked files prove finite-state physical push/retirement and the exact data of the changing-phase precision estimate. The standalone trace interpreter exercises 10,404 small boundary cases and depth 1000. Its numerical addresses only implement and measure physical tapes. The source binding checks actual chronological ownership and cold-stage numbers. The allocation and transfer argument supplies blank space, trace locality, physical high-water costs and arbitrary-value ownership for the issued supplier frames on the ordinary irreversible multitape model. It applies to the templates when their actual complete schedules and native execution contracts are established. The preceding operational bill gives a written application for the stream and common-grid portions of precision_tape. Layer input/outlet hypotheses are stated explicitly. + +The finite compiler's rank counts, every native chart identity and the outer production of accurate coefficient data require separate proofs. The 73-role [CRT terminal](https://github.com/CrocSwap/integer-mult-bounds/pull/7843) starts with an already bound eager Entry. Its caller must also supply the producer and the coefficient data. The all-input integer theorem remains open from these two Lean files alone. Cross-proof verification still requires linking the finite compiler's actual contexts, the positive/weighted native schedule and the outer root/normalization hypotheses without taking a precision or allocation predicate as a premise of itself. + +Source methods and finite-word credit remain with the [original mixed-cut and its predecessors](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-mixed-rank-supplier/NOTICE). Rohan Arun submitted the grade-14 cutoff and complete claim. Ali Romman prepared its source-bound all-column proof, port routing and cold service. The proofs here also use the original parking work, the complete covered-row proof and the scoped matching review. The new terms here concern the literal translated intervals, old backing, explicit finite-stage re-use and exact precision across changing deferred phases. [Grade-14 realization credit](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/NOTICE.md) diff --git a/research/mixed-rank-uniform-composition/FrameMachine.py b/research/mixed-rank-uniform-composition/FrameMachine.py new file mode 100644 index 0000000000..c561e54752 --- /dev/null +++ b/research/mixed-rank-uniform-composition/FrameMachine.py @@ -0,0 +1,140 @@ +"""A literal one-head controller for nested reservations on one physical tape.""" + +from collections import Counter +from itertools import product + + +BLANK = "_" +START = "[" +STOP = "]" +DATA = ("e", "0", "1") +ACTIVE = tuple((symbol, False) for symbol in DATA) +SAVED = tuple((symbol, True) for symbol in DATA) +ALPHABET = (BLANK, START, STOP, *ACTIVE, *SAVED) +DONE = "done" + +def expect(value, description): + if not value: + raise ValueError(description) + + +def table(): + moves = {} + + def rule(state, symbol, next_state, write=None, move=0): + key = (state, symbol) + expect(key not in moves, "duplicate table key") + moves[key] = (next_state, symbol if write is None else write, move) + + rule("init", BLANK, "init_data", START, 1) + rule("init_data", BLANK, "init_tip", ("e", False), 1) + rule("init_tip", BLANK, DONE, STOP, -1) + for symbol in DATA: + value = (symbol, False) + for written in DATA: + rule("write_" + written, value, DONE, (written, False)) + rule("right", value, "probe_right", move=1) + rule("probe_right", value, DONE) + rule("left", value, "probe_left", move=-1) + rule("probe_left", value, DONE) + rule("push", value, "seek_tip", (symbol, True), 1) + rule("seek_tip", value, "seek_tip", move=1) + rule("leave", value, "leave", move=1) + rule("clear", value, "clear", BLANK, -1) + rule("find_parent", value, "find_parent", move=-1) + rule("find_parent", (symbol, True), DONE, value) + rule("probe_right", STOP, "extend_tip", ("e", False), 1) + rule("extend_tip", BLANK, DONE, STOP, -1) + rule("probe_left", START, DONE, move=1) + rule("seek_tip", STOP, "init", move=1) + rule("leave", STOP, "clear", BLANK, -1) + rule("clear", START, "parent_tip", BLANK, -1) + rule("parent_tip", STOP, "find_parent", move=-1) + return moves + + +TABLE = table() + + +class Tape: + """The dictionary and counters measure the single physical head.""" + + def __init__(self, cells, head): + self.cells = dict(cells) + self.head = head + self.visits = Counter() + + def run(self, state): + first, last = self.head, self.head + count = 0 + while state != DONE: + raw = self.cells.get(self.head, BLANK) + state, write, move = TABLE[state, raw] + self.visits[self.head] += 1 + if write == BLANK: + self.cells.pop(self.head, None) + else: + self.cells[self.head] = write + self.head += move + count += 1 + first, last = min(first, self.head), max(last, self.head) + return count, first, last + + +def enumerate_frames(): + opaque = {i - len(ALPHABET) : sym for i, sym in enumerate(ALPHABET) if sym != BLANK} + checked = 0 + for n in range(1, 4): + for parent in product(DATA, repeat=n): + for j in range(n): + entry = dict(opaque) + entry[0], entry[n + 1] = START, STOP + entry.update((i+1, (sym,False)) for i,sym in enumerate(parent)) + for m in range(1, 4): + for child in product(DATA, repeat=m): + for k in range(m): + machine = Tape(entry, j+1) + steps, first, last = machine.run("push") + expect((steps, first, last) == (n-j+4, j+1, n+4), "push trace") + expect(machine.head == n+3, "child entry") + for i, sym in enumerate(child): + if i: + machine.run("right") + machine.run("write_"+sym) + for _ in range(m-1-k): + machine.run("left") + steps, first, last = machine.run("leave") + expect((steps, first, last) == + (m-k + 1 + m + 1 + 1 + n-1-j + 1, j+1, n+m+3), + "retirement trace") + expect(machine.cells == entry, "restored cells") + expect(machine.head == j+1, "restored head") + checked += 1 + return checked + + +def deeply_nested(depth): + machine = Tape({}, 0) + machine.run("init") + widths = [1 + ((11 * i + 7) % 23) for i in range(depth)] + for i, width in enumerate(widths): + for j in range(width): + if j: + machine.run("right") + machine.run("write_" + str((i + j) % 2)) + machine.run("push") + for i, width in reversed(list(enumerate(widths))): + machine.run("leave") + expect(machine.cells[machine.head] == (str((i + width - 1) % 2), False), + "deep restored data") + for _ in range(width-1): + machine.run("left") + expect(max(machine.visits) == sum(width + 2 for width in widths) + 2, + "historical extent") + expect(min(machine.visits) == 0, "old prefix scanned") + + +if __name__ == "__main__": + n = enumerate_frames() + deeply_nested(1000) + print(f"PASS {n} frame returns, depth 1000, {len(TABLE)} literal transitions") diff --git a/research/mixed-rank-uniform-composition/GAUSSIAN-FORMAL.md b/research/mixed-rank-uniform-composition/GAUSSIAN-FORMAL.md new file mode 100644 index 0000000000..13e884e843 --- /dev/null +++ b/research/mixed-rank-uniform-composition/GAUSSIAN-FORMAL.md @@ -0,0 +1,45 @@ +# Formal meaning of the Gaussian and synthetic checks + +Lean 4.34.1 with its bundled Std kernel-checks HaloRadius.lean, RationalInverse.lean and SyntheticBridge.lean. The files use ordinary signed integers and finite lists. They do not use an external numerical oracle. + +## From the fixed physical band to HaloRadius + +For public numerical precision P let D=2^P, let H be the generated dyadic narrow band including the exact identity hole rows, and let E=I-H. For a signed integer lift of a physical target row i, give the Lean row a list of pairs (D E(i,j), j). The index j includes the appropriate signed periodic lift of its occurrence and all spectator coordinates. The argument admits zero coefficients and arbitrary signed coefficients. The sum of their absolute integers is the encoded row mass. The row-gap proof gives mass/D <= 1-1/B where B=16p0² and p0 is the geometric precision. Here a is the single dyadic normalizer a*=2^ceil(log2(p0^100)), with a>=B. Thus the two required integer checks hold: + + D + B·mass <= B·D, D + a·mass <= a·D. + +The first bounds convergence and the second bounds the actual nonlinear iterate. Input words x and all iterates z are signed Gaussian numerators at common denominator D. The literal update in the shrinking reference takes a fixed x at each sweep, forms x/a+E z, then truncates real and imaginary parts toward zero after the sum. On the integer numerators this is exactly + + tdiv(D·x + a·sum_j (D E_ij) z_j, a·D), + +component by component. Since H itself already uses the same grid, the consumer's extra coefficient truncation is exact. The separately proved difference from the ideal, untruncated Gaussian is still required and is included in GROUPED-GAUSSIAN.md. Using rounded higher-precision input coefficients would require adding the predecessor's coefficient perturbation allowance. [Physical recurrence](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/shrinking-reference-halo/PROOF.md#L88-L120) + +* updateBound, eachIteration and everyAxis prove that the actual component-l1 radius remains at most the original bound, throughout any number of iterations and sequential axes. +* finiteNeumannError bounds the difference between actual and exact finite Neumann iteration, at every integer input and iteration count k, by 2B units of the input grid (the Lean inequality clears the common denominator (aD)^k). It derives the two-component truncation residual using signed division/remainder and the original band update. +* spectralNumeratorError bounds the final difference after any list of axes by e+2B·length grid units, with initial discrepancy e. It proves linearity and contraction for the exact finite polynomial, and it reanchors the numerical error at the actual input to each rounded axis. It does not assume linearity or nonexpansiveness of a truncated map. +* geometricTail proves that a rational fixed point y/s of the normalized inverse differs from the k-term polynomial by at most (max_i |y_i|/s)·(m/D)^k in input-grid units, where m bounds encoded row mass and the norm is maximum component-l1. The exact equation in Fixed is precisely aH(y/s)=x. Existence of this rational fixed point follows outside Lean by strictly dominant H, finite rational elimination and arbitrary rational input. Its size is at most the input's radius because a delta>=1. Thus k=16p0^4 gives exp(-p0²) as in the written proof. +* completeInverseError composes the actual rounded updates, the exact finite-polynomial contraction, and the geometric tail into one all-axis error estimate against the actual normalized inverse equations. Choose a common mathematical denominator S for the finite family of exact rational intermediate values. It is absent from the running machine. Take m=max_i mass(row_i), a row-gap reciprocal bound B, and one grid unit for each residual tail. On the geometric parameter family, (m/D)^J<=exp(-p0²) and the incoming numerical component-l1 magnitude is at most a constant times D=2^P, so one grid unit eventually suffices on all axes. With input discrepancy e the formal result gives e+(2B+1)·(#axes) units for the whole exact inverse trajectory before the separate D(j) diagonal. This conclusion includes numerical error at the actual incoming argument, coefficient-exact Horner and every finite truncation. It is not only a list of single-axis certificates. +* physicalCone is the exact integer containment for a signed offset in [-W,W] when a lifted interval is reduced by W at each end. savedRectangle explicitly uses the fact that the incoming zeroth iterate is zero, so a J-step update needs only (J-1)W input neighbors. It proves equality of *both* the actual rounded and the exact finite iterations on the target, when given the same physical band rows and original values on that cone. Source fields may differ off the saved rectangle. The permitted period lifts are unique because L+2(J-1)W=2. Its endpoint value is at most exp[-u rho(rho-1)]+exp[-u rho(rho+1)] <= exp(-u theta)+exp(-2u). For |h'|>=2 the remaining sum is <=2 sum_{j>=2} exp[-u j(j-1)]<3 exp(-2u). Thus ||I-H||_infinity<=1-delta with delta=1/(16p²) eventually. The same bound holds for every principal section and for the exact narrow operator after allowing its tiny diagonal aliases. This independently gives ||N^-1-H^-1||_infinity=O(p^4 W 2^-P) by the resolvent identity. Broad row and column norms are bounded by an absolute constant by integral comparison at lattice spacing at least 1/2. Also ||D||_infinity <= exp(u/4)=theta/2. The Jacobi product gives real part >=(1-exp[-gamma(1-2|w|)]) exp[-pi²/(3gamma)]=p^-O(1) and the kernel l1 norm <=3+sqrt(2pi/gamma). To see positivity, pair factors with exponents 2j-1±2|w|. Their interlaced arguments telescope to at most the argument of the first factor. Sum the negative logarithms of the remaining products with 1/(exp(x)-1)<=1/x to obtain the bound. Fourier integration transfers these bounds to every finite section. Rounding each kernel diagonal preserving the Toeplitz structure perturbs the operator by at most O(B2^-P), preserving accretivity. The circuit-made interior differs from the exact dyadic global H or U on that interior by poly(p) 2^-P, by comparison against their common unrounded Gaussian and its tails. Its inverse has polynomial norm and the resolvent identity controls the inverse error. No broad full inverse or arbitrary-principal broad inverse is needed. [Exact identities and accretivity](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/vendor/GAUGEFREE-INTERIORS.md) + +Partition the core matrix Q into block rows [A0 B0] and [C0 D0] in interior and boundary order. Set F=D0−C0 A0⁻¹ B0. Use, in matrix order, + + Q = diag(A0,I) E_C0 diag(A0^-1,F) E_B0 diag(A0,I), + Q^-1 = diag(A0^-1,I) E_-B0 diag(A0,F^-1) E_-C0 diag(A0^-1,I). + +The upper and lower shears use the original band. The middle diagonal acts separately on interiors and boundary. The forward broad program applies F. Narrow uses F^-1. Pages for F come from exact rational elimination on Q. Entries of the resulting Schur matrices are ratios of determinants with poly(p) bits because L and the dyadic input width are polynomial. Multiplying the displayed factors proves their endpoint for any input, including dirty holes. + +Compile the dyadic Toeplitz blocks by the established shallow no-ancilla circuit. Down its block Schur tree the rank of ZM-MZ increases by at most one per level. Each off-diagonal multiplier decomposes into O(log B) triangular Toeplitz products using the finite telescoping sum for the Stein displacement. A triangular invertible shift I+U(h)/gamma0, gamma0>=2||h||_1, realizes the product shear on dirty wires. Parity splitting of each triangular operator does its two children in parallel. All terminal shears use cyclic and negacyclic FFT shears on restored source wires. Accretivity of all original principal sections bounds every Schur descendant inverse, since it is a principal submatrix of an inverse of such a section. The Schur formula bounds descendant norms. This gives depth O(log^4 B), poly(p)-bounded individual gates and inverse gates, and exp(polylog p)-bounded prefixes. Exact Gram-Schmidt on rational unnormalized generators followed by interval square roots costs poly(p) private time and space. Relative errors for nonzero roots are feasible because input minors and orthogonalization determinants have polynomial bit length. [Shallow circuit and generation proof](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/vendor/SHALLOW-TOEPLITZ.md) + +Run equal-depth padded layers on existing coordinates. Use the common six-Hadamard word, including zero shears by the identity U(t)=U(t+c)U(-c) with c=2 max|t|+1. Beneš layers route matchings on each L-point axis. Site/coarse dependence enters the individual diagonal entries only. Each Hadamard applies to complete global spectator fibers, as the original caller requires. For each diagonal, gather local bits via the priced support router and load one-axis tables. The prefix-product odometer reads or rewinds O(jL) records for a carry of depth j, once per L^j records. This gives O(1) amortized moves and products per scalar. Compiled layers and bank pages can be regenerated for every core and stage: L^m absorbs every fixed poly(p). Switching from normalized H/2 to H costs one factor of 2 per participating bit. Put 2^m in a joint diagonal with m guard bits. The log of the maximal unfinished norm, counting repeat layers and changes from Euclidean norm to coordinate norm on L^m entries, stays O(m polylog p)=o(p). [Tensor compiler](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/vendor/TENSOR-COMPILER.md) · [Global support wrapper](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/kappa-rebuild/transfer-audit/OUTER-TRANSFER-AUDIT.md#L293-L364) + +In boundary order F has half-bandwidth O(W). Each eliminated interior joins only the W surviving neighbors on either side, while original edges have span at most W. Keep extra interior skirts separate when exposing F. Narrow row-diagonal-dominant elimination preserves the initial row gap delta and row norm bound 2. At a pivot j the sum of newly added magnitudes to row i is at most |m_ij| sum_(k!=j)|m_jk|/|m_jj|, less than the removed |m_ij|. The same triangle inequalities bound the diagonal loss plus off-diagonal growth. Thus in F=Lf Uf, every pivot magnitude is >=delta, ||Uf||_infinity<=2 and ||Lf||_infinity<=1+2L/delta. F^-1 is a principal block of the inverse of a narrow section. Consequently Lf^-1=Uf F^-1 and Uf^-1=F^-1 Lf have polynomial norms. The same holds for consecutive diagonal blocks of either triangular inverse. Standard no-pivot LU keeps the bandwidth. + +Choose dyadic block width between cW and 2cW large enough to cover the bandwidth. Each block row of a band multiply or triangular solve uses O(1) square products against a batch of that many independent RHSs. Precompute exact block coefficients and diagonal inverses, round on the common grid. Strassen evaluation costs O(W^(45/16)) word operations per square, since 7^16<2^45. Its recursive block sums and returns are sequential, depth-first on fixed tapes, with O(W²) scratch. Each computed triangular block equation has residual at most poly(p) 2^-P (1+||input||+||computed solution||) since the per-level sum growth is constant through O(log W) levels. The inverse bounds absorb the last norm for sufficiently large p. Applying this reasoning to leading/trailing subsystems also bounds intermediate prefix values. Thus the error is poly(p) 2^-P (1+R), including coefficient approximations and the final multiplication by rounded reciprocal blocks. Accumulated growth exponential in the number of block rows would invalidate the claimed precision. + +In every sparse window first obtain *current* values. Let I(v) be the axes where v_i belongs to E_i. Each sparse factor preserves all Cartesian classes with a fixed I. On visit j distribute by the j-th flagged axis, expose the short coordinate field, apply the corresponding line operator, undo the transpose and the distribution, then remove finished records with a stored split mask. Reconstruct the original order after the final visit. For a fixed axis, visit and coarse origin the eligible other coordinates form a union of Cartesian flag classes, with one common axis page. Every nonempty class contains at least min_i(|E_i|,L-|E_i|)^(m-1)>=W^(m-1) independent lines. Thus even a rare tag supplies a full block of RHSs eventually. Split into batches of width W'..2W' or pad a last shorter batch charging it to a previous full one. This is needed for the square Strassen bill. Total visits are exactly sum_v |I(v)|=O(m mu L^m) per core. The short-field transposes and radix tag splits use O(log m+log L) full-record movements per visit. All split masks combined fit at most m bits per starting record, flags use O(m log L)=o(p). Computing the original-coordinate membership using floors and the simple periodic-interior pattern costs O(m ell² polylog p)=o(p) bit steps per dense record, since z+2(1-e)<1. [Union schedule](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/vendor/UNION-SCHEDULE.md) · [Literal head accounting](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/pr4100-union-head-travel/README.md) · [RHS transpose](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/pr4100-row-field-movement/PROOF.md) + +The RHS batch stream runs continuously across prefix changes inside the stable tag substream of a single (core, visit, axis). A singleton suffix is allowed. Flush a short batch only at the end of that complete tag substream. The participating page depends only on the core and axis, and reversing the original zip recovers each full line, including lines in different prefixes of one batch. Each exact rational Schur factor is rounded into a packed numerical band page before the first RHS is scanned. Subsequent batch scans read O(p)-bit coefficients. Streaming, sign conversion, products and checks use the fixed-multitape Harvey–van der Hoeven O(N log N) bit algorithm for short words. One product of O(p)-bit words costs O(p log p). Only one such subcall is live at a time. Time bounds its work extent by O(p log p)=o(V), and its scratch is reused and cleared. The same fact gives O(r p log(rp))=2^o(p) scratch for one signed packed polynomial product, where r is the power-of-two polynomial suffix. No whole-field online record has that width. [Published word multiplication theorem](https://annals.math.princeton.edu/2021/193-2/p04) + +## Return the global rows, pay all normalizations and price the service + +Before core mutation save the immutable data needed for first-face rectangles. Discard core rows within A of any boundary, partitioned into 2m disjoint rectangles by their first boundary axis and its side. For narrow use the Neumann polynomial of I-H with J=16p^4 terms. Its error is <=(1-delta)^J/delta<=16p² exp(-p²). Its radius b=(J-1)W=O(p^5)=1/delta and error per axis <=((2W+1)R+2) 2^-P/delta + R (1-delta)^J/(d_i delta). For broad use one direct forward band pass of radius W on these same faces. This never requires a broad whole-axis inverse. Original signed periodic images, including clipped physical ends and identity holes, are available in both bands. + +Intersection/hole rows are neither duplicated nor omitted: the first boundary axis and side give a unique return key. Common-radius copy volume is O(M m A/L) for M records because (1+2A/L)^m is bounded. Each face's m-1 long edges of length >=L-O(A) absorb two full one-axis archive scans per face per axis, as z>1-e. The authenticated shrinking consumer gives O(V[d/m+d m A p^6/L])+2^o(p), including numerical loops, source-preserving tape movement, metadata, stable sorts, return and clearing. Its proof was stated with core p^400. The actual proof requires the inequalities just given and N_i>=2L, which also hold for L>=p^128. Its sparse exponent is e+z+54-128 < -72. [Transport and numerical join](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/first-face-reference-join/PROOF.md#L264-L298) · [Shrinking numerical solver](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/shrinking-reference-halo/PROOF.md) + +Use a*=2^ceil(log2(p^100)), computed as the least power of two at least p^100. Normalize each completed public axis by 1/a*, including D in the final compression. Set the shrinking Horner d_i equal to a* from the outset. The exact core and face branches then use the same net scalar with no compensation between them. In fact z_(k+1)=Q(x/a*+Ehat z_k) preserves the actual component-l1 radius R, since 1/a*+||Ehat||_infinity<=1 and truncation is toward zero. Every normalized polynomial and exact inverse is a contraction in that norm. Errors telescope against the exact maps at each actual incoming state. The face error is at most sum_i nu_i+R sum_i tau_i with nu_i=((2W+1)R+2)2^-P/delta and tau_i=(1-delta)^J/(a* delta). On kept rows the global and principal polynomials agree exactly. The corresponding normalized exact inverses differ there by at most 2 sum_i tau_i on a unit input. Disjoint return keys take the maximum of the kept and discarded bounds. If the D factors are applied together after the entire compression, ||tensor_i D_i||_infinity<=p^(2d)=2^o(p), also covered by the chosen C0. Within a group these scalar factors form one product diagonal, not one full scan per axis. Group prefix and suffix norms are exp(O(m polylog p)) in the coordinate norm, including the partial sparse solves. For a native primitive with a unit input radius, scale by a known dyadic prefix bound and compensate on returned values. The required extra bits are o(p). For all groups together the unscaled final compensation costs O(d log p)=o(p) bits. Each local/one-group residual is at most (1+R)2^(-P+o(p)), including the union of all coarse blocks (a direct sum) and the polynomial count of stages. The exact normalized complete maps are contractions on arbitrary hole values. Errors over groups add. Choosing C0 above c plus a fixed margin gives the claimed threshold. The only q-image operations are the initial all-axis embedding and the final all-axis extraction described above. + +The Gaussian exponents after dividing time by V, with fixed logarithmic factors omitted, are e-s z (complete Hadamards), e-a z (complete BIT routes), e-z (group scans), e+1/2-x (union movement), e+29/32-x (boundary arithmetic), and e+z+54-128 (halo). The boundary price per active record is O(W^(45/16-2)). Multiply by active fraction W/B and by d. Each exponent is strictly below 1-k at the pinned values. Online payloads on all fixed tapes, including auxiliary numerical buffers, are O(V). Local block setup is poly(p), the complete archive is d 2^O(ell) poly(p)=2^o(p) bits, and the sparse and recursive scratch backing is bounded by the largest simultaneous live region. Reuse work tapes between rectangles, erase current live bodies, and charge retained blank suffixes once to peak backing. Integer parameter bounds and geometry tests provide effective finite small-size fallback, without testing payload values. + +This is a written Gaussian-service implication with an explicit lower-level native boundary. Existing physical consumer and finite-word results retain their individual scopes. The old production catalogue cannot be used on this family, and #7834's per-axis dense implementation has a different time exponent. The innovations here are the explicit p^128 specialization, rare-tag RHS guarantee, direct physical reference/gap bound and integer width/rounding choice. The Toeplitz and five-factor construction, shifted-symbol argument, first-face solver and P104 words remain predecessor work. [Attribution](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/NOTICE.md) diff --git a/research/mixed-rank-uniform-composition/LICENSE b/research/mixed-rank-uniform-composition/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/mixed-rank-uniform-composition/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/research/mixed-rank-uniform-composition/NOTICE.md b/research/mixed-rank-uniform-composition/NOTICE.md new file mode 100644 index 0000000000..dbf5032058 --- /dev/null +++ b/research/mixed-rank-uniform-composition/NOTICE.md @@ -0,0 +1,10 @@ +# Attribution + +Ali Romman prepared the integration, proofs, source checks and experiments with substantial OpenAI Codex assistance, including separate adversarial mathematical and computational reviews. The new material is offered under the Apache License, Version 2.0. [License](LICENSE) + +- Clear1nsight supplied the mixed binary partition and the priced complete application at the head of PR #7830. The 48-call complex word follows Clear1nsight's two-return construction. Dugongue supplied the preceding comparison. Rohan Arun submitted the grade-14 proposal. Ali Romman's PR #7776 supplied the earlier two supplier/caller components. The native proof, chart catalogue and paid port/cold routing in PR #7837 were prepared by Ali Romman. The older 832-fold grade-14 price is outside the new proof. [Mixed notice](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-mixed-rank-supplier/NOTICE) · [Native notice](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/NOTICE.md) +- The native/cover line includes DreamingOfClouds, Jerry Chen (CubeJerry), zxv, SYLforge and the retained shared-wire and graded-supplier contributors. Jacob Alan Sussman's finite compilation, the ambient-cap and stopped-recursion work, and the retained all-column, cold-start, compact control and odd-scalar proofs supply the methods identified in the compiler and frame articles. Ross Richardson, Nick Petalas, Jose Manuel and Adam Gall supplied the cited bad-class, deterministic count, recursion and fresh-cover results. [Compiler provenance](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/kappa-rebuild/architecture/FINITE-PRECOMPILATION.md) · [Native attributions and links](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/NOTICE.md) +- Douglas Colkitt and OpenAI supplied the original fixed-tape framework. Cinna Davis supplied the balanced nonlinear CRT and the earlier grouped Gaussian/outer synthesis. Vlado Vojdanovski and colleagues supplied the capped phase cells, tensor compiler, support routing and Toeplitz circuit work. Chafik Boukhalfa supplied the fine-prime, shifted-symbol and union-schedule work. The first-face transport, shrinking numerical solver, uniform evaluator and reservoir placement are predecessor contributions. Ryanson Jonathan identified the guard-width correction. The end-target branch uses ToikY’s full-fibre switch and Nick Petalas’s single-buffer schedule. [Complete end-target switch](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/crt-tail-single-buffer/PROOF.md) [Outer notice](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/NOTICE.md) · [First-face join](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/first-face-reference-join/README.md) · [Guard correction](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/pr4100-guard-coloring/README.md) +- Tim Trudgian supplied the explicit prime-count estimate. David Harvey and Joris van der Hoeven supplied the unconditional shorter-word multiplier. The Lean and mathlib authors supplied the formal library, including the finite cyclic transform, its inverse and the foundational complex arithmetic. [Prime estimate](https://arxiv.org/html/1401.2689v2) · [Short-word multiplication](https://annals.math.princeton.edu/2021/193-2/p04) · [Formal cyclic DFT](https://github.com/leanprover-community/mathlib4/blob/d13f23b723b8a846827a245b89c10fc7d3f11612/Mathlib/Analysis/Fourier/ZMod.lean) + +The new work connects the actual priced words across complete operator, physical, precision and analytic boundaries. It includes the source-specific occurrence flow and integer price certificates, the translated dirty frames, the all-axis dyadic embedding, the mixed shrinking-face and fixed-schedule proofs, and the formal decoder at the physical CRT unit. The earlier campaign index gives historical context. [Campaign contributions](https://github.com/CrocSwap/integer-mult-bounds/discussions/7794) diff --git a/research/mixed-rank-uniform-composition/OBLIGATIONS.md b/research/mixed-rank-uniform-composition/OBLIGATIONS.md new file mode 100644 index 0000000000..49f4846f55 --- /dev/null +++ b/research/mixed-rank-uniform-composition/OBLIGATIONS.md @@ -0,0 +1,30 @@ +# Proof obligations and dependencies + +The five identifiers below are the statements in the complete proposal. The scope is this one fixed family of words, all operand lengths and all actual admitted intermediate states. Arbitrary native inputs include correlated contents in distinct owned fields. The product theorem uses ordinary irreversible fixed-tape computation. The source's upper-bound resource model permits erasing dirty storage by writing a blank, with full movement and historical backing charged. + +| Source obligation | Full statement required here | Producer and evidence | +|---|---|---| +| native_all_columns | Every positive multiplicity, both native directions, correct absolute Gaussian phases, all complete spectators, and each physical whole-job adapter | Ideal common-chart induction, current 48/36 calls, true port matchers, arbitrary-weight good/bad leaves. Source-data equality across the two different compiler applications is checked by [bind_compiler.py](bind_compiler.py). The [native proof](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/PROOF.md) and [weighted application proof](WEIGHTED-REVIEW.md) establish the quantified statement. | +| owned_erasure | Allocate arbitrary held centres and fresh zero scratch, exclusive loans, split and pad, preserve every public owner, retire and clear on arbitrarily deep actual calls | [Compiler occurrence flow](COMPILER.md), [actual native banks and physical stacks](FRAMES.md) and [kernel-checked one-head transitions](lean/PhysicalFrames.lean). Full fields, shape descriptors, transfers, old high fibres and backtracking are charged. | +| compiler | At every desired rank construct the actual ordered mixed product, positive disjoint splits, forward/dual completion, zero specialization and integer batches with strictly descending exits and realize the funded uniform ranks | [Construction and recurrence](COMPILER.md), [occurrence enumeration](lean/CompilerFlow.lean), [exact source prices](lean/CertifiedPrices.lean). The final materialized words are finite fixed constants. The new 480-factor rule is applied before the rational basis prime is chosen. | +| precision_tape | The actual source finite program, compact movement, common exact components, storage and row stock fit at all widths including nonmultiples, stopped paths and deferred phases | [Source frame and grid proof](FRAMES.md), [word-specific root argument](WEIGHTED-REVIEW.md), [ordinary high-row allocations](ORDINARY.md) and [complex layer](COMPLEX-LAYER.md). [Cover arithmetic](lean/CoverRows.lean) and [phase arithmetic](lean/PhaseBudget.lean) are kernel-checked. | +| analytic_recovery | Uniformly generate the fine geometry and coefficients, compute the normalized source transforms in both signs, and recover each pre-carry coefficient strictly within 1/2 in the claimed movement budget | [Assembly from bits](ASSEMBLY.md), [grouped numerical proof](GROUPED-GAUSSIAN.md), [synthetic ring](SYNTHETIC-ACCESS.md) and [recovery and cost](RECOVERY-AND-COST.md). [PublicGrid](lean/PublicGrid.lean) checks the exact grid-word decoder from the two raw transform error bounds. [RationalInverse](lean/RationalInverse.lean) checks the finite narrow inverse from the row guards. [The integer producer](gaussian_pages.py) emits those rows. | + +## Dependencies hidden by the top-level names + +| Needed by | Obligation at the actual boundary | Evidence for this construction | +|---|---|---| +| Finite words | Two different price compilations act on the same complete native graphs and layout. A scalar multiplier occurs once, an intrinsic tensor phase occurs on every column, and coupled ports share their matcher. | Pinned three-word checks, exact forward/transpose graph and absolute phases. [Native proof](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/PROOF.md) · [Word binding](bind_compiler.py) · [Covered good leaf](lean/RankOneBridge.lean) | +| Compiler price | Account for first-label strata, real work at trimmed zero endpoints, integer indivisibilities, complement depth and six fresh ordinary stages. | [CompilerFlow](lean/CompilerFlow.lean), [source-bound rank enclosures](lean/RankMoments.lean), [integer enclosure proof](lean/DyadicRoot.lean), [certified debits](lean/CertifiedPrices.lean) and [finite carrier guards](lean/Funding.lean). | +| Operational binary leaves | Each low class occurs with its whole high cube even after earlier branches. Conjugations use actual inherited weights. Radix padding is removed only after the unweighted exchange. | [Complete cover and stage proof](ORDINARY.md) and [independent bad-leaf analysis](WEIGHTED-REVIEW.md). | +| Staged recursion | Independent productive arrays retain one credit each, high rows remain in child bit volume, previous stages start from charged elementary digit swaps, and cleanup uses the historical frame extent. | [Physical transitions](lean/PhysicalFrames.lean), [source binding](check_binding.py), [cover addresses](lean/CoverRows.lean) and [ordinary recurrence](ORDINARY.md). | +| Native scalar grid | Gaussian Clifford entries have the correct denominator at each fixed source root, odd-scale division is exact, transient numerators fit, and completed phases change the root reference. | 140 binary denominator bits and 428 mass bits per open context, actual semantic coefficient 856, 14,083-bit threshold certificate, W+26 signed temporary. [Frame proof](FRAMES.md) · [Clifford and weight proof](WEIGHTED-REVIEW.md) | +| Whole synthetic H | Global full dyadic tensor, identical bit positions across coarse labels, paid supported layout and return, actual radius, original twiddle positions and both phase corrections. | [Complex service](COMPLEX-LAYER.md), [signed bridge](lean/SyntheticBridge.lean), [FFT and ring schedule](SYNTHETIC-ACCESS.md). | +| Gaussian production | Original occurrences and holes, generated coefficients, real shifted-symbol accretivity, polynomial-bit coefficient preparation, tensorizable interior circuits, current sparse values, sufficient independent RHSs, disjoint normalized halo output. | [Source-bound Gaussian proof](GROUPED-GAUSSIAN.md), [emitted pages and guards](GAUSSIAN-PAGES.md), [halo arithmetic](lean/HaloRadius.lean), [fixed coarse-controlled stage experiment](check_uniform_benes.py). | +| Fast CRT | Three nonlinear address maps including invalid coordinates, proper guard width, true inverse macro on bad keys, separately paid sparse and dense control computation. | [Complete CRT section](ASSEMBLY.md), [guard review](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/pr4100-guard-coloring/README.md), [extra cost row](lean/OuterPrices.lean). | +| Integer output | Both signs at the actual CRT character unit, two source factors, scaled independent operand inputs, opposite-leg radius, original coordinate extraction, integer rounding and radix carry. | [Original coordinate lemma](lean/Coordinates.lean), [product/error theorem](lean/Recovery.lean), [specialization](lean/Integrated.lean) and [actual finite splice](check_product.py). | +| Uniform, historically bounded machine | Effective prime and parameter selection with a finite initial regime. Only one short-word backend lives at a time. Tape extents are reclaimed between phases. | [Geometry](ASSEMBLY.md), [complete bill and fallback](RECOVERY-AND-COST.md), [physical frame derivation](FRAMES.md). | + +Read the dependency order from the ideal algebra through physical implementation. Prove the closed finite-word identities for formal fields first. Compile their occurrences and choose the finite prime and sites. Prove exact common-grid simulation using the ideal completed returns. Implement ordinary calls by induction on the earlier stage and, inside a stage, decreasing atom count. Only then use ordinary movement in the complex service. Use those completed primitives on the globally padded outer arrays, and finally invoke the product-error theorem. The previous four-premise grade-14 theorem and the earlier complete outer theorem are never taken as assumptions in this order. + +The claimed closure of these rows is a **written mathematical result** with the formal and finite boundaries stated in [VERIFICATION.md](VERIFICATION.md). The remaining external results include the classical CRT and character identities, finite linear algebra and Clifford stabilizer facts, Poisson summation for Gaussians, the Jacobi triple product, the explicit prime-number estimate, Strassen's identity, and the independent multitape O(N log N) multiplication theorem on short words. The proofs identify where each is used. None asserts the multiplier or the transform supplier being constructed. diff --git a/research/mixed-rank-uniform-composition/ORDINARY.md b/research/mixed-rank-uniform-composition/ORDINARY.md new file mode 100644 index 0000000000..49e424e45f --- /dev/null +++ b/research/mixed-rank-uniform-composition/ORDINARY.md @@ -0,0 +1,45 @@ +# Ordinary binary fields at the mixed-rank rates + +The consumer exchanges two equal-width complete binary fields in an arbitrary rectangular prefix, gap and suffix. It accepts an arbitrary binary string on those addresses. The product below uses six finite ordinary stages, including the stage that starts with individual digit swaps. The prime and the uniform rank are fixed before operand width varies. The following explanation retains the exact order of the stock and the exact size of a paid stream. [Mixed-rank source](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-mixed-rank-supplier/PROOF.md) · [Complete weighted and ordinary implementations](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/APPLICATION.md) + +## The two arithmetic bases and the array layout + +For E≥1 choose the least d such that q^d≥2^E. The input ordinal i in [0,2^E) has the same ordinal in [0,q^d). Implement this embedding by a tape copy in increasing address order. For each genuine first-field value, copy the full genuine second-field section at each gap label and insert its missing terminal section. Then append the missing first-field blocks. Prefix, gap and suffix keep their order. The resulting full volume is less than q² times the original volume. A small constant number of unary length guides, or binary countdowns with reset once per whole block, generate these sections in time proportional to the full padded volume. Constructing the fixed-q powers, exact lengths and guides once costs polynomial in the bit lengths of the extents plus the guide lengths. For complete rectangular positive ranges, this is O(V) after enlarging the fixed constant. The constructed tapes contain the original payload, explicit padding and their markers. External labels never enter a ring-operation coefficient. Apply the exact completed q-ary ordinary interchange to these records, across the given complete gap. It sends (p,x,g,y,s) to (p,y,g,x,s). Both selected extents are the same, so the genuine rectangle and its complement are invariant at the completed endpoint. Only then remove padding by reversing the insertion scans. This procedure also lets a previous binary stage exchange two old q^w-fields by first extending their ranges to the next power of two, with volume factor below four. No per-record binary-to-radix arithmetic is required. + +The elementary stage uses fixed q² digit buckets. For each digit position copy records by the two digit values, preserving gap and suffix order. Return in second-digit, gap, first-digit and suffix order. A pass traverses all genuine and padded records and resets the fixed bucket heads. The digit passes commute at distinct positions. This gives time O(Vd) and space O(V) on arbitrary full spectator fields. [Physical digit-bucket implementation](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/cover.py) + +## Exact allocations and fresh child types + +Fix one stopped recursion with atom width w≥1, prime q and uniform dimension N=2^1285200000000000. Write G=|GL_N(F_q)|, H=q^(N²(w−1)), L=B G and W=L H. The low type has a productive role and a low matrix. The high matrix has H values for each low matrix. If the root reserves P=T W^D rows, a packet after j low selections has + + T (L H)^(D−j) H^j + +rows. The unused stock still has (L H)^(D−j) choices per slab. Let a1, dropping the carry changes the map. Its coefficients are rational units and q-integral entries for fixed S. Gaussian elimination at the chosen q uses unit pivots throughout on the fixed rational matrix. Each fixed scaling, translation or ordered addition acts on complete fields. Upper additions use two previously funded complete ordinary interchanges. This charges O_F(V w^(1−b)) for a fixed list of high-field routes when the earlier stage has saving b. + +The decision to enter a good or bad child depends on the old low pivot. The bad body uses an unconditional slot list at that pivot. A coefficient that is zero modulo q can be a nonzero element of Z/q^w. The full coefficient is evaluated for that fixed slot. No future stock digit is a predicate of the dispatch. The emitted chronology is the same for all high values in a low packet. Therefore every individual paid occurrence sees the complete low/high cylinder at its fresh input, regardless of past branch decisions and of ancestor-dependent weights. Between child calls, the parent applies the inverse row placement to the full return. It does not stop on zero data or remove padded rows. These facts exclude both published conditional-frequency counterexamples. In particular, even an identity route with the correct final address map would fail if it removed the final incomplete slab early. [Fresh-fibre theorem and counterexamples](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/selected-cover-fresh-fibers/README.md) · [Source low/high operator and fallback](https://github.com/CrocSwap/integer-mult-bounds/blob/a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e/research/grade14-native-realization/ROUTES.md) + +At one request P is a conjugate of a split rank-one projector. Under the uniform low group, it is uniform on its similarity orbit. Write its low value as uvᵀ with vᵀu=1. Each projector has exactly q−1 representations. The chance of u₀=0 and the chance of v₀=0 both equal p=(q^(N−1)−1)/(q^N−1), by symmetry of nonzero vectors. Conditional on u₀=0, the value v₀ is free. Thus the bad pivot fraction equals (2−1/q)p<2/q when N>1. For N=1 this fraction is zero. A fresh low route preserves uniformity separately at each actual paid occurrence. The good child has at most floor(c/N) atoms for parent c. A bad low uses at most 32N² children of that same maximum width, including same-orientation correction children. The source's looser 2N³/q upper bound suffices. If P_calls/B is the uniform leaf ratio, the normalized recursive moment at s is at most + + (P_calls/B) N^(−s) (1+64 N^5/q). + +This sums over separately counted paid edges. No probabilistic independence is needed. Keep unused active high digits in each paid volume V/L. Each frame has a fixed number of parent banks, their full projected fields, descriptors and temporary buffers. With the proven allocation and stack primitives, the occupied volume along one coarse chain is bounded by a fixed multiple of V Σ_j L^(−j)≤2V. There is one active stack per ordinary stage at any instant. Calls to a previous stage during a parent route finish and return before that parent schedules its next child. That previous stage can borrow from the earlier operand of its own old swap while the parent parks all other data. The returned old permutation preserves arbitrary outer prefix, gap and suffix. Therefore it realizes the desired route on the parent high coordinates even when the old operand lies inside a current high cube. [Recursive closure and its physical boundary](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/selected-bit-recursive-closure/PROOF.md) + +## Stock growth, conversion, and the ordinary root + +Choose w as the least integer with w^250≥e and put d=max(1,ceil(e/w)). The bound D=2+ceil(log_N d) covers every coarse path, since its positive children have at most floor(c/N) atoms. Compute D by integer comparisons. Allocate W(w)^D before joining the body. For earlier stage stock multiply by its full reserve when both need to live. On the current stage log_q W(w)≤log_q(BG)+N²(w−1). The old stage exchanges O(w)-digit fields, up to fixed radix conversion constants. After finitely many older stages the sum of the logarithms of all simultaneous stock factors is O_F(w(1+log e)). This bound also follows by descending the finite stage index and bounding each older term by the same current w log(e+2). It includes high matrices, all low types and independent productive inputs. Because w≤e^(1/250)+1 and 1/250<1, the sufficient k=ceil(log_q stock) eventually satisfies k0, (log p)^K = o(p^δ) for fixed K. Thus the sum has time O(n(log n)^(1−κ)). + +Use a constant number of full arenas reused by serial stages. Frame backing is geometric along an active call chain. The number of different ordinary stage indices on a chain is bounded by six. Old high matrix fibres remain live in each low child. Price cold and fallback calls, return to the saved heads, then physically erase the largest historical interval in that child. Full CRT passes run by **level** in previous/output arenas. No chain of log d full parked arrays is held. Each sparse key has O(p) bits. All face buffers, keys, masks and full RHS transposes stay within O(V). The separate 2^o(p) tables, evaluator and short-product scratch for a single call fit in O(n). A time bound alone on the Harvey–van der Hoeven primitive suffices since only one such short product runs at once. All complete Gaussian fields, including native temporaries of each scalar, use O(p)=O(6 ceil(log₂ n)) bits per component. A packed polynomial is a sequential stream of r such scalars. Total maximum *ever visited* backing on the fixed tapes is O(n). + +## One machine for all lengths + +Generate both finite integer templates on the fixed carrier dimensions before the large-input recursion. All loop bounds used to produce them are finite integers. Exact matrix rank and rational basis calculations determine a finite list of denominators and minors. Exclude the primes dividing them and select one sufficiently large remaining prime by trial division. Keep this word fixed for all n. It may be placed in finite control or generated once from a fixed finite description on work tapes whose maximum setup cost is a constant relative to n. The same argument applies to fixed tables for fixed q, including the q² bucket interfaces. It cannot justify a free table as a function of p. The preceding proof charges those separately. All input-dependent dyadic exponents, guards, branch counters, windows, radius thresholds, row counts and tape extents are computable. Avoid transcendental equality tests by using integer width and outward intervals as in the Gaussian producer. + +Take a cutoff above all of the sufficient bounds in these proofs. Such a fixed integer is effective. Constants in finite templates come from finite enumeration. Powers beat logarithms effectively by bounding exp(δ log p) below by a Taylor term of sufficiently large fixed degree. Bounds involving exp(−c sqrt(log t)) use the explicit prime estimate and the same comparison. Fixed finite matrices and all requested inequality tests use exact rational or outward arithmetic with strict room. For horizons on stopped ordinary and complex recursions use integer power comparisons and the elementary branch at each stated bounded terminal. Alternatively check the integer geometric guards at each input and run elementary multiplication if a guard fails. The estimates above prove a common tail on which every guard passes. Use elementary multiplication at the bounded starting lengths. A large fixed constant absorbs all their times and scratch. This proves uniformity in n with a finite alphabet and tape count. It gives no practical size for the first fast input. diff --git a/research/mixed-rank-uniform-composition/SOURCES.json b/research/mixed-rank-uniform-composition/SOURCES.json new file mode 100644 index 0000000000..90a1d80656 --- /dev/null +++ b/research/mixed-rank-uniform-composition/SOURCES.json @@ -0,0 +1,432 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "path": "AGENTS.md", + "usage": "provenance", + "git_blob": "ff81117fca368042f6092964d1f54eb4e6e08fb9", + "sha256": "fece32cdec9c1572ddce354a0b623459cb2c4ca162125d36d36262a92e3caa83" + }, + { + "path": "LICENSE", + "usage": "provenance", + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4" + }, + { + "path": "NOTICE", + "usage": "provenance", + "git_blob": "59d8e0cf3102e15bd11db430838365531e2d7f18", + "sha256": "b49022cb4104d90b182e4c335f670faf45529025b15db77bf0291835083c28bd" + }, + { + "path": "autoresearch.md", + "usage": "provenance", + "git_blob": "2fe84a7b30b1e26e60ce0ec4775894eb1831c5d6", + "sha256": "d16f0d3bb4d4b213d06c128db6d6460b0fe9ec1ac5a6c1ea1febf1db40e7b60d" + }, + { + "path": "certificates/frontier7000/CLAIM.json", + "usage": "provenance", + "git_blob": "c9b816f8445be9dc19b2259e03e9d8709d18c87a", + "sha256": "3f8add8252adb223b60418ec69351a69b6b5edfe601ec1c6b4b65cd9e2afd9b2" + }, + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "75d77b328ea02ded535e7f23aee5b1e55d0bb1a8", + "sha256": "154c3d30455d778fd3343b6b4851f0fa4665f0f7625b0adb3675e2bafbbf6bf1" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81" + }, + { + "path": "research/capped-phase-fusion/SUPPLIER-SUPPORT-AUDIT.md", + "usage": "provenance", + "git_blob": "ae676a6504cc7987863da1827551c18e7ec20ce1", + "sha256": "c41a2571b9c4c1d7920633f10c3ed2c74da39ca3bc8d6a910e6ffed380327413" + }, + { + "path": "research/capped-phase-fusion/SUPPORT-ADVERSARIAL-AUDIT.md", + "usage": "provenance", + "git_blob": "80b2afa7433b3139ac926047012658ea500b4a5d", + "sha256": "b1290f8720bf075ea2ad58d6070f3e1fc95c0155f8e33b165bc13439bbb9222d" + }, + { + "path": "research/capped-phase-fusion/SUPPORT-ROUTER.md", + "usage": "provenance", + "git_blob": "4f39fa9eaf553d1df5111de8c19bcf5bf9829c2b", + "sha256": "6ddb322e11883c1177ba6cd1a77d23a1dac827d7290b32eaf642457b1d762a54" + }, + { + "path": "research/crt-arbitrary-source-repair/PROOF.md", + "usage": "provenance", + "git_blob": "147633ce18d41f44cbd6bdc2030fcdf962b415a4", + "sha256": "1b8cb76afc6bf923c31377ba22c7675b3e563e3341fc5db0cd9d1057be4ee624" + }, + { + "path": "research/crt-arena-batch-threshold/PROOF.md", + "usage": "provenance", + "git_blob": "f4aba806646d80dedc42af4e7a8d4f72ad18f782", + "sha256": "8c9dbbd057811cfbca421234bc9b1f43f71d367a374508231d344c072ed779bb" + }, + { + "path": "research/crt-mixed-width-caller/README.md", + "usage": "provenance", + "git_blob": "ff3b6d0708cd5296e71756a16b22167746ac1b24", + "sha256": "c5126d2e1f381fe5a34b8e3350799ac4c3a58fe2def590b12ad4354da7b01ebf" + }, + { + "path": "research/crt-reservoir-placement/PROOF.md", + "usage": "provenance", + "git_blob": "087ab4462282fc68d6f5b8b1f17167383e77df7c", + "sha256": "cea5eec3d4ec1008293e98213f519bdbf88dcd9aa801bff516eaee24340efa68" + }, + { + "path": "research/crt-tail-single-buffer/PROOF.md", + "usage": "provenance", + "git_blob": "49e4097ca9bccd7eb9e736a786c02bf7a32f1f75", + "sha256": "c2263237b6bff918d23a06cee44ce936c99525da239f7350eed0917b334e70fc" + }, + { + "path": "research/crt-uniform-evaluator/PROOF.md", + "usage": "provenance", + "git_blob": "7175c780b63378963c00ea29d76a9d1d7f86bbf0", + "sha256": "a67dce487dfaf0f1748458cf052b85203654d63f84c4e362ae78fe1bae1a3d42" + }, + { + "path": "research/delayed-cover-batch-allocation/PROOF.md", + "usage": "provenance", + "git_blob": "32303307679612e33f8f6a3416b2b48c0cb5c53e", + "sha256": "adab55de97f1336a58922b2fc92782af335a94a36cbaae34d6d3314d18a882ea" + }, + { + "path": "research/delayed-cover-physical-batch-routing/PROOF.md", + "usage": "provenance", + "git_blob": "af919b5ba2257c07ea17180f9b8c9fd457556079", + "sha256": "1c3dcd294d327a16fa081b7ea27497941ac6480d352f53e55e8b9e87f45d1454" + }, + { + "path": "research/fine-expansion-page-admission/README.md", + "usage": "provenance", + "git_blob": "82522c543c4d5c3ca2762bba25b8bd4f20bfce7b", + "sha256": "7ea8a51cc0ff464bbd360f7dc9a6cda18d466b541b7dbf3482450bbcccfe600d" + }, + { + "path": "research/fine-recovery-catalogue-obstruction/README.md", + "usage": "provenance", + "git_blob": "f4301b9d19b22e33522e883e3448bbc53fa8cf4b", + "sha256": "ca7f4eb5ced17d5aac11e5cc70643dd37102b93d4a71a3a9410967869f7ca8a9" + }, + { + "path": "research/finite-parking-frames/PROOF.md", + "usage": "provenance", + "git_blob": "15ea512d0f534649b11b4bb78eebf2c2d85f5a6b", + "sha256": "0aeddba71df2fba37ae026ac10585b8ee41dee96e453fd950f12f307f9252090" + }, + { + "path": "research/first-face-reference-join/PROOF.md", + "usage": "provenance", + "git_blob": "dd35fbaf22667621885c3255b9fecae91072c589", + "sha256": "70ea68e3ef401117266d5273d4d772db2f8ba01c28fbe2ffbb00b154947eceb5" + }, + { + "path": "research/first-face-reference-join/README.md", + "usage": "provenance", + "git_blob": "4f9830826eedae2fac0845e8f09b78123046d0d7", + "sha256": "6c837bae3f5591b1cc23ab5d4f7af82d26acc70a9158c8f1885e3d53d9380108" + }, + { + "path": "research/kappa-rebuild/architecture/FINITE-PRECOMPILATION.md", + "usage": "provenance", + "git_blob": "4badb40f0919c515823cb07e44c6470d4d6469ca", + "sha256": "4cb32f6b8e388ecf6ed41b5bbdeeb4539cb40c8424f194974afea58f7e0921e8" + }, + { + "path": "research/kappa-rebuild/transfer-audit/OUTER-TRANSFER-AUDIT.md", + "usage": "provenance", + "git_blob": "e8b7ef8956ece5bd493cbf52113916e5dc288535", + "sha256": "67569961d068633c6ff3ac9dfde47a0c17f0da6d20432799dcc920cff92b5779" + }, + { + "path": "research/literal-complete-row-parking-caller/PROOF.md", + "usage": "provenance", + "git_blob": "c80c6be99447a3e242120fff186662daa9b250ba", + "sha256": "c076d8638ea543f209b6c1438315dc25e39097c4b516f4a7a24d3fdaa1c4b38c" + }, + { + "path": "research/native-kappa-30201655/modern-sources/FINE-PRIME-PADDING.md", + "usage": "provenance", + "git_blob": "bf9899ee21be4058e4aac0b64bfa67d01ee8ddd3", + "sha256": "47d1b1b4df28aadda3cd6bdeb1fbc47290595e9208cd09c1a1f338520d33fdce" + }, + { + "path": "research/odd-native-common-grid/PROOF.md", + "usage": "provenance", + "git_blob": "edea8e98a082f4513aedbfb7bd55f32063e32b38", + "sha256": "b710cc953163ebe282fce7cf0a426744c155a0d5acbfb9bf7d67e81195b66a1e" + }, + { + "path": "research/p104-shared-native-helper-splits/retained/compiler/PROOF.md", + "usage": "provenance", + "git_blob": "f5ef0d2e8289adfb6c5e73c4b58970da462d7df2", + "sha256": "95cc9e31bc030ec94b04decddcca2d28ee98cfec0ca7803b54666b2b76a5c9ab" + }, + { + "path": "research/pr4100-chirp-odometer-tariff/README.md", + "usage": "provenance", + "git_blob": "c0f8b2a006965074c38484964d05f0a9cc1f3008", + "sha256": "6ed0793017d3c84003b0c7921c7b9598b868c48f05e46b8c0a88c52cfb843ff5" + }, + { + "path": "research/pr4100-guard-coloring/README.md", + "usage": "provenance", + "git_blob": "6948763f4a9e452aa39e3c5f6ce2000a7bbfe0fb", + "sha256": "0077e4ff3043b8af6ce8bc87d17250d46690605b7886fe533877936097f64118" + }, + { + "path": "research/pr4100-row-field-movement/PROOF.md", + "usage": "provenance", + "git_blob": "8cb9097d216677e218c5e59d9d6e7e77801e8727", + "sha256": "9b20f66269383535d20f1f0a762710a393ea036471a9383b7dafc07db341d02b" + }, + { + "path": "research/pr4100-union-head-travel/README.md", + "usage": "provenance", + "git_blob": "b66c8e1588be625353e08563f4f73a1319024f73", + "sha256": "590492b2d5439fb4cd8c711701f20fded712f973b9a517627c1b556566a78193" + }, + { + "path": "research/selected-bit-recursive-closure/PROOF.md", + "usage": "provenance", + "git_blob": "6c410cab5713979214a45835091fbeb9ee9b8531", + "sha256": "74cc8de20f21acb5123fe2d20996fe0925ea6e51b3dec633bd5221fb719b3344" + }, + { + "path": "research/selected-cover-fresh-fibers/README.md", + "usage": "provenance", + "git_blob": "8d9e84dc7c0c94df6f34a82b632f2c0a1773a13b", + "sha256": "00fd2fe89905052b75a17bff8ea6f5a249dda1293ec33c0c8d2e329a15694503" + }, + { + "path": "research/shrinking-reference-halo/PROOF.md", + "usage": "provenance", + "git_blob": "c47fc7013bfb814428a94ecc2984d2a75c92c300", + "sha256": "1f49c8289e05ff99673f83c810ccd9c310faee9ecebee96e5b1f20db2b7a6061" + }, + { + "path": "research/unconditional-batched-crt/CRT.md", + "usage": "provenance", + "git_blob": "d98dd8e368431cac33d5fc1c8c336696663641d6", + "sha256": "02c3a1e38cbee25aefe2640cc72676da62ba10eb7519fbcb9adb9d48b74eff2b" + }, + { + "path": "research/unconditional-batched-crt/NOTICE.md", + "usage": "provenance", + "git_blob": "886a8fdee275f01b459cbd68ae2815dc9269502f", + "sha256": "924109837e71c52392191710d49c9deb42780878d1094f0b01e8690dbe799461" + }, + { + "path": "research/unconditional-batched-crt/PROOF.md", + "usage": "provenance", + "git_blob": "406eb561cc8d6041ea3fba1a849653b654f2198c", + "sha256": "689fc7b01c5f04f77019ff02d1b79cb4f7020bd98e05b1052020bad295dec060" + }, + { + "path": "research/unconditional-batched-crt/vendor/GAUGEFREE-INTERIORS.md", + "usage": "provenance", + "git_blob": "20585e44fa4e49b13b5d8495bbf6ed254459a362", + "sha256": "d1423ac0ea0003521797209f4396e6981a66994bbee4f8b48026e5b95f8c5116" + }, + { + "path": "research/unconditional-batched-crt/vendor/SHALLOW-TOEPLITZ.md", + "usage": "provenance", + "git_blob": "bc4349b2daea548ffa09e1f38a31f1df86b0b7be", + "sha256": "b384b93f3fb4a8c97da2e617ebc14d55cebb0a739070e7f8dbb66f63e24e9310" + }, + { + "path": "research/unconditional-batched-crt/vendor/TENSOR-COMPILER.md", + "usage": "provenance", + "git_blob": "19efb9cb1c5a738e57caadf2dd6f5611af1bc78a", + "sha256": "4d3b8466598a864a234b978e25976648d4e761840aad9153dd18d73d3dfe4d15" + }, + { + "path": "research/unconditional-batched-crt/vendor/UNION-SCHEDULE.md", + "usage": "provenance", + "git_blob": "b5eb03e6745804f465a536fc9ffa87c2515d1bfa", + "sha256": "aabb28c343bcb9697a4cac7058060132617073df17ee18e591d2bf4defe9e921" + }, + { + "path": "upstream/build/sections/05-layers.tex", + "usage": "provenance", + "git_blob": "5ce8b3c83c455f221bb84858a97230b0285644aa", + "sha256": "20cfc8d12099d4e4ed9e3e7eeb6162edd9b6e0e076f24693364cd24377252594" + }, + { + "path": "upstream/build/sections/06-transforms.tex", + "usage": "provenance", + "git_blob": "de073e9292d58573f7065a3cd4f214e0d05f3444", + "sha256": "924316e4bc905066281d8f9e8746a49d8829aeb393688608deb1e61c3c87853c" + } + ], + "external_revisions": [ + { + "commit": "82553cf6f369459e18d00fb4e6bda808d5f10ce1", + "path": "research/gaussian-forward-parity-flux/README.md", + "usage": "provenance", + "git_blob": "923f3ac612a4fdcc31987053dcfa21a004993932", + "sha256": "c93f1e203c1869a4f3c5706f9432975e17f746442c587cffa450b3c09ba83df5" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-chart306-chain/DOUBLE-APPLICATION.json", + "usage": "provenance", + "git_blob": "714f7b48a2a70bb2cc9f7cd4206b2a8701bbb062", + "sha256": "1b2d87e93ae023f5ffd464546af53281b6cb4963dfd76ae4742e0a5540b752fa" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/AUDIT.json", + "usage": "provenance", + "git_blob": "26f17af68971430ff5dfd63dfb593071b8773b61", + "sha256": "a4f318b83a810758bc9dc80eec15326e2794441f36d872aa24811b61c5d9f376" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/BIT.json", + "usage": "provenance", + "git_blob": "00ef12054429b954309721969b4f167b5d29fad2", + "sha256": "8744587b49787bd9bfaed28a2595069d91afa45274284049bbba9764bc704a7d" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/NOTICE", + "usage": "provenance", + "git_blob": "fe51894a1a630c6feee4b13da2a0499e41ee6edf", + "sha256": "b213998c8dae6d88e4a1f0fd17c81dd78c31ef35bc9460fa16ca692326f1a02b" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/PROOF.md", + "usage": "provenance", + "git_blob": "9bdf397a0c8477b6a0dc2bf39ea6ce8f78b794d2", + "sha256": "9cccaa9fb7d5eed04bd215f2ff77dc99766d8db78e33f0e876199ac4c6a5ae4f" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/README.md", + "usage": "provenance", + "git_blob": "e6725724d8d69745a22d55c011df00d05684771f", + "sha256": "d73b3e3624e5f59e23b8c5f0f724f6f58732af495fc81aca46a169e23aa517f6" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/RESULT.json", + "usage": "provenance", + "git_blob": "da566a9558c46663b4f92f151dc67dddb1139e43", + "sha256": "036eb36b24467b6842e1348a49ec6ca7ac87d3e66c5856cfadf6d387189ea360" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/SOURCES.json", + "usage": "provenance", + "git_blob": "84a8e0ff6df50354ecbb05f02d4162011991b8cc", + "sha256": "357e6fe1a57bcb03be10874ba69ad075729802f15ac9614606856a16dc2c8e4f" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/bit_certificate.py", + "usage": "provenance", + "git_blob": "292c966e27d1a88fc38df30c4268c42ca905d672", + "sha256": "833bee1b33bb564cd44f3dc80201ab87c88d23db2fd9e2e879b46b1bfbf0b500" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/review/independent.py", + "usage": "provenance", + "git_blob": "12689d64db238d53620b2afbe3be958ccf2edc40", + "sha256": "a2366b60cb4cd535fbcbce2a834cdf2ed4b9daba3e7025c7403e6abcd598a7ca" + }, + { + "commit": "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15", + "path": "research/p104-mixed-rank-supplier/verify.py", + "usage": "provenance", + "git_blob": "69cbf014f5cd3a752d49e8bd6e339f47fa06b796", + "sha256": "5a073a31a4ea63ab5943057db2682029cb5524b8373116f51be580b1a3dde69b" + }, + { + "commit": "89a67c404226d51028e135de2b9169e9020d57af", + "path": "research/p104-iterated-returns/continuation/compiler.py", + "usage": "provenance", + "git_blob": "0e0580ae4a977010ed30a4ba259c2f0ad20ab33f", + "sha256": "c160563bc51f984224bbb0a00f9e69b276fa618a83591c00f38fb9fa8d958d9c" + }, + { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/APPLICATION.md", + "usage": "provenance", + "git_blob": "676314305f0d1d5f08ad7bc0584e7e88ba6e663c", + "sha256": "f098667098bacf5619b479e909dfe95331e0761b9e583876e9f3140d375233d0" + }, + { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/NOTICE.md", + "usage": "provenance", + "git_blob": "e349522f743a6c1818678368845c8b5703fa9125", + "sha256": "8f42538d8ac31c6e42cbd3b52298b6a74b0dbf6ad78828f7aaf1b3dce3b47621" + }, + { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/PROOF.md", + "usage": "provenance", + "git_blob": "861e5fb0cadfa799e58f80977b64fce23d73db80", + "sha256": "2acfa8dacf98629d3ec51a3475557706723f6bdecd37b1d6ffdfaa4a278de013" + }, + { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/ROUTES.md", + "usage": "provenance", + "git_blob": "2b73c1f1928a82e147bbb62c4c6714ca15bfe5c9", + "sha256": "5e7ff92ce2566158bef66536c76c0b2dbece45ac66f85c7c902f4de2ed802d16" + }, + { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/VALIDATION.md", + "usage": "provenance", + "git_blob": "2b9b88f0406cea3b15c8e0900d3f18b925b3cf1e", + "sha256": "ee24f7ab01d9e70314b75e637284fbd06532d3e3afaa3046aae779de243a62e9" + }, + { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/cover.py", + "usage": "provenance", + "git_blob": "a211f9a69ef58f3e9910e74652882b0e02f620bc", + "sha256": "52cfdb73f0289b1d2fd015865104dc66ecb7478eef2dbe3d48325791cea7b786" + }, + { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/leaf.py", + "usage": "provenance", + "git_blob": "1ded81c2c434537879972e4b711a70f7c2d5ee43", + "sha256": "a91655fd1f1429961ee1db4698b7f3f2ce091e2d94e775dc63f02c9eb8db6c64" + }, + { + "commit": "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e", + "path": "research/grade14-native-realization/retained/fallback.py", + "usage": "provenance", + "git_blob": "edae24edc2e53b1eb53d64323305b3fb1797014e", + "sha256": "c3c516a9b1541608b271acb9a782573d57f3e9a87ae97ca0c224e79b27d0a003" + }, + { + "commit": "f678a6e01df59ad0834a4544617021e5c208c37a", + "path": "research/three-axis-extremal-source-rank/README.md", + "usage": "provenance", + "git_blob": "657815cb70fe95d6b23f7bc59832da966b487ddc", + "sha256": "186ec51dc2a8f4748122470416d2b28b283daae31e21b188cbd9157a57332fe9" + } + ] +} diff --git a/research/mixed-rank-uniform-composition/SYNTHETIC-ACCESS.md b/research/mixed-rank-uniform-composition/SYNTHETIC-ACCESS.md new file mode 100644 index 0000000000..50304ccfcb --- /dev/null +++ b/research/mixed-rank-uniform-composition/SYNTHETIC-ACCESS.md @@ -0,0 +1,17 @@ +# Access from synthetic Fourier rounds to the mixed-rank P104 word + +Pin the 48-call rational word by SHA-256 7660985e0b618cdbee13e4190a4c6d5f91fbdf01a8f7a5186fdde8b980c19b48. The new 480-fold mixed-grade BIT stage implements the interchange underneath the unchanged rational word. Its signed numerical endpoint is C^tensor(h), where C=((1+i)I+(1-i)X)/2. The exact exterior-grid proof must return this value before the outer transform rounds anything. The application bound holds conditional on that all-column, uniform, restored, whole-row endpoint and its actual local time/space proof. [Pinned application](https://github.com/CrocSwap/integer-mult-bounds/blob/87fbf4f7b35b0f18ab12b5767775a9a424cf0b15/research/p104-chart306-chain/DOUBLE-APPLICATION.json) + +Let D=diag(1,i) and b=(1-i)/2. Multiplication gives H0=b D C D = (1/2)[[1,1],[1,-1]]. For h selected slots, multiply each complete coefficient by i raised to the popcount of its selected address modulo 4, apply the actual C^tensor(h), repeat that phase, and apply b^h. If h=2j then b^h=(-i)^j 2^-j. If h=2j+1 the additional factor is (1-i)/2. These operations need a sign, component interchange, addition and shift, paid on actual complete words. The exact C endpoint acts on any independent scalar array regardless of correlations between coefficient positions, previously applied twiddles, or earlier round outputs. Its unnormalized row norm can exceed one. An extra h integer guard bits cover it. In the Gaussian circuit, a dyadic prefix bound rescales larger actual inputs to unit radius first. Undoing that external scaling needs at most o(p) more bits. Round only the restored H0 output, once per Fourier round. [Exact kernel and native phase identity](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/upstream/build/sections/05-layers.tex#L41-L74) + +Use the full dyadic rectangle. The inner maximal length r=2^ell axis is the full polynomial suffix of r scalar coefficients in A=Z[i][y]/(y^r+1), after the common dyadic scalar grid is accounted for. Each outer H0 in a synthetic call acts on an actual selected axis slot, coefficientwise in this suffix, with all other coordinates complete. The top bit of the maximal-width axes is processed first. At the next level the shorter axes join them, and subsequent levels proceed by decreasing **original significance** t. Thus the active axes all target slot t, even if their original lengths are different. Different order of the independent axes' first levels only permutes commuting maps. For each active axis choose the same offset in a K-bit neighborhood, K=128(4 ceil(log2 p)+6), e.g. offset min(t,K-1). With ell-1>=K, the left edge t-offset and the right edge are within that original axis. Apply the actual selected-support gather and restore global order before every combined twiddle. + +The support router moves at most 2hK address positions. The additional address reservoirs use O(h (log p)^2)=o(p) positions uniformly for h<=d=Theta(p^(1-h0)), h0=10^-14. Keep the full inner polynomial suffix untouched. It has ell bits and ell/log²p tends to infinity, enough to group short words. When scalar-only grouped Gaussian calls expose local coordinates, use the global untouched-suffix placement in the source router. If the active reserve has h' remaining bits, the additive constant in the P104 stock bound can be huge. Above its fixed polylogarithmic threshold, the reserved set is at most h'/16. Defer those C kernels without pre-transforming them. Below that threshold, each remaining axis uses one linear full-field butterfly via splitting the two symbol blocks, joining paired values and merging them back on fixed tapes. This works for isolated most-significant or least-significant positions. h=0 is an identity. Zero-padded rows supplied to fill the native word's productive count are removed after the completed phase and before inverse exposure, since the completed map fixes their row index. A full call at each significance therefore costs O(V(h^(1-s)+1)polylog p) plus lower BIT terms. The sum over at most ell levels is O(V p^(1-e s) polylog p) using the names e,s in GROUPED-GAUSSIAN.md. This includes arbitrarily few active axes in an end level and arbitrary independent productive data. [Physical support and deferred reservation](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/kappa-rebuild/transfer-audit/OUTER-TRANSFER-AUDIT.md#L293-L364) · [Actual support router](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/capped-phase-fusion/SUPPORT-ROUTER.md) + +At significance t the current subdivision length is u=2^(t+1), and 2r/u is an integer. For an active address j set b_j to its bit at t and k_j to its strictly lower t digits. The one combined twiddle exponent is E=-sum_(active j)(2r/u)b_j k_j mod 2r. In a forward round apply the H0 layer first, then multiply the polynomial record by y^E. For opposite order, undo y^E before applying H0 in increasing significance. Other axes' twiddles commute with a given butterfly since its two inputs share their other coordinates. If E=ar+v with 0<=v0. The tail addition y→y+(ri·V(C⁻¹y)−Z(y))z uses coefficient P₀,ₙ₋₁₋ᵢ/P₀₀ at every i0 at least one numerator is odd, and (a²+b²)2^r=2^(2k). Modulo four this gives k≤floor((r+1)/2)≤ceil(D/2). The k=0 case is immediate. The new theorem `PhaseBudget.clifford_denominator` kernel-checks this last arithmetic implication, using the absolute values of the integer numerators. The flat-support argument and intrinsic Clifford status of the native operators remain mathematical steps outside that Lean theorem. After a completed outer phase re-anchor as in [the frame proof](FRAMES.md). This permits deferred axes without an active coordinate projector. + +## Historical outer tape space in terms of operand bits + +For every length in the defining positive range, b=ceil(log_2 n), p=6b and 4n/b≤T<8n/b. Therefore 24n≤T p<48n exactly. a complex record using O(p) signed bits changes only this fixed factor. All three CRT conversions operate on one complete padded cube at a time with a fixed finite number of sibling banks. Its balanced topology is executed level by level, with stable order restored between successive gates. No full parent cube is recursively retained at every tree level. The [actual CRT router](https://github.com/CrocSwap/integer-mult-bounds/blob/e54523517d0f03e58352e647c403a5af3e525a57/research/unconditional-batched-crt/CRT.md) prepares a switch using at most O(2^(4 ell) (p+2)^16) private space by its time bound. Since ell=Θ(p^(1-e)), this is 2^o(p)=o(n). Whole-volume scans for guarded holes use O(p)-bit keys and an O(p)-bit address counter, so carrying every key on every record would already take O(Tp). The runtime actually computes the expensive keys only for exceptions. Stable radix passes overwrite and erase their previous buffers. The compiled previous-stage ordinary swap may temporarily open geometric frames as proved separately in PROOF.md. The exact exponent of the re-priced conversion is 1-a+2(1-e)=1-κ-2·10^-14 up to absorbable logarithms, with a=κ+4·10^-14. The old numerical value of a in the earlier #4100 example would not justify this comparison. + +Three normalized transforms, one pointwise product and the two inputs can require several full fields simultaneously. Reserve one permanent O(Tp) extent per such fixed role and erase its current data after its last use. For middle ring products the scalar axis has length r=2^ell. One exact signed Kronecker convolution call on O(rp) bits has historical workspace O(rp log(rp)) from its independent ordinary multiplication time bound. The calls at distinct polynomial records take turns on the same work tapes. Thus this workspace is 2^o(p)=o(n). The same reasoning applies to the O(p)-bit scalar backend. The one-axis archive and all dyadic control-page setup use at most d·2^O(ell) poly(p)=2^o(p) and are also reused. During a sparse union round at most m stored split-indicator bits accrue per original record over all rounds, whence O(Tm)⊂O(Tp). Destination keys and coefficient records take O(p) bits apiece. Frame and transfer tape historical sizes depend on the *maximum*, over all completed or current calls, of the chain extent on that fixed tape. They do not sum full high-water sizes across three retained transforms, d level sweeps or repeated RHS batches. Including input, canonical zero padding and 2n output, these estimates give O(n) historical cells for these components. diff --git a/research/mixed-rank-uniform-composition/bind_compiler.py b/research/mixed-rank-uniform-composition/bind_compiler.py new file mode 100644 index 0000000000..64e6701e8e --- /dev/null +++ b/research/mixed-rank-uniform-composition/bind_compiler.py @@ -0,0 +1,82 @@ +"""Bind the native proofs and the changed mixed prices to immutable Git objects.""" + +import gzip +import hashlib +import json +import subprocess +from fractions import Fraction + + +MIXED = "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15" +NATIVE = "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e" +MP = "research/p104-mixed-rank-supplier" +NP = "research/grade14-native-realization" + + +def blob(head, path): + return subprocess.check_output(["git", "show", f"{head}:{path}"]) + + +def document(head, path): + return json.loads(blob(head, path)) + + +def require(ok, claim): + if not ok: + raise ValueError(claim) + + +def hash_bytes(raw): + return hashlib.sha256(raw).hexdigest() + + +def run(): + mixed = document(MIXED, f"{MP}/RESULT.json") + audit = document(MIXED, f"{MP}/AUDIT.json") + binary = document(MIXED, f"{MP}/BIT.json") + origins = document(NATIVE, f"{NP}/ORIGINS.json") + pins = document(MIXED, f"{MP}/SOURCES.json") + old_audit = document(NATIVE, f"{NP}/retained/grade14-audit.json") + old_binary = document(NATIVE, f"{NP}/retained/grade14-bit.json") + require(binary["native"] == old_binary["native"], "complete binary native record") + changes = sorted(k for k in audit | old_audit if audit.get(k) != old_audit.get(k)) + require(changes == ["compiler_report_sha256", "outer"], "complete complex physical record") + for local, field in (("binary", "binary_word"), ("complex", "rational_word"), ("layout", "layout")): + name = f"retained/data/{local}.json.gz" + old = next(row for row in origins if row["local"] == name) + new = next(row for row in pins if row["path"] == old["source"]) + raw = blob(NATIVE, f"{NP}/{name}") + require(raw == blob(new["head"], new["path"]) and hash_bytes(raw) == new["sha256"] == old["sha256"], + f"same compressed source for {local}") + canonical = json.dumps(json.loads(gzip.decompress(raw)), sort_keys=True, separators=(",", ":")).encode() + require(hash_bytes(canonical) == (mixed.get(field) or audit[field]), f"canonical {local}") + actual = [ + [sum(binary["native"][k].values()) for k in ("targets", "paid")], + [sum(audit["signed"][k].values()) for k in ("productive", "paid")], + ] + require(actual == [[20706, 107460], [52512, 283152]], "complete word populations") + stock = binary["delayed_cover_and_stock"] + rate = Fraction(stock["covered"]) + previous = Fraction(0) + for step in [dict(claim=stock["seed"])] + stock["stages"]: + claim = Fraction(step["claim"]) + envelope = (249*rate + previous)/250 + require(previous < claim < envelope < Fraction(1, 250), "strict stage and stock room") + if "previous" in step: + require(Fraction(step["previous"]) == previous and all(Fraction(e) == envelope for e in step["envelope"]), + "source stage binding") + previous = claim + gate = audit["outer"]["finite_compiler"] + require(previous == Fraction(mixed["binary_ordinary"]) and previous - Fraction(gate["tested"]) == Fraction(1, 62500000000000), + "separate supplier budgets") + h = int(gate["H"]) + c = audit["common_root"]["common_context_c"] + bits = (c*1920*153**1920*(h+1)**2).bit_length() + require((h, c, bits) == (15171300000000000000, 856, 14083) and bits < h, "same full root guard") + print(f"mixed {MIXED} native {NATIVE}") + print(f"native words and route layout match; binary and complex target/paid counts {actual}") + print(f"six stages from zero; complex trial {gate['tested']}; ordinary {previous}; depth guard {bits} < {h}") + + +if __name__ == "__main__": + run() diff --git a/research/mixed-rank-uniform-composition/check_binding.py b/research/mixed-rank-uniform-composition/check_binding.py new file mode 100644 index 0000000000..49897415ba --- /dev/null +++ b/research/mixed-rank-uniform-composition/check_binding.py @@ -0,0 +1,127 @@ +"""Check the ownership and precision bindings for the 480-factor application.""" + +import gzip +import hashlib +import json +import sys +from fractions import Fraction +from math import prod +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from bind_compiler import MIXED, MP, blob, document + + +def digest(data): + return hashlib.sha256(data).hexdigest() + + +def check(condition, label): + if not condition: + raise ValueError(label) + + +def check_binary(word, adjoint): + public = word["public"] + live = set(range(public)) + budget = public + word["owned_fields"] + peak = public + allocations = 0 + program = reversed(word["program"]) if adjoint else word["program"] + for opcode, owner, *args in program: + if opcode in ("INIT","CLEAR"): + check(public <= owner < budget, "public or unknown private owner") + opens = (opcode == "CLEAR") if adjoint else (opcode == "INIT") + if opens: + check(owner not in live, "aliased fresh owner") + live.add(owner) + allocations += 1 + else: + check(owner in live, "double clear") + live.remove(owner) + elif opcode in ("ADD", "SWAP"): + other = args[0] + check(owner in live and other in live and owner != other, "invalid pair") + elif opcode == "MOVE": + check(owner in live, "paid address has no owner") + else: + raise ValueError(opcode) + peak = max(peak, len(live)) + check(live == set(range(public)), "unretired owner") + return peak, allocations + + +def check_complex(graph): + public = len(graph["initial"]) + forms = dict(graph["forms"]) + available = {~i for i in range(public)} + returned = {i for i,_,_ in graph["moves"]} + terminal = set(range(graph["first_output"], graph["first_output"]+public)) + check(not returned & terminal, "output/return collision") + check(set(forms) == returned | terminal, "unknown or omitted row") + check(len(available) == public, "input alias") + terms = 0 + for row in graph["schedule"]: + check(row not in available, "reused immutable result") + for donor, scalar in forms[row]: + check(donor in available and Fraction(scalar), "unavailable donor") + terms += 1 + available.add(row) + check(available.issuperset(returned | terminal), "unfinished return") + return public, len(returned), terms + + +def main(): + pins = {row["path"]: row for row in document(MIXED, f"{MP}/SOURCES.json")} + def source(path): + row = pins[path] + raw = blob(row["head"], path) + check(digest(raw) == row["sha256"], f"source digest differs for {path}") + return raw + p = "research/p104-chart306-chain" + raw = gzip.decompress(source(f"{p}/DOUBLE-CANDIDATE.json.gz")) + binary = json.loads(gzip.decompress(source("research/p104-iterated-returns/binary/WORD.json.gz"))) + application = json.loads(source(f"{p}/DOUBLE-APPLICATION.json")) + claim = document(MIXED, f"{MP}/RESULT.json") + bit = document(MIXED, f"{MP}/BIT.json") + canonical = json.dumps(binary, separators=(",",":"), sort_keys=True).encode() + check(digest(raw) == claim["rational_word"] == + "7660985e0b618cdbee13e4190a4c6d5f91fbdf01a8f7a5186fdde8b980c19b48", + "complex word differs") + check(digest(canonical) == claim["binary_word"] == + "d3aa4426fa8fe7dc167270d01f2515184f2bff6a82744a14e941c5dd3afca27d", + "binary word differs") + check(int(claim["power"]) == 480 and claim["paid_cutoffs"] == + {"grades_1_to_4":10, "grades_above_4":11}, "wrong mixed rule") + print("complex immutable banks and donor reads", check_complex(json.loads(raw))) + print("binary peak live including public, total private opens", + check_binary(binary, False), check_binary(binary, True)) + factors = application["conversion"]["odd_factors"] + root = application["common_root"] + check(prod(factors) == root["native_odd"]["tested"], "wrong odd scale") + check(max(f.bit_length() for f in factors) <= 24, "odd scalar too wide") + H = int(application["common_depth_guards"]["tested"]["compiler_H"]) + c = 2 * max(root["context_binary_bits"], root["context_mass_bits"]) + d = (c*1920*153**1920*(H+1)**2).bit_length() + check((c, d) == (856, 14083) and d < H, "depth limit") + print("root c, exact context product bit length, compiler H", c, d, H) + cover = bit["delayed_cover_and_stock"] + covered = Fraction(cover["covered"]) + rho = Fraction(cover["rho"]) + cold = (1-rho)*covered + seed = Fraction(cover["seed"]) + check(cold > seed and rho > seed, "cold start misses ordinary seed") + previous = seed + for record in cover["stages"]: + result = Fraction(record["claim"]) + check(previous == Fraction(record["previous"]) and + result < min(rho, 1-rho, (1-rho)*covered+rho*previous), "stage gap") + previous = result + check(len(cover["stages"]) == 5 and previous == Fraction(claim["binary_ordinary"]), + "stage binding") + print("ordinary stages including cold stage", 1+len(cover["stages"]), + "cold excess over seed", cold-seed) + + +if __name__ == "__main__": + main() diff --git a/research/mixed-rank-uniform-composition/check_gaussian_pages.py b/research/mixed-rank-uniform-composition/check_gaussian_pages.py new file mode 100644 index 0000000000..6a0395417a --- /dev/null +++ b/research/mixed-rank-uniform-composition/check_gaussian_pages.py @@ -0,0 +1,122 @@ +"""Check fine-prime pages generated with integer interval arithmetic.""" + +from decimal import Decimal, localcontext +from math import isqrt +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from gaussian_pages import ceil_sqrt, admitted_row, recovery_diagonal, selected_source, width_parameter + + +def demand(condition, message): + if not condition: + raise ValueError(message) + + +def independent_pi(): + # This comparison uses the arithmetic-geometric mean on Decimal. + a, b, t, power = Decimal(1), (Decimal(1) / 2).sqrt(), Decimal(1) / 4, Decimal(1) + for _ in range(8): + mean = (a + b) / 2 + b = (a * b).sqrt() + t -= power * (a - mean) ** 2 + a, power = mean, power * 2 + return (a + b) ** 2 / (4 * t) + + +def audit(p, bits, r, t, fine): + unit = 1 << bits + alpha = width_parameter(p) + window = 8 * alpha * ceil_sqrt(p) + B = 16 * p * p + normalizer = 1 << (p**100 - 1).bit_length() + if fine: + demand(t <= 4*p*p*(t-r) and 2*p*p*(t-r) < t, 'source outside the fine interval') + demand(all(r % k for k in range(2, isqrt(r)+1)), 'composite source') + slots = [(2*t*j+r)//(2*r) for j in range(r)] + demand(slots == sorted(set(slots)), 'source image collision') + sources = {slot: j for j, slot in enumerate(slots)} + broad_cols = [0] * t + mass_max = left_wrap = right_wrap = aliased = samples = broadened_holes = 0 + with localcontext() as ctx: + ctx.prec = 82 + pi = independent_pi() + for v in range(t): + selected = v in sources + demand(selected_source(r,t,v) == sources.get(v), 'wrong original coordinate') + diagonal = recovery_diagonal(p, bits, r, t, v) + if selected: + beta = Decimal(t*sources[v]-r*v)/r + exact_d = (pi*(alpha*beta)**2).exp()*unit + demand(diagonal <= exact_d <= diagonal+2, 'diagonal interval') + else: + demand(diagonal == unit, 'hole diagonal') + mass = diag = broad_sum = 0 + seen = set() + emitted = {} + for col, period, broad, narrow in admitted_row(p,bits,r,t,v,window): + emitted[col, period] = broad, narrow + if broad: + aliased += col in seen + seen.add(col) + left_wrap += period < 0 + right_wrap += period > 0 + broadened_holes += not selected and col in sources + broad_cols[col] += broad + broad_sum += broad + if col == v: + diag += narrow + else: + mass += abs(narrow) + if col not in sources: + demand((col, period, broad, narrow) == (v,0,unit,unit), 'invalid identity column') + elif not selected: + demand(narrow == 0, 'invalid narrow coupling to a hole') + if col in sources and (not fine or (7*v+col)%113==0): + beta = Decimal(t*sources[col]-r*col)/r + delta = Decimal(col+period*t-v)+beta + exact_b = (-pi*(delta*r/(t*alpha))**2).exp()*unit/alpha + demand(broad <= exact_b <= broad+2, 'broad entry interval') + if selected and col != v: + exact_n = (-pi*alpha**2*(delta**2-beta**2)).exp()*unit + demand(narrow <= exact_n <= narrow+2, 'narrow entry interval') + samples += 1 + if not fine or v % 31 == 0: + # Choose the addresses independently of emitted support. + for off in (-window, -9, -3, 0, 2, 7, window): + period, col = divmod(v + off, t) + if col not in sources: + continue + beta = Decimal(t*sources[col]-r*col)/r + delta = off + beta + broad, narrow = emitted.get((col, period), (0, 0)) + exact_b = (-pi*(delta*r/(t*alpha))**2).exp()*unit/alpha + demand(broad <= exact_b <= broad+2, 'independent address broad interval') + if selected and col != v: + exact_n = (-pi*alpha**2*(delta**2-beta**2)).exp()*unit + demand(narrow <= exact_n <= narrow+2, 'independent address narrow interval') + samples += 1 + demand(diag == unit, 'missing principal narrow diagonal') + demand(unit+B*mass <= B*unit, 'Neumann row gap') + demand(unit+normalizer*mass <= normalizer*unit, 'normalized row radius') + demand(broad_sum <= 8*unit, 'broad row bound') + mass_max = max(mass_max,mass) + demand(max(broad_cols) <= 8*unit, 'broad column bound') + demand(min(left_wrap,right_wrap,broadened_holes,samples)>0, 'incomplete physical coverage') + if not fine: + demand(aliased>0,'a retained periodic occurrence was lost') + return r,t,mass_max,left_wrap,right_wrap,aliased,samples + + +if __name__ == '__main__': + for target in ((1013,1024,True),(2029,2048,True),(3,4,False)): + print('r, t, max mass, left/right wrap, repeated slots, independent entries =', audit(6,36,*target)) + try: + admitted_row(6, 36, 65535, 65536, 32767, 72) + except ValueError as failure: + demand(str(failure) == "narrow row fails the inverse bound", "unexpected rejection") + else: + raise ValueError("admitted a row with insufficient convergence margin") + print("PASS_PHYSICAL_GAUSSIAN_ADMISSION") diff --git a/research/mixed-rank-uniform-composition/check_group.py b/research/mixed-rank-uniform-composition/check_group.py new file mode 100644 index 0000000000..f164678e3e --- /dev/null +++ b/research/mixed-rank-uniform-composition/check_group.py @@ -0,0 +1,206 @@ +"""Finite, independent controls for GROUPED-GAUSSIAN.md. Standard library only.""" + +from decimal import Decimal, localcontext +from fractions import Fraction as F +from itertools import product +from math import prod + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def charge(): + k = F(".00387992803556") + gap = F(1, 10**14) + eps, beta = 1 - gap, 1 - 3 * gap + bit, hadamard = k + 4 * gap, k + 3 * gap + xi = eps * (1 + hadamard) - F(3, 32) + gap + exponents = { + "hadamard": eps - hadamard * beta, + "support": eps - bit * beta, + "group_scan": eps - beta, + "boundary": eps + F(29, 32) - xi, + "union": eps + F(1, 2) - xi, + "shrinking_halo": eps + beta + 54 - 128, + "physical_crt_if_admitted": 1 - bit + 2 * (1 - eps), + } + margins = {name: 1 - k - power for name, power in exponents.items()} + require(min(margins.values()) > 0, "power outside budget") + require(beta > 1 - eps and beta + 2 * (1 - eps) < 1, "archive/dense guard") + require(F(1, 2) < xi < 1 and beta < eps, "carve/precision") + naive = F(".003879928035646") + require(naive / (1 + naive) < k, "unfused transfer negative control") + require(eps + beta + 3 * 48 - 128 > 1 - k, "old cubic halo tariff negative") + return {name: str(value) for name, value in margins.items()} + + +def identity(n): + return [[F(i == j) for j in range(n)] for i in range(n)] + + +def multiply(a, b): + cols = tuple(zip(*b)) + return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a] + + +def apply(a, x): + return [sum(w * v for w, v in zip(row, x)) for row in a] + + +def inverse(a): + n = len(a) + aug = [row[:] + right for row, right in zip(a, identity(n))] + for i in range(n): + j = next(j for j in range(i, n) if aug[j][i]) + aug[i], aug[j] = aug[j], aug[i] + divisor = aug[i][i] + aug[i] = [v / divisor for v in aug[i]] + for j in range(n): + if i != j: + multiplier = aug[j][i] + aug[j] = [v - multiplier * q for v, q in zip(aug[j], aug[i])] + return [row[n:] for row in aug] + + +def sub(a, rows, columns): + return [[a[i][j] for j in columns] for i in rows] + + +def ref(r, t): + """Make two exact dyadic test bands. Decimal chooses finite test data only.""" + q = [(2 * t * j + r) // (2 * r) for j in range(r)] + selected = set(q) + h, u = identity(t), identity(t) + pi = Decimal("3.14159265358979323846264338327950288419716939937510582097") + alpha = Decimal(2) + scale = 1 << 17 + with localcontext() as ctx: + ctx.prec = 65 + rho = Decimal(t) / r + for j, col in enumerate(q): + b = rho * j - col + for v in range(t): + h[v][col] = F(0) + u[v][col] = F(0) + for period in (-1, 0, 1): + offset = col + period * t - v + if abs(offset) > 1: + continue + arg = Decimal(offset) + b + broad = (-pi * (arg / rho / alpha) ** 2).exp() / alpha + u[v][col] += F(int(scale * broad), scale) + if v in selected: + narrow = (-pi * alpha ** 2 * (arg**2 - b**2)).exp() + h[v][col] += F(int(scale * narrow), scale) + if v == col: + h[v][col] = F(1) + require(q[0] == 0 and all(a < b for a, b in zip(q, q[1:])), "q image") + require(u[0][-1] > 0 and u[-1][0] > 0, "cross-period columns lost") + require(any(i not in selected for i in range(t)), "holes empty") + return h, u, selected + + +def five(q, interior, x, inv): + """Evaluate the five suboperators, rightmost first, including dirty fields.""" + boundary = [i for i in range(len(q)) if i not in interior] + a = sub(q, interior, interior) + ai = inverse(a) + b = sub(q, interior, boundary) + c = sub(q, boundary, interior) + d = sub(q, boundary, boundary) + fill = multiply(multiply(c, ai), b) + f = [[u - v for u, v in zip(row, term)] for row, term in zip(d, fill)] + u = [x[i] for i in interior] + v = [x[i] for i in boundary] + if inv: + u = apply(ai, u) + v = [w - z for w, z in zip(v, apply(c, u))] + u, v = apply(a, u), apply(inverse(f), v) + u = [w - z for w, z in zip(u, apply(b, v))] + u = apply(ai, u) + else: + u = apply(a, u) + u = [w + z for w, z in zip(u, apply(b, v))] + u, v = apply(ai, u), apply(f, v) + v = [w + z for w, z in zip(v, apply(c, u))] + u = apply(a, u) + out = [F(0)] * len(q) + for indices, values in ((interior, u), (boundary, v)): + for i, value in zip(indices, values): + out[i] = value + return out + + +def infinity(q): + return max(sum(abs(v) for v in row) for row in q) + + +def splice(h, u, selected): + n, side, halo, terms = len(h), 16, 3, 3 + require(n == 32, "fixture shape") + x = [F(2 * ((i * i + 7 * i + 1) % 19) - 17, 27) for i in range(n)] + require(any(x[i] != 0 for i in range(n) if i not in selected), "dirty holes") + e = [[F(i == j) - h[i][j] for j in range(n)] for i in range(n)] + rho = infinity(e) + require(0 < rho < 1, "strict row gap") + neumann = x[:] + for _ in range(terms - 1): + neumann = [v + q for v, q in zip(x, apply(e, neumann))] + direct_inverse, direct_broad = apply(inverse(h), x), apply(u, x) + checked, kept, faces = 0, 0, 0 + largest_error = F(0) + for start in range(0, n, side): + rows = list(range(start, start + side)) + interior = [i for i in range(2, side - 2) + if i % 6 in (2, 3) and start + i in selected] + for matrix, inv in ((h, True), (u, False)): + section = sub(matrix, rows, rows) + computed = five(section, interior, x[start:start + side], inv) + oracle = apply(inverse(section) if inv else section, x[start:start + side]) + require(computed == oracle, "five factors changed sectional endpoint") + checked += len(computed) + for i, actual in enumerate(computed): + global_i = start + i + face = min(i, side - 1 - i) < halo + if inv: + result = neumann[global_i] if face else actual + error = abs(result - direct_inverse[global_i]) + limit = (1 if face else 2) * max(map(abs, x)) * rho**terms / (1 - rho) + require(error <= limit, "global inverse error above Neumann proof") + largest_error = max(largest_error, error) + kept += int(not face) + faces += int(face) + else: + result = direct_broad[global_i] if face else actual + require(result == direct_broad[global_i], "forward halo splice") + require(any(neumann[i] != direct_inverse[i] for i in range(n)), "Neumann control vacuous") + return checked, kept, faces, str(float(largest_error)) + + +def flags(): + masks = [{1, 3}, {0, 1, 5}, {2, 3}, {2, 4, 5}] + radices = (7, 6, 5, 7) + classes = {} + visits = 0 + for point in product(*(range(n) for n in radices)): + active = [i for i, v in enumerate(point) if v in masks[i]] + for visit, i in enumerate(active): + key = (visit, i) + classes.setdefault(key, set()).add(point[:i] + point[i+1:]) + visits += 1 + for (_, i), lines in classes.items(): + require(len(lines) >= prod(min(len(masks[j]), radices[j] - len(masks[j])) + for j in range(len(masks)) if j != i), + "rare tag lacks full RHS set") + expected = sum(len(masks[i]) * prod(radices[:i] + radices[i+1:]) + for i in range(len(masks))) + require(visits == expected, "union tariff") + return len(classes), min(map(len, classes.values())), visits + + +if __name__ == "__main__": + print("exact power margins", charge()) + print("finite structural axis test reports", splice(*ref(29, 32)), splice(*ref(31, 32))) + print("sparse tag classes, smallest RHS count, total visits", flags()) diff --git a/research/mixed-rank-uniform-composition/check_ordinary.py b/research/mixed-rank-uniform-composition/check_ordinary.py new file mode 100644 index 0000000000..9fc094e818 --- /dev/null +++ b/research/mixed-rank-uniform-composition/check_ordinary.py @@ -0,0 +1,101 @@ +"""Check the actual stock address routines and cold radix swap on opaque records.""" + +import itertools +import subprocess +import sys +import types +from collections import Counter + + +BASE = "e54523517d0f03e58352e647c403a5af3e525a57" +NATIVE = "a7f99a5f5f919dd3ffb2987f90c1e7d6527feb1e" + + +def load_module(name, head, path): + source = subprocess.check_output(["git", "show", f"{head}:{path}"]) + module = types.ModuleType(name) + sys.modules[name] = module + exec(compile(source, f"{head}:{path}", "exec"), module.__dict__) + return module + + +def require(statement, reason): + if not statement: + raise ValueError(reason) + + +def stock_rows(Layout): + checked = 0 + for L, H, depth in itertools.product((2, 3, 5), (1, 2, 5), (1, 2, 3)): + layer = Layout(L, H, depth, 2) + power = (L*H)**depth + for j in range(depth): + remaining = depth-j-1 + # Fix the earlier low labels independently from the retained high digits. + for earlier in itertools.product(range(L), repeat=j): + counted = Counter() + for hi in itertools.product(range(H), repeat=j): + prefix = sum((l*H+h)*(L*H)**i for i, (l,h) in enumerate(zip(earlier, hi, strict=True))) + ancestor = sum(h*H**i for i,h in enumerate(hi)) + for tail, low, high in itertools.product(range(2*(L*H)**remaining), range(L), range(H)): + row = prefix + (low*H + high + L*H*tail)*(L*H)**j + expected = (tail*H + high)*H**j + ancestor + types, current = layer.descend(row, j+1) + require(types == earlier+(low,) and current == expected and layer.return_address(types,current) == row, + "literal retained split/return or high index") + counted[hi,low] += 1 + checked += 1 + require(set(counted.values()) == {2*H*(L*H)**remaining}, "fresh complete low packet at fixed ancestry") + # The final genuine row occupies the first current low of the second slab. + subset = [r for r in range(power, power+1)] + bad = sum(layer.split(r,0)[0] == 0 for r in subset) + require(bad == len(subset) and L*bad != len(subset), "early padding removal control") + return checked + + +def padded_swap(cold_swap): + checked = 0 + for q, E, prefix_count, gap, tail in itertools.product((3,5), range(1,6), (1,2), (1,3), (1,2)): + base = 2**E + d = 0 + while q**d < base: + d += 1 + side = q**d + require(base <= side < q*base, "fixed volume factor") + dims = (range(prefix_count),range(side),range(gap),range(side),range(tail)) + # The padding has distinct nonzero tokens. An incorrect intermediate gate + # cannot pass by assuming the designated padding values stay zero. + padded = list(itertools.product(*dims)) + swapped = cold_swap(padded, q, d, prefix_count, gap, tail) + for address, old in zip(itertools.product(*dims), swapped, strict=True): + p, a, g, b, s = address + require(old == (p,b,g,a,s), "actual q-digit swaps on the whole padded stream") + if a < base and b < base: + require(old[1] < base and old[3] < base, "binary rectangle after whole return") + checked += len(padded) + return checked + + +def weighted_wrapper(): + checked = 0 + for q, w, atoms in itertools.product((3,5), (1,2), (1,2,3,4)): + modulus = q**w + for case in range(12): + H = tuple((7*case+3*i*i+i) % modulus for i in range(atoms)) + D = tuple((13*case+5*i+2) % modulus for i in range(atoms)) + difference = tuple((v-u) % modulus for u,v in zip(H,D,strict=True)) + h,d = difference[::-1], H[::-1] + d = tuple((u+v) % modulus for u,v in zip(h,d,strict=True)) + h,d = d[::-1], h[::-1] + d = tuple((u-v) % modulus for u,v in zip(h,d,strict=True)) + require((h,d) == (D,H), "two reversed swaps and ordered additions") + checked += 1 + return checked + + +if __name__ == "__main__": + layout = load_module("pinned_all_depth_layout",BASE,"research/delayed-cover-batch-allocation/layout.py") + cover = load_module("pinned_grade_native_cover",NATIVE,"research/grade14-native-realization/cover.py") + print("live wide row/return occurrences", stock_rows(layout.Layout)) + print("complete radix-padded opaque records", padded_swap(cover.cold_swap)) + print("ordered ordinary wrapper checks", weighted_wrapper()) diff --git a/research/mixed-rank-uniform-composition/check_product.py b/research/mixed-rank-uniform-composition/check_product.py new file mode 100644 index 0000000000..a42b5d918c --- /dev/null +++ b/research/mixed-rank-uniform-composition/check_product.py @@ -0,0 +1,165 @@ +"""Exercise the joined Gaussian, ring, CRT and carry maps at small sizes.""" + +import cmath +import math +import sys +from fractions import Fraction +from functools import cache +from itertools import product +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from check_group import five +from check_synthetic import rounds +from gaussian_pages import admitted_row, recovery_diagonal + + +SIDES = (5, 7) +TARGET = (8, 8) +BASE = 256 +SCALE = 1 << 96 +DIVISOR = 64 + + +def demand(condition, reason): + if not condition: + raise ValueError(reason) + + +@cache +def page(axis): + r, t = SIDES[axis], TARGET[axis] + slots = [(2 * t * j + r) // (2 * r) for j in range(r)] + selected = set(slots) + broad = [[Fraction(0) for _ in range(t)] for _ in range(t)] + narrow = [[Fraction(0) for _ in range(t)] for _ in range(t)] + diagonal = [] + for v in range(t): + diagonal.append(Fraction(recovery_diagonal(6, 96, r, t, v), SCALE)) + for col, _, wide, thin in admitted_row(6, 96, r, t, v, 96): + broad[v][col] += Fraction(wide, SCALE) + narrow[v][col] += Fraction(thin, SCALE) + # Both cuts contain a real interior and a nonempty exterior. + interior = sorted(selected)[1:3] + return slots, broad, narrow, diagonal, interior + + +def coordinates(k): + slow, fast = SIDES + return (k * pow(fast, -1, slow)) % slow, k % fast + + +def all_pos(sides): + return product(*(range(t) for t in sides)) + + +def grouped(field, inverse): + for axis in range(2): + _, broad, narrow, diagonal, interior = page(axis) + matrix = narrow if inverse else broad + for fixed in range(TARGET[1-axis]): + line = [(fixed, j) if axis else (j, fixed) for j in range(TARGET[axis])] + result = five(matrix, interior, [field[pos] for pos in line], inverse) + for j, pos in enumerate(line): + field[pos] = complex(result[j]) * (diagonal[j] if inverse else 1) / DIVISOR + return field + + +def grid(z): + return round(z.real*SCALE), round(z.imag*SCALE) + + +def signed_product(left, right, r): + # Store one exact signed linear convolution in a single integer product. + # The base exceeds twice the largest possible accumulated coefficient. + bound = r * max(map(abs, left)) * max(map(abs, right)) + radix = 1 << (2*bound+1).bit_length() + def pack(values): + total = 0 + for v in reversed(values): + total = total * radix + v + return total + encoded = pack(left) * pack(right) + coefficients = [] + for _ in range(2*r-1): + residue = (encoded+radix//2) % radix - radix//2 + encoded = (encoded-residue)//radix + coefficients.append(residue) + demand(encoded == 0, "signed carry escaped polynomial") + return [coefficients[i] - (coefficients[i+r] if i+r < len(coefficients) else 0) + for i in range(r)] + + +def ring_product(left, right): + r = len(left) + a, b = zip(*left) + c, d = zip(*right) + ac, bd = signed_product(a,c,r), signed_product(b,d,r) + ad, bc = signed_product(a,d,r), signed_product(b,c,r) + return tuple((u-v, w+x) for u,v,w,x in zip(ac,bd,ad,bc)) + + +def convolution(f, g): + outer, r = TARGET + twist = [cmath.exp(1j*math.pi*j/r) for j in range(r)] + def forward(h): + arrays = {(i,): tuple(grid(h[i,j]*twist[j]) for j in range(r)) for i in range(outer)} + return rounds(arrays, (outer,), r) + left, right = forward(f), forward(g) + pairs = {k: ring_product(lv, right[k]) for k, lv in left.items()} + returned = rounds(pairs, (outer,), r, opposite=True) + # Two forwards and one opposite each divide by outer. The final shift multiplies by outer. + divisor = SCALE**2 * outer**2 * r + return {(i,j): complex(*returned[(i,)][j])*twist[j].conjugate()/divisor + for i,j in all_pos(TARGET)} + + +def source_transform(data, opposite): + slots = [page(axis)[0] for axis in range(2)] + field = {pos: 0j for pos in all_pos(TARGET)} + for k, val in enumerate(data): + i, j = coordinates(k) + field[slots[0][i],slots[1][j]] = val.conjugate() if opposite else val + expanded = grouped(field, False) + chirp = {x: cmath.exp(-1j*math.pi*sum(r*j*j/t for r,j,t in zip(SIDES,x,TARGET))) + for x in field} + middle = convolution(chirp, {x: chirp[x].conjugate()*v for x,v in expanded.items()}) + cropped = grouped({x: chirp[x].conjugate()*v for x,v in middle.items()}, True) + output = [] + for k in range(len(data)): + i, j = coordinates(k) + z = cropped[slots[0][i],slots[1][j]] * DIVISOR**4 + output.append(z.conjugate() if opposite else z) + return output + + +def multiply(left, right): + count = math.prod(SIDES) + def encode(n): + digits = [] + for _ in range(count): + n, digit = divmod(n, BASE) + digits.append(complex(digit/(4*BASE))) + demand(n == 0, "test input exceeds cyclic range") + return digits + fa, fb = (source_transform(encode(n), False) for n in (left,right)) + recovered = source_transform([x*y for x,y in zip(fa,fb)], True) + values = [v*(count*4*BASE)**2 for v in recovered] + coeffs = [round(v.real) for v in values] + demand(all(c >= 0 and abs(v-c) < .25 for v,c in zip(values,coeffs)), "rounding radius") + carry = total = 0 + for j,c in enumerate(coeffs): + carry, digit = divmod(carry+c, BASE) + total += digit << (8*j) + total += carry << (8*count) + return total, coeffs + + +if __name__ == "__main__": + for left, right in [(741503,466013), (0,65535), (65535,65535), (256**4+1,255)]: + result, coeffs = multiply(left,right) + demand(result == left*right, "independent integer oracle") + if left == 741503: + demand(coeffs == [11811,10996,4152,868,77]+[0]*30, "pre-carry coefficients") + print("741503 x 466013 =", result, "coefficients", coeffs[:5]) + print("PASS_JOINED_SMALL_GEOMETRY") diff --git a/research/mixed-rank-uniform-composition/check_synthetic.py b/research/mixed-rank-uniform-composition/check_synthetic.py new file mode 100644 index 0000000000..798f6ed0ca --- /dev/null +++ b/research/mixed-rank-uniform-composition/check_synthetic.py @@ -0,0 +1,137 @@ +"""Exact synthetic ring and C-to-H checks. No floating-point arithmetic.""" + +from itertools import product +from math import prod + + +def demand(value, label): + if not value: + raise ValueError(label) + + +def add(x, y): + return x[0] + y[0], x[1] + y[1] + + +def scale(x, n): + return n * x[0], n * x[1] + + +def mul(x, y): + return x[0] * y[0] - x[1] * y[1], x[0] * y[1] + x[1] * y[0] + + +def rotate(x, exponent): + return mul(x, ((1, 0), (0, 1), (-1, 0), (0, -1))[exponent % 4]) + + +def mono(xs, exponent): + """Multiply by y**exponent in Z[i][y]/(y**r+1).""" + r = len(xs) + vals = [(0, 0)] * r + for i, x in enumerate(xs): + wrap, out = divmod(i + exponent, r) + vals[out] = scale(x, (-1) ** (wrap % 2)) + return tuple(vals) + + +def zip_add(x, y): + return tuple(add(a, b) for a, b in zip(x, y)) + + +def h_layer(array, active, slot): + """Return H0 on these slots as integer numerator at denominator 2**len(active).""" + out = dict(array) + for axis in active: + nxt = {} + for pos in out: + partner = list(pos) + partner[axis] ^= 1 << slot + b = (pos[axis] >> slot) & 1 + left, right = (out[tuple(partner)], out[pos]) if b else (out[pos], out[tuple(partner)]) + nxt[pos] = tuple(add(x, scale(y, (-1) ** b)) for x, y in zip(left, right)) + out = nxt + return out + + +def c_bridge(array, active, slot): + """Evaluate D C^h D b^h with C's numerator and b=(1-i)/2.""" + count = len(active) + phase = lambda pos: sum((pos[j] >> slot) & 1 for j in active) + out = {pos: tuple(rotate(v, phase(pos)) for v in xs) for pos, xs in array.items()} + for axis in active: + nxt = {} + for pos, xs in out.items(): + partner = list(pos) + partner[axis] ^= 1 << slot + nxt[pos] = tuple(add(mul(x, (1, 1)), mul(y, (1, -1))) + for x, y in zip(xs, out[tuple(partner)])) + out = nxt + finish = (1, 0) + for _ in range(count): + finish = mul(finish, (1, -1)) + final = {} + for pos, xs in out.items(): + entries = [] + for x in xs: + z = mul(rotate(x, phase(pos)), finish) + demand(all(v % (1 << count) == 0 for v in z), "H0 output grid") + entries.append(tuple(v // (1 << count) for v in z)) + final[pos] = tuple(entries) + demand(final == h_layer(array, active, slot), "C-to-H0 signed address convention") + return final + + +def rounds(array, lengths, r, opposite=False): + max_width = max(t.bit_length() - 1 for t in lengths) + slots = range(max_width) if opposite else reversed(range(max_width)) + out = array + for slot in slots: + active = [j for j, t in enumerate(lengths) if 1 << slot < t] + u = 2 << slot + def twiddle(pos): + return sum(-((2 * r) // u) * ((pos[j] >> slot) & 1) + * (pos[j] % (u // 2)) for j in active) % (2 * r) + if opposite: + out = {pos: mono(xs, -twiddle(pos)) for pos, xs in out.items()} + out = c_bridge(out, active, slot) + else: + out = c_bridge(out, active, slot) + out = {pos: mono(xs, twiddle(pos)) for pos, xs in out.items()} + return out + + +def reverse(value, side): + return int(format(value, "0" + str(side.bit_length() - 1) + "b")[::-1], 2) + + +def oracle(array, sides, r): + spectrum = {} + for freq in product(*(range(t) for t in sides)): + total = ((0, 0),) * r + for pos, poly in array.items(): + exponent = -sum(x * j * ((2 * r) // t) for x, j, t in zip(pos, freq, sides)) + total = zip_add(total, mono(poly, exponent)) + spectrum[tuple(reverse(j, t) for j, t in zip(freq, sides))] = total + return spectrum + + +def experiment(sides, r): + data = {} + for n, p in enumerate(product(*(range(t) for t in sides))): + data[p] = tuple(((n * n + k * n + 31 * k + 13) % 37 - 20, + (3 * n - k * k + 21 * k * n + 7) % 41 - 23) + for k in range(r)) + forward = rounds(data, sides, r) + demand(forward == oracle(data, sides, r), "forward synthetic Fourier operator") + returned = rounds(forward, sides, r, opposite=True) + demand(all(poly == tuple(scale(v, prod(sides)) for v in data[pos]) + for pos, poly in returned.items()), "opposite/source-volume shift") + # The represented denominator is prod(sides) on each pass. + return prod(sides) * r + + +if __name__ == "__main__": + fixtures = [((8, 4, 4), 8), ((4, 2, 2), 4), ((8,), 8)] + print("Exact signed Gaussian/ring coordinates in three fixtures", + sum(experiment(s, r) for s, r in fixtures)) diff --git a/research/mixed-rank-uniform-composition/check_uniform_benes.py b/research/mixed-rank-uniform-composition/check_uniform_benes.py new file mode 100644 index 0000000000..07b34ec2ef --- /dev/null +++ b/research/mixed-rank-uniform-composition/check_uniform_benes.py @@ -0,0 +1,146 @@ +"""Exact common H schedule on complete coarse fibers with different local matchings.""" + +from fractions import Fraction as F +from itertools import product +from math import prod + +BITS = (0, 1, 0) +N = 4 +AXES = 3 + + +def check(condition, message): + if not condition: + raise ValueError(message) + + +def pairs(bit): + return [(i, i ^ (1 << bit)) for i in range(N) if (i >> bit) & 1 == 0] + + +def route(mask): + permutation = list(range(N)) + for k, bit in enumerate(BITS): + for j, (u, v) in enumerate(pairs(bit)): + if mask & (1 << (2 * k + j)): + permutation[u], permutation[v] = permutation[v], permutation[u] + return tuple(permutation) + + +ROUTES = {route(mask): mask for mask in range(64)} +check(len(ROUTES) == 24, "three stages realize all four-wire permutations") + + +def compile_steps(steps): + # Endianness here is execution order. Entries are pairs on adjacent wires. + diagonals = [(F(1), F(1))] + for step in steps: + if step is None: + diagonals.append((F(1), F(1))) + else: + diagonals[-1] = tuple(v * w for v, w in zip(diagonals[-1], step)) + return diagonals + + +def shear(q): + q = F(q) + return [(5 / (4 * q), 1), None, (-3, 1), None, (2, 1), None, + (-F(1, 8), -F(1, 6)), (4 * q / 5, 1)] + + +def gate(kind, t): + if kind in ("U", "L"): + c = 2 * abs(t) + 1 + steps = shear(-c) + shear(t + c) + if kind == "L": + steps.reverse() + else: + first = (1, 1 if kind == "I" else -1) + steps = [None, first, None, (F(1, 2), F(1, 2))] + steps += [None, None, (F(1, 2), F(1, 2))] * 2 + ds = compile_steps(steps) + check(len(ds) == 7, "six actual Hadamards on both controls") + return ds + + +def program(permutation, gates): + mask = ROUTES[permutation] + layers = [] + for k, bit in enumerate(BITS): + diag = [F(1)] * N + for j, (_, v) in enumerate(pairs(bit)): + if mask & (1 << (2 * k + j)): + diag[v] = -1 + layers.append((bit, diag)) + def switches(group): + out = [] + for bit, diag in group: + out += [("H", bit), ("D", diag), ("H", bit), ("D", [F(1, 2)] * N)] + return out + middle = [] + gd = [gate(*info) for info in gates] + for k in range(7): + middle.append(("D", [gd[i // 2][k][i % 2] for i in range(N)])) + if k < 6: + middle.append(("H", 0)) + return switches(layers) + middle + switches(reversed(layers)) + + +def direct(permutation, gates): + matrix = [[F(0)] * N for _ in range(N)] + for i, (kind, t) in enumerate(gates): + local = { + "U": ((1, t), (0, 1)), + "L": ((1, 0), (t, 1)), + "I": ((1, 0), (0, 1)), + "J": ((0, 1), (1, 0)), + }[kind] + for r, c in product(range(2), repeat=2): + matrix[permutation[2 * i + r]][permutation[2 * i + c]] = F(local[r][c]) + return matrix + + +def replay(): + specs = [[((2, 0, 3, 1), (("U", 0), ("L", F(-4, 9)))), + ((1, 3, 2, 0), (("J", 0), ("U", F(3, 7)))), + ((2, 3, 0, 1), (("L", 1), ("I", 0)))], + [((0, 1, 2, 3), (("I", 0), ("U", F(-1, 5)))), + ((2, 1, 0, 3), (("L", F(2, 11)), ("J", 0))), + ((1, 2, 3, 0), (("U", -2), ("L", 0)))]] + plans = [[program(*spec) for spec in group] for group in specs] + matrices = [[direct(*spec) for spec in group] for group in specs] + positions = tuple(product(range(N), repeat=AXES)) + steps = len(plans[0][0]) + hbits = [] + for step in range(steps): + cases = [plans[c][j][step] for c in range(2) for j in range(AXES)] + check(len({t[0] for t in cases}) == 1, "nonuniform call shape") + if cases[0][0] == "H": + check(len({t[1] for t in cases}) == 1, "nonuniform selected slot") + hbits.append(cases[0][1]) + for col in positions: + x = {(c, row): F(row == col) for c in range(2) for row in positions} + for step in range(steps): + typ, d = plans[0][0][step] + if typ == "D": + x = {(c, row): v * prod(plans[c][j][step][1][row[j]] for j in range(AXES)) + for (c, row), v in x.items()} + else: + # Exactly H^tensor(3) on this slot, independently of the coarse label. + # Factorization below is the slow oracle for this one uniform public gate. + for j in range(AXES): + nxt = {} + for (c, row), v in x.items(): + partner = list(row) + partner[j] ^= 1 << d + w = x[c, tuple(partner)] + nxt[c, row] = w - v if (row[j] >> d) & 1 else v + w + x = nxt + for (c, row), v in x.items(): + expected = prod(matrices[c][j][row[j]][col[j]] for j in range(AXES)) + check(v == expected, "global H/diagonal word differs from wanted tensor") + return len(hbits), 2 * len(positions) ** 2 + + +if __name__ == "__main__": + print("Common complete Hadamard calls and exact matrix entries", replay()) diff --git a/research/mixed-rank-uniform-composition/check_weighted.py b/research/mixed-rank-uniform-composition/check_weighted.py new file mode 100644 index 0000000000..4f1c9ecb4e --- /dev/null +++ b/research/mixed-rank-uniform-composition/check_weighted.py @@ -0,0 +1,89 @@ +"""Differential checks of the pinned covered rank-one lowering at new rings.""" + +import sys +from math import gcd +from pathlib import Path +from random import Random + + +def assert_equal(actual, expected): + if actual != expected: + raise ValueError((actual, expected)) + + +def lift(seed_u, seed_v, pivot, prime, modulus, random): + u = [a + prime*random.randrange(modulus//prime) for a in seed_u] + v = [a + prime*random.randrange(modulus//prime) for a in seed_v] + v[pivot] = (1 - sum(a*b for i,(a,b) in enumerate(zip(u,v)) if i != pivot)) * pow( + u[pivot], -1, modulus) % modulus + assert_equal(sum(a*b for a,b in zip(u,v)) % modulus, 1) + return u,v,[[a*b % modulus for b in v] for a in u] + + +def oracle(u, v, weights, head, tail, modulus, wrong_tail=False): + n, f = len(u), len(weights) + out = [[0]*f for _ in range(2*n)] + for j, units in enumerate(weights): + logical = j if wrong_tail else f-1-j + x = [row[j] * pow(a,-1,modulus) % modulus for row,a in zip(head,units)] + y = [tail[n-1-i][logical] for i in range(n)] + pairing = sum(v[i]*(y[i]-x[i]) for i in range(n)) % modulus + for i in range(n): + out[i][j] = units[i]*(x[i]+u[i]*pairing) % modulus + out[2*n-1-i][logical] = (y[i]-u[i]*pairing) % modulus + return out + + +def topology(program): + return tuple(tuple(op) if op[0] == "sign" else tuple(op[:3]) for op in program) + + +def main(package): + sys.path.insert(0,str(package.resolve())) + from leaf import column_program, run_columns + rng = Random(7830480) + counts = {"cases":0,"good":0,"bad":0,"nonzero_nonunit":0,"wrong_tail_rejected":0, + "wrong_weight_rejected":0} + for prime, power in ((3,2),(3,3),(5,2),(7,2)): + modulus = prime**power + units = tuple(x for x in range(1,modulus) if gcd(x,prime)==1) + for n in (2,3,5): + for seed in range(4): + # Both genuine good and genuine bad residue classes. + pivot = 0 if seed%2==0 else n-1 + seed_u = [rng.randrange(prime) for _ in range(n)] + seed_u[pivot] = 1 + if seed%2: + seed_u[0] = 0 + seed_v = [rng.randrange(prime) for _ in range(n)] + fixed_topology = None + for _ in range(4): + u,v,p = lift(seed_u,seed_v,pivot,prime,modulus,rng) + for f in (1,2,3,6,7): + weights = [[rng.choice(units) for _ in range(n)] for _ in range(f)] + head = [[rng.randrange(modulus) for _ in range(f)] for _ in range(n)] + tail = [[rng.randrange(modulus) for _ in range(f)] for _ in range(n)] + actual,good,calls = run_columns(p, weights, head, tail,prime,power) + assert_equal(actual, oracle(u,v,weights,head,tail,modulus)) + assert_equal(good,gcd(p[0][0],prime)==1) + assert_equal(all(c in (f,f//2) and c>0 for c in calls),True) + assert_equal(calls==[f] if good else len(calls)<32*n*n, True) + for coeff in weights: + ops, mode = column_program(p,coeff,prime,power) + if fixed_topology is None: + fixed_topology = topology(ops) + assert_equal((topology(ops),mode),(fixed_topology,good)) + counts["cases"] += 1 + counts["good" if good else "bad"] += 1 + counts["nonzero_nonunit"] += int(not good and p[0][0]!=0) + counts["wrong_tail_rejected"] += int(actual!=oracle( + u,v,weights,head,tail,modulus,wrong_tail=True)) + counts["wrong_weight_rejected"] += int(actual!=oracle( + u,v,[[1]*n for _ in range(f)],head,tail,modulus)) + for x in counts.values(): + assert_equal(x>0,True) + print(counts) + + +if __name__ == "__main__": + main(Path(sys.argv[1])) diff --git a/research/mixed-rank-uniform-composition/gaussian_pages.py b/research/mixed-rank-uniform-composition/gaussian_pages.py new file mode 100644 index 0000000000..d013dbd43d --- /dev/null +++ b/research/mixed-rank-uniform-composition/gaussian_pages.py @@ -0,0 +1,167 @@ +"""Generate the dyadic Gaussian coefficients in physical row order.""" + +from functools import lru_cache +from math import isqrt + + +def ceil_div(number, divisor): + return -(-number // divisor) + + +def ceil_sqrt(number): + root = isqrt(number) + return root + (root * root < number) + + +def width_parameter(p): + return ceil_sqrt((16 * p - 1).bit_length()) + + +def selected_source(r, t, v): + """Return the unique original source at dyadic slot v, or None.""" + j = max(0, ceil_div(r * (2 * v - 1), 2 * t)) + if j < r and 2 * t * j < r * (2 * v + 1): + return j + return None + + +def atan_inverse_bounds(divisor, scale): + """Bound atan(1/divisor) by the alternating power series.""" + low = high = 0 + power = divisor + k = 0 + while True: + denom = (2 * k + 1) * power + a, b = scale // denom, ceil_div(scale, denom) + if k % 2: + low, high = low - b, high - a + else: + low, high = low + a, high + b + k += 1 + power *= divisor * divisor + if (2 * k + 1) * power >= scale: + return (low - 1, high) if k % 2 else (low, high + 1) + + +@lru_cache(maxsize=16) +def pi_bounds(bits): + scale = 1 << bits + a, b = atan_inverse_bounds(5, scale) + c, d = atan_inverse_bounds(239, scale) + return 16 * a - 4 * d, 16 * b - 4 * c + + +def negative_exp_bounds(lo, hi, scale): + """Bound exp(-x) on x in [lo, hi]/scale on the same grid.""" + squares = 0 + while hi > scale // 2: + lo, hi = lo // 2, ceil_div(hi, 2) + squares += 1 + term_lo = term_hi = scale + result_lo = result_hi = scale + k = 0 + while True: + k += 1 + term_lo = term_lo * lo // (scale * k) + term_hi = ceil_div(term_hi * hi, scale * k) + if k % 2: + result_lo, result_hi = result_lo - term_hi, result_hi - term_lo + else: + result_lo, result_hi = result_lo + term_lo, result_hi + term_hi + if term_hi <= 1: + if k % 2: + result_hi += 1 + else: + result_lo -= 1 + break + result_lo = max(0, result_lo) + result_hi = min(scale, result_hi) + for _ in range(squares): + result_lo = result_lo * result_lo // scale + result_hi = ceil_div(result_hi * result_hi, scale) + return result_lo, result_hi + + +@lru_cache(maxsize=8192) +def encode_exp(bits, num, denom, divisor=1, positive=False): + """Return a lower dyadic approximation to exp(±pi*num/denom)/divisor. + + The exact error is at most two units of the requested output grid. + Each rounding operation below is outward on its private grid. + """ + if num < 0 or min(denom, divisor) <= 0: + raise ValueError('invalid exponential input') + if num == 0: + return (1 << bits) // divisor + if not positive and 3 * num >= (bits + 3) * denom: + return 0 + work = bits + 4 * (bits + 1).bit_length() + 24 + while True: + scale = 1 << work + a, b = pi_bounds(work) + xlo, xhi = a * num // denom, ceil_div(b * num, denom) + lo, hi = negative_exp_bounds(xlo, xhi, scale) + if positive: + if lo == 0: + work += 16 + continue + lo, hi = scale * scale // hi, ceil_div(scale * scale, lo) + unit = (1 << (work - bits)) * divisor + lower = lo // unit + if hi - lower * unit <= 2 * unit: + return lower + work += 16 + + +def physical_row(p, bits, r, t, v, window): + """Yield (source slot, period, broad numerator, narrow numerator). + + v and each returned source slot are in the original dyadic rectangle. + The signed period separates distinct occurrences at the same address. + The generator visits zero-valued occurrences and omits their stored zeros. + The principal narrow diagonal is exactly one, including hole rows. + """ + alpha = width_parameter(p) + unit = 1 << bits + row_selected = selected_source(r, t, v) is not None + for offset in range(-window, window + 1): + period, col = divmod(v + offset, t) + j = selected_source(r, t, col) + if j is None: + if offset == 0: + yield col, period, unit, unit + continue + beta = t * j - r * col + delta = r * offset + beta + broad = encode_exp(bits, delta * delta, (t * alpha) ** 2, alpha) + if col == v: + narrow = unit if offset == 0 else 0 + elif row_selected: + narrow = encode_exp(bits, alpha**2 * (delta * delta - beta * beta), r * r) + else: + narrow = 0 + if broad or narrow: + yield col, period, broad, narrow + + +def admitted_row(p, bits, r, t, v, window): + """Return one physical row after checking the two inverse bounds.""" + entries = tuple(physical_row(p, bits, r, t, v, window)) + unit = 1 << bits + diagonal = sum(narrow for col, _, _, narrow in entries if col == v) + mass = sum(abs(narrow) for col, _, _, narrow in entries if col != v) + gap = 16 * p * p + normalizer = 1 << (p**100 - 1).bit_length() + if diagonal != unit or unit + gap * mass > gap * unit: + raise ValueError("narrow row fails the inverse bound") + if unit + normalizer * mass > normalizer * unit: + raise ValueError("narrow row fails the normalized radius bound") + return entries + + +def recovery_diagonal(p, bits, r, t, slot): + j = selected_source(r, t, slot) + if j is None: + return 1 << bits + beta = t * j - r * slot + return encode_exp(bits, (width_parameter(p) * beta) ** 2, r * r, positive=True) diff --git a/research/mixed-rank-uniform-composition/lean/.gitignore b/research/mixed-rank-uniform-composition/lean/.gitignore new file mode 100644 index 0000000000..01f8cdb637 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/.gitignore @@ -0,0 +1 @@ +.lake/ diff --git a/research/mixed-rank-uniform-composition/lean/CertifiedPrices.lean b/research/mixed-rank-uniform-composition/lean/CertifiedPrices.lean new file mode 100644 index 0000000000..166acd505f --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/CertifiedPrices.lean @@ -0,0 +1,87 @@ +import Funding +import RankMoments + +/-! Both tensor debit comparisons use the actual enclosed source moments. -/ +namespace CertifiedPrices +open RankMoments + +def ratio (a b : Nat) : Rat := (a : Rat) / (b : Rat) + +def bitDebit : Rat := + let target := lowerTarget bitMain + let α := ratio (upperPaid bitMain) target + let firstLow := ratio (upperPaid bitLow (fun r => r ≤ 4) * grid) (lowCut.lo * target) + let anyLow := ratio (upperPaid bitLow * grid) (lowCut.lo * target) + let firstHigh := ratio (upperPaid bitHigh (fun r => 4 < r) * grid) (highCut.lo * target) + let anyHigh := ratio (upperPaid bitHigh * grid) (highCut.lo * target) + let dropped := ratio (floorCost.hi * upperTarget bitDrop) (grid * target) + 1 / (1 + 480*(1-α)) + 2*firstLow*anyLow^(479 : Nat) + + 2*firstHigh*anyHigh^(479 : Nat) + dropped^(480 : Nat) + +def complexDebit : Rat := + let target := lowerTarget complexMain + let α := ratio (upperPaid complexMain) target + let γ := ratio (upperPaid complexTilt * grid) (complexCut.lo * target) + let δ := ratio (12 * targetCount complexMain * grid^2) (complexCost.lo * target) + 1 / (1 + 1920*(1-α)) + 2*γ^(1920 : Nat) + 2*δ^(1920 : Nat) + +def commonDen : Nat := 7*10^15 +def bitSaving : Nat := 7*3879928046148 +def complexSaving : Nat := 70*387992803563 + +def hasExponent (value : Nat) (c : DyadicRoot.Claim) : Bool := c.num*commonDen == value*c.den + +def weights (xs : List Row) (weight : Row → Nat) : List (Nat × Nat) := + xs.filterMap (fun r => if weight r = 0 then none else some (r.power.rank, weight r)) + +def sourceBindings : Bool := + let b := commonDen-bitSaving + let c := commonDen-complexSaving + bitMain.all (fun r => hasExponent b r.power) && + bitLow.all (fun r => hasExponent (b+11*(commonDen/50)) r.power) && + bitHigh.all (fun r => hasExponent (b+13*(commonDen/50)) r.power) && + bitDrop.all (fun r => hasExponent (b-17*(commonDen/50)) r.power) && + complexMain.all (fun r => hasExponent c r.power) && + complexTilt.all (fun r => hasExponent (c+commonDen/7) r.power) && + hasExponent (11*(commonDen/50)) lowCut && lowCut.rank == 10 && + hasExponent (13*(commonDen/50)) highCut && highCut.rank == 11 && + hasExponent (17*(commonDen/50)) floorCost && floorCost.rank == 16 && + hasExponent (commonDen/7) complexCut && complexCut.rank == 11 && + hasExponent complexSaving complexCost && complexCost.rank == 11 && + weights bitMain Row.paid == weights bitLow Row.paid && + weights bitMain Row.paid == weights bitHigh Row.paid && + weights bitMain Row.target == weights bitDrop Row.target && + weights complexMain Row.paid == weights complexTilt Row.paid && + targetCount bitMain == 20706 && (bitMain.map Row.paid).sum == 107460 && + targetCount complexMain == 52512 && (complexMain.map Row.paid).sum == 283152 && + bitMain.any (fun r => r.power.rank == 4 && 0 < r.target) && + bitMain.any (fun r => r.power.rank == 64 && 1 < r.target) + +set_option maxRecDepth 16384 +set_option maxHeartbeats 10000000 + +theorem bit_funded : bitDebit < 1 - 12309863319385 / 10^25 := by decide +kernel +theorem complex_funded : complexDebit < 1 := by decide +kernel +theorem source_exponents_and_weights : sourceBindings = true := by decide +kernel +theorem source_savings : + ratio bitSaving commonDen = MixedFunding.rawBit ∧ + ratio complexSaving commonDen = MixedFunding.trialC := by decide +kernel + +theorem bit_floor_occurs : (4 : Nat)^240*64^240 = 16^480 := by decide +kernel + +/-- Source root bounds, the two paid tensor totals, the six ordinary stage +inequalities and their common application price hold together. -/ +theorem mixed_prices : + (∀ c ∈ claims, 0 < c.den ∧ c.lo^c.den ≤ c.rank^c.num * 2^(frac*c.den) ∧ + c.rank^c.num * 2^(frac*c.den) ≤ c.hi^c.den) ∧ + sourceBindings = true ∧ ratio bitSaving commonDen = MixedFunding.rawBit ∧ + ratio complexSaving commonDen = MixedFunding.trialC ∧ + bitDebit < 1 - 12309863319385 / 10^25 ∧ + complexDebit < 1 ∧ MixedFunding.validStages 0 MixedFunding.stages ∧ + MixedFunding.trialC = MixedFunding.finalClaim + 7 / 10^14 := + ⟨table_sound, source_exponents_and_weights, source_savings.1, source_savings.2, + bit_funded, complex_funded, MixedFunding.cold_through_six_stages, MixedFunding.supplier_room.1⟩ + +end CertifiedPrices + +#print axioms CertifiedPrices.mixed_prices diff --git a/research/mixed-rank-uniform-composition/lean/CompilerFlow.lean b/research/mixed-rank-uniform-composition/lean/CompilerFlow.lean new file mode 100644 index 0000000000..4f7e2704ee --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/CompilerFlow.lean @@ -0,0 +1,524 @@ +import Std + +/-! +An address uses occurrence labels. Two equal ranks can name different ports. +The paid history is in reverse time order. The first remaining target label +determines the port at which the next paid request enters the child. +-/ +namespace MixedCompiler + +variable {K J : Type} + +structure Node (K J : Type) where + history : List J + future : List K + deriving DecidableEq + +structure Demand (K J : Type) where + node : Node K J + paid : J + deriving DecidableEq + +structure Port (K J : Type) where + node : Node K J + target : K + deriving DecidableEq + +def child : Demand K J → Option (Port K J) + | ⟨⟨_, []⟩, _⟩ => none + | ⟨⟨p, k :: a⟩, j⟩ => some ⟨⟨j :: p, a⟩, k⟩ + +def parent : Port K J → Option (Demand K J) + | ⟨⟨[], _⟩, _⟩ => none + | ⟨⟨j :: p, a⟩, k⟩ => some ⟨⟨p, k :: a⟩, j⟩ + +theorem matched_iff (d : Demand K J) (s : Port K J) : + child d = some s ↔ parent s = some d := by + obtain ⟨⟨p, a⟩, j⟩ := d + obtain ⟨⟨q, b⟩, k⟩ := s + cases a <;> cases q <;> simp [child, parent, and_comm, and_left_comm, and_assoc, eq_comm] + +def mass {A : Type} (rank : A → Nat) : List A → Nat + | [] => 1 + | x :: xs => rank x * mass rank xs + +def scale (rank : K → Nat) (paid : J → Nat) (u : Node K J) : Nat := + mass paid u.history * mass rank u.future + +def live (rank : K → Nat) (paid : J → Nat) (A n : Nat) (u : Node K J) : Prop := + A * scale rank paid u ≤ n + +def demandRank (rank : K → Nat) (paid : J → Nat) (d : Demand K J) : Nat := + paid d.paid * scale rank paid d.node + +def portRank (rank : K → Nat) (paid : J → Nat) (s : Port K J) : Nat := + rank s.target * scale rank paid s.node + +def depth (u : Node K J) : Nat := u.history.length + u.future.length + +variable (rank : K → Nat) (paid : J → Nat) + +theorem edge (d : Demand K J) (s : Port K J) (h : child d = some s) : + demandRank rank paid d = portRank rank paid s ∧ + depth d.node = depth s.node ∧ + d.node.future.length = s.node.future.length + 1 := by + obtain ⟨⟨p, a⟩, j⟩ := d + cases a with + | nil => simp [child] at h + | cons k a => + cases h + simp [demandRank, portRank, scale, depth, mass, + Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm, Nat.add_comm, Nat.add_left_comm] + +theorem fits_child (A n : Nat) (separated : ∀ j k, paid j ≤ rank k) + (d : Demand K J) (s : Port K J) (h : child d = some s) + (hl : live rank paid A n d.node) : live rank paid A n s.node := by + obtain ⟨⟨p, a⟩, j⟩ := d + cases a with + | nil => simp [child] at h + | cons k a => + cases h + have hmul := Nat.mul_le_mul_left (A * mass paid p * mass rank a) (separated j k) + simp only [live, scale, mass] at hl ⊢ + apply Nat.le_trans _ hl + simpa only [Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm] using hmul + +/-- A port is external if its unique parent is missing or is above the ambient cap. -/ +def external (A n : Nat) (s : Port K J) : Prop := + match parent s with + | none => True + | some d => ¬live rank paid A n d.node + +theorem external_or_unique (A n : Nat) (s : Port K J) : + (external rank paid A n s ∧ + ¬∃ d, live rank paid A n d.node ∧ child d = some s) ∨ + (¬external rank paid A n s ∧ + ∃ d, (live rank paid A n d.node ∧ child d = some s) ∧ + (∀ e, live rank paid A n e.node → child e = some s → e = d)) := by + cases h : parent s with + | none => + left + refine ⟨by simp [external, h], ?_⟩ + rintro ⟨d, _, hd⟩ + rw [matched_iff, h] at hd + cases hd + | some d => + by_cases hd : A * scale rank paid d.node ≤ n + · right + refine ⟨?_, d, ⟨hd, (matched_iff d s).mpr h⟩, ?_⟩ + · unfold external + rw [h] + exact fun nope => nope hd + · intro e _ he + exact Option.some.inj ((matched_iff e s).mp he |>.symm.trans h) + · left + refine ⟨by simpa [external, h, live] using hd, ?_⟩ + rintro ⟨e, he, hed⟩ + have hs : e = d := Option.some.inj (((matched_iff e s).mp hed).symm.trans h) + exact hd (hs ▸ he) + +theorem external_interval (A n G : Nat) + (positive : ∀ j, 0 < paid j) (bounded : ∀ k, rank k ≤ A) + (top : ∀ a : List K, a.length = G + 1 → n < A * mass rank a) + (s : Port K J) (hl : live rank paid A n s.node) + (hg : depth s.node = G) (hx : external rank paid A n s) : + n < A * portRank rank paid s ∧ portRank rank paid s ≤ n := by + constructor + · obtain ⟨⟨p,a⟩,k⟩ := s + cases p with + | nil => + have ha : a.length = G := by simpa [depth] using hg + simpa [portRank, scale, mass] using + top (k :: a) (by simp [ha]) + | cons j p => + have hv : n < A * scale rank paid ⟨p, k :: a⟩ := by + simpa [external, parent, live] using hx + have hmul := Nat.le_mul_of_pos_left + (A * scale rank paid ⟨p, k :: a⟩) (positive j) + apply Nat.lt_of_lt_of_le hv + simpa only [portRank, scale, mass, Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm] using hmul + · exact Nat.le_trans (Nat.mul_le_mul_right _ (bounded s.target)) hl + +theorem product_bounds {A : Type} (w : A → Nat) (xs : List A) (lo hi : Nat) + (lower : ∀ x, lo ≤ w x) (upper : ∀ x, w x ≤ hi) : + lo ^ xs.length ≤ mass w xs ∧ mass w xs ≤ hi ^ xs.length := by + induction xs with + | nil => simp [mass] + | cons x xs ih => + simp only [List.length_cons, Nat.pow_succ, mass] + constructor + · rw [Nat.mul_comm] + exact Nat.mul_le_mul (lower x) ih.1 + · rw [Nat.mul_comm (hi ^ xs.length)] + exact Nat.mul_le_mul (upper x) ih.2 + +/-- Advance the floor by one target, with an explicit bound on the number of steps. -/ +def horizon (n k a : Nat) : Nat → Nat + | 0 => 0 + | fuel+1 => if a*k ≤ n then horizon n k (a*k) fuel + 1 else 0 + +theorem horizon_spec (n k a fuel : Nat) (hk : 1 < k) (ha : 0 < a) + (start : a ≤ n) (enough : n - a < fuel) : + a * k ^ horizon n k a fuel ≤ n ∧ n < a * k ^ (horizon n k a fuel + 1) := by + induction fuel generalizing a with + | zero => omega + | succ fuel ih => + by_cases step : a*k ≤ n + · have growth : a < a*k := by + simpa only [Nat.mul_one] using Nat.mul_lt_mul_of_pos_left hk ha + have later := ih (a*k) (Nat.mul_pos ha (by omega)) step (by omega) + simp only [horizon, step, ite_true] + constructor + · rw [Nat.pow_succ] + simpa only [Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm] using later.1 + · rw [Nat.pow_succ] + simpa only [Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm] using later.2 + · simpa [horizon, step] using And.intro start (Nat.lt_of_not_ge step) + +theorem root_cut (A n lo : Nat) (ha : 0 < A) (han : A ≤ n) (hm : 1 < lo) + (lower : ∀ k, lo ≤ rank k) (upper : ∀ k, rank k ≤ A) (a : List K) + (h : a.length = horizon n lo A (n+1) + 1) : n < A * mass rank a := by + have ht := (horizon_spec n lo A (n+1) hm ha han (by omega)).2 + have hw := (product_bounds rank a lo A lower upper).1 + rw [h] at hw + exact Nat.lt_of_lt_of_le ht (Nat.mul_le_mul_left A hw) + +theorem exit_bound (G hi : Nat) (upper : ∀ j, paid j ≤ hi) + (d : Demand K J) (hg : depth d.node = G) (he : child d = none) : + demandRank rank paid d ≤ hi ^ (G + 1) := by + obtain ⟨⟨p, a⟩, j⟩ := d + cases a with + | cons k a => simp [child] at he + | nil => + have hp : p.length = G := by simpa [depth] using hg + have h := (product_bounds paid p 0 hi (fun _ => Nat.zero_le _) upper).2 + rw [← hp, Nat.pow_succ, Nat.mul_comm] + simpa [demandRank, scale, mass] using Nat.mul_le_mul (upper j) h + +section Census + +/-- Enumerate ordered occurrence labels. A sum with the indicator of a rank counts +that rank over the integers. Thus the same census applies to real moment prices. -/ +def total {X : Type} (xs : List X) (f : X → Int) : Int := + (xs.map f).sum + +theorem total_nil {X : Type} (f : X → Int) : total [] f = 0 := rfl + +theorem total_cons {X : Type} (x : X) (xs : List X) (f : X → Int) : + total (x::xs) f = f x + total xs f := by simp [total] + +theorem total_congr {X : Type} (xs : List X) (f g : X → Int) (eq : ∀ x, f x = g x) : + total xs f = total xs g := by + induction xs with + | nil => rfl + | cons x xs h => simp only [total_cons, eq, h] + +theorem total_zero {X : Type} (xs : List X) : total xs (fun _ => 0) = 0 := by + induction xs <;> simp [total_nil, total_cons, *] + +theorem total_add {X : Type} (xs : List X) (f g : X → Int) : + total xs (fun x => f x + g x) = total xs f + total xs g := by + induction xs with + | nil => rfl + | cons x xs h => simp only [total_cons, h]; omega + +theorem total_sub {X : Type} (xs : List X) (f g : X → Int) : + total xs (fun x => f x - g x) = total xs f - total xs g := by + induction xs with + | nil => rfl + | cons x xs h => simp only [total_cons, h]; omega + +theorem total_append {X : Type} (xs ys : List X) (f : X → Int) : + total (xs ++ ys) f = total xs f + total ys f := by + induction xs with + | nil => simp [total_nil] + | cons x xs h => simp only [List.cons_append, total_cons, h, Int.add_assoc] + +theorem total_map {X Y : Type} (xs : List X) (f : X → Y) (g : Y → Int) : + total (xs.map f) g = total xs (fun x => g (f x)) := by simp [total, List.map_map, Function.comp_def] + +theorem total_flatMap {X Y : Type} (xs : List X) (f : X → List Y) (g : Y → Int) : + total (xs.flatMap f) g = total xs (fun x => total (f x) g) := by + induction xs with + | nil => rfl + | cons x xs h => simp only [List.flatMap_cons, total_append, h, total_cons] + +def words (xs : List K) : Nat → List (List K) + | 0 => [[]] + | m+1 => (words xs m).flatMap (fun a => xs.map (fun k => k::a)) + +theorem mem_words (ks : List K) (m : Nat) (a : List K) : + a ∈ words ks m ↔ a.length = m ∧ ∀ k ∈ a, k ∈ ks := by + induction m generalizing a with + | zero => + cases a with + | nil => + constructor + · intro _ + exact ⟨rfl, fun _ h => nomatch h⟩ + · intro _ + exact List.Mem.head _ + | cons k a => + constructor + · intro h + have hnil : k::a = [] := List.mem_singleton.mp h + cases hnil + · intro h + cases h.1 + | succ m ih => + cases a with + | nil => + constructor + · intro h + obtain ⟨a, _, ha⟩ := List.mem_flatMap.mp h + obtain ⟨i, _, impossible⟩ := List.mem_map.mp ha + cases impossible + · intro h + cases h.1 + | cons k a => + simp only [words, List.mem_flatMap, List.mem_map, List.cons.injEq, + List.length_cons, Nat.succ.injEq, List.forall_mem_cons] + constructor + · rintro ⟨b, hb, i, hi, rfl, rfl⟩ + exact ⟨((ih b).mp hb).1, hi, ((ih b).mp hb).2⟩ + · rintro ⟨ha, hk, hs⟩ + exact ⟨a, (ih a).mpr ⟨ha, hs⟩, k, hk, rfl, rfl⟩ + +theorem words_nodup (ks : List K) (unique : ks.Nodup) (m : Nat) : + (words ks m).Nodup := by + induction m with + | zero => simp [words] + | succ m ih => + simp only [words, List.Nodup, List.pairwise_flatMap, List.pairwise_map] + constructor + · intro a _ + exact unique.imp (fun h eq => h (List.cons.inj eq).1) + · apply ih.imp + intro a b hab x hx y hy + obtain ⟨i, _, rfl⟩ := List.mem_map.mp hx + obtain ⟨k, _, rfl⟩ := List.mem_map.mp hy + exact fun eq => hab (List.cons.inj eq).2 + +def legal (ks : List K) (js : List J) (G : Nat) (u : Node K J) : Prop := + depth u = G ∧ (∀ j ∈ u.history, j ∈ js) ∧ (∀ k ∈ u.future, k ∈ ks) + +theorem legal_edge (ks : List K) (js : List J) (G : Nat) + (d : Demand K J) (s : Port K J) (h : child d = some s) : + (legal ks js G d.node ∧ d.paid ∈ js) ↔ (legal ks js G s.node ∧ s.target ∈ ks) := by + obtain ⟨⟨p, a⟩, j⟩ := d + cases a with + | nil => simp [child] at h + | cons k a => + cases h + simp [legal, depth, Nat.add_comm, Nat.add_left_comm, + and_comm, and_left_comm, and_assoc] + +/-- A genuine portal has exactly its live enumerated parent, or is charged as a source. -/ +theorem enumerated_sources (ks : List K) (js : List J) (G A n : Nat) (s : Port K J) + (hs : legal ks js G s.node ∧ s.target ∈ ks) : + external rank paid A n s ↔ + ¬∃ d, (legal ks js G d.node ∧ d.paid ∈ js) ∧ + live rank paid A n d.node ∧ child d = some s := by + rcases external_or_unique rank paid A n s with ⟨he,hn⟩ | ⟨hn,d,hd,_⟩ + · exact ⟨fun _ ⟨d,_,h⟩ => hn ⟨d,h⟩, fun _ => he⟩ + · have hl := (legal_edge ks js G d s hd.2).mpr hs + exact ⟨fun he => (hn he).elim, fun h => (h ⟨d,hl,hd⟩).elim⟩ + +theorem admitted_source (ks : List K) (js : List J) (A n lo : Nat) + (base : A ≤ n) (ambient : 0 < A) (floorGt : 1 < lo) + (paidPos : ∀ j, 0 < paid j) (atLeast : ∀ k, lo ≤ rank k) (atMost : ∀ k, rank k ≤ A) + (s : Port K J) (hlive : live rank paid A n s.node) + (hin : legal ks js (horizon n lo A (n+1)) s.node ∧ s.target ∈ ks) + (outside : external rank paid A n s) : + (n < A * portRank rank paid s ∧ portRank rank paid s ≤ n) ∧ + ¬∃ d, (legal ks js (horizon n lo A (n+1)) d.node ∧ d.paid ∈ js) ∧ + live rank paid A n d.node ∧ child d = some s := by + constructor + · apply external_interval rank paid A n _ paidPos atMost _ s hlive hin.1.1 outside + exact root_cut rank A n lo ambient base floorGt atLeast atMost + · exact (enumerated_sources rank paid ks js _ A n s hin).mp outside + +theorem mass_replicate (k : K) (m : Nat) : + mass rank (List.replicate m k) = rank k ^ m := by + induction m with + | zero => rfl + | succ m ih => simp [List.replicate_succ, mass, ih, Nat.pow_succ, Nat.mul_comm] + +theorem has_root (ks : List K) (k : K) (hk : k ∈ ks) (A n : Nat) + (ha : 0 < A) (han : A ≤ n) (hm : 1 < rank k) : + let G := horizon n (rank k) A (n+1) + ∃ a ∈ words ks G, live rank paid A n ⟨[],a⟩ ∧ + ∀ i ∈ ks, external rank paid A n ⟨⟨[],a⟩,i⟩ := by + intro G + refine ⟨List.replicate G k, (mem_words ks G _).mpr ⟨by simp, ?_⟩, ?_, ?_⟩ + · intro i hi + exact (List.eq_of_mem_replicate hi).symm ▸ hk + · have hh := (horizon_spec n (rank k) A (n+1) hm ha han (by omega)).1 + simpa only [live, scale, mass, Nat.one_mul, mass_replicate, G] using hh + · intro i _ + trivial + +variable (ks : List K) (js : List J) (A n : Nat) (price : Nat → Int) + +def charge (u : Node K J) (v : Int) : Int := + if A * scale rank paid u ≤ n then v else 0 + +def inputs (p : List J) (m : Nat) : Int := + total (words ks m) (fun a => total ks (fun k => + charge rank paid A n ⟨p,a⟩ (price (portRank rank paid ⟨⟨p,a⟩, k⟩)))) + +def paidAt (p : List J) (j : J) (m : Nat) : Int := + total (words ks m) (fun a => + charge rank paid A n ⟨p,a⟩ (price (demandRank rank paid ⟨⟨p,a⟩, j⟩))) + +def newSources (p : List J) (j : J) (m : Nat) : Int := + total (words ks m) (fun a => total ks (fun k => + if A * scale rank paid ⟨p, k :: a⟩ ≤ n then 0 else + charge rank paid A n ⟨j :: p, a⟩ (price (portRank rank paid ⟨⟨j :: p,a⟩,k⟩)))) + +theorem count_edge (sep : ∀ j k, paid j ≤ rank k) (p : List J) (j : J) (m : Nat) : + newSources rank paid ks A n price p j m + paidAt rank paid ks A n price p j (m+1) = + inputs rank paid ks A n price (j::p) m := by + simp only [newSources, paidAt, inputs, words, total_flatMap, total_map] + rw [← total_add] + apply total_congr + intro a + rw [← total_add] + apply total_congr + intro k + by_cases h : A * scale rank paid ⟨p, k::a⟩ ≤ n + · have hl := fits_child rank paid A n sep ⟨⟨p,k::a⟩,j⟩ ⟨⟨j::p,a⟩,k⟩ rfl h + have he := (edge rank paid ⟨⟨p,k::a⟩,j⟩ ⟨⟨j::p,a⟩,k⟩ rfl).1 + simp only [live] at hl + simp only [charge, h, hl, ite_true, Int.zero_add, he] + · simp only [charge, h, ite_false, Int.add_zero] + +/-- Pay the local cost at each retained unit before visiting its child classes. -/ +def sumLocal (p : List J) : Nat → Int + | 0 => inputs rank paid ks A n price p 0 - total js (fun j => paidAt rank paid ks A n price p j 0) + | m+1 => inputs rank paid ks A n price p (m+1) - + total js (fun j => paidAt rank paid ks A n price p j (m+1)) + + total js (fun j => sumLocal (j::p) m) + +/-- Count external ports below the current class. -/ +def deeperSources (p : List J) : Nat → Int + | 0 => 0 + | m+1 => total js (fun j => + newSources rank paid ks A n price p j m + deeperSources (j::p) m) + +/-- Keep the exact order of paid labels at a leaf class. -/ +def exits (p : List J) : Nat → Int + | 0 => total js (fun j => paidAt rank paid ks A n price p j 0) + | m+1 => total js (fun j => exits (j::p) m) + +theorem cancellation (sep : ∀ j k, paid j ≤ rank k) (p : List J) (m : Nat) : + sumLocal rank paid ks js A n price p m = + inputs rank paid ks A n price p m + deeperSources rank paid ks js A n price p m - + exits rank paid ks js A n price p m := by + induction m generalizing p with + | zero => simp only [sumLocal, deeperSources, exits, Int.add_zero] + | succ m ih => + simp only [sumLocal, deeperSources, exits] + have tt := total_congr js _ _ (fun j => ih (j::p)) + rw [tt, total_sub, total_add, total_add] + have hs := total_congr js _ _ (fun j => count_edge rank paid ks A n price sep p j m) + rw [total_add] at hs + omega + +end Census + +section Batching + +def replication (width : Nat → Nat) (ranks : List Nat) : Nat := + mass width ranks + +theorem replication_positive (width : Nat → Nat) (positive : ∀ r, 0 < width r) + (ranks : List Nat) : 0 < replication width ranks := by + induction ranks with + | nil => exact Nat.zero_lt_one + | cons e es ih => exact Nat.mul_pos (positive e) ih + +theorem width_divides (width : Nat → Nat) (ranks : List Nat) (r : Nat) (h : r ∈ ranks) : + width r ∣ replication width ranks := by + induction ranks with + | nil => simp at h + | cons e es ih => + rcases List.mem_cons.mp h with he | he + · subst r + exact Nat.dvd_mul_right _ _ + · exact Nat.dvd_trans (ih he) (Nat.dvd_mul_left _ _) + +/-- At a fixed slot, assign one contiguous block of arrays to each smaller program. +Ranks can repeat at different slots. -/ +theorem cleared_batch (width : Nat → Nat) (ranks : List Nat) + (r multiplicity work : Nat) (hr : r ∈ ranks) : + let copies := replication width ranks * multiplicity + let groups := copies / width r + groups * width r = copies ∧ (groups * work) * width r = copies * work := by + intro copies groups + have h : width r ∣ copies := + Nat.dvd_trans (width_divides width ranks r hr) (Nat.dvd_mul_right _ _) + have eqn : groups * width r = copies := Nat.div_mul_cancel h + exact ⟨eqn, by rw [← eqn]; ac_rfl⟩ + +/-- A chronological word has ordinary records and complete, synchronous calls. -/ +inductive Record (I P : Type) where + | ordinary : I → Record I P + | call : P → Record I P + +def inline {I P Q : Type} (body : P → List (Record I Q)) : + List (Record I P) → List (Record I Q) + | [] => [] + | .ordinary i :: tail => .ordinary i :: inline body tail + | .call p :: tail => body p ++ inline body tail + +def execute {I P S : Type} (op : I → S → S) (call : P → S → S) : + List (Record I P) → S → S + | [], s => s + | .ordinary i :: tail, s => execute op call tail (op i s) + | .call p :: tail, s => execute op call tail (call p s) + +theorem execute_append {I P S : Type} (op : I → S → S) (childOp : P → S → S) + (left right : List (Record I P)) (s : S) : + execute op childOp (left ++ right) s = execute op childOp right (execute op childOp left s) := by + induction left generalizing s with + | nil => rfl + | cons r tail ih => cases r <;> exact ih _ + +/-- Inlining preserves the complete state at every returned job. The state can +contain payloads, parked banks, private work and tapes. -/ +theorem execute_inline {I P Q S : Type} (op : I → S → S) (req : P → S → S) + (leaves : Q → S → S) (body : P → List (Record I Q)) + (correct : ∀ p s, execute op leaves (body p) s = req p s) + (word : List (Record I P)) (s : S) : + execute op leaves (inline body word) s = execute op req word s := by + induction word generalizing s with + | nil => rfl + | cons r tail ih => + cases r with + | ordinary i => exact ih (op i s) + | call p => + simp only [inline, execute_append, correct, execute] + exact ih _ + +end Batching + +end MixedCompiler + +#print axioms MixedCompiler.edge +#print axioms MixedCompiler.matched_iff +#print axioms MixedCompiler.fits_child +#print axioms MixedCompiler.external_or_unique +#print axioms MixedCompiler.external_interval +#print axioms MixedCompiler.exit_bound +#print axioms MixedCompiler.horizon_spec +#print axioms MixedCompiler.root_cut +#print axioms MixedCompiler.count_edge +#print axioms MixedCompiler.mem_words +#print axioms MixedCompiler.words_nodup +#print axioms MixedCompiler.enumerated_sources +#print axioms MixedCompiler.admitted_source +#print axioms MixedCompiler.has_root +#print axioms MixedCompiler.cancellation +#print axioms MixedCompiler.cleared_batch +#print axioms MixedCompiler.execute_inline diff --git a/research/mixed-rank-uniform-composition/lean/Coordinates.lean b/research/mixed-rank-uniform-composition/lean/Coordinates.lean new file mode 100644 index 0000000000..fbd57b1c5a --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/Coordinates.lean @@ -0,0 +1,58 @@ +import Mathlib.Analysis.Fourier.ZMod +import Mathlib.Data.Nat.GCD.BigOperators +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Ring + +namespace MixedRankCoordinates + +open Finset +open scoped BigOperators Real + +variable {ι : Type*} [Fintype ι] [DecidableEq ι] + +def cofactor (s : ι → ℕ) (i : ι) : ℕ := ∏ j ∈ univ.erase i, s j +def weight (s m : ι → ℕ) : ℕ := ∑ i, cofactor s i * m i + +theorem cofactor_mul (s : ι → ℕ) (i : ι) : cofactor s i * s i = ∏ j, s j := + Finset.prod_erase_mul _ _ (mem_univ i) + +theorem admissible_weight (s m : ι → ℕ) + (hs : Pairwise fun i j ↦ Nat.Coprime (s i) (s j)) + (hm : ∀ i, Nat.Coprime (m i) (s i)) : Nat.Coprime (weight s m) (∏ i, s i) := by + apply Nat.coprime_fintype_prod_right_iff.mpr + intro i + have hc : Nat.Coprime (cofactor s i) (s i) := by + apply Nat.Coprime.prod_left + intro j hj + exact hs (mem_erase.mp hj).1 + apply (ZMod.isUnit_iff_coprime _ _).mp + have he : (weight s m : ZMod (s i)) = (cofactor s i * m i : ℕ) := by + simp only [weight, Nat.cast_sum, Nat.cast_mul] + apply Finset.sum_eq_single i + · intro j _ hji + have hd : s i ∣ cofactor s j := Finset.dvd_prod_of_mem _ (mem_erase.mpr ⟨Ne.symm hji, mem_univ _⟩) + rw [(ZMod.natCast_eq_zero_iff _ _).mpr hd, zero_mul] + · simp + rw [he, Nat.cast_mul] + exact ((ZMod.unitOfCoprime _ hc).isUnit.mul (ZMod.unitOfCoprime _ (hm i)).isUnit) + +theorem physical_kernel (s m : ι → ℕ) [∀ i, NeZero (s i)] [NeZero (∏ i, s i)] (v : ℤ) : + (∏ i, ZMod.stdAddChar (((v * (m i : ℤ) : ℤ) : ZMod (s i)))) = + ZMod.stdAddChar (((v * (weight s m : ℤ) : ℤ) : ZMod (∏ i, s i))) := by + simp only [ZMod.stdAddChar_coe] + simp only [Int.cast_mul, Int.cast_natCast, ← Complex.exp_sum] + congr 1 + simp only [weight, Nat.cast_sum, Nat.cast_mul, Finset.mul_sum, Finset.sum_div] + apply Finset.sum_congr rfl + intro i _ + have hp : ((cofactor s i : ℕ) : ℂ) * (s i : ℂ) = ((∏ j, s j : ℕ) : ℂ) := by + exact_mod_cast cofactor_mul s i + have hi : (s i : ℂ) ≠ 0 := NeZero.ne _ + have hS : (((∏ j, s j : ℕ) : ℂ)) ≠ 0 := NeZero.ne _ + field_simp + rw [← hp] + ring + +#print axioms admissible_weight +#print axioms physical_kernel +end MixedRankCoordinates diff --git a/research/mixed-rank-uniform-composition/lean/CoverRows.lean b/research/mixed-rank-uniform-composition/lean/CoverRows.lean new file mode 100644 index 0000000000..b116d3dbee --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/CoverRows.lean @@ -0,0 +1,94 @@ +import Std + +/-! All rows in a packet retain the full high-matrix range at every ancestor. -/ +namespace CoverRows + +def pack (radix group digit : Nat) : Nat := group*radix + digit + +theorem pack_div {radix group digit : Nat} (h : digit < radix) : + pack radix group digit / radix = group := by + unfold pack + rw [Nat.mul_comm group, Nat.mul_add_div (by omega), Nat.div_eq_of_lt h, Nat.add_zero] + +theorem pack_mod {radix group digit : Nat} (h : digit < radix) : + pack radix group digit % radix = digit := Nat.mul_add_mod_of_lt h + +theorem pack_parts (radix i : Nat) : + pack radix (i/radix) (i%radix) = i := Nat.div_add_mod' _ _ + +def split (L H A row : Nat) : Nat × Nat := + let a := row % A + let u := row / A + let h := u % H + let t := u / H + (t % L, pack A (pack H (t/L) h) a) + +def join (L H A low packetRow : Nat) : Nat := + let a := packetRow % A + let un := packetRow / A + pack A (pack H (pack L (un/H) low) (un%H)) a + +theorem split_number (L H A u l h a : Nat) (hl : l < L) (hh : h < H) (ha : a < A) : + split L H A (pack A (pack H (pack L u l) h) a) = + (l, pack A (pack H u h) a) := by + simp [split, pack_mod ha, pack_div ha, pack_mod hh, pack_div hh, pack_mod hl, pack_div hl] + +theorem join_number (L H A u l h a : Nat) (hh : h < H) (ha : a < A) : + join L H A l (pack A (pack H u h) a) = pack A (pack H (pack L u l) h) a := by + simp [join, pack_mod ha, pack_div ha, pack_mod hh, pack_div hh] + +theorem packet_inverse (L H A : Nat) (hp : 0 < H) (ap : 0 < A) + (low packetRow : Nat) (hl : low < L) : + split L H A (join L H A low packetRow) = (low, packetRow) := by + let a := packetRow % A + let h := (packetRow / A) % H + let u := packetRow / A / H + have rep : pack A (pack H u h) a = packetRow := by + simp only [u,h,a,pack_parts] + have ha : a < A := Nat.mod_lt _ ap + have hh : h < H := Nat.mod_lt _ hp + rw [← rep, join_number L H A u low h a hh ha, split_number L H A u low h a hl hh ha] + +theorem row_inverse (L H A : Nat) (lp : 0 < L) (hp : 0 < H) (ap : 0 < A) (row : Nat) : + let packet := split L H A row + join L H A packet.1 packet.2 = row := by + let a := row % A + let h := (row / A) % H + let l := (row / A / H) % L + let u := row / A / H / L + have rep : pack A (pack H (pack L u l) h) a = row := by + simp only [u,l,h,a,pack_parts] + have ha : a < A := Nat.mod_lt _ ap + have hh : h < H := Nat.mod_lt _ hp + have hl : l < L := Nat.mod_lt _ lp + dsimp only + rw [← rep, split_number L H A u l h a hl hh ha, join_number L H A u l h a hh ha] + +def activeRows (T L H D j : Nat) : Nat := T * (L*H)^(D-j) * H^j + +theorem volume (T L H D j : Nat) (depth : j < D) : + activeRows T L H D j = L * activeRows T L H D (j+1) := by + have h : D-j = D-(j+1)+1 := by omega + unfold activeRows + rw [h, Nat.pow_succ, Nat.pow_succ H] + ac_rfl + +def slabs (rows stock : Nat) : Nat := + if rows % stock = 0 then rows/stock else rows/stock+1 + +theorem one_padding (rows stock : Nat) (hs : 0 < stock) (fits : stock ≤ rows) : + rows ≤ slabs rows stock * stock ∧ slabs rows stock * stock < 2 * rows := by + have rem := Nat.mod_lt rows hs + have eqn := Nat.div_add_mod' rows stock + by_cases eq : rows % stock = 0 + · simp only [slabs, eq, ite_true] + omega + · simp only [slabs, eq, ite_false, Nat.add_mul, Nat.one_mul] + omega + +end CoverRows + +#print axioms CoverRows.packet_inverse +#print axioms CoverRows.row_inverse +#print axioms CoverRows.volume +#print axioms CoverRows.one_padding diff --git a/research/mixed-rank-uniform-composition/lean/DyadicRoot.lean b/research/mixed-rank-uniform-composition/lean/DyadicRoot.lean new file mode 100644 index 0000000000..019211e955 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/DyadicRoot.lean @@ -0,0 +1,147 @@ +import Std + +/-! Integer certificates for bounds on a positive rational power. The checker +stores a power of two outside each mantissa. Its soundness statement uses the +complete mathematical integers, including when they have trillions of bits. -/ +namespace DyadicRoot + +structure Sci where + mant : Nat + scale : Nat + deriving Repr + +def val (x : Sci) := x.mant * 2^x.scale + +def roundUp (m u : Nat) := m/u + if m%u = 0 then 0 else 1 + +theorem roundUp_spec (m u : Nat) (hu : 0 [] + | fuel+1, e => if e=0 then [] else (e%2 == 1) :: digits fuel (e/2) + +def exponent : List Bool → Nat + | [] => 0 + | b::bs => (if b then 1 else 0) + (exponent bs + exponent bs) + +def powered (bits : Nat) (up : Bool) (x : Sci) : List Bool → Sci + | [] => ⟨1,0⟩ + | b::bs => + let r := powered bits up x bs + let z := multiply bits up r r + if b then multiply bits up x z else z + +theorem low_pow (bits : Nat) (x : Sci) (bs : List Bool) : + val (powered bits false x bs) ≤ val x ^ exponent bs := by + induction bs with + | nil => simp [powered, exponent, val] + | cons b bs ih => + let r := powered bits false x bs + have h := Nat.le_trans (low_mul bits r r) (Nat.mul_le_mul ih ih) + cases b with + | false => simpa [powered, exponent, Nat.pow_add, r] using h + | true => + have hh := Nat.le_trans (low_mul bits x (multiply bits false r r)) (Nat.mul_le_mul_left (val x) h) + simpa [powered, exponent, Nat.pow_add, r] using hh + +theorem high_pow (bits : Nat) (x : Sci) (bs : List Bool) : + val x ^ exponent bs ≤ val (powered bits true x bs) := by + induction bs with + | nil => simp [powered, exponent, val] + | cons b bs ih => + let r := powered bits true x bs + have h := Nat.le_trans (Nat.mul_le_mul ih ih) (high_mul bits r r) + cases b with + | false => simpa [powered, exponent, Nat.pow_add, r] using h + | true => + have hh := Nat.le_trans (Nat.mul_le_mul_left (val x) h) (high_mul bits x (multiply bits true r r)) + simpa [powered, exponent, Nat.pow_add, r] using hh + +def shift (s : Nat) (x : Sci) : Sci := ⟨x.mant, x.scale+s⟩ + +theorem val_shift (s : Nat) (x : Sci) : val (shift s x) = val x * 2^s := + by simp [val, shift, Nat.pow_add, Nat.mul_assoc] + +def leTest (x y : Sci) : Bool := + if x.scale ≤ y.scale then decide (x.mant ≤ y.mant * 2^(y.scale-x.scale)) + else decide (x.mant * 2^(x.scale-y.scale) ≤ y.mant) + +theorem leTest_sound (x y : Sci) (ht : leTest x y = true) : val x ≤ val y := by + by_cases h : x.scale ≤ y.scale + · have hr : x.mant ≤ y.mant * 2^(y.scale-x.scale) := by simpa [leTest,h] using ht + have hs : y.scale-x.scale+x.scale=y.scale := by omega + have hm := Nat.mul_le_mul_right (2^x.scale) hr + simpa only [val, Nat.mul_assoc, ←Nat.pow_add, hs] using hm + · have hr : x.mant * 2^(x.scale-y.scale) ≤ y.mant := by simpa [leTest,h] using ht + have hs : x.scale-y.scale+y.scale=x.scale := by omega + have hm := Nat.mul_le_mul_right (2^y.scale) hr + simpa only [val, Nat.mul_assoc, ←Nat.pow_add, hs] using hm + +structure Claim where + rank : Nat + num : Nat + den : Nat + lo : Nat + hi : Nat + +def valid (bits frac : Nat) (c : Claim) : Bool := + let m := digits 64 c.num + let d := digits 64 c.den + let k : Sci := ⟨c.rank,0⟩ + exponent m == c.num && exponent d == c.den && c.den > 0 && + leTest (powered bits true ⟨c.lo,0⟩ d) (shift (frac*c.den) (powered bits false k m)) && + leTest (shift (frac*c.den) (powered bits true k m)) (powered bits false ⟨c.hi,0⟩ d) + +theorem valid_sound (bits frac : Nat) (c : Claim) (ok : valid bits frac c = true) : + 0 < c.den ∧ c.lo^c.den ≤ c.rank^c.num * 2^(frac*c.den) ∧ + c.rank^c.num * 2^(frac*c.den) ≤ c.hi^c.den := by + let m := digits 64 c.num + let d := digits 64 c.den + let k : Sci := ⟨c.rank,0⟩ + simp only [valid, Bool.and_eq_true, beq_iff_eq, decide_eq_true_eq] at ok + obtain ⟨⟨⟨⟨hm,hd⟩,hpos⟩,hl⟩,hu⟩ := ok + have lo := Nat.le_trans (high_pow bits ⟨c.lo,0⟩ d) (leTest_sound _ _ hl) + have hi := Nat.le_trans (leTest_sound _ _ hu) (low_pow bits ⟨c.hi,0⟩ d) + rw [val_shift] at lo hi + have lowMiddle := Nat.mul_le_mul_right (2^(frac*c.den)) (low_pow bits k m) + have highMiddle := Nat.mul_le_mul_right (2^(frac*c.den)) (high_pow bits k m) + refine ⟨hpos, ?_, ?_⟩ + · simpa [m,d,k,val,hm,hd] using Nat.le_trans lo lowMiddle + · simpa [m,d,k,val,hm,hd] using Nat.le_trans highMiddle hi + +end DyadicRoot + +#print axioms DyadicRoot.valid_sound diff --git a/research/mixed-rank-uniform-composition/lean/Funding.lean b/research/mixed-rank-uniform-composition/lean/Funding.lean new file mode 100644 index 0000000000..64c7662df4 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/Funding.lean @@ -0,0 +1,84 @@ +import Std + +/-! Exact arithmetic for the two suppliers at the fixed #7830 mixed price. +The six BIT caps are the outward entries of BIT.json, separation.upper_caps. +Their derivation from each rank histogram is a separate numerical proof. -/ +namespace MixedFunding + +def alpha : Rat := 249999999999998000563 / 250000000000000000000 +def lowFirst : Rat := 720828660325258853331 / 2000000000000000000000 +def lowOther : Rat := 9460180868969874332523 / 10000000000000000000000 +def highFirst : Rat := 5969937509690282459981 / 10000000000000000000000 +def highOther : Rat := 9247497622443579677377 / 10000000000000000000000 +def dropped : Rat := 1178602023822729540311 / 1250000000000000000000 + +def paidAndDropped : Rat := + 1 / (1 + 480 * (1-alpha)) + + 2 * lowFirst * lowOther ^ (479 : Nat) + + 2 * highFirst * highOther ^ (479 : Nat) + dropped ^ (480 : Nat) + +def complexPaid : Rat := + 1 / (1 + 1920 / 10^27) + 4 * (31 / 32) ^ (1920 : Nat) + +set_option maxHeartbeats 4000000 +set_option maxRecDepth 16384 + +theorem bit_moment : paidAndDropped < 1 - 12309863319385 / 10^25 := by decide +kernel +theorem complex_moment : complexPaid < 1 := by decide +kernel + +def rawBit : Rat := 3879928046148 / 10^15 +def trialC : Rat := 387992803563 / 10^14 +def finalClaim : Rat := 387992803556 / 10^14 +def uniformLoss : Rat := 1 / 400000000000 +def coverLoss : Rat := 1 / 125000000000 +def covered : Rat := rawBit - uniformLoss - coverLoss +def seed : Rat := 12039 / 3125000 +def stages : List Rat := + [seed, 3879818243504 / 10^15, 3879927596478 / 10^15, 3879928033890 / 10^15, + 3879928035639 / 10^15, 3879928035646 / 10^15] +def validStages (old : Rat) : List Rat → Prop + | [] => True + | c :: rest => old < c ∧ c < (249 * covered + old) / 250 ∧ c < 1 / 250 ∧ validStages c rest +instance stagesDec (old : Rat) : (xs : List Rat) → Decidable (validStages old xs) + | [] => isTrue True.intro + | c :: xs => + letI := stagesDec c xs + inferInstanceAs (Decidable (_ ∧ _ ∧ _ ∧ validStages c xs)) + +theorem cold_through_six_stages : validStages 0 stages := by decide +kernel +theorem supplier_room : + trialC = finalClaim + 7 / 10^14 ∧ + 3879928035646 / (10^15 : Rat) - trialC = 1 / 62500000000000 ∧ + rawBit < 97 / 25000 ∧ trialC < 97 / 25000 ∧ 97 / (25000 : Rat) < 1 / 250 := + by decide +kernel + +/-- Raising both positive sides to 625 verifies bounds for the two real powers, +because 480 * (97/25000) = 1164/625 and 1920 * (97/25000) = 4656/625. -/ +theorem ambient_upper : + (134 : Nat)^1164 < 9160^625 ∧ (153 : Nat)^4656 < 18900000000000000^625 ∧ + (9160 : Nat) < 2^64 ∧ (18900000000000000 : Nat) < 2^2381 := by decide +kernel + +theorem eta_guards : + (9160 * 250 : Nat)*13^64 < 249*15^64 ∧ + (18900000000000000 * 250 : Nat)*63^2381 < 249*64^2381 := by decide +kernel + +theorem logarithm_guards : + (11 : Nat)^15 < 16^13 ∧ 4*11^(480*15) ≤ 134^(480*13) ∧ + (11 : Nat)^64 < 12^63 ∧ 2*11^(1920*64) ≤ 153^(1920*63) := by decide +kernel + +theorem fixed_carriers : + (1285200000000000 + 1 : Nat)^64 < 2^3213 ∧ + (15171300000000000000 + 1 : Nat)^2381 < 2^151713 ∧ + 1285200000000000 = (400000000000 : Nat)*3213 ∧ + 15171300000000000000 = (10^14 : Nat)*151713 := by decide +kernel + +end MixedFunding + +#print axioms MixedFunding.bit_moment +#print axioms MixedFunding.complex_moment +#print axioms MixedFunding.cold_through_six_stages +#print axioms MixedFunding.supplier_room +#print axioms MixedFunding.ambient_upper +#print axioms MixedFunding.eta_guards +#print axioms MixedFunding.logarithm_guards +#print axioms MixedFunding.fixed_carriers diff --git a/research/mixed-rank-uniform-composition/lean/HaloRadius.lean b/research/mixed-rank-uniform-composition/lean/HaloRadius.lean new file mode 100644 index 0000000000..cae39fa5e2 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/HaloRadius.lean @@ -0,0 +1,510 @@ +import Std + +namespace HaloRadius + +structure Datum where + re : Int + im : Int + deriving DecidableEq, Repr + +def radius (v : Datum) : Nat := v.re.natAbs + v.im.natAbs + +def plus (x y : Datum) : Datum := ⟨x.re + y.re, x.im + y.im⟩ + +def times (n : Int) (x : Datum) : Datum := ⟨n * x.re, n * x.im⟩ + +def truncate (d : Nat) (x : Datum) : Datum := ⟨x.re.tdiv d, x.im.tdiv d⟩ + +theorem plusBound (x y : Datum) : radius (plus x y) ≤ radius x + radius y := by + have hr := Int.natAbs_add_le x.re y.re + have hi := Int.natAbs_add_le x.im y.im + simp only [radius, plus] + omega + +theorem timesRadius (c : Int) (x : Datum) : radius (times c x) = c.natAbs * radius x := by + simp [radius, times, Int.natAbs_mul, Nat.mul_add] + +theorem truncateRadius (d : Nat) (x : Datum) : radius (truncate d x) ≤ radius x / d := by + simp only [radius, truncate, Int.natAbs_tdiv, Int.natAbs_natCast] + change x.re.natAbs / d + x.im.natAbs / d ≤ (x.re.natAbs + x.im.natAbs) / d + exact Nat.div_add_div_le_add_div + +variable {ι : Type} + +abbrev Row (ι : Type) := List (Int × ι) + +def mass (row : Row ι) : Nat := (row.map fun term => term.1.natAbs).sum + +def dot (z : ι → Datum) : Row ι → Datum + | [] => ⟨0, 0⟩ + | (w, j) :: rest => plus (times w (z j)) (dot z rest) + +theorem dotBound (z : ι → Datum) (R : Nat) (hz : ∀ i, radius (z i) ≤ R) (row : Row ι) : + radius (dot z row) ≤ mass row * R := by + induction row with + | nil => simp [radius, dot, mass] + | cons item tail ih => + obtain ⟨w, j⟩ := item + exact calc + radius (dot z ((w,j)::tail)) + ≤ radius (times w (z j)) + radius (dot z tail) := plusBound .. + _ ≤ w.natAbs * R + mass tail * R := + Nat.add_le_add (by rw [timesRadius]; exact Nat.mul_le_mul_left _ (hz j)) ih + _ = mass ((w,j)::tail) * R := by simp [mass, Nat.add_mul] + +/-- Base grid has unit 1/D. Input, state and reference coefficients use that grid. +The row computes x/a + sum cⱼ zⱼ/D and truncates only the full sum. -/ +def update (D a : Nat) (x : Datum) (z : ι → Datum) (row : Row ι) : Datum := + truncate (a * D) (plus (times D x) (times a (dot z row))) + +theorem updateBound (D a R : Nat) (hd : 0 < a * D) (row : Row ι) + (hg : D + a * mass row ≤ a * D) (x : Datum) (z : ι → Datum) + (hx : radius x ≤ R) (hz : ∀ i, radius (z i) ≤ R) : + radius (update D a x z row) ≤ R := by + let v := plus (times D x) (times a (dot z row)) + have hv : radius v ≤ a * D * R := by + calc + radius v ≤ radius (times D x) + radius (times a (dot z row)) := plusBound .. + _ ≤ D * R + a * (mass row * R) := by + simp only [timesRadius, Int.natAbs_natCast] + exact Nat.add_le_add (Nat.mul_le_mul_left D hx) + (Nat.mul_le_mul_left a (dotBound z R hz row)) + _ = (D + a * mass row) * R := by simp [Nat.add_mul, Nat.mul_assoc] + _ ≤ a * D * R := Nat.mul_le_mul_right _ hg + have hquot : radius v / (a * D) ≤ (a * D * R) / (a * D) := Nat.div_le_div_right hv + calc + radius (update D a x z row) ≤ radius v / (a * D) := truncateRadius .. + _ ≤ (a * D * R) / (a * D) := hquot + _ = R := Nat.mul_div_cancel_left R hd + +structure Axis (ι : Type) where + D : Nat + a : Nat + J : Nat + rows : ι → Row ι + +def Admitted (axis : Axis ι) : Prop := + 0 < axis.a * axis.D ∧ ∀ i, axis.D + axis.a * mass (axis.rows i) ≤ axis.a * axis.D + +def iterate (axis : Axis ι) (x : ι → Datum) : Nat → ι → Datum + | 0, _ => ⟨0, 0⟩ + | k+1, i => update axis.D axis.a (x i) (iterate axis x k) (axis.rows i) + +theorem eachIteration (axis : Axis ι) (ha : Admitted axis) (x : ι → Datum) (R : Nat) + (hx : ∀ i, radius (x i) ≤ R) (k : Nat) : ∀ i, radius (iterate axis x k i) ≤ R := by + induction k with + | zero => simp [iterate, radius] + | succ k ih => exact fun i => updateBound _ _ _ ha.1 _ (ha.2 i) _ _ (hx i) ih + +def sweep (x : ι → Datum) : List (Axis ι) → ι → Datum + | [] => x + | a :: rest => sweep (iterate a x a.J) rest + +theorem everyAxis (axes : List (Axis ι)) (x : ι → Datum) (R : Nat) + (ha : ∀ a ∈ axes, Admitted a) (hx : ∀ i, radius (x i) ≤ R) : + ∀ i, radius (sweep x axes i) ≤ R := by + induction axes generalizing x with + | nil => exact hx + | cons a rest ih => + apply ih (iterate a x a.J) + · exact fun b hb => ha b (List.mem_cons_of_mem _ hb) + · exact eachIteration a (ha a (by simp)) x R hx a.J + +def minus (x y : Datum) : Datum := ⟨x.re - y.re, x.im - y.im⟩ + +theorem truncateResidual (d : Nat) (hd : 0 < d) (v : Datum) : + radius (minus (times d (truncate d v)) v) ≤ 2*d := by + have single (x : Int) : ((d : Int) * x.tdiv d - x).natAbs < d := by + have eq : (d : Int) * x.tdiv d - x = -x.tmod d := by + have := Int.mul_tdiv_add_tmod x d + omega + rw [eq, Int.natAbs_neg, Int.natAbs_tmod, Int.natAbs_natCast] + exact Nat.mod_lt _ hd + have hr := single v.re + have hi := single v.im + simp only [radius, minus, times, truncate] + omega + +theorem linearDot (row : Row ι) (z w : ι → Datum) (n : Int) : + dot (fun j => minus (times n (z j)) (w j)) row = + minus (times n (dot z row)) (dot w row) := by + induction row with + | nil => simp [dot, minus, times] + | cons el rest ih => + obtain ⟨coef,j⟩ := el + simp only [dot] + rw [ih] + simp only [minus, times, plus, Datum.mk.injEq] + constructor <;> grind + +def den (axis : Axis ι) (k : Nat) : Nat := (axis.a * axis.D)^k + +/-- The unrounded Horner numerator at common denominator (aD)^k, measured +in input grid units. This is precisely the k-term finite Neumann polynomial. -/ +def exactIter (axis : Axis ι) (x : ι → Datum) : Nat → ι → Datum + | 0, _ => ⟨0,0⟩ + | k+1, i => plus (times (axis.D * den axis k : Nat) (x i)) + (times axis.a (dot (exactIter axis x k) (axis.rows i))) + +def defect (axis : Axis ι) (x : ι → Datum) (k : Nat) (i : ι) : Datum := + minus (times (den axis k) (iterate axis x k i)) (exactIter axis x k i) + +private theorem errorAlgebra (a D n : Int) (x y z v : Datum) : + minus (times (n * (a * D)) v) (plus (times (D * n) x) (times a z)) = + plus (times n (minus (times (a * D) v) (plus (times D x) (times a y)))) + (times a (minus (times n y) z)) := by + simp only [minus, plus, times, Datum.mk.injEq] + constructor <;> grind + +theorem defectStep (axis : Axis ι) (x : ι → Datum) (k : Nat) (i : ι) : + defect axis x (k+1) i = + let raw := plus (times axis.D (x i)) + (times axis.a (dot (iterate axis x k) (axis.rows i))) + plus (times (den axis k) + (minus (times (axis.a * axis.D : Nat) (truncate (axis.a * axis.D) raw)) raw)) + (times axis.a (dot (defect axis x k) (axis.rows i))) := by + have row := linearDot (axis.rows i) (iterate axis x k) (exactIter axis x k) (den axis k) + change dot (defect axis x k) (axis.rows i) = _ at row + rw [row] + simp only [defect, iterate, update, exactIter, den, Nat.pow_succ, Int.natCast_mul] + apply errorAlgebra + +/-- With B an integer bound for the inverse row gap, numerical Horner error +stays at most 2B input-grid units, after clearing the exact denominator. -/ +theorem finiteNeumannError (axis : Axis ι) (x : ι → Datum) (B : Nat) + (hd : 0 < axis.a * axis.D) + (hg : ∀ i, axis.D + B * mass (axis.rows i) ≤ B * axis.D) + (k : Nat) : ∀ i, radius (defect axis x k i) ≤ 2 * B * den axis k := by + induction k with + | zero => simp [defect, den, iterate, exactIter, radius, times, minus] + | succ k ih => + intro i + let row := axis.rows i + let raw := plus (times axis.D (x i)) (times axis.a (dot (iterate axis x k) row)) + rw [defectStep] + exact calc + _ ≤ _ := plusBound _ _ + _ ≤ den axis k * (2 * (axis.a * axis.D)) + + axis.a * (mass row * (2 * B * den axis k)) := by + simp only [timesRadius, Int.natAbs_natCast] + exact Nat.add_le_add + (Nat.mul_le_mul_left _ (truncateResidual _ hd raw)) + (Nat.mul_le_mul_left _ (dotBound _ _ ih row)) + _ = (2 * den axis k * axis.a) * (axis.D + B * mass row) := by grind + _ ≤ (2 * den axis k * axis.a) * (B * axis.D) := Nat.mul_le_mul_left _ (hg i) + _ = 2 * B * den axis (k+1) := by simp only [den, Nat.pow_succ]; grind + +theorem finiteContraction (axis : Axis ι) (ha : Admitted axis) (x : ι → Datum) + (R : Nat) (hx : ∀ i, radius (x i) ≤ R) (k : Nat) : + ∀ i, radius (exactIter axis x k i) ≤ R * den axis k := by + induction k with + | zero => simp [exactIter, den, radius] + | succ k ih => + intro i + calc + _ ≤ _ := plusBound _ _ + _ ≤ (axis.D * den axis k) * R + + axis.a * (mass (axis.rows i) * (R * den axis k)) := by + simp only [timesRadius, Int.natAbs_natCast] + exact Nat.add_le_add (Nat.mul_le_mul_left _ (hx i)) + (Nat.mul_le_mul_left _ (dotBound _ _ ih (axis.rows i))) + _ = (R * den axis k) * (axis.D + axis.a * mass (axis.rows i)) := by grind + _ ≤ (R * den axis k) * (axis.a * axis.D) := Nat.mul_le_mul_left _ (ha.2 i) + _ = R * den axis (k+1) := by simp [den, Nat.pow_succ, Nat.mul_assoc] + +theorem scaleDot (row : Row ι) (z : ι → Datum) (n : Int) : + dot (fun j => times n (z j)) row = times n (dot z row) := by + induction row with + | nil => simp [dot, times] + | cons term tail ih => + obtain ⟨c,j⟩ := term + simp only [dot] + rw [ih] + simp only [times, plus, Datum.mk.injEq] + constructor <;> grind + +def tailNumerator (axis : Axis ι) (x y : ι → Datum) (S k : Nat) (i : ι) : Datum := + minus (times (den axis k) (y i)) (times S (exactIter axis x k i)) + +private theorem fixedAlgebra (a d n s : Int) (x y row prev : Datum) + (hf : times (a*d) y = plus (times (d*s) x) (times a row)) : + minus (times (n*(a*d)) y) (times s (plus (times (d*n) x) (times a prev))) = + times a (minus (times n row) (times s prev)) := by + have hm : times (n*(a*d)) y = times n (times (a*d) y) := by simp [times, Int.mul_assoc] + rw [hm, hf] + simp only [times, plus, minus, Datum.mk.injEq] + constructor <;> grind + +def Fixed (axis : Axis ι) (x y : ι → Datum) (s : Nat) : Prop := + ∀ i, times (axis.a * axis.D : Nat) (y i) = + plus (times (axis.D*s : Nat) (x i)) (times axis.a (dot y (axis.rows i))) + +theorem tailStep (axis : Axis ι) (x y : ι → Datum) (s k : Nat) (hf : Fixed axis x y s) (i : ι) : + tailNumerator axis x y s (k+1) i = times axis.a (dot (tailNumerator axis x y s k) (axis.rows i)) := by + have hd := linearDot (axis.rows i) y (fun j => times s (exactIter axis x k j)) (den axis k) + change dot (tailNumerator axis x y s k) (axis.rows i) = _ at hd + rw [hd, scaleDot] + simp only [tailNumerator, exactIter, den, Nat.pow_succ, Int.natCast_mul] + apply fixedAlgebra + simpa only [Int.natCast_mul] using hf i + +/-- For a rational fixed point y/s, the finite Neumann numerator differs from +it by at most R (a m)^k at denominator s(aD)^k. The physical contraction +ratio is m/D, where m bounds the absolute row sum of encoded coefficients. -/ +theorem geometricTail (axis : Axis ι) (x y : ι → Datum) (s m R : Nat) + (hf : Fixed axis x y s) (hm : ∀ i, mass (axis.rows i) ≤ m) + (hr : ∀ i, radius (y i) ≤ R) (k : Nat) : + ∀ i, radius (tailNumerator axis x y s k i) ≤ R * (axis.a*m)^k := by + induction k with + | zero => + intro i + simpa [tailNumerator, exactIter, den, minus, times, radius] using hr i + | succ k ih => + intro i + rw [tailStep _ _ _ _ _ hf, timesRadius, Int.natAbs_natCast] + exact calc + _ ≤ axis.a * (mass (axis.rows i) * (R * (axis.a*m)^k)) := + Nat.mul_le_mul_left _ (dotBound _ _ ih _) + _ ≤ axis.a * (m * (R * (axis.a*m)^k)) := + Nat.mul_le_mul_left _ (Nat.mul_le_mul_right _ (hm i)) + _ = _ := by simp only [Nat.pow_succ]; grind + +theorem dotSame (row : Row ι) (x y : ι → Datum) (h : ∀ term ∈ row, x term.2 = y term.2) : + dot x row = dot y row := by + induction row with + | nil => rfl + | cons item tail ih => + obtain ⟨w,j⟩ := item + simp only [dot] + rw [h (w,j) (by simp), ih (fun t ht => h t (List.mem_cons_of_mem _ ht))] + +/-- Rows of the full and the principal polynomial agree whenever the entire +backward dependency cone stays inside the retained physical section. -/ +theorem locality (a b : Axis ι) (x : ι → Datum) (zone : Nat → ι → Prop) + (hd : a.D=b.D) (hs : a.a=b.a) + (rows : ∀ k i, zone (k+1) i → a.rows i = b.rows i) + (cone : ∀ k i, zone (k+1) i → ∀ term ∈ a.rows i, zone k term.2) + (k : Nat) : ∀ i, zone k i → exactIter a x k i = exactIter b x k i := by + induction k with + | zero => intros; rfl + | succ k ih => + intro i hi + have eq := dotSame (a.rows i) _ _ (fun t ht => ih t.2 (cone k i hi t ht)) + rw [rows k i hi] at eq + simp only [exactIter, den, hd, hs, rows k i hi, eq] + +theorem roundedLocality (a b : Axis ι) (x : ι → Datum) (zone : Nat → ι → Prop) + (hd : a.D=b.D) (hs : a.a=b.a) + (rows : ∀ k i, zone (k+1) i → a.rows i = b.rows i) + (cone : ∀ k i, zone (k+1) i → ∀ term ∈ a.rows i, zone k term.2) + (k : Nat) : ∀ i, zone k i → iterate a x k i = iterate b x k i := by + induction k with + | zero => intros; rfl + | succ k ih => + intro i hi + have eq := dotSame (a.rows i) _ _ (fun t ht => ih t.2 (cone k i hi t ht)) + rw [rows k i hi] at eq + simp only [iterate, update, hd, hs, rows k i hi, eq] + +theorem dotZero (row : Row ι) : dot (fun _ => ⟨0,0⟩) row = ⟨0,0⟩ := by + induction row with + | nil => rfl + | cons term tail ih => + obtain ⟨c,j⟩ := term + simp only [dot, ih, times, plus, Int.mul_zero, Int.add_zero] + +/-- In step one the incoming iterate is zero, so no input-band neighbor is +needed. This is the J-1 transition count of the physical shrinking rectangle. -/ +theorem savedRectangle (a b : Axis ι) (x y : ι → Datum) (inside : Nat → ι → Prop) + (hd : a.D=b.D) (hs : a.a=b.a) + (source : ∀ k i, inside k i → x i=y i) + (rows : ∀ k i, inside (k+1) i → a.rows i=b.rows i) + (cone : ∀ k i, inside (k+1) i → ∀ term ∈ a.rows i, inside k term.2) + (k : Nat) : ∀ i, inside k i → + iterate a x (k+1) i = iterate b y (k+1) i ∧ + exactIter a x (k+1) i = exactIter b y (k+1) i := by + induction k with + | zero => + intro i hi + simp [iterate, exactIter, update, den, dotZero, hd, hs, source _ i hi] + | succ k ih => + intro i hi + have hn := dotSame (a.rows i) _ _ (fun t ht => (ih t.2 (cone k i hi t ht)).1) + have he := dotSame (a.rows i) _ _ (fun t ht => (ih t.2 (cone k i hi t ht)).2) + rw [rows k i hi] at hn he + constructor + · change update a.D a.a (x i) (iterate a x (k+1)) (a.rows i) = + update b.D b.a (y i) (iterate b y (k+1)) (b.rows i) + simp only [update, hd, hs, source _ i hi, rows k i hi, hn] + · change plus (times (a.D * den a (k+1) : Nat) (x i)) + (times a.a (dot (exactIter a x (k+1)) (a.rows i))) = + plus (times (b.D * den b (k+1) : Nat) (y i)) + (times b.a (dot (exactIter b y (k+1)) (b.rows i))) + simp only [den, hd, hs, source _ i hi, rows k i hi, he] + +def inset (lo hi w : Int) (k : Nat) (i : Int) : Prop := + lo + k*w ≤ i ∧ i < hi - k*w + +/-- Every physical neighbor at signed offset in [-w,w] stays inside the +previous lifted (possibly period-crossing) rectangle. -/ +theorem physicalCone (lo hi w i j : Int) (k : Nat) (h : inset lo hi w (k+1) i) + (left : i-w ≤ j) (right : j ≤ i+w) : inset lo hi w k j := by + simp only [inset, Int.natCast_succ, Int.add_mul, Int.one_mul] at h ⊢ + omega + +theorem linearExact (axis : Axis ι) (x y : ι → Datum) (n : Int) (k : Nat) : + ∀ i, exactIter axis (fun i => minus (times n (x i)) (y i)) k i = + minus (times n (exactIter axis x k i)) (exactIter axis y k i) := by + induction k with + | zero => simp [exactIter, times, minus] + | succ k ih => + intro i + simp only [exactIter] + rw [funext ih, linearDot] + simp only [minus, times, plus, Datum.mk.injEq] + constructor <;> grind + +/-- An exact input uses one integer denominator d for the entire field. -/ +def Close (d e : Nat) (x y : ι → Datum) : Prop := + ∀ i, radius (minus (times d (x i)) (y i)) ≤ e * d + +private theorem splitStep (s t : Int) (a b c : Datum) : + minus (times (s*t) a) c = plus (times s (minus (times t a) b)) (minus (times s b) c) := by + simp only [minus, times, plus, Datum.mk.injEq] + constructor <;> grind + +theorem nextExactComparison (axis : Axis ι) (ha : Admitted axis) (B : Nat) + (hg : ∀ i, axis.D + B * mass (axis.rows i) ≤ B * axis.D) + (s e : Nat) (x y : ι → Datum) (hc : Close s e x y) : + Close (s * den axis axis.J) (e + 2*B) (iterate axis x axis.J) (exactIter axis y axis.J) := by + intro i + have hlin := linearExact axis x y s axis.J i + have hcon := finiteContraction axis ha (fun j => minus (times s (x j)) (y j)) (e*s) hc axis.J i + have hnum := finiteNeumannError axis x B ha.1 hg axis.J i + simp only [Int.natCast_mul] + rw [splitStep (s : Int) (den axis axis.J) _ (exactIter axis x axis.J i) _, ← hlin] + calc + _ ≤ _ := plusBound _ _ + _ ≤ s * (2*B*den axis axis.J) + e*s*den axis axis.J := by + rw [timesRadius, Int.natAbs_natCast] + exact Nat.add_le_add (Nat.mul_le_mul_left s hnum) hcon + _ = _ := by grind + +def exactSweep (x : ι → Datum) : List (Axis ι) → ι → Datum + | [] => x + | a :: rest => exactSweep (exactIter a x a.J) rest + +def sweepDen (axes : List (Axis ι)) : Nat := (axes.map fun a => den a a.J).prod + +/-- Rounded successive axis evaluations are compared at their actual inputs. +No linearity or one-Lipschitz assertion about the rounded operation is needed. -/ +theorem spectralNumeratorError (axes : List (Axis ι)) (B s e : Nat) (x y : ι → Datum) + (ha : ∀ a ∈ axes, Admitted a ∧ ∀ i, a.D+B*mass (a.rows i) ≤ B*a.D) + (hc : Close s e x y) : + Close (s * sweepDen axes) (e + 2*B*axes.length) (sweep x axes) (exactSweep y axes) := by + induction axes generalizing s e x y with + | nil => simpa [sweepDen, sweep, exactSweep] using hc + | cons a rest ih => + have h := ha a (by simp) + have step := nextExactComparison a h.1 B h.2 s e x y hc + have tail := ih (s*den a a.J) (e+2*B) _ _ + (fun t ht => ha t (List.mem_cons_of_mem _ ht)) step + simpa [sweep, exactSweep, sweepDen, Nat.mul_assoc, Nat.mul_add, + Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using tail + +def splice (keep : ι → Bool) (core face : ι → Datum) (i : ι) : Datum := + if keep i then core i else face i + +/-- At fixed denominator all first-face and kept-row returns have disjoint ownership. -/ +theorem disjointSplice (keep : ι → Bool) (core face ideal : ι → Datum) + (d ec ef : Nat) + (hc : ∀ i, keep i = true → radius (minus (times d (core i)) (ideal i)) ≤ ec*d) + (hf : ∀ i, keep i = false → radius (minus (times d (face i)) (ideal i)) ≤ ef*d) : + Close d (max ec ef) (splice keep core face) ideal := by + intro i + cases h : keep i with + | false => + simpa [splice, h] using Nat.le_trans (hf i h) (Nat.mul_le_mul_right d (Nat.le_max_right ec ef)) + | true => + simpa [splice, h] using Nat.le_trans (hc i h) (Nat.mul_le_mul_right d (Nat.le_max_left ec ef)) + +private theorem differenceTriangle (x y z : Datum) : + radius (minus x z) ≤ radius (minus x y) + radius (minus z y) := by + have re : x.re-z.re = (x.re-y.re) + -(z.re-y.re) := by omega + have im : x.im-z.im = (x.im-y.im) + -(z.im-y.im) := by omega + have hr := Int.natAbs_add_le (x.re-y.re) (-(z.re-y.re)) + have hi := Int.natAbs_add_le (x.im-y.im) (-(z.im-y.im)) + rw [← re, Int.natAbs_neg] at hr + rw [← im, Int.natAbs_neg] at hi + simp only [radius, minus] + omega + +private theorem commonDenominator (s d : Nat) (x y : Datum) : + minus (times (s*d : Nat) x) (times d y) = times d (minus (times s x) y) := by + simp only [times, minus, Int.natCast_mul, Datum.mk.injEq] + constructor <;> grind + +/-- Both ideal fields have denominator S. The tail bound is rounded upward +to t grid units, so the final integer bound adds t to the numerical bill. -/ +theorem compareToInverse (axis : Axis ι) (B S e R m t : Nat) + (actual before after : ι → Datum) (ha : Admitted axis) + (hg : ∀ i, axis.D + B * mass (axis.rows i) ≤ B * axis.D) + (hm : ∀ i, mass (axis.rows i) ≤ m) (hf : Fixed axis before after 1) + (hr : ∀ i, radius (after i) ≤ R) (small : R*(axis.a*m)^axis.J ≤ t*S*den axis axis.J) + (hc : Close S e actual before) : + Close S (e + 2*B + t) (iterate axis actual axis.J) after := by + intro i + have hn := nextExactComparison axis ha B hg S e actual before hc i + have ht := geometricTail axis before after 1 m R hf hm hr axis.J i + have hone (v : Datum) : times 1 v = v := by cases v; simp [times] + have oneCast : ((1 : Nat) : Int) = 1 := rfl + simp only [tailNumerator, oneCast, hone] at ht + have both := differenceTriangle + (times (S*den axis axis.J : Nat) (iterate axis actual axis.J i)) + (exactIter axis before axis.J i) (times (den axis axis.J) (after i)) + rw [commonDenominator, timesRadius, Int.natAbs_natCast] at both + have sum := Nat.add_le_add hn (Nat.le_trans ht small) + have hc' := Nat.le_trans both sum + have hd : 0 < den axis axis.J := Nat.pow_pos ha.1 + apply Nat.le_of_mul_le_mul_left (c := den axis axis.J) (hc := hd) + calc + _ ≤ _ := hc' + _ = _ := by grind + +/-- The mathematical inverse trajectory is expressed by its exact rational +linear equations. The algorithm consumes none of these fields at runtime. -/ +inductive InverseChain (B S t : Nat) : List (Axis ι) → (ι → Datum) → (ι → Datum) → Prop + | nil (v : ι → Datum) : InverseChain B S t [] v v + | cons (a : Axis ι) (tail : List (Axis ι)) (x y z : ι → Datum) (R m : Nat) + (ha : Admitted a) (hg : ∀ i, a.D + B * mass (a.rows i) ≤ B * a.D) + (hm : ∀ i, mass (a.rows i) ≤ m) (hf : Fixed a x y 1) (hr : ∀ i, radius (y i) ≤ R) + (small : R*(a.a*m)^a.J ≤ t*S*den a a.J) (rest : InverseChain B S t tail y z) : + InverseChain B S t (a::tail) x z + +/-- Rounded physical iteration over all axes versus the full normalized +inverse, including the geometric tails and actual-input error at every stage. -/ +theorem completeInverseError (axes : List (Axis ι)) (B S t e : Nat) + (actual before after : ι → Datum) (chain : InverseChain B S t axes before after) + (hc : Close S e actual before) : + Close S (e + (2*B+t)*axes.length) (sweep actual axes) after := by + induction chain generalizing actual e with + | nil => simpa [sweep] using hc + | cons a tail x y z R m ha hg hm hf hr small rest ih => + have hs := compareToInverse a B S e R m t actual x y ha hg hm hf hr small hc + have combined := ih (e := e + 2*B + t) (actual := iterate a actual a.J) hs + simpa [sweep, Nat.mul_add, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using combined + +#print axioms updateBound +#print axioms eachIteration +#print axioms everyAxis +#print axioms finiteNeumannError +#print axioms geometricTail +#print axioms locality +#print axioms roundedLocality +#print axioms savedRectangle +#print axioms physicalCone +#print axioms spectralNumeratorError +#print axioms disjointSplice +#print axioms completeInverseError + +end HaloRadius diff --git a/research/mixed-rank-uniform-composition/lean/Integrated.lean b/research/mixed-rank-uniform-composition/lean/Integrated.lean new file mode 100644 index 0000000000..d8b43d379c --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/Integrated.lean @@ -0,0 +1,66 @@ +import Coordinates +import Recovery +import Mathlib.Tactic.NormNum + +namespace MixedRankIntegrated + +open Finset MixedRankCoordinates MixedRankRecovery + +variable {d : ℕ} (s t : Fin d → ℕ) + (hs : Pairwise fun i j ↦ Nat.Coprime (s i) (s j)) + (ht : ∀ i, Nat.Coprime (t i) (s i)) + [∀ i, NeZero (s i)] [NeZero (∏ i, s i)] + +def prefixProduct (s : Fin d → ℕ) (i : Fin d) := ∏ j ∈ univ.filter (· < i), s j + +omit [∀ i, NeZero (s i)] [NeZero (∏ i, s i)] in +include hs in +theorem prefix_coprime (i : Fin d) : Nat.Coprime (prefixProduct s i) (s i) := by + apply Nat.Coprime.prod_left + intro j hj + exact hs (ne_of_lt (mem_filter.mp hj).2) + +def mu (i : Fin d) : (ZMod (s i))ˣ := (ZMod.unitOfCoprime _ (prefix_coprime s hs i))⁻¹ + +omit [∀ i, NeZero (s i)] [NeZero (∏ i, s i)] in +theorem prefix_inverse (i : Fin d) : ((prefixProduct s i : ℕ) : ZMod (s i)) * (mu s hs i).val = 1 := by + change ((ZMod.unitOfCoprime _ (prefix_coprime s hs i)).val) * + ((ZMod.unitOfCoprime _ (prefix_coprime s hs i))⁻¹).val = 1 + simp + +def factor (i : Fin d) : ℕ := t i * (mu s hs i).val.val ^ 2 + +omit [NeZero (∏ i, s i)] in +include ht in +theorem factor_coprime (i : Fin d) : Nat.Coprime (factor s t hs i) (s i) := by + apply (ZMod.isUnit_iff_coprime _ _).mp + simp only [factor, Nat.cast_mul, Nat.cast_pow, ZMod.natCast_zmod_val] + exact ((ZMod.unitOfCoprime _ (ht i)).isUnit.mul ((mu s hs i).isUnit.pow 2)) + +def sourceUnit : (ZMod (∏ i, s i))ˣ := + ZMod.unitOfCoprime _ (admissible_weight s (factor s t hs) hs (factor_coprime s t hs ht)) + +theorem physical_character (v : ℤ) : + (∏ i, ZMod.stdAddChar (((v * (factor s t hs i : ℤ) : ℤ) : ZMod (s i)))) = + ZMod.stdAddChar ((v : ZMod (∏ i, s i)) * (sourceUnit s t hs ht).val) := by + rw [physical_kernel] + simp [sourceUnit] + +abbrev SourceSignal (s : Fin d → ℕ) := Signal (∏ i, s i) + +theorem product_at_physical_coordinates (B : ℕ) (hB : 32 ≤ B) (hbnd : ∏ i, s i ≤ B) + (fw bw : SourceSignal s → SourceSignal s) (mul : ℂ → ℂ → ℂ) + (e : ℝ) (he : 0 ≤ e) (herr : e ≤ 3 / (B : ℝ)^6) + (hfw : ∀ x, disk x (1/2) → ∀ j, ‖fw x j - forward (sourceUnit s t hs ht) x j‖ ≤ e) + (hbw : ∀ x, disk x (1/2) → ∀ j, ‖bw x j - opposite (sourceUnit s t hs ht) x j‖ ≤ e) + (hm : ∀ x y, ‖x‖ ≤ 1/2 → ‖y‖ ≤ 1/2 → ‖mul x y - x*y‖ ≤ e) + (a b : ZMod (∏ i, s i) → ℕ) (ha : ∀ j, a j ≤ B) (hb : ∀ j, b j ≤ B) + (hspan : ∀ i j, a i ≠ 0 → b j ≠ 0 → i.val + j.val < ∏ i, s i) : + pack B (carry B 0 (ordered (decode B fw bw mul a b))) = + radixValue B a * radixValue B b := + recovered_product B hB hbnd (sourceUnit s t hs ht) fw bw mul e he herr hfw hbw hm a b ha hb hspan + +#print axioms prefix_inverse +#print axioms physical_character +#print axioms product_at_physical_coordinates +end MixedRankIntegrated diff --git a/research/mixed-rank-uniform-composition/lean/OuterPrices.lean b/research/mixed-rank-uniform-composition/lean/OuterPrices.lean new file mode 100644 index 0000000000..9275fa26c4 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/OuterPrices.lean @@ -0,0 +1,29 @@ +import Mathlib.Tactic.NormNum + +namespace MixedRankPrices + +abbrev k : Rat := 387992803556 / 100000000000000 +abbrev h : Rat := 1 / 100000000000000 +abbrev e : Rat := 1-h +abbrev z : Rat := 1-3*h +abbrev q : Rat := k+3*h +abbrev a : Rat := k+4*h +abbrev x : Rat := e*(1+q)-3/32+h +abbrev ordinary : Rat := 3879928035646 / 1000000000000000 + +def costs : List Rat := [ + 1-e*q, 1-a, e-q*z, e-a*z, e-z, e-x+29/32, e+1/2-x, + 1-e, e+z+54-128, 1-ordinary+2*(1-e), 1-e] + +theorem costs_fit : ∀ u ∈ costs, u < 1-k := by + norm_num [costs, x, e, z, q, a, ordinary, k, h, List.forall_mem_cons] + +theorem crt_saving : ordinary-2*(1-e) = 3879928035626 / 1000000000000000 := by + norm_num [ordinary, e, h] +theorem actual_word : ordinary-(k+7*h) = 16 / 1000000000000000 := by + norm_num [ordinary, k, h] + +#print axioms costs_fit +#print axioms crt_saving +#print axioms actual_word +end MixedRankPrices diff --git a/research/mixed-rank-uniform-composition/lean/PhaseBudget.lean b/research/mixed-rank-uniform-composition/lean/PhaseBudget.lean new file mode 100644 index 0000000000..39196a5db7 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/PhaseBudget.lean @@ -0,0 +1,85 @@ +import Std + +namespace PhaseBudget + +/-- Numerators of a Gaussian value at one common binary denominator. -/ +structure Gauss where + re : Int + im : Int + deriving DecidableEq + +/-- Twice the output of the actual C kernel at its first source address. +The caller supplies the partner address to obtain the other output. -/ +def twiceC (x y : Gauss) : Gauss := + ⟨x.re - x.im + y.re + y.im, x.re + x.im + y.im - y.re⟩ + +def Fits (m : Int) (x : Gauss) : Prop := + -m ≤ x.re ∧ x.re ≤ m ∧ -m ≤ x.im ∧ x.im ≤ m + +theorem one_axis_bound {x y : Gauss} {m : Int} (hx : Fits m x) + (hy : Fits m y) : Fits (4*m) (twiceC x y) := by + rcases hx with ⟨a,b,c,d⟩ + rcases hy with ⟨e,f,g,h⟩ + simp only [Fits, twiceC] + omega + +/-- Each partner map is the reversal of the indicated selected coordinate. +The bound also permits any sequence of partner maps. -/ +def kernels {A : Type} (x : A → Gauss) : List (A → A) → A → Gauss + | [], a => x a + | f :: fs, a => kernels (fun i => twiceC (x i) (x (f i))) fs a + +theorem kernel_numerators {A : Type} (fs : List (A → A)) + (x : A → Gauss) (m : Int) (hx : ∀ a, Fits m (x a)) : + ∀ a, Fits ((4:Int)^fs.length * m) (kernels x fs a) := by + induction fs generalizing x m with + | nil => simpa [kernels] using hx + | cons f fs ih => + have step := ih (fun i => twiceC (x i) (x (f i))) (4*m) + (fun i => one_axis_bound (hx i) (hx (f i))) + simpa [kernels, Int.pow_succ, Int.mul_assoc] using step + +/-- Compatibility of the local all-prefix proof with a common physical +format when a previous completed phase has a finer input grid. -/ +theorem same_guard (p h m a d : Nat) (had : m+a ≤ d) : + (p+m)+a ≤ p+d ∧ (h+m)+a+2 ≤ h+d+2 ∧ + (p+m)+(h+m)+2*a+3 ≤ p+h+2*d+3 := by omega + +theorem denominator_composition (p : Nat) (bits : List Nat) : + bits.foldl (· + ·) p = p + bits.sum := by + induction bits generalizing p with + | nil => simp + | cons b bs ih => simp [ih, Nat.add_assoc] + +private theorem square_residue (a : Nat) : + a*a%4 = a%2 := by + have ha : a%4=0 ∨ a%4=1 ∨ a%4=2 ∨ a%4=3 := by omega + have mod2 : a%4%2 = a%2 := by omega + rw [Nat.mul_mod, ← mod2] + rcases ha with h|h|h|h <;> rw [h] <;> decide + +/-- Apply to the absolute values of the two reduced numerators of a nonzero +Gaussian-dyadic Clifford entry. A row with 2^r equal-modulus entries has +squared modulus 2^(-r). No ambient factor is charged for completed siblings. -/ +theorem clifford_denominator (a b k r : Nat) + (reduced : a%2=1 ∨ b%2=1) + (flat : (a*a+b*b)*2^r = 2^(2*k)) : + k ≤ (r+1)/2 := by + by_cases h : k ≤ (r+1)/2 + · exact h + have hexp : 2*k = (2+(2*k-r-2))+r := by omega + rw [hexp, Nat.pow_add] at flat + have hs := Nat.eq_of_mul_eq_mul_right (Nat.pow_pos (by decide : 0<2)) flat + rw [Nat.pow_add] at hs + have hzero : (a*a+b*b)%4 = 0 := by + rw [hs] + simp + rw [Nat.add_mod, square_residue, square_residue] at hzero + omega + +#print axioms kernel_numerators +#print axioms same_guard +#print axioms denominator_composition +#print axioms clifford_denominator + +end PhaseBudget diff --git a/research/mixed-rank-uniform-composition/lean/PhysicalFrames.lean b/research/mixed-rank-uniform-composition/lean/PhysicalFrames.lean new file mode 100644 index 0000000000..03d73db4d2 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/PhysicalFrames.lean @@ -0,0 +1,181 @@ +import Std + +namespace PhysicalFrames + +inductive Datum | empty | zero | one deriving DecidableEq, Repr + +inductive Sym + | blank | start | stop | data (x : Datum) (saved : Bool) + deriving DecidableEq, Repr + +structure Tape where + left : List Sym + right : List Sym + deriving DecidableEq, Repr + +def Tape.read (z : Tape) := z.right.headD .blank +def Tape.forward (z : Tape) (s : Sym) : Tape := ⟨s :: z.left, z.right.tail⟩ +def Tape.backward (z : Tape) (s : Sym) : Tape := + ⟨z.left.tail, z.left.headD .blank :: s :: z.right.tail⟩ +def Tape.stay (z : Tape) (s : Sym) : Tape := ⟨z.left, s :: z.right.tail⟩ + +inductive State + | push | seek | init | initData | initTip | leave | clear | parentTip | find + | halted | fault deriving DecidableEq, Repr + +abbrev Config := State × Tape +def tick (c : Config) : Config := + let (q,z) := c + match q, z.read with + | .push, .data a false => (.seek, z.forward (.data a true)) + | .seek, .data a false => (.seek, z.forward (.data a false)) + | .seek, .stop => (.init, z.forward .stop) + | .init, .blank => (.initData, z.forward .start) + | .initData, .blank => (.initTip, z.forward (.data .empty false)) + | .initTip, .blank => (.halted, z.backward .stop) + | .leave, .data a false => (.leave, z.forward (.data a false)) + | .leave, .stop => (.clear, z.backward .blank) + | .clear, .data _ false => (.clear, z.backward .blank) + | .clear, .start => (.parentTip, z.backward .blank) + | .parentTip, .stop => (.find, z.backward .stop) + | .find, .data a false => (.find, z.backward (.data a false)) + | .find, .data a true => (.halted, z.stay (.data a false)) + | .halted, _ => c + | _, _ => (.fault, z) + +def run : Nat → Config → Config + | 0, c => c + | n+1, c => run n (tick c) + +theorem run_add (n k : Nat) (c : Config) : + run (n+k) c = run k (run n c) := by + induction n generalizing c with + | zero => simp [run] + | succ n ih => + rw [Nat.succ_add, run, run, ih] + +def live (a : Datum) : Sym := .data a false + +private theorem walk_right (q : State) + (step : ∀ (a : Datum) (l r : List Sym), + tick (q, ⟨l, live a :: r⟩) = (q, ⟨live a :: l, r⟩)) + (xs : List Datum) (l r : List Sym) : + run xs.length (q, ⟨l, xs.map live ++ r⟩) = + (q, ⟨(xs.map live).reverse ++ l, r⟩) := by + induction xs generalizing l r with + | nil => rfl + | cons x xs ih => + simp only [List.length_cons, List.map_cons, List.cons_append, run, + step, ih, List.reverse_cons, List.append_assoc, List.cons_append, List.nil_append] + +def bwd (vis : List Datum) (endmark : Sym) (l r : List Sym) : Tape := + match vis with + | [] => ⟨l, endmark :: r⟩ + | a :: xs => ⟨xs.map live ++ endmark :: l, live a :: r⟩ + +private theorem walk_left (q : State) (w : Datum → Sym) + (step : ∀ (a : Datum) (l r : List Sym) (k : Sym), + tick (q, ⟨k :: l, live a :: r⟩) = (q, ⟨l, k :: w a :: r⟩)) + (xs : List Datum) (endmark : Sym) (l r : List Sym) : + run xs.length (q, bwd xs endmark l r) = + (q, ⟨l, endmark :: (xs.map w).reverse ++ r⟩) := by + induction xs generalizing l r with + | nil => rfl + | cons a xs ih => + simp only [List.length_cons, run] + have mov : tick (q, bwd (a :: xs) endmark l r) = + (q, bwd xs endmark l (w a :: r)) := by + cases xs <;> simp [bwd, step] + rw [mov, ih] + simp + +/-- Suspend the current head and install a child on three previously +untouched cells. The program never reads the lists l, r as metadata. -/ +theorem push_correct (head : Datum) (suffix : List Datum) (l r : List Sym) : + run (1+suffix.length+4) + (.push, ⟨l, live head :: suffix.map live ++ [.stop,.blank,.blank,.blank] ++ r⟩) = + (.halted, ⟨.start :: .stop :: (suffix.map live).reverse ++ .data head true :: l, + live .empty :: .stop :: r⟩) := by + rw [run_add (1+suffix.length) 4, run_add 1 suffix.length] + simp only [List.append_assoc, List.cons_append, List.nil_append] + change run 4 (run suffix.length + (.seek, ⟨.data head true :: l, suffix.map live ++ (.stop :: .blank :: .blank :: .blank :: r)⟩)) = _ + rw [walk_right .seek (fun _ _ _ => rfl) suffix (.data head true :: l) + (.stop :: .blank :: .blank :: .blank :: r)] + rfl + +/-- Return from an arbitrary data position of a nonempty, dirty child. +The cleanup visits every cell of its old extent, including formerly blank +payloads. The parent original head, both sides of it and the old tail of +the tape are restored. -/ +theorem leave_correct (parent child : Datum) (pTail cLeft cRight : List Datum) + (l r : List Sym) : + let pBack := (pTail.map live).reverse ++ .data parent true :: l + let childWord := cLeft ++ [child] ++ cRight + let childLen := childWord.length + let z : Tape := ⟨(cLeft.map live).reverse ++ .start :: .stop :: pBack, + live child :: cRight.map live ++ .stop :: r⟩ + run ((1+cRight.length) + 1 + childLen + 2 + pTail.length + 1) (.leave, z) = + (.halted, ⟨l, live parent :: pTail.map live ++ .stop :: + List.replicate (childLen+2) .blank ++ r⟩) := by + dsimp only + let x := cLeft ++ [child] ++ cRight + let pb := (pTail.map live).reverse ++ .data parent true :: l + have e₁ : run (1+cRight.length) + (.leave, ⟨(cLeft.map live).reverse ++ .start :: .stop :: pb, + live child :: cRight.map live ++ .stop :: r⟩) = + (.leave, ⟨(x.map live).reverse ++ .start :: .stop :: pb, .stop :: r⟩) := by + rw [run_add 1 cRight.length] + change run cRight.length (.leave, ⟨live child :: (cLeft.map live).reverse ++ + Sym.start :: .stop :: pb, cRight.map live ++ .stop :: r⟩) = _ + rw [walk_right .leave (fun _ _ _ => rfl)] + simp [x, List.append_assoc] + have e₂ : run 1 (.leave, ⟨(x.map live).reverse ++ .start :: .stop :: pb, .stop :: r⟩) = + (.clear, bwd x.reverse .start (.stop :: pb) (.blank :: r)) := by + rw [← List.map_reverse] + cases x.reverse <;> rfl + have e₃ := walk_left .clear (fun _ => Sym.blank) (fun _ _ _ _ => rfl) + x.reverse .start (.stop :: pb) (.blank :: r) + simp only [List.length_reverse, List.map_const', List.length_reverse, + List.reverse_replicate] at e₃ + let erased := List.replicate x.length Sym.blank ++ .blank :: r + have e₄ : run 2 (.clear, ⟨.stop :: pb, .start :: erased⟩) = + (.find, bwd pTail.reverse (.data parent true) l (.stop :: .blank :: erased)) := by + dsimp [pb] + rw [← List.map_reverse] + cases pTail.reverse <;> rfl + have e₅ := walk_left .find live (fun _ _ _ _ => rfl) + pTail.reverse (.data parent true) l (.stop :: .blank :: erased) + simp [List.map_reverse] at e₅ + change run (((((1+cRight.length)+1)+x.length)+2)+pTail.length+1) + (.leave, ⟨(cLeft.map live).reverse ++ .start :: .stop :: pb, + live child :: cRight.map live ++ .stop :: r⟩) = _ + simp only [List.cons_append] at e₃ + rw [run_add (((1+cRight.length+1)+x.length)+2+pTail.length) 1, + run_add (((1+cRight.length+1)+x.length)+2) pTail.length, + run_add ((1+cRight.length+1)+x.length) 2, + run_add (1+cRight.length+1) x.length, run_add (1+cRight.length) 1, e₁, e₂, e₃, e₄, e₅] + have blank_move (n : Nat) : List.replicate n Sym.blank ++ Sym.blank :: r = + Sym.blank :: (List.replicate n Sym.blank ++ r) := by + induction n with + | zero => rfl + | succ n ih => simp [List.replicate_succ, ih] + simp [run, tick, Tape.read, Tape.stay, erased, x, live, List.replicate_succ, + List.append_assoc, blank_move] + +inductive Chain : Nat → List Nat → Prop +| base (v : Nat) : Chain v [] +| next {v c : Nat} {tail : List Nat} (shrink : 2*c ≤ v) (inner : Chain c tail) : + Chain v (c :: tail) + +theorem chain_space {v : Nat} {tail : List Nat} (valid : Chain v tail) : + tail.sum ≤ v := by + induction valid with + | base => simp + | next shrink _ ih => simp only [List.sum_cons]; omega + +#print axioms push_correct +#print axioms leave_correct +#print axioms chain_space + +end PhysicalFrames diff --git a/research/mixed-rank-uniform-composition/lean/PublicGrid.lean b/research/mixed-rank-uniform-composition/lean/PublicGrid.lean new file mode 100644 index 0000000000..cd2fdb68ec --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/PublicGrid.lean @@ -0,0 +1,313 @@ +import Integrated + +/-! The public fixed-point boundary on both signs and on the pointwise product. -/ +namespace MixedRankPublicGrid + +open MixedRankRecovery + +noncomputable def towardZero (x : ℝ) : ℤ := + if 0 ≤ x then ⌊x⌋ else -⌊-x⌋ + +theorem towardZero_int (k : ℤ) : towardZero (k : ℝ) = k := by + unfold towardZero + split + · simp + · rw [← Int.cast_neg, Int.floor_intCast, neg_neg] + +theorem towardZero_division (k : ℤ) {c : ℕ} (hc : 0 < c) : + towardZero ((k : ℝ)/c) = k.tdiv c := by + have hc' : 0 < (c : ℝ) := by exact_mod_cast hc + by_cases hk : 0 ≤ k + · have hr : 0 ≤ (k : ℝ)/c := div_nonneg (by exact_mod_cast hk) hc'.le + simp [towardZero, hr, Int.floor_div_natCast, Int.tdiv_eq_ediv_of_nonneg hk] + · have hr : ¬ 0 ≤ (k : ℝ)/c := not_le.mpr (div_neg_of_neg_of_pos (by exact_mod_cast lt_of_not_ge hk) hc') + simp only [towardZero, hr, ↓reduceIte] + rw [← neg_div, ← Int.cast_neg, Int.floor_div_natCast, Int.floor_intCast, + ← Int.tdiv_eq_ediv_of_nonneg (show 0 ≤ -k by omega), Int.neg_tdiv, neg_neg] + +theorem towardZero_bounds (x : ℝ) : + |(towardZero x : ℝ)| ≤ |x| ∧ |(towardZero x : ℝ) - x| ≤ 1 := by + by_cases hx : 0 ≤ x + · have hf := Int.floor_le x + have hl := Int.lt_floor_add_one x + have hpos : (0 : ℝ) ≤ (⌊x⌋ : ℤ) := by exact_mod_cast Int.floor_nonneg.mpr hx + simp only [towardZero, hx, ↓reduceIte] + rw [abs_of_nonneg hpos, abs_of_nonneg hx, + abs_of_nonpos (sub_nonpos.mpr hf)] + exact ⟨hf, by linarith⟩ + · have hneg : 0 ≤ -x := by linarith + have hf := Int.floor_le (-x) + have hl := Int.lt_floor_add_one (-x) + have hpos : (0 : ℝ) ≤ (⌊-x⌋ : ℤ) := by exact_mod_cast Int.floor_nonneg.mpr hneg + simp only [towardZero, hx, ↓reduceIte] + rw [Int.cast_neg, abs_neg, abs_of_nonneg hpos, + abs_of_nonpos (le_of_not_ge hx), abs_of_nonneg (by linarith : 0 ≤ -(⌊-x⌋ : ℝ) - x)] + exact ⟨hf, by linarith⟩ + +noncomputable def snapReal (D : ℕ) (x : ℝ) : ℝ := + (towardZero ((D : ℝ) * x) : ℝ) / D + +noncomputable def snap (D : ℕ) (z : ℂ) : ℂ := + ⟨snapReal D z.re, snapReal D z.im⟩ + +theorem snap_finer_word {D c : ℕ} (hD : 0 < D) (hc : 0 < c) (k : ℤ) : + snapReal D ((k : ℝ)/((D:ℝ)*c)) = (k.tdiv c : ℝ)/D := by + have hd : (D : ℝ) ≠ 0 := by exact_mod_cast hD.ne' + have hc' : (c : ℝ) ≠ 0 := by exact_mod_cast hc.ne' + rw [snapReal, show (D:ℝ)*((k:ℝ)/((D:ℝ)*c)) = (k:ℝ)/c by field_simp, + towardZero_division k hc] + +def Represented (D : ℕ) (z : ℂ) : Prop := + ∃ a b : ℤ, z.re = (a : ℝ)/D ∧ z.im = (b : ℝ)/D + +theorem snap_represented (D : ℕ) (z : ℂ) : Represented D (snap D z) := + ⟨_, _, rfl, rfl⟩ + +theorem snapReal_word {D : ℕ} (hD : 0 < D) (k : ℤ) : + snapReal D ((k : ℝ)/D) = (k : ℝ)/D := by + have h : (D : ℝ) ≠ 0 := by exact_mod_cast hD.ne' + rw [snapReal, show (D : ℝ) * ((k : ℝ) / D) = k by field_simp, towardZero_int] + +theorem snap_word {D : ℕ} (hD : 0 < D) {z : ℂ} (hz : Represented D z) : + snap D z = z := by + obtain ⟨a, b, ha, hb⟩ := hz + apply Complex.ext + · change snapReal D z.re = z.re + rw [ha, snapReal_word hD] + · change snapReal D z.im = z.im + rw [hb, snapReal_word hD] + +theorem snapReal_bounds {D : ℕ} (hD : 0 < D) (x : ℝ) : + |snapReal D x| ≤ |x| ∧ |snapReal D x - x| ≤ 1 / (D : ℝ) := by + have hd : 0 < (D : ℝ) := by exact_mod_cast hD + obtain ⟨hs, ht⟩ := towardZero_bounds ((D : ℝ)*x) + rw [abs_mul, abs_of_pos hd] at hs + constructor + · rw [snapReal, abs_div, abs_of_pos hd, div_le_iff₀ hd] + simpa [mul_comm] using hs + · have hx : snapReal D x - x = ((towardZero ((D : ℝ) * x) : ℝ) - D*x) / D := by + unfold snapReal + field_simp + rw [hx, abs_div, abs_of_pos hd] + exact div_le_div_of_nonneg_right ht hd.le + +theorem snap_radius {D : ℕ} (hD : 0 < D) (z : ℂ) : ‖snap D z‖ ≤ ‖z‖ := by + rw [Complex.norm_def, Complex.norm_def] + apply Real.sqrt_le_sqrt + have hr := sq_le_sq.mpr (snapReal_bounds hD z.re).1 + have hi := sq_le_sq.mpr (snapReal_bounds hD z.im).1 + simpa [Complex.normSq_apply, snap, pow_two] using add_le_add hr hi + +theorem snap_error {D : ℕ} (hD : 0 < D) (z : ℂ) : + ‖snap D z - z‖ ≤ (10/7 : ℝ) / D := by + have hd : 0 < (D : ℝ) := by exact_mod_cast hD + have hinv : 0 ≤ 1 / (D : ℝ) := by positivity + have hr := sq_le_sq.mpr ((snapReal_bounds hD z.re).2.trans_eq (abs_of_nonneg hinv).symm) + have hi := sq_le_sq.mpr ((snapReal_bounds hD z.im).2.trans_eq (abs_of_nonneg hinv).symm) + rw [Complex.norm_def, Real.sqrt_le_iff] + refine ⟨by positivity, ?_⟩ + calc + Complex.normSq (snap D z - z) ≤ (1 / (D : ℝ))^2 + (1 / (D : ℝ))^2 := by + simpa [Complex.normSq_apply, snap, pow_two] using add_le_add hr hi + _ ≤ ((10/7 : ℝ) / D)^2 := by + field_simp + norm_num + +abbrev GridSignal (S D : ℕ) := {x : Signal S // ∀ k, Represented D (x k)} + +noncomputable def enter {S : ℕ} (D : ℕ) (x : Signal S) : GridSignal S D := + ⟨fun k ↦ snap D (x k), fun k ↦ snap_represented D (x k)⟩ + +theorem enter_word {S D : ℕ} (hD : 0 < D) (x : GridSignal S D) : + enter D x.val = x := by + apply Subtype.ext + funext k + exact snap_word hD (x.property k) + +theorem enter_disk {S D : ℕ} (hD : 0 < D) {x : Signal S} {r : ℝ} (hx : disk x r) : + disk (enter D x).val r := + fun k ↦ (snap_radius hD _).trans (hx k) + +noncomputable def run {S D : ℕ} (raw : GridSignal S D → Signal S) (x : Signal S) : + Signal S := fun k ↦ snap D (raw (enter D x) k) + +noncomputable def roundedMul (D : ℕ) (x y : ℂ) : ℂ := + snap D (snap D x * snap D y) + +theorem run_on_words {S D : ℕ} (hD : 0 < D) (raw : GridSignal S D → Signal S) + (x : GridSignal S D) (k : ZMod S) : run raw x.val k = snap D (raw x k) := by + rw [run, enter_word hD] + +theorem roundedMul_words {D : ℕ} (hD : 0 < D) {x y : ℂ} + (hx : Represented D x) (hy : Represented D y) : + roundedMul D x y = snap D (x * y) := by + rw [roundedMul, snap_word hD hx, snap_word hD hy] + +theorem residual_room {D : ℕ} (hD : 2 ≤ D) : + 1 / (D : ℝ)^4 ≤ (1/7 : ℝ) / D := by + have h : (2 : ℝ) ≤ D := by exact_mod_cast hD + have hd : 0 < (D : ℝ) := by linarith + have hh : (2:ℝ)^3 ≤ (D : ℝ)^3 := by gcongr + have hh' : (7:ℝ) ≤ (D:ℝ)^3 := by norm_num at hh; linarith + calc + 1 / (D:ℝ)^4 = (1 / (D:ℝ)^3) / D := by field_simp + _ ≤ (1/7 : ℝ) / D := by gcongr + +variable {S : ℕ} [NeZero S] + +theorem forward_error (u : (ZMod S)ˣ) (x y : Signal S) (e : ℝ) + (h : ∀ j, ‖x j - y j‖ ≤ e) (k : ZMod S) : + ‖forward u x k - forward u y k‖ ≤ e := by + have he : forward u x k - forward u y k = forward u (x-y) k := by + simp [forward, mul_sub] + rw [he] + exact forward_bound u (x-y) e h k + +def RawAccuracy (D : ℕ) (ideal : Signal S → Signal S) + (raw : GridSignal S D → Signal S) : Prop := + ∀ x : GridSignal S D, disk x.val (1/2) → + ∀ k, ‖raw x k - ideal x.val k‖ ≤ 1 / (D : ℝ)^4 + +omit [NeZero S] in +theorem run_accuracy {D : ℕ} (hD : 2 ≤ D) (ideal : Signal S → Signal S) + (nonexp : ∀ x y e, (∀ j, ‖x j - y j‖ ≤ e) → ∀ k, ‖ideal x k - ideal y k‖ ≤ e) + (raw : GridSignal S D → Signal S) (hraw : RawAccuracy D ideal raw) + (x : Signal S) (hx : disk x (1/2)) (k : ZMod S) : + ‖run raw x k - ideal x k‖ ≤ 3 / (D : ℝ) := by + have hpos : 0 < D := by omega + let y := enter D x + have hy : disk y.val (1/2) := enter_disk hpos hx + have h1 := hraw y hy k + have h2 := nonexp y.val x ((10/7 : ℝ)/D) (fun j ↦ snap_error hpos (x j)) k + have h3 := snap_error hpos (raw y k) + have hr := residual_room hD + have a := dist_triangle (run raw x k) (raw y k) (ideal y.val k) + have b := dist_triangle (run raw x k) (ideal y.val k) (ideal x k) + simp only [dist_eq_norm] at a b + change ‖run raw x k - raw y k‖ ≤ _ at h3 + have hsum : (10/7 : ℝ)/D + (1/7 : ℝ)/D + (10/7 : ℝ)/D = 3/D := by ring + linarith only [a, b, h1, h2, h3, hr, hsum] + +theorem roundedMul_accuracy {D : ℕ} (hD : 0 < D) (x y : ℂ) + (hx : ‖x‖ ≤ 1/2) (hy : ‖y‖ ≤ 1/2) : + ‖roundedMul D x y - x*y‖ ≤ 3/(D : ℝ) := by + let a := snap D x + let b := snap D y + have ht := dist_triangle (roundedMul D x y) (a*b) (x*y) + simp only [dist_eq_norm] at ht + have hi : a*b - x*y = (a-x)*b + x*(b-y) := by ring + have h1 := norm_add_le ((a-x)*b) (x*(b-y)) + rw [← hi] at h1 + simp only [norm_mul] at h1 + have hr : 0 ≤ (10/7 : ℝ)/D := by positivity + have h2 := mul_le_mul (snap_error hD x) ((snap_radius hD y).trans hy) (norm_nonneg _) hr + have h3 := mul_le_mul hx (snap_error hD y) (norm_nonneg _) (by norm_num : (0:ℝ) ≤ 1/2) + have h4 : ‖roundedMul D x y - a*b‖ ≤ (10/7 : ℝ)/D := snap_error hD _ + change ‖a-x‖ * ‖b‖ ≤ _ at h2 + change ‖x‖ * ‖b-y‖ ≤ _ at h3 + have hsum : (10/7 : ℝ)/D + ((10/7 : ℝ)/D)*(1/2) + (1/2)*((10/7 : ℝ)/D) ≤ 3/D := by + calc + _ = (20/7 : ℝ)/D := by ring + _ ≤ 3/D := div_le_div_of_nonneg_right (by norm_num) (by positivity) + linarith only [ht, h1, h2, h3, h4, hsum] + +theorem dyadic_denominator (b : ℕ) : ((2 : ℕ)^b)^6 = 2^(6*b) := by + rw [← pow_mul, Nat.mul_comm b 6] + +theorem dyadic_even {b : ℕ} (hb : 0 < b) : Even ((2 : ℕ)^b) := by + cases b with + | zero => omega + | succ b => exact ⟨2^b, by rw [pow_succ]; omega⟩ + +theorem radix_input_divides {B : ℕ} (hB : Even B) : 4*B ∣ B^6 := by + obtain ⟨k, hk⟩ := hB + refine ⟨8*k^5, ?_⟩ + rw [hk] + ring + +omit [NeZero S] in +theorem digit_words {D K : ℕ} (hD : 0 < D) (hK : 0 < K) (hdiv : D ∣ K) + (a : ZMod S → ℕ) (j : ZMod S) : Represented K (digitInput D a j) := by + obtain ⟨c, rfl⟩ := hdiv + have hdn : (D:ℝ) ≠ 0 := by exact_mod_cast hD.ne' + have hc : c ≠ 0 := by intro h; simp [h] at hK + have hcn : (c:ℝ) ≠ 0 := by exact_mod_cast hc + have he : digitInput D a j = Complex.ofReal ((a j:ℝ) / (D:ℝ)) := by + simp [digitInput, div_eq_inv_mul] + rw [he] + refine ⟨((a j*c : ℕ):ℤ), 0, ?_, ?_⟩ + · rw [Complex.ofReal_re] + push_cast + field_simp + · simp + +omit [NeZero S] in +theorem radix_digit_words {B : ℕ} (hB : 0 < B) (hEven : Even B) + (a : ZMod S → ℕ) (j : ZMod S) : Represented (B^6) (digitInput (4*B) a j) := + digit_words (by positivity) (by positivity) (radix_input_divides hEven) a j + +noncomputable def radixWords {B : ℕ} (hB : 0 < B) (hEven : Even B) + (a : ZMod S → ℕ) : GridSignal S (B^6) := + ⟨digitInput (4*B) a, radix_digit_words hB hEven a⟩ + +noncomputable def wordPacket {D : ℕ} (fw : GridSignal S D → Signal S) + (x y : GridSignal S D) : GridSignal S D := + ⟨fun k ↦ snap D (snap D (fw x k) * snap D (fw y k)), fun _ ↦ snap_represented D _⟩ + +omit [NeZero S] in +theorem packet_on_words {D : ℕ} (hD : 0 < D) (fw : GridSignal S D → Signal S) + (x y : GridSignal S D) : + packet (run fw) (roundedMul D) x.val y.val = (wordPacket fw x y).val := by + funext k + change roundedMul D (run fw x.val k) (run fw y.val k) = _ + rw [run_on_words hD, run_on_words hD, roundedMul_words hD (snap_represented _ _) (snap_represented _ _)] + rfl + +noncomputable def wordDecode {B : ℕ} (hB : 0 < B) (hEven : Even B) + (fw bw : GridSignal S (B^6) → Signal S) (a b : ZMod S → ℕ) (k : ZMod S) : ℕ := + let z := wordPacket fw (radixWords hB hEven a) (radixWords hB hEven b) + (round ((((S : ℂ) * ((4*B : ℕ):ℂ))^2 * snap (B^6) (bw z k)).re)).toNat + +omit [NeZero S] in +theorem decode_on_words {B : ℕ} (hB : 0 < B) (hEven : Even B) + (fw bw : GridSignal S (B^6) → Signal S) (a b : ZMod S → ℕ) : + decode B (run fw) (run bw) (roundedMul (B^6)) a b = wordDecode hB hEven fw bw a b := by + have hD : 0 < B^6 := by positivity + let x := radixWords hB hEven a + let y := radixWords hB hEven b + funext k + change (round ((((S : ℂ) * ((4*B : ℕ):ℂ))^2 * + run bw (packet (run fw) (roundedMul (B^6)) x.val y.val) k).re)).toNat = _ + rw [packet_on_words hD, run_on_words hD] + rfl + +theorem grid_product_at_physical_coordinates {d : ℕ} (s t : Fin d → ℕ) + (hs : Pairwise fun i j ↦ Nat.Coprime (s i) (s j)) + (ht : ∀ i, Nat.Coprime (t i) (s i)) [∀ i, NeZero (s i)] [NeZero (∏ i, s i)] + (B : ℕ) (hB : 32 ≤ B) (hEven : Even B) (hsize : ∏ i, s i ≤ B) + (fw bw : GridSignal (∏ i, s i) (B^6) → MixedRankIntegrated.SourceSignal s) + (hfw : RawAccuracy (B^6) (forward (MixedRankIntegrated.sourceUnit s t hs ht)) fw) + (hbw : RawAccuracy (B^6) (opposite (MixedRankIntegrated.sourceUnit s t hs ht)) bw) + (a b : ZMod (∏ i, s i) → ℕ) (ha : ∀ j, a j ≤ B) (hb : ∀ j, b j ≤ B) + (hspan : ∀ i j, a i ≠ 0 → b j ≠ 0 → i.val + j.val < ∏ i, s i) : + pack B (carry B 0 (ordered (wordDecode (by omega : 0 < B) hEven fw bw a b))) = + radixValue B a * radixValue B b := by + rw [← decode_on_words] + have low : 2 ≤ B^6 := by calc + 2 ≤ 32^6 := by decide + _ ≤ B^6 := by gcongr + refine MixedRankIntegrated.product_at_physical_coordinates s t hs ht B hB hsize + (run fw) (run bw) (roundedMul (B^6)) (3 / ((B^6:ℕ):ℝ)) (by positivity) (by simp) + (run_accuracy low _ (forward_error _) fw hfw) + (run_accuracy low _ (opposite_error _) bw hbw) + (roundedMul_accuracy (by omega)) a b ha hb hspan + +#print axioms snap_radius +#print axioms snap_error +#print axioms snap_finer_word +#print axioms run_accuracy +#print axioms roundedMul_accuracy +#print axioms radix_digit_words +#print axioms grid_product_at_physical_coordinates + +end MixedRankPublicGrid diff --git a/research/mixed-rank-uniform-composition/lean/RankMoments.lean b/research/mixed-rank-uniform-composition/lean/RankMoments.lean new file mode 100644 index 0000000000..c1f7a0ed9b --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/RankMoments.lean @@ -0,0 +1,226 @@ +import DyadicRoot + +/-! Dyadic enclosures for the complete pinned BIT and complex rank histograms. +Generated by generate_moments.py. Root certificates use integer arithmetic. -/ +namespace RankMoments + +open DyadicRoot + +structure Row where + power : Claim + paid : Nat + target : Nat + +set_option maxRecDepth 65536 +set_option maxHeartbeats 40000000 + +def bits : Nat := 352 +def frac : Nat := 160 +def grid : Nat := 2^frac + +def bitMain : List Row := [ + ⟨⟨1, 249030017988463, 250000000000000, 1461501637330902918203684832716283019655932542974, 1461501637330902918203684832716283019655932542979⟩, 49980, 288⟩, + ⟨⟨2, 249030017988463, 250000000000000, 2915152824188523749825804055252332302314056475678, 2915152824188523749825804055252332302314056475683⟩, 46116, 324⟩, + ⟨⟨3, 249030017988463, 250000000000000, 4365855574177860630494645375313588340881443216172, 4365855574177860630494645375313588340881443216177⟩, 1944, 0⟩, + ⟨⟨4, 249030017988463, 250000000000000, 5814646916095272513586027121615486698302011023171, 5814646916095272513586027121615486698302011023176⟩, 1584, 1548⟩, + ⟨⟨5, 249030017988463, 250000000000000, 7262018605442310967744423352625882616115465481238, 7262018605442310967744423352625882616115465481243⟩, 612, 288⟩, + ⟨⟨6, 249030017988463, 250000000000000, 8708259971782851121204390088149987013900137450514, 8708259971782851121204390088149987013900137450519⟩, 3672, 36⟩, + ⟨⟨7, 249030017988463, 250000000000000, 10153562037415877480947636148190928480370704804767, 10153562037415877480947636148190928480370704804772⟩, 444, 0⟩, + ⟨⟨8, 249030017988463, 250000000000000, 11598060478447751272511251750400648231904168904030, 11598060478447751272511251750400648231904168904035⟩, 0, 14448⟩, + ⟨⟨14, 249030017988463, 250000000000000, 20252584255055909498951234477269343906755881901959, 20252584255055909498951234477269343906755881901964⟩, 444, 0⟩, + ⟨⟨15, 249030017988463, 250000000000000, 21693389592265808293436717547380384451855368618425, 21693389592265808293436717547380384451855368618430⟩, 0, 444⟩, + ⟨⟨21, 249030017988463, 250000000000000, 30331122652568173075476960151393263834592655293294, 30331122652568173075476960151393263834592655293299⟩, 444, 0⟩, + ⟨⟨22, 249030017988463, 250000000000000, 31769727053898122409824256457651591457720168795000, 31769727053898122409824256457651591457720168795005⟩, 0, 444⟩, + ⟨⟨28, 249030017988463, 250000000000000, 40396381830994133432117409818577887004665647819681, 40396381830994133432117409818577887004665647819686⟩, 444, 0⟩, + ⟨⟨29, 249030017988463, 250000000000000, 41833413671372038733573024115249229822797023374215, 41833413671372038733573024115249229822797023374220⟩, 0, 444⟩, + ⟨⟨35, 249030017988463, 250000000000000, 50451778187458985110305101357202542644440630506228, 50451778187458985110305101357202542644440630506233⟩, 444, 0⟩, + ⟨⟨36, 249030017988463, 250000000000000, 51887585890528639494069827910059682398340263229416, 51887585890528639494069827910059682398340263229421⟩, 0, 444⟩, + ⟨⟨42, 249030017988463, 250000000000000, 60499321795438546909360428984621294291540029787324, 60499321795438546909360428984621294291540029787329⟩, 444, 0⟩, + ⟨⟨43, 249030017988463, 250000000000000, 61934127202547089191875667945421735884668975916319, 61934127202547089191875667945421735884668975916324⟩, 0, 444⟩, + ⟨⟨49, 249030017988463, 250000000000000, 70540339753523560848970043314675416040189687122194, 70540339753523560848970043314675416040189687122199⟩, 444, 0⟩, + ⟨⟨50, 249030017988463, 250000000000000, 71974296593995306781579462381243965664157277932487, 71974296593995306781579462381243965664157277932492⟩, 0, 444⟩, + ⟨⟨56, 249030017988463, 250000000000000, 80575774650985052037755894366427027423372104616860, 80575774650985052037755894366427027423372104616865⟩, 444, 0⟩, + ⟨⟨57, 249030017988463, 250000000000000, 82008995765585703669957541387111262758666777256160, 82008995765585703669957541387111262758666777256165⟩, 0, 444⟩, + ⟨⟨64, 249030017988463, 250000000000000, 92038902609368572125567582610974745871540699336715, 92038902609368572125567582610974745871540699336720⟩, 0, 444⟩, + ⟨⟨127, 249030017988463, 250000000000000, 182154716205709830792506870789110373845033609950988, 182154716205709830792506870789110373845033609950993⟩, 0, 222⟩] + +def bitLow : List Row := [ + ⟨⟨1, 304030017988463, 250000000000000, 1461501637330902918203684832716283019655932542974, 1461501637330902918203684832716283019655932542979⟩, 49980, 0⟩, + ⟨⟨2, 304030017988463, 250000000000000, 3395376404020747154823349485189285358070488057822, 3395376404020747154823349485189285358070488057827⟩, 46116, 0⟩, + ⟨⟨3, 304030017988463, 250000000000000, 5559503920896228438372746811316015622667272619987, 5559503920896228438372746811316015622667272619992⟩, 1944, 0⟩, + ⟨⟨4, 304030017988463, 250000000000000, 7888175168955106571095829904873253994456087164197, 7888175168955106571095829904873253994456087164202⟩, 1584, 0⟩, + ⟨⟨5, 304030017988463, 250000000000000, 10347388569520255210252427799705690377712400505072, 10347388569520255210252427799705690377712400505077⟩, 612, 0⟩, + ⟨⟨6, 304030017988463, 250000000000000, 12915899612364219054155793206737543310768665354187, 12915899612364219054155793206737543310768665354192⟩, 3672, 0⟩, + ⟨⟨7, 304030017988463, 250000000000000, 15579014999961396508556754937450690457213811389097, 15579014999961396508556754937450690457213811389102⟩, 444, 0⟩, + ⟨⟨14, 304030017988463, 250000000000000, 36193336071355851876273151017654412987269643423421, 36193336071355851876273151017654412987269643423426⟩, 444, 0⟩, + ⟨⟨21, 304030017988463, 250000000000000, 59262058121373525393921753862126200564075602730543, 59262058121373525393921753862126200564075602730548⟩, 444, 0⟩, + ⟨⟨28, 304030017988463, 250000000000000, 84084749644143395141054929017177870290931716356143, 84084749644143395141054929017177870290931716356148⟩, 444, 0⟩, + ⟨⟨35, 304030017988463, 250000000000000, 110298967594305132582234722615588243659158502258804, 110298967594305132582234722615588243659158502258809⟩, 444, 0⟩, + ⟨⟨42, 304030017988463, 250000000000000, 137678254104794833857135214336721195345199171931054, 137678254104794833857135214336721195345199171931059⟩, 444, 0⟩, + ⟨⟨49, 304030017988463, 250000000000000, 166065984580262548377515852566887389463971531211419, 166065984580262548377515852566887389463971531211424⟩, 444, 0⟩, + ⟨⟨56, 304030017988463, 250000000000000, 195346599406563401727300113722883167197246304850641, 195346599406563401727300113722883167197246304850646⟩, 444, 0⟩] + +def bitHigh : List Row := [ + ⟨⟨1, 314030017988463, 250000000000000, 1461501637330902918203684832716283019655932542974, 1461501637330902918203684832716283019655932542979⟩, 49980, 0⟩, + ⟨⟨2, 314030017988463, 250000000000000, 3490833427675484886026884843525774712967559581578, 3490833427675484886026884843525774712967559581583⟩, 46116, 0⟩, + ⟨⟨3, 314030017988463, 250000000000000, 5809261027225502276332102500255665298655270738545, 5809261027225502276332102500255665298655270738550⟩, 1944, 0⟩, + ⟨⟨4, 314030017988463, 250000000000000, 8337943460693862326236463550904980886473020116789, 8337943460693862326236463550904980886473020116794⟩, 1584, 0⟩, + ⟨⟨5, 314030017988463, 250000000000000, 11035437574458025018469968710514624509446435532958, 11035437574458025018469968710514624509446435532963⟩, 612, 0⟩, + ⟨⟨6, 314030017988463, 250000000000000, 13875566106765669753063461475553373869250537784889, 13875566106765669753063461475553373869250537784894⟩, 3672, 0⟩, + ⟨⟨7, 314030017988463, 250000000000000, 16840070955657330776321907685860374324384047399288, 16840070955657330776321907685860374324384047399293⟩, 444, 0⟩, + ⟨⟨14, 314030017988463, 250000000000000, 40222933122260863052922772418042128311650716998910, 40222933122260863052922772418042128311650716998915⟩, 444, 0⟩, + ⟨⟨21, 314030017988463, 250000000000000, 66936885597386874771039238445048894200949868557219, 66936885597386874771039238445048894200949868557224⟩, 444, 0⟩, + ⟨⟨28, 314030017988463, 250000000000000, 96073487648479920607767200302801233846614542219393, 96073487648479920607767200302801233846614542219398⟩, 444, 0⟩, + ⟨⟨35, 314030017988463, 250000000000000, 127155212853534517614792541903278090235548698802073, 127155212853534517614792541903278090235548698802078⟩, 444, 0⟩, + ⟨⟨42, 314030017988463, 250000000000000, 159880435176647645641278523382529250087420991435991, 159880435176647645641278523382529250087420991435996⟩, 444, 0⟩, + ⟨⟨49, 314030017988463, 250000000000000, 194038776658151364364779751343598714300863091324017, 194038776658151364364779751343598714300863091324022⟩, 444, 0⟩, + ⟨⟨56, 314030017988463, 250000000000000, 229473942163465345702342452574043376464324825052713, 229473942163465345702342452574043376464324825052718⟩, 444, 0⟩] + +def bitDrop : List Row := [ + ⟨⟨1, 164030017988463, 250000000000000, 1461501637330902918203684832716283019655932542974, 1461501637330902918203684832716283019655932542979⟩, 0, 288⟩, + ⟨⟨2, 164030017988463, 250000000000000, 2303091161504130168439587795163886693168851653025, 2303091161504130168439587795163886693168851653030⟩, 0, 324⟩, + ⟨⟨4, 164030017988463, 250000000000000, 3629300688219138274107252520222253724704119284800, 3629300688219138274107252520222253724704119284805⟩, 0, 1548⟩, + ⟨⟨5, 164030017988463, 250000000000000, 4201530840814043985651818414042515707620417597660, 4201530840814043985651818414042515707620417597665⟩, 0, 288⟩, + ⟨⟨6, 164030017988463, 250000000000000, 4735435882081094275564147350755226144362466768435, 4735435882081094275564147350755226144362466768440⟩, 0, 36⟩, + ⟨⟨8, 164030017988463, 250000000000000, 5719193276268534492592486498083507038112996475015, 5719193276268534492592486498083507038112996475020⟩, 0, 14448⟩, + ⟨⟨15, 164030017988463, 250000000000000, 8638859041197138533681160920162990988218549063764, 8638859041197138533681160920162990988218549063769⟩, 0, 444⟩, + ⟨⟨22, 164030017988463, 250000000000000, 11106820985502410080387054674684023059225605526728, 11106820985502410080387054674684023059225605526733⟩, 0, 444⟩, + ⟨⟨29, 164030017988463, 250000000000000, 13313982624697806148515428212431551919292230084405, 13313982624697806148515428212431551919292230084410⟩, 0, 444⟩, + ⟨⟨36, 164030017988463, 250000000000000, 15343364947749276569845354695620021807726290099366, 15343364947749276569845354695620021807726290099371⟩, 0, 444⟩, + ⟨⟨43, 164030017988463, 250000000000000, 17240535330709759220477657341840785034127208875778, 17240535330709759220477657341840785034127208875783⟩, 0, 444⟩, + ⟨⟨50, 164030017988463, 250000000000000, 19033893182130216627447827854045117170670119330124, 19033893182130216627447827854045117170670119330129⟩, 0, 444⟩, + ⟨⟨57, 164030017988463, 250000000000000, 20742640615657003756115565527288078205343672523748, 20742640615657003756115565527288078205343672523753⟩, 0, 444⟩, + ⟨⟨64, 164030017988463, 250000000000000, 22380523494349964227705903752907565510346007903564, 22380523494349964227705903752907565510346007903569⟩, 0, 444⟩, + ⟨⟨127, 164030017988463, 250000000000000, 35087074177672963095263750957412740780312687525678, 35087074177672963095263750957412740780312687525683⟩, 0, 222⟩] + +def complexMain : List Row := [ + ⟨⟨1, 99612007196437, 100000000000000, 1461501637330902918203684832716283019655932542974, 1461501637330902918203684832716283019655932542979⟩, 184800, 960⟩, + ⟨⟨2, 99612007196437, 100000000000000, 2915152824209776735755549495747499707137668276588, 2915152824209776735755549495747499707137668276593⟩, 37920, 336⟩, + ⟨⟨3, 99612007196437, 100000000000000, 4365855574228308982517045619028170820884880460351, 4365855574228308982517045619028170820884880460356⟩, 23472, 480⟩, + ⟨⟨4, 99612007196437, 100000000000000, 5814646916180056136639518986608048492107203654113, 5814646916180056136639518986608048492107203654118⟩, 11040, 11616⟩, + ⟨⟨5, 99612007196437, 100000000000000, 7262018605565242912246830097710206804437616338374, 7262018605565242912246830097710206804437616338379⟩, 15072, 1536⟩, + ⟨⟨6, 99612007196437, 100000000000000, 8708259971946964603418591819774446198599681146715, 8708259971946964603418591819774446198599681146720⟩, 1920, 0⟩, + ⟨⟨7, 99612007196437, 100000000000000, 10153562037623691277384819043097366198209296426490, 10153562037623691277384819043097366198209296426495⟩, 144, 672⟩, + ⟨⟨8, 99612007196437, 100000000000000, 11598060478701419019310631552220697441436124278597, 11598060478701419019310631552220697441436124278602⟩, 1296, 1536⟩, + ⟨⟨9, 99612007196437, 100000000000000, 13041856682302716523687720692940393300591502311172, 13041856682302716523687720692940393300591502311177⟩, 0, 26016⟩, + ⟨⟨16, 99612007196437, 100000000000000, 23133822019925104989581511854320164977027997701912, 23133822019925104989581511854320164977027997701917⟩, 1248, 0⟩, + ⟨⟨17, 99612007196437, 100000000000000, 24573904962778951107707306571098632296674817787105, 24573904962778951107707306571098632296674817787110⟩, 0, 1248⟩, + ⟨⟨24, 99612007196437, 100000000000000, 34646185606503782501347831532030120574433670560564, 34646185606503782501347831532030120574433670560569⟩, 1248, 0⟩, + ⟨⟨25, 99612007196437, 100000000000000, 36084060996255616257773974817794973598699510268602, 36084060996255616257773974817794973598699510268607⟩, 0, 1248⟩, + ⟨⟨32, 99612007196437, 100000000000000, 46143380803398999124170092163265188442577878743085, 46143380803398999124170092163265188442577878743090⟩, 1248, 0⟩, + ⟨⟨33, 99612007196437, 100000000000000, 47579680489677594770168874380075508276822780607887, 47579680489677594770168874380075508276822780607892⟩, 0, 1248⟩, + ⟨⟨40, 99612007196437, 100000000000000, 57629310042114530845735958317098261885400604096773, 57629310042114530845735958317098261885400604096778⟩, 1248, 0⟩, + ⟨⟨41, 99612007196437, 100000000000000, 59064383825731103001413915017559712984463443155917, 59064383825731103001413915017559712984463443155922⟩, 0, 1248⟩, + ⟨⟨48, 99612007196437, 100000000000000, 69106269359606712401606040650290995185019772562370, 69106269359606712401606040650290995185019772562375⟩, 1248, 0⟩, + ⟨⟨49, 99612007196437, 100000000000000, 70540339756411070818826754086771711378434130607650, 70540339756411070818826754086771711378434130607655⟩, 0, 1248⟩, + ⟨⟨56, 99612007196437, 100000000000000, 80575774654396521485379327450017947899080071326532, 80575774654396521485379327450017947899080071326537⟩, 1248, 0⟩, + ⟨⟨57, 99612007196437, 100000000000000, 82008995769073120898560002389435448512740802422290, 82008995769073120898560002389435448512740802422295⟩, 0, 1248⟩, + ⟨⟨65, 99612007196437, 100000000000000, 93471387514324672139552798792007635630364431557128, 93471387514324672139552798792007635630364431557133⟩, 0, 1248⟩, + ⟨⟨129, 99612007196437, 100000000000000, 185012077705720177414075708289631337416139397496082, 185012077705720177414075708289631337416139397496087⟩, 0, 624⟩] + +def complexTilt : List Row := [ + ⟨⟨1, 797284050375059, 700000000000000, 1461501637330902918203684832716283019655932542974, 1461501637330902918203684832716283019655932542979⟩, 184800, 0⟩, + ⟨⟨2, 797284050375059, 700000000000000, 3218589663966612945105421635444589921838352127537, 3218589663966612945105421635444589921838352127542⟩, 37920, 0⟩, + ⟨⟨3, 797284050375059, 700000000000000, 5107748960343969173661363731868890351327593348892, 5107748960343969173661363731868890351327593348897⟩, 23472, 0⟩, + ⟨⟨4, 797284050375059, 700000000000000, 7088133985201434444981784695165457577394072974782, 7088133985201434444981784695165457577394072974787⟩, 11040, 0⟩, + ⟨⟨5, 797284050375059, 700000000000000, 9139242794645280052624390809539768208551892398233, 9139242794645280052624390809539768208551892398238⟩, 15072, 0⟩, + ⟨⟨6, 797284050375059, 700000000000000, 11248532050858825203640529100302802750543166218760, 11248532050858825203640529100302802750543166218765⟩, 1920, 0⟩, + ⟨⟨7, 797284050375059, 700000000000000, 13407466425866091118668065480272237521741234663286, 13407466425866091118668065480272237521741234663291⟩, 144, 0⟩, + ⟨⟨8, 797284050375059, 700000000000000, 15609831832445956431113297508631134544932893339015, 15609831832445956431113297508631134544932893339020⟩, 1296, 0⟩, + ⟨⟨16, 797284050375059, 700000000000000, 34376727407519290707472434418770800472646798659072, 34376727407519290707472434418770800472646798659077⟩, 1248, 0⟩, + ⟨⟨24, 797284050375059, 700000000000000, 54554233999306751336116539571759973893406404287091, 54554233999306751336116539571759973893406404287096⟩, 1248, 0⟩, + ⟨⟨32, 797284050375059, 700000000000000, 75706093437504647846220715693250667480738252676769, 75706093437504647846220715693250667480738252676774⟩, 1248, 0⟩, + ⟨⟨40, 797284050375059, 700000000000000, 97613331012646481028965011530758977645442349157102, 97613331012646481028965011530758977645442349157107⟩, 1248, 0⟩, + ⟨⟨48, 797284050375059, 700000000000000, 120141975342877674498877749191577872824227014465381, 120141975342877674498877749191577872824227014465386⟩, 1248, 0⟩, + ⟨⟨56, 797284050375059, 700000000000000, 143200863318327805355599598986694337887174314034914, 143200863318327805355599598986694337887174314034919⟩, 1248, 0⟩] + +def lowCut : Claim := ⟨10, 11, 50, 2425488982512924493014879543340159618052184678638, 2425488982512924493014879543340159618052184678643⟩ + +def highCut : Claim := ⟨11, 13, 50, 2726223169118157683569082859190315987564460060854, 2726223169118157683569082859190315987564460060859⟩ + +def floorCost : Claim := ⟨16, 17, 50, 3751458101362136341527504761035997125100712438316, 3751458101362136341527504761035997125100712438321⟩ + +def complexCut : Claim := ⟨11, 1, 7, 2058589199190980830650682003974609807383732971288, 2058589199190980830650682003974609807383732971293⟩ + +def complexCost : Claim := ⟨11, 387992803563, 100000000000000, 1475162402281397758280503096807531758032739501864, 1475162402281397758280503096807531758032739501869⟩ + +def scalarRows : List Claim := [lowCut, highCut, floorCost, complexCut, complexCost] + +theorem bitMain_ok : (bitMain.map Row.power).all (valid bits frac) = true := by decide +kernel + +theorem bitLow_ok : (bitLow.map Row.power).all (valid bits frac) = true := by decide +kernel + +theorem bitHigh_ok : (bitHigh.map Row.power).all (valid bits frac) = true := by decide +kernel + +theorem bitDrop_ok : (bitDrop.map Row.power).all (valid bits frac) = true := by decide +kernel + +theorem complexMain_ok : (complexMain.map Row.power).all (valid bits frac) = true := by decide +kernel + +theorem complexTilt_ok : (complexTilt.map Row.power).all (valid bits frac) = true := by decide +kernel + +theorem scalars_ok : scalarRows.all (valid bits frac) = true := by decide +kernel + + +def tables : List (List Row) := [bitMain, bitLow, bitHigh, bitDrop, complexMain, complexTilt] +def claims : List Claim := tables.flatMap (fun xs => xs.map Row.power) ++ scalarRows + +theorem table_sound (c : Claim) (hc : c ∈ claims) : + 0 < c.den ∧ c.lo^c.den ≤ c.rank^c.num * 2^(frac*c.den) ∧ + c.rank^c.num * 2^(frac*c.den) ≤ c.hi^c.den := by + apply valid_sound bits + apply List.all_eq_true.mp _ c hc + simp only [claims, tables, List.flatMap_cons, List.flatMap_nil, List.all_append, + List.all_nil, Bool.and_true, bitMain_ok, bitLow_ok, bitHigh_ok, bitDrop_ok, + complexMain_ok, complexTilt_ok, scalars_ok] + +def upperPaid (xs : List Row) (select : Nat → Bool := fun _ => true) : Nat := + (xs.map (fun row => if select row.power.rank then row.paid * row.power.hi else 0)).sum + +def lowerTarget (xs : List Row) : Nat := (xs.map (fun row => row.target * row.power.lo)).sum +def upperTarget (xs : List Row) : Nat := (xs.map (fun row => row.target * row.power.hi)).sum +def targetCount (xs : List Row) : Nat := (xs.map Row.target).sum + +def ratioBelow (x y num den : Nat) : Prop := 0 < y ∧ x*den < num*y +instance (x y num den : Nat) : Decidable (ratioBelow x y num den) := + inferInstanceAs (Decidable (0 < y ∧ x*den < num*y)) + +theorem bit_alpha : ratioBelow (upperPaid bitMain) (lowerTarget bitMain) 249999999999998000563 250000000000000000000 := by decide +kernel + +theorem bit_first_low : ratioBelow (upperPaid bitLow (fun r => r ≤ 4) * grid) (lowCut.lo * lowerTarget bitMain) 720828660325258853331 2000000000000000000000 := by decide +kernel + +theorem bit_rest_low : ratioBelow (upperPaid bitLow * grid) (lowCut.lo * lowerTarget bitMain) 9460180868969874332523 10000000000000000000000 := by decide +kernel + +theorem bit_first_high : ratioBelow (upperPaid bitHigh (fun r => 4 < r) * grid) (highCut.lo * lowerTarget bitMain) 5969937509690282459981 10000000000000000000000 := by decide +kernel + +theorem bit_rest_high : ratioBelow (upperPaid bitHigh * grid) (highCut.lo * lowerTarget bitMain) 9247497622443579677377 10000000000000000000000 := by decide +kernel + +theorem bit_discard : ratioBelow (floorCost.hi * upperTarget bitDrop) (grid * lowerTarget bitMain) 1178602023822729540311 1250000000000000000000 := by decide +kernel + +theorem complex_alpha : ratioBelow (upperPaid complexMain) (lowerTarget complexMain) 999999999999999999999999999 1000000000000000000000000000 := by decide +kernel + +theorem complex_gamma : ratioBelow (upperPaid complexTilt * grid) (complexCut.lo * lowerTarget complexMain) 31 32 := by decide +kernel + +theorem complex_delta : ratioBelow (12 * targetCount complexMain * grid^2) (complexCost.lo * lowerTarget complexMain) 31 32 := by decide +kernel + + +end RankMoments + +#print axioms RankMoments.table_sound + +#print axioms RankMoments.bit_alpha + +#print axioms RankMoments.bit_first_low + +#print axioms RankMoments.bit_rest_low + +#print axioms RankMoments.bit_first_high + +#print axioms RankMoments.bit_rest_high + +#print axioms RankMoments.bit_discard + +#print axioms RankMoments.complex_alpha + +#print axioms RankMoments.complex_gamma + +#print axioms RankMoments.complex_delta diff --git a/research/mixed-rank-uniform-composition/lean/RankOneBridge.lean b/research/mixed-rank-uniform-composition/lean/RankOneBridge.lean new file mode 100644 index 0000000000..3d5d1a8ad6 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/RankOneBridge.lean @@ -0,0 +1,217 @@ +import Mathlib.Algebra.Module.LinearMap.End +import Mathlib.Tactic.Abel +import Mathlib.Tactic.LinearCombination +import Mathlib.Tactic.Ring + +namespace RankOneBridge + +variable {R X Y : Type*} [CommRing R] [AddCommGroup X] [Module R X] + [AddCommGroup Y] [Module R Y] + +/-- Cross-bank additions. The head is read only. -/ +def shear (K : X →ₗ[R] Y) (v : X × Y) : X × Y := (v.1, v.2 + K v.1) + +/-- The rank-one residual after the head and tail elimination. -/ +def residual (e : X) (b : Y) (a : X →ₗ[R] R) (Z : Y →ₗ[R] R) + (d : R) (v : X × Y) : X × Y := + let t := a v.1 + d * Z v.2 + (v.1 + t • e, v.2 + t • b) + +/-- Replace one head and one tail coordinate. Keep their complements. -/ +def exchange (e : X) (z : Y) (E : X →ₗ[R] R) (Z : Y →ₗ[R] R) + (d i : R) (v : X × Y) : X × Y := + (v.1 + (d * Z v.2 - E v.1) • e, v.2 + (i * E v.1 - Z v.2) • z) + +/-- The cross-bank coefficients in the good branch of the leaf program. -/ +def lower (e : X) (b z : Y) (E a : X →ₗ[R] R) (i : R) : X →ₗ[R] Y := + E.smulRight (-(b + i • z)) + (a - a e • E).smulRight (i • z) + +theorem lower_at (e : X) (b z : Y) (E a : X →ₗ[R] R) (i : R) + (he : E e = 1) : lower e b z E a i e = -(b + i • z) := by + simp [lower, he] + +theorem lower_row (e : X) (b z : Y) (E a : X →ₗ[R] R) (Z : Y →ₗ[R] R) + (d i : R) (hi : d * i = 1) (hz : Z z = 1) (hc : a e + d * Z b = -2) (x : X) : + d * Z (lower e b z E a i x) = a x + E x := by + simp only [lower, LinearMap.add_apply, LinearMap.smulRight_apply, LinearMap.sub_apply, + LinearMap.smul_apply, map_add, map_smul, map_neg, hz, smul_eq_mul, mul_one] + calc + _ = (d*i) * a x - E x * (d * Z b + d*i + (d*i) * a e) := by ring + _ = _ := by rw [hi]; linear_combination -(E x) * hc + +theorem shear_undo (K : X →ₗ[R] Y) (v : X × Y) : + shear (-K) (shear K v) = v := by + obtain ⟨x,y⟩ := v + simp [shear] + +theorem conjugated (e : X) (b z : Y) (E a : X →ₗ[R] R) (Z : Y →ₗ[R] R) + (d i : R) (hi : d * i = 1) (he : E e = 1) (hz : Z z = 1) + (hc : a e + d * Z b = -2) (v : X × Y) : + let K := lower e b z E a i + shear K (residual e b a Z d (shear (-K) v)) = exchange e z E Z d i v := by + let K := lower e b z E a i + change shear K (residual e b a Z d (shear (-K) v)) = exchange e z E Z d i v + obtain ⟨x,y⟩ := v + have hk : K e = -(b + i • z) := lower_at _ _ _ _ _ _ he + have hr : d * Z (K x) = a x + E x := lower_row _ _ _ _ _ _ _ _ hi hz hc x + have ht : a x + d * Z (y - K x) = d * Z y - E x := by + rw [map_sub, mul_sub, hr] + ring + apply Prod.ext + · simp only [shear, residual, exchange, LinearMap.neg_apply, ← sub_eq_add_neg, ht] + · simp only [shear, residual, exchange, LinearMap.neg_apply, map_add, + map_smul, ← sub_eq_add_neg, ht, hk] + have hm : (d * Z y - E x) * i = Z y - i * E x := by + calc _ = (d*i) * Z y - i * E x := by ring + _ = _ := by rw [hi, one_mul] + simp only [smul_neg, smul_add, smul_smul, hm, sub_smul] + abel + +/-- The program executes the lower shears, one weighted exchange, then their inverse. -/ +theorem good_leaf (e : X) (b z : Y) (E a : X →ₗ[R] R) (Z : Y →ₗ[R] R) + (d i : R) (hi : d * i = 1) (he : E e = 1) (hz : Z z = 1) + (hc : a e + d * Z b = -2) (v : X × Y) : + let K := lower e b z E a i + shear (-K) (exchange e z E Z d i (shear K v)) = residual e b a Z d v := by + let K := lower e b z E a i + change shear (-K) (exchange e z E Z d i (shear K v)) = _ + rw [← conjugated e b z E a Z d i hi he hz hc (shear K v)] + change shear (-K) (shear K (residual e b a Z d (shear (-K) (shear K v)))) = _ + rw [shear_undo, shear_undo] + +def rowAdd (f : X →ₗ[R] R) (v : X) : X →ₗ[R] X := LinearMap.id + f.smulRight v + +theorem rowAdd_apply (f : X →ₗ[R] R) (v x : X) : rowAdd f v x = x + f x • v := rfl + +theorem rowAdd_undo (f : X →ₗ[R] R) (v x : X) (hz : f v = 0) : + rowAdd f (-v) (rowAdd f v x) = x := by + simp [rowAdd_apply, hz] + +/-- A single rank-one displacement before the first local elimination. -/ +def displaced (s : X) (t : Y) (α : X →ₗ[R] R) (β : Y →ₗ[R] R) + (v : X × Y) : X × Y := + let t₀ := α v.1 + β v.2 + (v.1 + t₀ • s, v.2 + t₀ • t) + +/-- The first head-to-head and tail-to-tail elimination, all cross-bank + additions, one exchange and the inverse additions on both banks. -/ +def program (e s : X) (z t : Y) (E α : X →ₗ[R] R) (Z β : Y →ₗ[R] R) + (l li r ri : R) (v : X × Y) : X × Y := + let vH := e - li • s + let fT := ri • β - Z + let H := rowAdd E vH + let H' := rowAdd E (-vH) + let T := rowAdd fT z + let T' := rowAdd fT (-z) + let b := li • T t + let a := l • (α.comp H') + let K := lower e b z E a (li*ri) + let out := shear (-K) (exchange e z E Z (l*r) (li*ri) (shear K (H v.1,T v.2))) + (H' out.1, T' out.2) + +theorem normalized_word (e s : X) (z t : Y) (E α : X →ₗ[R] R) (Z β : Y →ₗ[R] R) + (l li r ri : R) (hl : l * li = 1) (hr : r * ri = 1) + (he : E e = 1) (hz : Z z = 1) (hs : E s = l) (hb : β z = r) + (hc : α s + β t = -2) (v : X × Y) : + program e s z t E α Z β l li r ri v = displaced s t α β v := by + let vH := e - li • s + let fT := ri • β - Z + let H := rowAdd E vH + let H' := rowAdd E (-vH) + let T := rowAdd fT z + let T' := rowAdd fT (-z) + let b := li • T t + let a := l • (α.comp H') + let K := lower e b z E a (li*ri) + let v' := (H v.1,T v.2) + let out := shear (-K) (exchange e z E Z (l*r) (li*ri) (shear K v')) + change (H' out.1,T' out.2) = _ + have hl' : li * l = 1 := by rw [mul_comm, hl] + have hr' : ri * r = 1 := by rw [mul_comm, hr] + have hH : E vH = 0 := by simp [vH, he, hs, hl'] + have hT : fT z = 0 := by simp [fT, hz, hb, hr'] + have hHi (x : X) : H' (H x) = x := rowAdd_undo _ _ _ hH + have hTi (y : Y) : T' (T y) = y := rowAdd_undo _ _ _ hT + have hHe : H' e = li • s := by simp [H', rowAdd_apply, he, vH] + have hHs : H s = l • e := by + simp [H,rowAdd_apply,hs,vH,smul_sub,smul_smul,hl] + have hZ (y : Y) : Z (T y) = ri * β y := by + simp [T,rowAdd_apply, hz,fT] + have hA (x : X) : a (H x) = l * α x := by simp [a,hHi] + have hAe : a e = α s := by simp [a,hHe,← mul_assoc,hl] + have hZb : (l*r) * Z b = β t := by + change (l*r) * Z (li • T t) = β t + simp only [map_smul, smul_eq_mul, hZ] + calc _ = (l*li) * (r*ri) * β t := by ring + _ = _ := by rw [hl,hr,one_mul,one_mul] + have hd : (l*r) * (li*ri) = 1 := by + calc _ = (l*li) * (r*ri) := by ring + _ = _ := by rw [hl,hr,one_mul] + have h₁ : out = residual e b a Z (l*r) v' := by + exact good_leaf e b z E a Z _ _ hd he hz (by rw [hAe,hZb,hc]) v' + let t₀ := α v.1 + β v.2 + have hφ : a (H v.1) + (l*r) * Z (T v.2) = l * t₀ := by + rw [hA,hZ] + change l * α v.1 + (l*r) * (ri * β v.2) = l * (α v.1 + β v.2) + calc _ = l * α v.1 + l * (r*ri) * β v.2 := by ring + _ = _ := by rw [hr,mul_one,mul_add] + have hout : out = (H (v.1 + t₀ • s),T (v.2 + t₀ • t)) := by + rw [h₁] + simp only [residual,v',b,hφ,map_add,map_smul,hHs,smul_smul] + have hh : l * t₀ * li = t₀ := by + calc _ = (l*li) * t₀ := by ring + _ = _ := by rw [hl,one_mul] + rw [hh,mul_comm l t₀] + rw [hout,hHi,hTi] + rfl + +def partialExchange (P : X →ₗ[R] X) (v : X × X) : X × X := + let δ := P (v.2 - v.1) + (v.1 + δ, v.2 - δ) + +def weighted (P : X →ₗ[R] X) (A : X ≃ₗ[R] X) (C : X ≃ₗ[R] Y) + (v : X × Y) : X × Y := + let w := partialExchange P (A.symm v.1,C.symm v.2) + (A w.1,C w.2) + +/-- The entire good branch acts on an arbitrary split rank-one projector, + invertible head weights and physical tail placement. -/ +theorem whole_good (u e : X) (z : Y) (V E : X →ₗ[R] R) (Z : Y →ₗ[R] R) + (A : X ≃ₗ[R] X) (C : X ≃ₗ[R] Y) + (l li r ri : R) (hl : l * li = 1) (hr : r * ri = 1) + (hu : V u = 1) (he : E e = 1) (hz : Z z = 1) + (hs : E (A u) = l) (hb : V (C.symm z) = r) (v : X × Y) : + program e (A u) z (-(C u)) E (-(V.comp A.symm.toLinearMap)) Z + (V.comp C.symm.toLinearMap) l li r ri v = weighted (V.smulRight u) A C v := by + rw [normalized_word _ _ _ _ _ _ _ _ _ _ _ _ hl hr he hz hs hb (by simp [hu]; ring)] + apply Prod.ext <;> + simp only [weighted,partialExchange,displaced,LinearMap.smulRight_apply, + LinearMap.neg_apply,LinearMap.comp_apply,LinearEquiv.coe_coe,map_add,map_smul, + LinearEquiv.apply_symm_apply,smul_neg,sub_eq_add_neg,map_neg,add_smul,neg_smul] <;> + abel + +/-- One inverse of the actual weighted pivot gives both elementary reductions. -/ +theorem covered_good (u e : X) (z : Y) (V E : X →ₗ[R] R) (Z : Y →ₗ[R] R) + (A : X ≃ₗ[R] X) (C : X ≃ₗ[R] Y) (di : R) + (hu : V u = 1) (he : E e = 1) (hz : Z z = 1) + (hd : E (A u) * V (C.symm z) * di = 1) (v : X × Y) : + let l := E (A u) + let r := V (C.symm z) + program e (A u) z (-(C u)) E (-(V.comp A.symm.toLinearMap)) Z + (V.comp C.symm.toLinearMap) l (r*di) r (l*di) v = weighted (V.smulRight u) A C v := by + apply whole_good + · rwa [← mul_assoc] + · calc _ = E (A u) * V (C.symm z) * di := by ring + _ = 1 := hd + · exact hu + · exact he + · exact hz + · rfl + · rfl + +end RankOneBridge + +#print axioms RankOneBridge.good_leaf +#print axioms RankOneBridge.normalized_word +#print axioms RankOneBridge.whole_good +#print axioms RankOneBridge.covered_good diff --git a/research/mixed-rank-uniform-composition/lean/RationalInverse.lean b/research/mixed-rank-uniform-composition/lean/RationalInverse.lean new file mode 100644 index 0000000000..9516d63b8c --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/RationalInverse.lean @@ -0,0 +1,487 @@ +import HaloRadius + +namespace RationalInverse + +/-- A finite row sum in physical coordinate order. -/ +def isum (f : Fin n → Int) : Int := (List.ofFn f).sum + +@[simp] theorem sumEmpty (f : Fin 0 → Int) : isum f = 0 := by simp [isum] +theorem sumStep (f : Fin (n+1) → Int) : isum f = f 0 + isum (fun j => f j.succ) := by simp [isum, List.ofFn_succ] + +theorem sumAdd (f g : Fin n → Int) : isum (fun i => f i+g i) = isum f + isum g := by + induction n with + | zero => simp + | succ n ih => simpa only [sumStep, ih] using (show (f 0 + g 0) + (isum (fun i : Fin n => f i.succ) + isum (fun i : Fin n => g i.succ)) = (f 0 + isum (fun i : Fin n => f i.succ)) + (g 0 + isum (fun i : Fin n => g i.succ)) by omega) + +theorem sumScale (c : Int) (f : Fin n → Int) : isum (fun i => c*f i) = c*isum f := by + induction n with + | zero => simp + | succ n ih => rw [sumStep, sumStep f, Int.mul_add, ← ih] + +theorem sumSub (f g : Fin n → Int) : isum (fun i => f i-g i) = isum f - isum g := by + induction n with + | zero => simp + | succ n ih => rw [sumStep, sumStep f, sumStep g, ih]; omega + +theorem sumLe {f g : Fin n → Int} (h : ∀ i, f i ≤ g i) : isum f ≤ isum g := by + induction n with + | zero => simp + | succ n ih => rw [sumStep f, sumStep g]; exact Int.add_le_add (h _) (ih (fun i => h i.succ)) + +@[simp] theorem sumZero {n} : isum (fun _ : Fin n => 0) = 0 := by + induction n with + | zero => simp + | succ n ih => rw [sumStep, ih]; simp + +@[simp] theorem firstNeLater (i : Fin n) : (0 : Fin (n+1)) ≠ i.succ := Ne.symm (Fin.succ_ne_zero i) + +@[simp] theorem sumSingle (i : Fin n) (x : Int) : isum (fun j => if j=i then x else 0) = x := by + induction n with + | zero => exact Fin.elim0 i + | succ n ih => + cases i using Fin.cases with + | zero => simp [sumStep, Fin.succ_ne_zero] + | succ i => simpa [sumStep, Fin.succ_inj] using ih i + +def amag (v : Int) : Int := (v.natAbs : Int) +@[simp] theorem magNonneg (v : Int) : 0 ≤ amag v := by simp [amag] +@[simp] theorem magZero : amag 0=0 := rfl +@[simp] theorem magMul (a b : Int) : amag (a*b) = amag a*amag b := by simp [amag, Int.natAbs_mul] +@[simp] theorem magNeg (a : Int) : amag (-a)=amag a := by simp [amag] +theorem magSub (a b : Int) : amag (a-b) ≤ amag a+amag b := by simpa [amag] using (Int.ofNat_le.mpr (Int.natAbs_sub_le a b)) +theorem magPos (a : Int) (h : 0 ≤ a) : amag a=a := Int.natAbs_of_nonneg h +theorem leMag (a : Int) : a ≤ amag a := Int.le_natAbs + +abbrev Matrix (n : Nat) := Fin n → Fin n → Int + +def offDiag (row : Fin n → Int) (i : Fin n) : Int := isum (fun j => if j=i then 0 else amag (row j)) +def norm1 (row : Fin n → Int) : Int := isum (fun j => amag (row j)) +def Dominant (A : Matrix n) : Prop := ∀ i, offDiag (A i) i < A i i + +theorem offNonneg (f : Fin n → Int) (i : Fin n) : 0 ≤ offDiag f i := by + change 0 ≤ isum _ + rw [← @sumZero n] + apply sumLe + intro j + split <;> simp + +theorem offSplit (f : Fin n → Int) (i : Fin n) : offDiag f i + amag (f i) = norm1 f := by + unfold offDiag norm1 + rw [← sumSingle i (amag (f i)), ← sumAdd] + congr 1; funext j; split <;> simp_all + +@[simp] theorem offFirst (f : Fin (n+1) → Int) : offDiag f 0 = norm1 (fun j => f j.succ) := by simp [offDiag, norm1, sumStep, Fin.succ_ne_zero] +@[simp] theorem offLater (f : Fin (n+1) → Int) (i : Fin n) : offDiag f i.succ = amag (f 0) + offDiag (fun j => f j.succ) i := by simp [offDiag, sumStep, Fin.succ_inj] + +def schur (A : Matrix (n+1)) : Matrix n := fun i j => A 0 0 * A i.succ j.succ - A i.succ 0 * A 0 j.succ + +theorem schurOff (A : Matrix (n+1)) (hA : Dominant A) (i : Fin n) : + offDiag (schur A i) i ≤ A 0 0 * offDiag (fun j => A i.succ j.succ) i + amag (A i.succ 0) * offDiag (fun j => A 0 j.succ) i := by + have hpos : 0 ≤ A 0 0 := Int.le_trans (offNonneg _ _) (Int.le_of_lt (hA 0)) + unfold offDiag + rw [← sumScale, ← sumScale, ← sumAdd] + apply sumLe; intro j; by_cases hj : j=i + · simp [hj] + · simp only [hj, ↓reduceIte, schur] + simpa only [magMul, magPos _ hpos] using magSub (A 0 0 * A i.succ j.succ) (A i.succ 0 * A 0 j.succ) + +theorem schurDominant (A : Matrix (n+1)) (ha : Dominant A) : Dominant (schur A) := by + intro i + have hp : 0 < A 0 0 := Int.lt_of_le_of_lt (offNonneg _ _) (ha 0) + have h0 := ha 0 + rw [offFirst] at h0 + have hi := ha i.succ + rw [offLater] at hi + have hscale := Int.mul_lt_mul_of_pos_left hi hp + have hsplit := offSplit (fun j : Fin n => A 0 j.succ) i + have hcol := Int.mul_le_mul_of_nonneg_left (Int.le_of_lt h0) (magNonneg (A i.succ 0)) + have hcross := leMag (A i.succ 0 * A 0 i.succ) + rw [magMul] at hcross + have hoff := schurOff A ha i + change offDiag (schur A i) i < A 0 0 * A i.succ i.succ - A i.succ 0 * A 0 i.succ + rw [← hsplit, Int.mul_add] at hcol + rw [Int.mul_add] at hscale + grind + + +/-- Evaluate the dense row after collecting equal physical addresses. -/ +def act (A : Matrix n) (x : Fin n → Int) (i : Fin n) : Int := isum (fun j => A i j*x j) + +theorem schurAct (A : Matrix (n+1)) (y : Fin n → Int) (i : Fin n) : + act (schur A) y i = A 0 0 * isum (fun j => A i.succ j.succ*y j) - A i.succ 0 * isum (fun j => A 0 j.succ*y j) := by + unfold act schur + rw [← sumScale, ← sumScale, ← sumSub] + congr 1; funext j; grind + +theorem tailScaled (p : Int) (row x : Fin n → Int) : isum (fun j => row j*(p*x j)) = p*isum (fun j => row j*x j) := by + rw [← sumScale]; congr 1; funext j; grind + +/-- Fraction-free elimination produces a positive common denominator and an exact +solution for every integer right hand side. The pivot need not be a unit. -/ +theorem solve (A : Matrix n) (ha : Dominant A) (rhs : Fin n → Int) : + ∃ S : Int, 0 < S ∧ ∃ y : Fin n → Int, ∀ i, act A y i = S * rhs i := by + induction n with + | zero => exact ⟨1, by decide, Fin.elim0, fun i => i.elim0⟩ + | succ n ih => + have hp : 0 < A 0 0 := Int.lt_of_le_of_lt (offNonneg _ _) (ha 0) + obtain ⟨s, hs, y, hy⟩ := ih (schur A) (schurDominant A ha) (fun i => A 0 0 * rhs i.succ - A i.succ 0 * rhs 0) + let w := s*rhs 0 - isum (fun j => A 0 j.succ*y j) + let z : Fin (n+1) → Int := Fin.cases w (fun j => A 0 0*y j) + refine ⟨A 0 0*s, Int.mul_pos hp hs, z, ?_⟩ + intro i; cases i using Fin.cases with + | zero => + simp only [act, sumStep, z, Fin.cases_zero, Fin.cases_succ, tailScaled, w] + grind + | succ i => + have h := hy i + rw [schurAct] at h + simp only [act, sumStep, z, Fin.cases_zero, Fin.cases_succ, tailScaled, w] + grind + +#print axioms schurDominant +#print axioms solve + + +open HaloRadius + +/-- Physical rows can contain repeated signed period indices. Collect their +signed coefficients, while retaining their original absolute mass bound. -/ +def entry : Row (Fin n) → Fin n → Int + | [], _ => 0 + | (c,k)::r, j => (if j=k then c else 0) + entry r j + +def scalarDot (f : Fin n → Int) : Row (Fin n) → Int + | [] => 0 + | (c,j)::r => c*f j + scalarDot f r + +theorem physicalSum (row : Row (Fin n)) (f : Fin n → Int) : + isum (fun j => entry row j * f j) = scalarDot f row := by + induction row with + | nil => simp [entry, scalarDot] + | cons term row ih => + obtain ⟨c,k⟩ := term + simp only [entry, scalarDot, Int.add_mul, sumAdd, ih] + congr 1 + rw [← sumSingle k (c*f k)] + congr 1; funext j; by_cases h : j=k <;> simp [h] + +theorem eachPhysicalComponent (row : Row (Fin n)) (f : Fin n → Datum) : + (dot f row).re = scalarDot (fun j => (f j).re) row ∧ (dot f row).im = scalarDot (fun j => (f j).im) row := by + induction row with + | nil => simp [dot, scalarDot] + | cons term row ih => + obtain ⟨c,k⟩ := term + simp [dot, plus, times, scalarDot, ih] + +theorem entryNorm (row : Row (Fin n)) : norm1 (entry row) ≤ (mass row : Int) := by + induction row with + | nil => simp [entry, norm1, mass] + | cons term row ih => + obtain ⟨c,k⟩ := term + have hdis : norm1 (entry ((c,k)::row)) ≤ amag c + norm1 (entry row) := by + unfold norm1 + rw [← sumSingle k (amag c), ← sumAdd] + apply sumLe; intro j; by_cases hj : j=k + · subst j + simpa [entry, amag] using Int.ofNat_le.mpr (Int.natAbs_add_le c (entry row k)) + · simp [entry, hj] + unfold mass at * + simp only [List.map_cons, List.sum_cons, Int.natCast_add] + exact Int.le_trans hdis (Int.add_le_add_left ih _) + +def physicalMatrix (a : Axis (Fin n)) : Matrix n := fun i j => (if j=i then (a.D : Int) else 0) - entry (a.rows i) j + +theorem perRowMass (a : Axis (Fin n)) (ha : Admitted a) (i : Fin n) : mass (a.rows i) < a.D := by + have hp := ha.1 + have hg := ha.2 i + have hd : 0 < a.D := Nat.pos_of_mul_pos_left hp + by_cases h : mass (a.rows i) < a.D + · exact h + · have hmul := Nat.mul_le_mul_left a.a (Nat.le_of_not_gt h) + omega + +theorem physicalDominant (a : Axis (Fin n)) (ha : Admitted a) : Dominant (physicalMatrix a) := by + intro i + have he : offDiag (physicalMatrix a i) i = offDiag (entry (a.rows i)) i := by + unfold offDiag; congr 1; funext j; by_cases h : j=i <;> simp [h, physicalMatrix] + rw [he] + have hmass := entryNorm (a.rows i) + have hdiag := offSplit (entry (a.rows i)) i + have hpos := Int.ofNat_lt.mpr (perRowMass a ha i) + have he := leMag (entry (a.rows i) i) + simp only [physicalMatrix, ↓reduceIte] + omega + +theorem physicalAction (a : Axis (Fin n)) (f : Fin n → Int) (i : Fin n) : + act (physicalMatrix a) f i = a.D*f i - scalarDot f (a.rows i) := by + simp only [act, physicalMatrix, Int.sub_mul, sumSub, physicalSum] + congr 1; rw [← sumSingle i (a.D*f i)]; congr 1; funext j; by_cases h : j=i <;> simp [h] + +theorem scaledPhysicalDot (f : Fin n → Int) (c : Int) (row : Row (Fin n)) : + scalarDot (fun j => c*f j) row = c*scalarDot f row := by + induction row with + | nil => simp [scalarDot] + | cons term row ih => obtain ⟨w,j⟩ := term; simp only [scalarDot, ih]; grind + +/-- Every admitted, finite physical row system has an exact rational normalized +inverse on every complex integer input. No mathematical inverse is an input. -/ +theorem inverseExists (a : Axis (Fin n)) (ha : Admitted a) (x : Fin n → Datum) : + ∃ s : Nat, 0 < s ∧ ∃ y : Fin n → Datum, Fixed a x y s := by + have hm := physicalDominant a ha + obtain ⟨r, hr, u, hu⟩ := solve (physicalMatrix a) hm (fun i => (a.D : Int)*(x i).re) + obtain ⟨s, hs, v, hv⟩ := solve (physicalMatrix a) hm (fun i => (a.D : Int)*(x i).im) + let y : Fin n → Datum := fun j => ⟨s*u j, r*v j⟩ + have hnat : 0 < a.a * r.toNat*s.toNat := Nat.mul_pos (Nat.mul_pos (Nat.pos_of_mul_pos_right ha.1) (by omega)) (by omega) + refine ⟨a.a*r.toNat*s.toNat, hnat, y, ?_⟩ + intro i + have h1 := hu i; have h2 := hv i + rw [physicalAction] at h1 h2 + obtain ⟨er, ei⟩ := eachPhysicalComponent (a.rows i) y + simp only [y, scaledPhysicalDot] at er ei + simp only [y, times, plus, Datum.mk.injEq, Int.natCast_mul, Int.toNat_of_nonneg (Int.le_of_lt hr), Int.toNat_of_nonneg (Int.le_of_lt hs)] + change _ = _ + _*(dot y (a.rows i)).re ∧ _ = _ + _*(dot y (a.rows i)).im + rw [er, ei]; constructor <;> grind + +#print axioms inverseExists + + +/-- A finite nonempty field attains its largest component radius. -/ +theorem attainment (f : Fin (n+1) → Nat) : ∃ k, ∀ j, f j ≤ f k := by + induction n with + | zero => + refine ⟨0, ?_⟩; intro j + have h : j=0 := Fin.ext (by have := j.isLt; change j.val=0; omega) + rw [h]; exact Nat.le_refl _ + | succ n ih => + obtain ⟨k, hk⟩ := ih (fun j => f j.succ) + by_cases h : f 0 ≤ f k.succ + · refine ⟨k.succ, ?_⟩; intro j; cases j using Fin.cases with + | zero => exact h + | succ j => exact hk j + · refine ⟨0, ?_⟩; intro j; cases j using Fin.cases with + | zero => exact Nat.le_refl _ + | succ j => exact Nat.le_trans (hk j) (Nat.le_of_lt (Nat.lt_of_not_ge h)) + +/-- Normalization makes the exact normalized inverse a contraction in the +same component-l1 radius as the actual rounded iteration. -/ +theorem inverseContraction (a : Axis (Fin n)) (ha : Admitted a) (x y : Fin n → Datum) (s R : Nat) + (hf : Fixed a x y s) (hx : ∀ i, radius (x i) ≤ R) : ∀ i, radius (y i) ≤ s*R := by + cases n with + | zero => exact fun i => i.elim0 + | succ n => + obtain ⟨k, hk⟩ := attainment (fun j => radius (y j)) + let M := radius (y k) + have hright : (a.a*a.D)*M ≤ (a.D*s)*R + a.a*(mass (a.rows k)*M) := by + calc + _ = radius (times (a.a*a.D : Nat) (y k)) := by simp [M, timesRadius, Int.natAbs_mul] + _ ≤ radius (times (a.D*s : Nat) (x k)) + radius (times a.a (dot y (a.rows k))) := by rw [hf]; exact plusBound .. + _ ≤ _ := by simp only [timesRadius, Int.natAbs_natCast]; exact Nat.add_le_add (Nat.mul_le_mul_left _ (hx k)) (Nat.mul_le_mul_left _ (dotBound y M hk _)) + have hleft := Nat.mul_le_mul_right M (ha.2 k) + have hboth := Nat.le_trans hleft hright + rw [Nat.add_mul, Nat.mul_assoc a.a] at hboth + have hbound : M ≤ s*R := Nat.le_of_mul_le_mul_left (c:=a.D) (hc:=Nat.pos_of_mul_pos_left ha.1) (by simpa [Nat.mul_assoc] using Nat.le_of_add_le_add_right hboth) + exact fun i => Nat.le_trans (hk i) hbound + +private theorem scaleInput (a : Axis (Fin n)) (x y : Fin n → Datum) (s c : Nat) (hf : Fixed a x y s) : + Fixed a (fun i => times (c*s : Nat) (x i)) (fun i => times c (y i)) 1 := by + intro i; rw [scaleDot] + have h := hf i + have xp := congrArg Datum.re h; have xq := congrArg Datum.im h + simp only [times, plus, Int.natCast_mul] at xp xq + simp only [times, plus, Datum.mk.injEq, Nat.mul_one, Int.natCast_mul] + constructor <;> grind + +/-- For a fixed family radius R and P-grid tail tolerance t, this condition +only asks about the generated grid, row mass and the specified iteration count. -/ +def Ready (B t R : Nat) (a : Axis (Fin n)) : Prop := Admitted a ∧ + (∀ i, a.D+B*mass (a.rows i) ≤ B*a.D) ∧ + ∃ m, (∀ i, mass (a.rows i) ≤ m) ∧ R*(a.a*m)^a.J ≤ t*den a a.J + +/-- Construct a common positive denominator for every exact intermediate +and final field. Its size does not enter the tape algorithm or the error. -/ +theorem trajectory (axes : List (Axis (Fin n))) (B t R S : Nat) (x : Fin n → Datum) + (ready : ∀ a ∈ axes, Ready B t R a) (bound : ∀ i, radius (x i) ≤ S*R) : + ∃ c : Nat, 0 < c ∧ ∃ y : Fin n → Datum, + InverseChain B (c*S) t axes (fun i => times c (x i)) y ∧ ∀ i, radius (y i) ≤ (c*S)*R := by + induction axes generalizing S x with + | nil => + refine ⟨1, by decide, (fun i => times (1 : Nat) (x i)), .nil _, ?_⟩ + intro i; simpa [timesRadius] using bound i + | cons a tail ih => + obtain ⟨ha, hg, m, hm, ht⟩ := ready a (by simp) + obtain ⟨s, hs, y, hf⟩ := inverseExists a ha x + have hy : ∀ i, radius (y i) ≤ (s*S)*R := fun i => by simpa [Nat.mul_assoc] using inverseContraction a ha x y s (S*R) hf bound i + obtain ⟨c, hc, z, hz, hzb⟩ := ih (s*S) y (fun b hb => ready b (by simp [hb])) hy + refine ⟨c*s, Nat.mul_pos hc hs, z, ?_, ?_⟩ + · apply InverseChain.cons a tail _ (fun i => times c (y i)) _ (((c*s)*S)*R) m ha hg hm (scaleInput a x y s c hf) + · intro i; rw [timesRadius, Int.natAbs_natCast]; simpa [Nat.mul_assoc] using Nat.mul_le_mul_left c (hy i) + · have hscl := Nat.mul_le_mul_left ((c*s)*S) ht + simpa [Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm] using hscl + · simpa only [Nat.mul_assoc] using hz + · simpa only [Nat.mul_assoc] using hzb + +/-- Unconditional on existence of inverse values: every admitted finite +physical band list has its unique normalized rational inverse output, and the +literal P-grid evaluation meets the accumulated radius bound on any input. -/ +theorem physicalInverseError (axes : List (Axis (Fin n))) (B t R : Nat) (x : Fin n → Datum) + (ready : ∀ a ∈ axes, Ready B t R a) (bound : ∀ i, radius (x i) ≤ R) : + ∃ S : Nat, 0 < S ∧ ∃ y : Fin n → Datum, + InverseChain B S t axes (fun i => times S (x i)) y ∧ + Close S ((2*B+t)*axes.length) (sweep x axes) y := by + obtain ⟨s, hs, y, h, _⟩ := trajectory axes B t R 1 x ready (by simpa using bound) + rw [Nat.mul_one] at h + refine ⟨s, hs, y, h, ?_⟩ + have hc : Close s 0 x (fun i => times s (x i)) := by intro i; simp [minus, radius] + simpa using completeInverseError axes B s t 0 x _ y h hc + +#print axioms inverseContraction +#print axioms trajectory +#print axioms physicalInverseError + + +/-- Cross-multiply exact input and output numerators. Equal rational inputs +to a normalized row solve have equal rational outputs at any denominators. -/ +theorem uniqueStep (a : Axis (Fin n)) (ha : Admitted a) (r s : Nat) + (x u y z : Fin n → Datum) (hy : Fixed a x y 1) (hz : Fixed a u z 1) + (he : ∀ i, times r (x i) = times s (u i)) : + ∀ i, times r (y i) = times s (z i) := by + let dif := fun i => minus (times r (y i)) (times s (z i)) + let zeroField : Fin n → Datum := fun _ => ⟨0,0⟩ + have hf : Fixed a zeroField dif 1 := by + intro i; dsimp only [dif] + rw [linearDot, scaleDot] + have p := hy i; have q := hz i; have e := he i + have pr := congrArg Datum.re p; have pi := congrArg Datum.im p + have qr := congrArg Datum.re q; have qi := congrArg Datum.im q + have er := congrArg Datum.re e; have ei := congrArg Datum.im e + simp only [times, plus, Nat.mul_one, Int.natCast_mul] at pr pi qr qi er ei + simp only [zeroField, times, plus, minus, Int.mul_zero, Int.zero_add, Int.natCast_mul, Datum.mk.injEq] + constructor <;> grind + intro i + have h := inverseContraction a ha zeroField dif 1 0 hf (fun _ => by simp [zeroField, radius]) i + simp [dif, radius, minus] at h + simp only [times, Datum.mk.injEq] at h ⊢ + constructor <;> omega + +/-- Every exact inverse trajectory on the same physical bands has the +same rational result, including different common denominators. -/ +theorem uniqueTrajectory (axes : List (Axis (Fin n))) (B t S T r s : Nat) + (x u y z : Fin n → Datum) (one : InverseChain B S t axes x y) (two : InverseChain B T t axes u z) + (he : ∀ i, times r (x i) = times s (u i)) : ∀ i, times r (y i) = times s (z i) := by + induction one generalizing u z with + | nil x => cases two; exact he + | cons a tail x mid y R m ha hg hm hf hr hsmall rest ih => + cases two with + | cons _ _ _ next _ _ _ _ _ _ hnext _ _ rest2 => + exact ih next z rest2 (uniqueStep a ha r s x u mid next hf hnext he) + +/-- The returned exact target exists and is unique as a rational field. +The final error includes every normalized inverse and all actual grid sweeps. -/ +theorem actualGaussianInverse (axes : List (Axis (Fin n))) (B t R : Nat) (x : Fin n → Datum) + (ready : ∀ a ∈ axes, Ready B t R a) (bound : ∀ i, radius (x i) ≤ R) : + ∃ S : Nat, 0 < S ∧ ∃ y : Fin n → Datum, + InverseChain B S t axes (fun i => times S (x i)) y ∧ + Close S ((2*B+t)*axes.length) (sweep x axes) y ∧ + ∀ (T : Nat) (z : Fin n → Datum), InverseChain B T t axes (fun i => times T (x i)) z → + ∀ i, times T (y i) = times S (z i) := by + obtain ⟨s, hs, y, h, close⟩ := physicalInverseError axes B t R x ready bound + refine ⟨s, hs, y, h, close, ?_⟩ + intro T z h2 + apply uniqueTrajectory axes B t s T T s _ _ y z h h2 + intro i; simp only [times, Datum.mk.injEq]; constructor <;> grind + +#print axioms uniqueStep +#print axioms uniqueTrajectory +#print axioms actualGaussianInverse + + +/-- The first two terms of the binomial expansion suffice for a discrete +geometric tail bound. This proof uses integer powers alone. -/ +theorem binomialLower (m g j : Nat) : m^(j+1) + (j+1)*g*m^j ≤ (m+g)^(j+1) := by + induction j with + | zero => simp + | succ j ih => + calc + _ ≤ m^(j+1+1) + (j+1+1)*g*m^(j+1) + (j+1)*g*g*m^j := Nat.le_add_right _ _ + _ = (m^(j+1) + (j+1)*g*m^j)*(m+g) := by rw [Nat.pow_succ m (j+1), Nat.pow_succ m j]; grind + _ ≤ (m+g)^(j+1)*(m+g) := Nat.mul_le_mul_right _ ih + _ = _ := (Nat.pow_succ _ _).symm + +theorem halfInOneBlock (B D m : Nat) (hB : 0 omega + | succ b => + have hprod := Nat.mul_le_mul_right (m^b) hmg + have first : 2*m^(b+1) ≤ m^(b+1) + (b+1)*g*m^b := by rw [Nat.pow_succ]; grind + exact Nat.le_trans first (by simpa only [hs] using binomialLower m g b) + +/-- A row contraction 1-1/B loses at least one binary bit every B +steps, uniformly for every matrix grid D and maximum physical row mass. -/ +theorem poweredTail (B D m j H : Nat) (hB : 0 + refine ⟨0, fun i => i.elim0, ?_⟩ + simpa using Nat.mul_le_mul_right a.D (show 1 ≤ B by omega) + | succ n => + obtain ⟨k, hk⟩ := attainment (fun j => mass (a.rows j)) + exact ⟨mass (a.rows k), hk, hg k⟩ + obtain ⟨m, hm, gap⟩ := hm + refine ⟨m, hm, ?_⟩ + have h1 := Nat.le_trans (Nat.mul_le_mul_right (m^a.J) bits) (poweredTail B a.D m a.J H hB hd gap length) + have h2 := Nat.mul_le_mul_left (a.a^a.J) h1 + simpa [den, Nat.mul_pow, Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm] using h2 + +/-- Fine-family specialization. The generated absolute row mass and common +dyadic normalizer imply accuracy on all inputs with numerator radius 2^(p²). +The implementation uses P=Cp bits, below p² for all sufficiently large p. -/ +theorem fineGaussianInverse (axes : List (Axis (Fin n))) (p : Nat) (x : Fin n → Datum) + (hp : 0 times S (x i)) y ∧ + Close S ((2*(16*p*p)+1)*axes.length) (sweep x axes) y ∧ + ∀ (T : Nat) (z : Fin n → Datum), InverseChain (16*p*p) T 1 axes (fun i => times T (x i)) z → + ∀ i, times T (y i) = times S (z i) := by + apply actualGaussianInverse axes (16*p*p) 1 (2^(p*p)) x _ bound + intro a ha + exact readyFromGrid _ _ (p*p) _ (Nat.mul_pos (Nat.mul_pos (by decide) hp) hp) (admitted _ ha) (gap _ ha) (Nat.le_refl _) (sweeps _ ha) + +#print axioms poweredTail +#print axioms readyFromGrid +#print axioms fineGaussianInverse + +end RationalInverse diff --git a/research/mixed-rank-uniform-composition/lean/Recovery.lean b/research/mixed-rank-uniform-composition/lean/Recovery.lean new file mode 100644 index 0000000000..efd883d8f6 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/Recovery.lean @@ -0,0 +1,300 @@ +import Mathlib.Analysis.Fourier.ZMod +import Mathlib.Algebra.Order.Round +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Ring +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.NormNum + +/-! Normalized Fourier recovery on the cyclic index of the original digit stream. -/ +namespace MixedRankRecovery + +open Finset +open scoped BigOperators ZMod + +variable {S : ℕ} [NeZero S] +abbrev Signal (S : ℕ) := ZMod S → ℂ + +noncomputable def cyclic (f g : Signal S) (k : ZMod S) : ℂ := + ∑ j : ZMod S, f j * g (k - j) + +noncomputable def forward (u : (ZMod S)ˣ) (f : Signal S) (k : ZMod S) := + (S : ℂ)⁻¹ * ZMod.dft f (u.val * k) + +noncomputable def opposite (u : (ZMod S)ˣ) (f : Signal S) (k : ZMod S) := + ZMod.dft.symm f (u.val * k) + +theorem dft_cyclic (f g : Signal S) : + ZMod.dft (cyclic f g) = fun k ↦ ZMod.dft f k * ZMod.dft g k := by + classical + funext k + simp only [ZMod.dft_apply, smul_eq_mul, cyclic] + rw [Finset.sum_mul] + simp only [Finset.mul_sum] + rw [sum_comm] + apply sum_congr rfl + intro j _ + + refine Fintype.sum_equiv (Equiv.subRight j) _ _ (fun x ↦ ?_) + simp only [Equiv.subRight_apply] + have h : -(x * k) = -(j * k) + -((x-j)*k) := by ring + rw [h, AddChar.map_add_eq_mul] + ring + +theorem exact_sandwich (u : (ZMod S)ˣ) (f g : Signal S) (k : ZMod S) : + opposite u (fun j ↦ forward u f j * forward u g j) k = + ((S : ℂ)⁻¹)^2 * cyclic f g k := by + have hc : (fun j ↦ forward u f j * forward u g j) = + ((S : ℂ)⁻¹)^2 • (fun j ↦ ZMod.dft (cyclic f g) (u.val * j)) := by + funext j + simp only [forward, dft_cyclic, Pi.smul_apply, smul_eq_mul] + ring + rw [hc, opposite, map_smul] + simp only [Pi.smul_apply, smul_eq_mul, ZMod.invDFT_apply'] + rw [ZMod.dft_comp_unitMul, ← mul_neg, u.inv_mul_cancel_left, ZMod.dft_dft] + simp [NeZero.ne (S : ℂ)] + +private theorem mean_bound (a x : Signal S) (B : ℝ) + (ha : ∀ j, ‖a j‖ = 1) (hx : ∀ j, ‖x j‖ ≤ B) : + ‖(S : ℂ)⁻¹ * ∑ j, a j * x j‖ ≤ B := by + have hs : ‖∑ j, a j * x j‖ ≤ ∑ _ : ZMod S, B := by + refine (norm_sum_le _ _).trans (sum_le_sum fun j _ ↦ ?_) + simpa [ha j] using hx j + calc + _ = (S : ℝ)⁻¹ * ‖∑ j, a j * x j‖ := by simp + _ ≤ (S : ℝ)⁻¹ * ∑ _ : ZMod S, B := + mul_le_mul_of_nonneg_left hs (by positivity) + _ = B := by simp [nsmul_eq_mul, ZMod.card, NeZero.ne (S : ℝ)] + +theorem forward_bound (u : (ZMod S)ˣ) (x : Signal S) (B : ℝ) + (hx : ∀ j, ‖x j‖ ≤ B) (k : ZMod S) : ‖forward u x k‖ ≤ B := by + simp only [forward, ZMod.dft_apply, smul_eq_mul] + apply mean_bound _ x B _ hx + intro j + simp [ZMod.stdAddChar_apply] + +theorem opposite_error (u : (ZMod S)ˣ) (x y : Signal S) (e : ℝ) + (h : ∀ j, ‖x j - y j‖ ≤ e) (k : ZMod S) : + ‖opposite u x k - opposite u y k‖ ≤ e := by + change ‖ZMod.dft.symm x _ - ZMod.dft.symm y _‖ ≤ e + have hsub : ZMod.dft.symm x (u.val*k) - ZMod.dft.symm y (u.val*k) = + ZMod.dft.symm (x-y) (u.val*k) := by simp + rw [hsub, ZMod.invDFT_apply] + simp only [smul_eq_mul] + apply mean_bound _ (x-y) e _ h + intro j + simp [ZMod.stdAddChar_apply] + +def disk (x : Signal S) (B : ℝ) : Prop := ∀ j, ‖x j‖ ≤ B + +def packet (fw : Signal S → Signal S) (mul : ℂ → ℂ → ℂ) (f g : Signal S) : Signal S := + fun j ↦ mul (fw f j) (fw g j) + +theorem product_error (u : (ZMod S)ˣ) (fw bw : Signal S → Signal S) + (mul : ℂ → ℂ → ℂ) (e : ℝ) (he : 0 ≤ e) (he' : e ≤ 1/8) + (hfw : ∀ x, disk x (1/2) → ∀ j, ‖fw x j - forward u x j‖ ≤ e) + (hbw : ∀ x, disk x (1/2) → ∀ j, ‖bw x j - opposite u x j‖ ≤ e) + (hm : ∀ a b, ‖a‖ ≤ 1/2 → ‖b‖ ≤ 1/2 → ‖mul a b - a*b‖ ≤ e) + (f g : Signal S) (hf : disk f (1/4)) (hg : disk g (1/4)) (k : ZMod S) : + ‖bw (packet fw mul f g) k - ((S : ℂ)⁻¹)^2 * cyclic f g k‖ ≤ 3*e := by + have close (x : Signal S) (hx : disk x (1/4)) (j : ZMod S) : + ‖fw x j - forward u x j‖ ≤ e := + hfw x (fun i ↦ (hx i).trans (by norm_num)) j + have approx (x : Signal S) (hx : disk x (1/4)) (j : ZMod S) : ‖fw x j‖ ≤ 1/2 := by + have ht := norm_le_insert' (fw x j) (forward u x j) + linarith [close x hx j, forward_bound u x (1/4) hx j] + have hp (j : ZMod S) := hm _ _ (approx f hf j) (approx g hg j) + have hdom : disk (packet fw mul f g) (1/2) := by + intro j + have ht := norm_le_insert' (mul (fw f j) (fw g j)) (fw f j * fw g j) + rw [norm_mul] at ht + have hx := mul_le_mul (approx f hf j) (approx g hg j) (norm_nonneg _) (by norm_num) + change ‖mul (fw f j) (fw g j)‖ ≤ 1/2 + linarith [hp j] + let exactPoint : Signal S := fun j ↦ forward u f j * forward u g j + have hpt (j : ZMod S) : ‖packet fw mul f g j - exactPoint j‖ ≤ 2*e := by + have h1 := dist_triangle (packet fw mul f g j) (fw f j * fw g j) (exactPoint j) + simp only [dist_eq_norm] at h1 + have hi : fw f j * fw g j - exactPoint j = + (fw f j-forward u f j) * fw g j + forward u f j * (fw g j-forward u g j) := by + dsimp [exactPoint]; ring + have hh := norm_add_le ((fw f j-forward u f j)*fw g j) + (forward u f j*(fw g j-forward u g j)) + rw [hi] at h1 + simp only [norm_mul] at hh + have h2 := mul_le_mul (close f hf j) (approx g hg j) (norm_nonneg _) he + have h3 := mul_le_mul (forward_bound u f (1/4) hf j) (close g hg j) (norm_nonneg _) (by norm_num) + have hr : ‖packet fw mul f g j - fw f j * fw g j‖ ≤ e := hp j + linarith only [h1, hh, h2, h3, hr, he] + rw [← exact_sandwich u f g k] + have ht := dist_triangle (bw (packet fw mul f g) k) (opposite u (packet fw mul f g) k) + (opposite u exactPoint k) + simp only [dist_eq_norm] at ht + change ‖bw (packet fw mul f g) k - opposite u exactPoint k‖ ≤ 3*e + linarith [hbw _ hdom k, opposite_error u _ _ _ hpt k] + +def coefficient (a b : ZMod S → ℕ) (k : ZMod S) : ℕ := + ∑ j : ZMod S, a j * b (k-j) + +noncomputable def digitInput (D : ℕ) (a : ZMod S → ℕ) : Signal S := + fun j ↦ (D : ℂ)⁻¹ * (a j : ℂ) + +theorem remove_scales (D : ℕ) (hD : 0 < D) (a b : ZMod S → ℕ) (k : ZMod S) : + ((S : ℂ) * D)^2 * (((S : ℂ)⁻¹)^2 * cyclic (digitInput D a) (digitInput D b) k) = + (coefficient a b k : ℂ) := by + have hz : (D : ℂ) ≠ 0 := by exact_mod_cast hD.ne' + simp only [cyclic, digitInput, coefficient, Nat.cast_sum, Nat.cast_mul, mul_sum] + apply sum_congr rfl + intro j _ + field_simp [hz, NeZero.ne (S : ℂ)] + +theorem final_round (D : ℕ) (hD : 0 < D) (a b : ZMod S → ℕ) (k : ZMod S) + (out : ℂ) (err : ℝ) + (h : ‖out - ((S : ℂ)⁻¹)^2 * cyclic (digitInput D a) (digitInput D b) k‖ ≤ err) + (hprec : ((S : ℝ) * D)^2 * err < 1/2) : + round ((((S : ℂ) * D)^2 * out).re) = (coefficient a b k : ℤ) := by + have hn : ‖((S : ℂ) * D)^2 * out - (coefficient a b k : ℂ)‖ < (1/2 : ℝ) := by + rw [← remove_scales D hD a b k, ← mul_sub, norm_mul] + simp only [norm_pow, norm_mul, Complex.norm_natCast] + exact (mul_le_mul_of_nonneg_left h (by positivity)).trans_lt hprec + have hr := (Complex.abs_re_le_norm _).trans_lt hn + simp only [Complex.sub_re, Complex.natCast_re] at hr + rw [round_eq_iff] + change (coefficient a b k : ℝ) - 1/2 ≤ _ ∧ _ < (coefficient a b k : ℝ) + 1/2 + exact ⟨by linarith [(abs_lt.mp hr).1], by linarith [(abs_lt.mp hr).2]⟩ + +omit [NeZero S] in +theorem public_grid_margin (B : ℕ) (hB : 32 ≤ B) (hs : S ≤ B) : + ((S : ℝ) * (4 * B))^2 * (3 * (3 / (B : ℝ)^6)) < 1/2 := by + have hlow : (32 : ℝ) ≤ B := by exact_mod_cast hB + have hpos : 0 < (B : ℝ) := by linarith + have hsb : (S : ℝ) ≤ B := by exact_mod_cast hs + have hsq : (S : ℝ)^2 ≤ (B : ℝ)^2 := by gcongr + have h32 : 32^2 ≤ (B : ℝ)^2 := by gcongr + have ht : ((S : ℝ) * (4 * B))^2 * (3 * (3 / (B : ℝ)^6)) ≤ 144 / (B : ℝ)^2 := by + field_simp + nlinarith [mul_nonneg (sub_nonneg.mpr hsq) (sq_nonneg ((B : ℝ)^2))] + refine ht.trans_lt ?_ + rw [div_lt_iff₀ (by positivity)] + nlinarith + +def radixValue (B : ℕ) (a : ZMod S → ℕ) : ℕ := + ∑ j : ZMod S, a j * B^j.val + +theorem radix_product (B : ℕ) (a b : ZMod S → ℕ) + (hspan : ∀ i j, a i ≠ 0 → b j ≠ 0 → i.val + j.val < S) : + radixValue B (coefficient a b) = radixValue B a * radixValue B b := by + classical + simp only [radixValue, coefficient] + rw [Finset.sum_mul] + simp only [Finset.mul_sum, Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i _ + refine Fintype.sum_equiv (Equiv.subRight i) _ _ (fun x ↦ ?_) + simp only [Equiv.subRight_apply] + by_cases ha : a i = 0 + · simp [ha] + by_cases hb : b (x-i) = 0 + · simp [hb] + have hv := ZMod.val_add_of_lt (hspan i (x-i) ha hb) + have hx : i + (x-i) = x := by abel + rw [hx] at hv + rw [hv, pow_add] + ring + +def pack (B : ℕ) : List ℕ → ℕ + | [] => 0 + | a :: rest => a + B * pack B rest + +def carry (B : ℕ) (k : ℕ) : List ℕ → List ℕ + | [] => [k] + | a :: rest => (a+k)%B :: carry B ((a+k)/B) rest + +theorem carry_value (B k : ℕ) (cs : List ℕ) : + pack B (carry B k cs) = k + pack B cs := by + induction cs generalizing k with + | nil => simp [pack, carry] + | cons a as ih => + simp only [carry, pack, ih, Nat.mul_add] + have hd := Nat.mod_add_div (a+k) B + omega + +theorem pack_indices (B m : ℕ) (a : Fin m → ℕ) : + pack B (List.ofFn a) = ∑ i, a i * B^i.val := by + induction m with + | zero => simp [pack] + | succ n ih => + rw [List.ofFn_succ, pack, Fin.sum_univ_succ, ih] + simp only [Fin.val_zero, pow_zero, mul_one, Fin.val_succ, pow_succ, mul_sum] + congr 1 + apply sum_congr rfl + intro i _ + ring + +def ordered (a : ZMod S → ℕ) : List ℕ := + List.ofFn (fun i : Fin S ↦ a (i.val : ZMod S)) + +theorem ordered_value (B : ℕ) (a : ZMod S → ℕ) : + pack B (ordered a) = radixValue B a := by + unfold ordered radixValue + rw [pack_indices] + let bij : Fin S ≃ ZMod S := { + toFun := fun i ↦ (i.val : ZMod S) + invFun := fun j ↦ ⟨j.val,j.val_lt⟩ + left_inv := fun i ↦ Fin.ext (ZMod.val_natCast_of_lt i.isLt) + right_inv := ZMod.natCast_zmod_val } + refine Fintype.sum_equiv bij _ _ (fun i ↦ ?_) + change a (i.val : ZMod S) * _ = a (i.val : ZMod S) * B^(i.val : ZMod S).val + rw [ZMod.val_natCast_of_lt i.isLt] + +noncomputable def decode (B : ℕ) (fw bw : Signal S → Signal S) + (mul : ℂ → ℂ → ℂ) (a b : ZMod S → ℕ) (k : ZMod S) : ℕ := + let z := packet fw mul (digitInput (4*B) a) (digitInput (4*B) b) + (round ((((S : ℂ) * ((4*B : ℕ) : ℂ))^2 * bw z k).re)).toNat + +theorem recovered_product (B : ℕ) (hB : 32 ≤ B) (hs : S ≤ B) (u : (ZMod S)ˣ) + (fw bw : Signal S → Signal S) (mul : ℂ → ℂ → ℂ) (e : ℝ) + (he : 0 ≤ e) (hpublic : e ≤ 3 / (B : ℝ)^6) + (hfw : ∀ x, disk x (1/2) → ∀ j, ‖fw x j - forward u x j‖ ≤ e) + (hbw : ∀ x, disk x (1/2) → ∀ j, ‖bw x j - opposite u x j‖ ≤ e) + (hm : ∀ x y, ‖x‖ ≤ 1/2 → ‖y‖ ≤ 1/2 → ‖mul x y - x*y‖ ≤ e) + (a b : ZMod S → ℕ) (ha : ∀ j, a j ≤ B) (hb : ∀ j, b j ≤ B) + (hspan : ∀ i j, a i ≠ 0 → b j ≠ 0 → i.val + j.val < S) : + pack B (carry B 0 (ordered (decode B fw bw mul a b))) = + radixValue B a * radixValue B b := by + have hpos : 0 < B := by omega + have hpos' : (0 : ℝ) < B := by exact_mod_cast hpos + have hlow : (32 : ℝ) ≤ B := by exact_mod_cast hB + have h6 : (32 : ℝ)^6 ≤ (B : ℝ)^6 := by gcongr + have he' : e ≤ 1/8 := hpublic.trans (by rw [div_le_iff₀ (by positivity)]; linarith) + have dom (x : ZMod S → ℕ) (hx : ∀ j, x j ≤ B) : disk (digitInput (4*B) x) (1/4) := by + intro j + simp only [digitInput, norm_mul, norm_inv, Complex.norm_natCast] + rw [← div_eq_inv_mul] + push_cast + apply (div_le_iff₀ (by positivity)).mpr + have hx' : (x j : ℝ) ≤ B := by exact_mod_cast hx j + linarith + have budget : ((S : ℝ) * (4*B : ℕ))^2 * (3*e) < 1/2 := by + norm_cast + push_cast + exact (mul_le_mul_of_nonneg_left (mul_le_mul_of_nonneg_left hpublic (by norm_num : (0:ℝ) ≤ 3)) + (sq_nonneg _)).trans_lt (public_grid_margin B hB hs) + have hc : decode B fw bw mul a b = coefficient a b := by + funext j + have err := product_error u fw bw mul e he he' hfw hbw hm _ _ (dom a ha) (dom b hb) j + have h := final_round (4*B) (by omega) a b j _ _ err budget + simpa [decode] using congrArg Int.toNat h + rw [hc, carry_value, Nat.zero_add, ordered_value, radix_product B a b hspan] + +#print axioms recovered_product +#print axioms remove_scales +#print axioms final_round +#print axioms public_grid_margin +#print axioms radix_product +#print axioms carry_value +#print axioms product_error +#print axioms dft_cyclic +#print axioms exact_sandwich +end MixedRankRecovery diff --git a/research/mixed-rank-uniform-composition/lean/SyntheticBridge.lean b/research/mixed-rank-uniform-composition/lean/SyntheticBridge.lean new file mode 100644 index 0000000000..06b82ba9cf --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/SyntheticBridge.lean @@ -0,0 +1,112 @@ +import Std + +namespace SyntheticBridge + +structure Gaussian where + re : Int + im : Int + deriving DecidableEq, Repr + +inductive Step where + | ident | quarter | plusI | minusI | twice | negTwice + deriving DecidableEq, Repr + +def act (s : Step) (v : Gaussian) : Gaussian := + match s with + | .ident => v + | .quarter => ⟨-v.im, v.re⟩ + | .plusI => ⟨v.re - v.im, v.re + v.im⟩ + | .minusI => ⟨v.re + v.im, v.im - v.re⟩ + | .twice => ⟨2 * v.re, 2 * v.im⟩ + | .negTwice => ⟨-2 * v.re, -2 * v.im⟩ + +theorem commute (s t : Step) (v : Gaussian) : act s (act t v) = act t (act s v) := by + cases s <;> cases t <;> cases v <;> simp [act, Gaussian.mk.injEq] <;> omega + +def run : List Step → Gaussian → Gaussian + | [], v => v + | s :: rest, v => act s (run rest v) + +theorem pull (xs : List Step) (s : Step) (v : Gaussian) : + run xs (act s v) = act s (run xs v) := by + induction xs with + | nil => rfl + | cons t ts ih => + simp only [run, ih] + exact commute t s _ + +abbrev Slot := Bool × Bool + +def phase (b : Bool) : Step := if b then .quarter else .ident + +def native (x : Slot) : Step := if x.1 == x.2 then .plusI else .minusI + +def halfNumerator (x : Slot) : Step := if x.1 && x.2 then .negTwice else .twice + +theorem oneSlot (x : Slot) (v : Gaussian) : + act .minusI (act (phase x.1) (act (native x) (act (phase x.2) v))) = + act (halfNumerator x) v := by + obtain ⟨r, c⟩ := x + cases r <;> cases c <;> cases v <;> + simp [phase, native, halfNumerator, act, Gaussian.mk.injEq] <;> omega + +/-- Matrix coefficient of b^h D C^tensor(h) D, applied to the given Gaussian +numerator after clearing the common denominator 4^h. A slot is (row bit, column bit). -/ +def completed (xs : List Slot) (v : Gaussian) : Gaussian := + run (xs.map fun _ => Step.minusI) + (run (xs.map fun x => phase x.1) + (run (xs.map native) (run (xs.map fun x => phase x.2) v))) + +theorem completed_cons (x : Slot) (xs : List Slot) (v : Gaussian) : + completed (x :: xs) v = act (halfNumerator x) (completed xs v) := by + simp only [completed, List.map_cons, run, pull] + rw [commute (phase x.2) .minusI, commute (phase x.2) (phase x.1), + commute (phase x.2) (native x), oneSlot] + +/-- Every coefficient of the completed native layer equals the corresponding +coefficient of H0^tensor(h) at that same cleared denominator. -/ +theorem allWidths (xs : List Slot) (v : Gaussian) : + completed xs v = run (xs.map halfNumerator) v := by + induction xs with + | nil => rfl + | cons x xs ih => simp only [completed_cons, ih, List.map_cons, run] + +def sign (x : Slot) : Int := if x.1 && x.2 then -1 else 1 + +def scale (a : Int) (v : Gaussian) : Gaussian := ⟨a * v.re, a * v.im⟩ + +theorem scales (a b : Int) (v : Gaussian) : scale a (scale b v) = scale (a * b) v := by + simp [scale, Int.mul_assoc] + +theorem oneSign (x : Slot) (v : Gaussian) : + act (halfNumerator x) v = scale (2 * sign x) v := by + obtain ⟨r, c⟩ := x + cases r <;> cases c <;> simp [sign, halfNumerator, scale, act] + +/-- At denominator 4^h, the unabsorbed scalar is 2^h times the signed +row/column Hadamard character. Dividing gives the normalization 1/2^h. -/ +theorem clearedCharacter (xs : List Slot) (v : Gaussian) : + completed xs v = scale (2 ^ xs.length * (xs.map sign).prod) v := by + induction xs with + | nil => cases v <;> simp [completed, run, scale] + | cons x xs ih => + rw [completed_cons, ih, oneSign, scales] + congr 1 + simp [Int.pow_succ, Int.mul_assoc, Int.mul_left_comm, Int.mul_comm] + +def sum : List Gaussian → Gaussian + | [] => ⟨0, 0⟩ + | v :: vs => ⟨v.re + (sum vs).re, v.im + (sum vs).im⟩ + +/-- The source coordinates and their signed dyadic numerators may be arbitrary. +Use all columns of any fixed row to obtain the complete operator equality. -/ +theorem anyInputs (inputs : List (List Slot × Gaussian)) : + sum (inputs.map fun it => completed it.1 it.2) = + sum (inputs.map fun it => run (it.1.map halfNumerator) it.2) := by + simp only [allWidths] + +#print axioms allWidths +#print axioms anyInputs +#print axioms clearedCharacter + +end SyntheticBridge diff --git a/research/mixed-rank-uniform-composition/lean/generate_moments.py b/research/mixed-rank-uniform-composition/lean/generate_moments.py new file mode 100644 index 0000000000..43facbf7e0 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/generate_moments.py @@ -0,0 +1,133 @@ +"""Generate proposed dyadic endpoints from the immutable paid and target histograms.""" + +import argparse +import json +import subprocess +from decimal import Decimal, localcontext +from fractions import Fraction as Q +from pathlib import Path + +HEAD = "87fbf4f7b35b0f18ab12b5767775a9a424cf0b15" +PKG = "research/p104-mixed-rank-supplier" +S = 160 +BITS = 352 + + +def artifact(name): + return json.loads(subprocess.check_output(["git", "show", f"{HEAD}:{PKG}/{name}.json"])) + + +def enclosure(r, a): + with localcontext() as ctx: + ctx.prec = 90 + candidate = int(Decimal(r) ** (Decimal(a.numerator) / Decimal(a.denominator)) * (1 << S)) + # These are proposals. The Lean proof checks both sides using only integers. + return candidate-2, candidate+3 + + +def claim(r, a): + lower, upper = enclosure(r,a) + return f"⟨{r}, {a.numerator}, {a.denominator}, {lower}, {upper}⟩" + + +def table(name, a, p, t): + rows = [] + for rank in sorted(set(p) | set(t)): + rows.append(f" ⟨{claim(rank,a)}, {p.get(rank,0)}, {t.get(rank,0)}⟩") + return f"def {name} : List Row := [\n" + ",\n".join(rows) + "]\n" + + +def counts(raw): + return {int(rank): qty for rank,qty in raw.items()} + + +def generate(): + bit, complex_report = (artifact(name) for name in ("BIT","AUDIT")) + btc = Q(bit["separation"]["trial"]) + cpc = Q(complex_report["outer"]["finite_compiler"]["tested"]) + p,t = (counts(bit["native"][key]) for key in ("paid","targets")) + pc,tc = (counts(complex_report["signed"][key]) for key in ("paid","productive")) + caps = {k:Q(v) for k,v in bit["separation"]["upper_caps"].items()} + start = """import DyadicRoot + +/-! Dyadic enclosures for the complete pinned BIT and complex rank histograms. +Generated by generate_moments.py. Root certificates use integer arithmetic. -/ +namespace RankMoments + +open DyadicRoot + +structure Row where + power : Claim + paid : Nat + target : Nat + +set_option maxRecDepth 65536 +set_option maxHeartbeats 40000000 +""" + blocks = [start, f"def bits : Nat := {BITS}\ndef frac : Nat := {S}\ndef grid : Nat := 2^frac\n"] + blocks += [table("bitMain",1-btc,p,t), table("bitLow",1-btc+Q(11,50),p,{}), + table("bitHigh",1-btc+Q(13,50),p,{}),table("bitDrop",1-btc-Q(17,50),{},t), + table("complexMain",1-cpc,pc,tc),table("complexTilt",1-cpc+Q(1,7),pc,{})] + scalar = [("lowCut",10,Q(11,50)),("highCut",11,Q(13,50)),("floorCost",16,Q(17,50)), + ("complexCut",11,Q(1,7)),("complexCost",11,cpc)] + for name,r,a in scalar: + blocks.append(f"def {name} : Claim := {claim(r,a)}\n") + names = ["bitMain","bitLow","bitHigh","bitDrop","complexMain","complexTilt"] + blocks.append("def scalarRows : List Claim := [" + ", ".join(name for name,_,_ in scalar) + "]\n") + for name in names: + blocks.append(f"theorem {name}_ok : ({name}.map Row.power).all (valid bits frac) = true := by decide +kernel\n") + blocks.append("theorem scalars_ok : scalarRows.all (valid bits frac) = true := by decide +kernel\n") + blocks.append(""" +def tables : List (List Row) := [bitMain, bitLow, bitHigh, bitDrop, complexMain, complexTilt] +def claims : List Claim := tables.flatMap (fun xs => xs.map Row.power) ++ scalarRows + +theorem table_sound (c : Claim) (hc : c ∈ claims) : + 0 < c.den ∧ c.lo^c.den ≤ c.rank^c.num * 2^(frac*c.den) ∧ + c.rank^c.num * 2^(frac*c.den) ≤ c.hi^c.den := by + apply valid_sound bits + apply List.all_eq_true.mp _ c hc + simp only [claims, tables, List.flatMap_cons, List.flatMap_nil, List.all_append, + List.all_nil, Bool.and_true, bitMain_ok, bitLow_ok, bitHigh_ok, bitDrop_ok, + complexMain_ok, complexTilt_ok, scalars_ok] + +def upperPaid (xs : List Row) (select : Nat → Bool := fun _ => true) : Nat := + (xs.map (fun row => if select row.power.rank then row.paid * row.power.hi else 0)).sum + +def lowerTarget (xs : List Row) : Nat := (xs.map (fun row => row.target * row.power.lo)).sum +def upperTarget (xs : List Row) : Nat := (xs.map (fun row => row.target * row.power.hi)).sum +def targetCount (xs : List Row) : Nat := (xs.map Row.target).sum + +def ratioBelow (x y num den : Nat) : Prop := 0 < y ∧ x*den < num*y +instance (x y num den : Nat) : Decidable (ratioBelow x y num den) := + inferInstanceAs (Decidable (0 < y ∧ x*den < num*y)) +""") + ratios=[ + ("bit_alpha","upperPaid bitMain","lowerTarget bitMain",caps["alpha"]), + ("bit_first_low","upperPaid bitLow (fun r => r ≤ 4) * grid","lowCut.lo * lowerTarget bitMain",caps["grades_1_to_4_first"]), + ("bit_rest_low","upperPaid bitLow * grid","lowCut.lo * lowerTarget bitMain",caps["grades_1_to_4_rest"]), + ("bit_first_high","upperPaid bitHigh (fun r => 4 < r) * grid","highCut.lo * lowerTarget bitMain",caps["grades_above_4_first"]), + ("bit_rest_high","upperPaid bitHigh * grid","highCut.lo * lowerTarget bitMain",caps["grades_above_4_rest"]), + ("bit_discard","floorCost.hi * upperTarget bitDrop","grid * lowerTarget bitMain",caps["discarded_targets"]), + ("complex_alpha","upperPaid complexMain","lowerTarget complexMain",1-Q(1,10**27)), + ("complex_gamma","upperPaid complexTilt * grid","complexCut.lo * lowerTarget complexMain",Q(31,32)), + ("complex_delta","12 * targetCount complexMain * grid^2","complexCost.lo * lowerTarget complexMain",Q(31,32)), + ] + for name, x,y,a in ratios: + blocks.append(f"theorem {name} : ratioBelow ({x}) ({y}) {a.numerator} {a.denominator} := by decide +kernel\n") + blocks.append("\nend RankMoments\n\n#print axioms RankMoments.table_sound\n") + for name,_,_,_ in ratios: + blocks.append(f"#print axioms RankMoments.{name}\n") + return "\n".join(blocks) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check",action="store_true") + args = parser.parse_args() + path = Path(__file__).resolve().with_name("RankMoments.lean") + output = generate() + if args.check: + if path.read_text() != output: + raise ValueError("generated source bindings differ") + else: + path.write_text(output) diff --git a/research/mixed-rank-uniform-composition/lean/lake-manifest.json b/research/mixed-rank-uniform-composition/lean/lake-manifest.json new file mode 100644 index 0000000000..55e86a6f6a --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/lake-manifest.json @@ -0,0 +1,117 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + } + ], + "name": "MixedRankMultiplication", + "lakeDir": ".lake", + "fixedToolchain": true +} diff --git a/research/mixed-rank-uniform-composition/lean/lakefile.toml b/research/mixed-rank-uniform-composition/lean/lakefile.toml new file mode 100644 index 0000000000..2f3b47b0b5 --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/lakefile.toml @@ -0,0 +1,12 @@ +name = "MixedRankMultiplication" +version = "1.0.0" +defaultTargets = ["MixedRankProofs"] + +[[require]] +name = "mathlib" +git = "https://github.com/leanprover-community/mathlib4.git" +rev = "d13f23b723b8a846827a245b89c10fc7d3f11612" + +[[lean_lib]] +name = "MixedRankProofs" +roots = ["Recovery", "Coordinates", "Integrated", "PhysicalFrames", "PhaseBudget", "CompilerFlow", "Funding", "DyadicRoot", "RankMoments", "CertifiedPrices", "CoverRows", "OuterPrices", "SyntheticBridge", "HaloRadius", "RankOneBridge", "PublicGrid", "RationalInverse"] diff --git a/research/mixed-rank-uniform-composition/lean/lean-toolchain b/research/mixed-rank-uniform-composition/lean/lean-toolchain new file mode 100644 index 0000000000..ba8ebf2dba --- /dev/null +++ b/research/mixed-rank-uniform-composition/lean/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.34.1 diff --git a/research/mixed-rank-uniform-composition/replay_sources.py b/research/mixed-rank-uniform-composition/replay_sources.py new file mode 100644 index 0000000000..dd84c44f96 --- /dev/null +++ b/research/mixed-rank-uniform-composition/replay_sources.py @@ -0,0 +1,71 @@ +"""Replay the pinned native packages and the two mixed-price verifiers.""" + +import argparse +import hashlib +import json +import subprocess +import sys +import tarfile +from pathlib import Path +from tempfile import TemporaryDirectory + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from bind_compiler import MIXED, MP, NATIVE, NP + +BASE = "e54523517d0f03e58352e647c403a5af3e525a57" +HERE = Path(__file__).resolve().parent + + +def extract(head, paths, destination): + with TemporaryDirectory() as staging: + archive = Path(staging) / "source.tar" + with archive.open("wb") as output: + subprocess.run(["git", "archive", head, "--", *paths], stdout=output, check=True) + with tarfile.open(archive) as source: + source.extractall(destination, filter="data") + + +def execute(script, *arguments): + subprocess.run([sys.executable, "-I", "-B", str(script), *map(str, arguments)], check=True) + + +def main(cache, fetch): + if not cache.is_dir() and not fetch: + raise ValueError("Provide a populated mixed-source cache or use --fetch.") + for script in ["bind_compiler.py", "check_binding.py", "check_ordinary.py"]: + execute(HERE / script) + execute(HERE / "lean/generate_moments.py", "--check") + with TemporaryDirectory() as temporary: + work = Path(temporary) + extract(NATIVE, [NP], work) + native = work / NP + manifest = json.loads((native / "VERIFY.json").read_text()) + extract(BASE, manifest["inputs"], work) + for name in ["check_complex.py", "check_binary.py", "check_leaves.py"]: + execute(native / name) + execute(native / "charts.py", "--check-build") + execute(HERE / "check_weighted.py", native) + extract(MIXED, [MP], work) + source = work / MP + producer, review = work / "producer", work / "review" + network = ["--fetch"] if fetch else [] + execute(source / "verify.py", "--work", cache, "--out", producer, *network) + execute(source / "review/independent.py", "--work", cache, "--out", review, + "--producer", producer, *network) + for name in ["RESULT.json", "BIT.json", "AUDIT.json"]: + if (source / name).read_bytes() != (producer / name).read_bytes(): + raise ValueError(f"Producer changed {name}.") + for name in ["APPLICATION.json", "AUDIT.json"]: + result = (producer / name).read_bytes() + if result != (review / name).read_bytes(): + raise ValueError(f"Review changed {name}.") + print(name, hashlib.sha256(result).hexdigest(), flush=True) + print("PASS_PINNED_COMPLETE_APPLICATION_AND_NATIVE_REPLAYS") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cache", type=Path, required=True, help="Mixed-source cache directory") + parser.add_argument("--fetch", action="store_true", help="Fetch missing source inputs") + args = parser.parse_args() + main(args.cache.resolve(), args.fetch)