diff --git a/research/staged544-reversible-lattice-macro/.gitattributes b/research/staged544-reversible-lattice-macro/.gitattributes new file mode 100644 index 0000000000..394331b5c4 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/.gitattributes @@ -0,0 +1,4 @@ +*.py text eol=lf +*.md text eol=lf +*.json text eol=lf +frozen/** -text diff --git a/research/staged544-reversible-lattice-macro/.gitignore b/research/staged544-reversible-lattice-macro/.gitignore new file mode 100644 index 0000000000..7a60b85e14 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/research/staged544-reversible-lattice-macro/CREDITS.md b/research/staged544-reversible-lattice-macro/CREDITS.md new file mode 100644 index 0000000000..b2e860939e --- /dev/null +++ b/research/staged544-reversible-lattice-macro/CREDITS.md @@ -0,0 +1,37 @@ +# Attribution and source boundaries + +The staged544 provider and helper 277 residual are Dugongue's PR3945, building +on dataisfire's PR3734 and the retained scalar, frame, native, owner and outer +lineage. No provider-construction credit is transferred by this implementation. +Jeremy Kothe's frame work, Sagar Thakrar, roger-sato and Arham Tahir's audit +contracts, DreamingOfClouds's residual adapters, chafreaky's PR458 wrappers, +and Cinna Davis's dirty-borrowing work remain credited. The complete preserved +predecessor lineage is in frozen/NOTICE-PR3945.md and frozen/SOURCE-CREDITS.md; +these copied files are authenticated byte-for-byte, not rewritten. + +The exact phase recipe and independent Gaussian oracle are reused from +Chris R / Clear1nsight's PR3987 at fc536202fdaa924158789a5ef59ac079bbe21922. +Fresh replay here covers its one helper 277 class. The complete-call allowance +is PR3994 at eb2ac25838a3d39ac8fd6acfa62b8b613c847629; its global theorem is +not claimed as newly derived or its full registry rerun by this package. + +Reversible lifting and modular accumulators are established mathematical ideas. +The borrowed-bit multiple-control decomposition and 4n-8 Toffoli cost are +credited to Adriano Barenco et al., *Elementary gates for quantum computation*, +arXiv:quant-ph/9503016, Lemma 7.2: +https://arxiv.org/pdf/quant-ph/9503016 . The implementation contains a +self-contained derivation and checks, and uses literal classical Toffolis, +not the paper's later relative-phase substitutions. No new general gate +decomposition theorem or first-use claim is made. + +The new contribution is the source-bound dirty half-sum accumulator, its +explicit application/bill/error contract for the actual residual, a fair +constructed clean comparison, and the actual-macro nonadditivity discriminator. +Chris R / Clear1nsight with substantial OpenAI Codex assistance. A coordinating +agent suggested the clean comparison and classical borrowed ladder; a separate +same-team graph agent independently implemented elementary-gate controls. +These AI reviews are neither independent human review nor proof-kernel checks. + +PR3881's exact-residue Gaussian recovery lane was read during overlap checking. +It uses a different numerical producer/consumer and is not a baseline or source +of this macro's constants. No exhaustive novelty claim is made. diff --git a/research/staged544-reversible-lattice-macro/FROZEN-SOURCES.json b/research/staged544-reversible-lattice-macro/FROZEN-SOURCES.json new file mode 100644 index 0000000000..2eb6a59f55 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/FROZEN-SOURCES.json @@ -0,0 +1,106 @@ +[ + { + "path": "frozen/WORD-base.json.gz", + "sha256": "08e6c96fbe3dfec96cb8451b3867ef8c1a214109ecd1e5af7fcc28e0f05728d0", + "source": { + "local_path": "frozen/WORD-base.json.gz", + "sha256": "08e6c96fbe3dfec96cb8451b3867ef8c1a214109ecd1e5af7fcc28e0f05728d0", + "origin_commit": "91f81d131252db704f945891da1ea54e29d46b8b", + "origin": "CrocSwap/integer-mult-bounds research/staged544-terminal-gap-fill; exact public frozen bytes, native receipts are author evidence only", + "origin_repository": "CrocSwap/integer-mult-bounds", + "origin_path": "research/staged544-terminal-gap-fill/inputs/NEW-base.json.gz", + "git_blob": "806784bf99d9d15004d2d227d06268556a0726c8" + } + }, + { + "path": "frozen/WORD-extra.json.gz", + "sha256": "d83c2ec9cecc0ad092d34ea4080b28a4fd7199579356b6d5a8fc6cd53ff93299", + "source": { + "local_path": "frozen/WORD-extra.json.gz", + "sha256": "d83c2ec9cecc0ad092d34ea4080b28a4fd7199579356b6d5a8fc6cd53ff93299", + "origin_commit": "91f81d131252db704f945891da1ea54e29d46b8b", + "origin": "CrocSwap/integer-mult-bounds research/staged544-terminal-gap-fill; exact public frozen bytes, native receipts are author evidence only", + "origin_repository": "CrocSwap/integer-mult-bounds", + "origin_path": "research/staged544-terminal-gap-fill/inputs/NEW-extra.json.gz", + "git_blob": "c531be7383ad3ba941600c7ced14e5e10d6d1c67" + } + }, + { + "path": "frozen/clifford_exact.py", + "sha256": "2982ead07721e83358dc67c6f49c2b4c16a236a6bebdfd72f58221be1f5d0962", + "source": { + "local_path": "vendor/clifford_exact.py", + "sha256": "2982ead07721e83358dc67c6f49c2b4c16a236a6bebdfd72f58221be1f5d0962", + "origin_commit": "91f81d131252db704f945891da1ea54e29d46b8b", + "origin": "native/vendor/native/new/code/borrow/vendor/clifford/clifford_exact.py", + "usage": "Only clifford_exact.py used in optional reference generation; independent verifier executes none of these sources", + "origin_repository": "CrocSwap/integer-mult-bounds", + "origin_path": "research/staged544-terminal-gap-fill/native/vendor/native/new/code/borrow/vendor/clifford/clifford_exact.py", + "git_blob": "166841a037f069249f6f7f6dedb89248812f59e2" + } + }, + { + "path": "frozen/bw_adapters.py", + "sha256": "c5907050a9a7fa36d4fcba3ad4fe440d1bec2063360c095013891785ba65c3ce", + "source": { + "local_path": "vendor/bw_adapters.py", + "sha256": "c5907050a9a7fa36d4fcba3ad4fe440d1bec2063360c095013891785ba65c3ce", + "origin_commit": "91f81d131252db704f945891da1ea54e29d46b8b", + "origin": "native/vendor/native/new/code/borrow/bw_adapters.py", + "usage": "Only clifford_exact.py used in optional reference generation; independent verifier executes none of these sources", + "origin_repository": "CrocSwap/integer-mult-bounds", + "origin_path": "research/staged544-terminal-gap-fill/native/vendor/native/new/code/borrow/bw_adapters.py", + "git_blob": "82beaa9c1d13bcd5f79d0a5e10e8a10733eac347" + } + }, + { + "path": "frozen/bw_transport.py", + "sha256": "9818e08b819310b40f1441b89be8c4369584a5b3fa5dfe9b86b1df9a7f5d6a76", + "source": { + "local_path": "vendor/bw_transport.py", + "sha256": "9818e08b819310b40f1441b89be8c4369584a5b3fa5dfe9b86b1df9a7f5d6a76", + "origin_commit": "91f81d131252db704f945891da1ea54e29d46b8b", + "origin": "native/vendor/native/new/code/borrow/bw_transport.py", + "usage": "Only clifford_exact.py used in optional reference generation; independent verifier executes none of these sources", + "origin_repository": "CrocSwap/integer-mult-bounds", + "origin_path": "research/staged544-terminal-gap-fill/native/vendor/native/new/code/borrow/bw_transport.py", + "git_blob": "08248542b18864c94a5ac050c8669f68519838e1" + } + }, + { + "path": "frozen/NOTICE-PR3945.md", + "sha256": "6881464d7731757b63275f056cb9ef8406db04e76c73093d3e5b418529a879cc", + "source": { + "repository": "Clear1nsight/integer-mult-bounds", + "head": "fc536202fdaa924158789a5ef59ac079bbe21922", + "path": "research/staged544-native-quadratic-audit/NOTICE-PR3945.md" + } + }, + { + "path": "frozen/SOURCE-CREDITS.md", + "sha256": "d4a13d8b8ed9cdb594f00efb3d1a336e09d934423330f02a1514308a720c278b", + "source": { + "repository": "Clear1nsight/integer-mult-bounds", + "head": "fc536202fdaa924158789a5ef59ac079bbe21922", + "path": "research/staged544-native-quadratic-audit/SOURCE-CREDITS.md" + } + }, + { + "path": "frozen/RECIPES.json", + "sha256": "64b85f6aef485026eebaec7acddb41999f57e074b0dfde8077b6543700cd684b", + "source": { + "repository": "Clear1nsight/integer-mult-bounds", + "head": "fc536202fdaa924158789a5ef59ac079bbe21922", + "path": "research/staged544-native-quadratic-audit/RECIPES.json" + } + }, + { + "path": "frozen/exact_phase.py", + "sha256": "e3d76b3373ff40a83a4b212b3fe1c0b431b3cfdc807da601d6e7f273c02c6d30", + "source": { + "repository": "Clear1nsight/integer-mult-bounds", + "head": "fc536202fdaa924158789a5ef59ac079bbe21922", + "path": "research/staged544-native-quadratic-audit/exact_phase.py" + } + } +] diff --git a/research/staged544-reversible-lattice-macro/LEDGER.json b/research/staged544-reversible-lattice-macro/LEDGER.json new file mode 100644 index 0000000000..178a24f11d --- /dev/null +++ b/research/staged544-reversible-lattice-macro/LEDGER.json @@ -0,0 +1,38 @@ +{ + "scope": "Actual PR3945 helper277 residual L C5 R, both providers, fixed mathematical map; f spectator lanes and b-bit real data", + "proved": { + "finite_permutation": "All data/scratch bit states; exact inverse and arbitrary dirty scratch return; temporary borrowed pair bits restored after each elementary gate", + "arithmetic_primitives_per_lane": { + "dirty_add_sub_conditional_decrement": 23040, + "constructed_clean_add_sub": 17920, + "real_swaps": 3792, + "real_negations": 2304 + }, + "scratch": "One b+1 bit word, arbitrary initial state restored; no clean ancilla. Data1024bf bits counted separately. Serially reuse scratch across1280f pairs.", + "elementary_gate_upper_bound": "(6b+4)(10240b^2+41584b+10240)f X/CNOT/Toffoli; exact split at b8,32,64 in RESULT.json", + "bounded_fanin_method": "Barenco et al. Lemma7.2 borrowed-bit decomposition, literal classical gates; temporary bits selected only outside current controls/target among pair and scratch", + "numerical_error": "80sqrt(f)Delta completed Hilbert error, conditional on no data wrap; scratch wrap allowed exactly", + "data_range": "Signed range8H is sufficient if Delta<=H/(128sqrt(f)); b=p+4 for Delta=H2^-p, H power of two", + "cut_allowance": "p>=beta+32+ceil(log2sqrt(f)) suffices for PR3994 absolute aggregate-cut allowance H2^(-beta-25)", + "negative_result": "Actual rounded rank5 macro has Q(2e0)-2Q(e0) nonzero at24 coordinates; standalone inverse does not establish whole-provider linear dirty-cleanup identities" + }, + "constructed_comparison": { + "baseline": "Explicit clean accumulator introduced here, not an authenticated predecessor implementation", + "improvement": "Removes requirement to initialize b+1 scratch bits to zero", + "additional_cost": "5120f real-word arithmetic primitives;1280(b^2+5b)f generalized gates. At b32, extra61683200f Toffolis plus X/CNOT delta.", + "no_claim": "No speedup, selected sigma, kappa or admitted recursive replacement" + }, + "inherited": { + "source_paid_object": "One rank5 recursive child, not a scalar primitive allowance", + "source_semantics": "Exact monomial/Clifford recipe and Gaussian dyadic semantics; PR3987 all-column oracle reused and freshly executed for this single class", + "global_word": "PR3994 ideal linear endpoint identities and full-cut error theorem, not rerun wholesale" + }, + "unknown_not_zero": { + "actual_caller_budget": "No authenticated conversion from one paid rank5 child into our serial scalar bit tariff", + "physical_time_space": "Native scheduling, owner stock/tape, parallelism and actual tensor multiplicity", + "borrowed_provider_restoration": "Whole-word nonlinear dirty compensation after interleaved arithmetic and exact recovery/disposal", + "uniform_selected_stock": "Selected m73 producer mapping, all-size recursion and selected sigma", + "hardware_noise": "Boolean permutation model has exact X/CNOT/Toffoli; stochastic hardware faults not modeled" + }, + "family_gate_decision": "Narrow: finite implementation closes a real module-level obligation and exposes precise nonadditivity/affordability stops. No further implementation expansion or new construction search justified without actual consumer budget." +} diff --git a/research/staged544-reversible-lattice-macro/MACRO.json b/research/staged544-reversible-lattice-macro/MACRO.json new file mode 100644 index 0000000000..33e97094fb --- /dev/null +++ b/research/staged544-reversible-lattice-macro/MACRO.json @@ -0,0 +1,102 @@ +{ + "kind": "residual", + "entrance": [], + "terminal": [ + 388, + 74, + 40, + 26, + 1 + ], + "recipe": { + "rank": 5, + "left": { + "matrix_rows": [ + 1, + 48, + 68, + 152, + 26, + 8, + 10, + 260, + 4 + ], + "offset": 0, + "quadratic_rows": [ + 0, + 18, + 0, + 8, + 2, + 0, + 0, + 0, + 0 + ], + "linear_Z4": [ + 2, + 3, + 2, + 3, + 2, + 0, + 0, + 0, + 0 + ], + "phase": 0 + }, + "right": { + "matrix_rows": [ + 1, + 80, + 388, + 8, + 58, + 82, + 260, + 120, + 384 + ], + "offset": 29, + "quadratic_rows": [ + 0, + 106, + 132, + 66, + 80, + 98, + 58, + 132, + 0 + ], + "linear_Z4": [ + 2, + 3, + 3, + 2, + 3, + 1, + 0, + 3, + 2 + ], + "phase": 0 + } + }, + "coverage": [ + { + "provider": "base", + "kind": "terminal", + "helper": 277, + "version": "new" + }, + { + "provider": "extra", + "kind": "terminal", + "helper": 277, + "version": "new" + } + ] +} diff --git a/research/staged544-reversible-lattice-macro/PROOF.md b/research/staged544-reversible-lattice-macro/PROOF.md new file mode 100644 index 0000000000..5a4e52b7d2 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/PROOF.md @@ -0,0 +1,197 @@ +# One actual rank-five residual on a finite lattice + +Chris R / Clear1nsight with substantial OpenAI Codex assistance. Apache-2.0. +This is a finite implementation and an admission discriminator, not a replacement +of the staged544 recursive provider or a new kappa. + +## Source and paid boundary + +PR3945 at `91f81d131252db704f945891da1ea54e29d46b8b` gives helper 277 +an empty entrance and terminal U=[388,74,40,26,1], in both providers. +`bw_adapters.py:S_of,main` constructs its residual T_U and lowers it to +L C_[5] R. The exact serialized L/R recipe is the corresponding PR3987 +descriptor at `fc536202fdaa924158789a5ef59ac079bbe21922`; frozen source and +recipe hashes are authenticated before tests. These definitions include all +global/relative phases. The source's charged object is a rank-five recursive +child, tensored with the other coordinates. Its exact compiler's `zero_state` +uses Gaussian integer numerators and a growing denominator; it is a semantic +evaluator, not a paid finite-precision implementation. + +We implement this actual 512-coordinate residual with spectator multiplicity f. +No scalar instruction, native mathematical map, selected frontier or recursive +paid profile is changed. The basis-size convention is 512f complex coordinates, +so there are 256f pairs at each of five layers, or 1280f pairs. A source caller +using f for a different tensor-factor exponent must convert that dimension; +there is no silent reuse of an incompatible f convention. + +## Reversible half-sum with one dirty word + +Data words have b bits, modulus M=2^b; scratch D has b+1 bits, modulus 2M. +Let a,c be signed b-bit integers and s=a+c or a-c. The following operations +are modular, with source sign-extension into the scratch word: + + D += a; D += (+/- c) + y += floor(unsigned(D)/2) + D -= (+/- c); D -= a + y -= floor(unsigned(D)/2) + y -= (D mod 2) * ((a mod 2) XOR (c mod 2)) + +The four scratch operations restore every possible initial D exactly. For +integers d,s, floor((d+s)/2)-floor(d/2) equals floor(s/2) plus the product +of their parities. Reducing d+s modulo 2M changes its half by a multiple of M, +which vanishes in y. Signed versus unsigned s has the same property. Thus this +implements y += floor(s/2) mod M independently of D. No low bit is discarded +from a data or scratch register; shifts are read-only source slices. The final +parity correction is essential: a=1,c=0,D=1 gives the wrong increment if it is +omitted. Reversing target updates implements the inverse accumulation. + +This costs seven real-word addition/subtraction/conditional-decrement +primitives per component. An explicitly constructed clean comparison starts +D=0 and omits the last two target corrections: five primitives. This comparison +is ours, not a claimed pre-existing physical implementation. Both compute the +same rounded map. The improvement is removal of the clean initialization +requirement for b+1 workspace bits, at a cost of two extra primitives per +half-sum. Scratch is dirty, not absent. + +## Literal bit realization and tariff + +The gate alphabet is NOT and generalized controlled-X with arbitrary positive +or negative controls. Source-controlled addition of 2^j flips target bits +k=b-1,...,j when source_j=1 and all target bits j,...,k-1 are one. +Descending order leaves the lower controls unchanged. Composing these increments +for each source bit is modular addition; reversing the gate list subtracts. +There are b(b+1)/2 gates, with no ancilla. Sign-extension into b+1 target bits +adds the sign bit at position b as well as its ordinary position; its cost is +b(b+3)/2+1 gates. A read-only right shift uses the existing scratch bits 1..b. + +The parity-controlled decrement splits into the two disjoint conjunctions +D0 & a0 & !c0 and D0 & !a0 & c0. For each conjunction, descending target-bit +flips controlled on lower zeros implement decrement. Cost:2b gates; the controls +are preserved source/scratch bits, so no predicate scratch is hidden. A real +word SWAP uses3b CNOTs. Negation uses b NOTs followed by b increment gates. +These conservative counts intentionally retain canceling gates. + +The dirty half-sum costs 3b²+9b+4 gates. Its clean counterpart costs +(5b²+13b+8)/2. These circuits are explicitly simulated against the modular +arithmetic specification on all small-bit states. They are finite Boolean +permutations with no clean ancilla. The next paragraphs supply bounded-fanin +counts; the supplier's recursive stock/tape admission remains separate. + +For n>=3 controls, the classical borrowed-bit construction of Barenco et al., +[Elementary gates for quantum computation, Lemma 7.2](https://arxiv.org/pdf/quant-ph/9503016), +implements controlled-X with 4n-8 literal Toffoli gates and n-2 arbitrary +borrowed bits restored. Here is a self-contained reconstruction. Set +A=Toffoli(a1,a2;d1). Let F compute the chain d2^=d1*a3,..., +d[n-2]^=d[n-3]*a[n-1], flip t by d[n-2]*an, then undo that chain. +For n=3, F is just Toffoli(d1,a3;t). The sequence F,A,F,A cancels all terms +involving the initial dirty bits; changing d1 by a1*a2 changes F's target +increment by the product of all controls. F has 2n-5 gates. Negative controls +are conjugated by X before and after. No relative-phase substitute is used. + +Every actual pair gate has at most b+2 controls and 5b+1 available data/scratch +bits. After excluding its controls and target, at least4b-2 bits remain, enough +for the at most b borrowed bits. They are selected within the existing pair +and scratch, returned after each gate; no additional clean or dirty workspace +is allocated. This requires transient access to those actual bits, explicitly +part of this implementation's interface. Each generalized gate costs at most +4b core elementary gates plus2(b+2) X gates, giving the bound below. +The executable emits literal X/CNOT/Toffoli gate lists, verifies the borrowed +ladder on every small state, and tests complete pair circuits with dirty data. + +## Reversible C pair and completed numerical error + +For C=((1+i)I+(1-i)X)/2, define t(d) by componentwise floor of (1-i)d/2. +On two complex words execute + + x -= y; y += t(x); x *= i; x += y. + +Each half of t uses the preceding accumulator with the same dirty scratch. +The exact inverse is x-=y; x*=-i; y-=t(x); x+=y. Both are permutations on +all b-bit data states, including overflowing states, and return arbitrary D. +Four ordinary real additions and two half-sums give18 word primitives plus +one quarterturn; the clean comparison uses14. With the bit circuit above the +pair costs 8b²+25b+8 gates dirty, versus 7b²+20b+8 clean. + +Numerical interpretation is separate from modular reversibility. Let grid +spacing be Delta. When data operations do not wrap, t(d)=(1-i)d/2+e where +each real component of e lies in [-Delta/2,0]. The exact C output is perturbed +by (e,e), whose two-complex-coordinate Hilbert norm is at most Delta. +This applies to the exact inverse map as well: applying the unitary C^-1 +to the forward error preserves its norm. Alternatively the inverse's explicit +formula gives the same bound directly. Arbitrary dirty D cannot change output. + +At one layer, 256f disjoint pairs contribute squared error at most256f Delta², +so its Hilbert error is at most16 sqrt(f) Delta. Exact C layers and L/R are +unitary; telescoping five layers bounds the completed macro and its inverse by +80 sqrt(f) Delta. This is an absolute bound for arbitrary data, not a sampled +state claim. The scalar inverse controls do not establish linearity of the +rounded transformation. + +With initial whole-block Hilbert norm at most H, every completed layer has +norm at most B=H+80 sqrt(f) Delta. Within a pair the difference has magnitude +at most2B; the half-sum target has magnitude below3B+Delta. Thus signed data +range greater than4B+2Delta is a conservative sufficient no-wrap condition. +Scratch may wrap freely and does not need a numerical range premise. The +sign-extended numerator lives modulo2M and its wrap is handled by the proved +half-accumulation identity. If Delta<=H/(128 sqrt(f)), signed range8H suffices. +For H a power of two and Delta=H2^-p, choose b=p+4, giving that range. + +## Full wrapper and comparison bill + +Each exact monomial is implemented by its fixed coordinate-permutation cycles +and coordinate phases. A cycle of length k takes k-1 complex swaps, decomposed +into two real swaps. Multiplication by i or -i takes a real swap and a real +negation; -1 takes two negations. These use only live coordinate words. +The exact source recipe gives L:1248 real swaps,512 negations; R:1264 swaps, +512 negations per spectator lane. Both phase histograms are [128,128,128,128]. +No full vector copy is needed: cycle swaps use existing data words. The Python +simulator's allocated lists are not claimed as the circuit's workspace. + +The completed rank-five residual therefore costs, per spectator lane: + +* 1280 C pairs,23040 real-word addition/subtraction/conditional-decrement + primitives,3792 real swaps and 2304 real negations; +* 10240b²+41584b+10240 generalized controlled-X/NOT gates; +* one arbitrary dirty (b+1)-bit word, restored exactly and reusable serially + across all pairs and f lanes. The 1024bf data bits are not counted as scratch. + +The constructed clean comparison uses17920 word primitives, the same routing +and quarterturns, and 8960b²+35184b+10240 gates per lane. Dirty operation costs +5120 additional word primitives or1280(b²+5b) additional gates per lane. +Serial depth is at most the total gate count. Five conceptual butterfly layers +do not mean five physical clock steps when sharing one scratch word. + +After borrowed-bit decomposition, the complete dirty macro has at most +`(6b+4)(10240b²+41584b+10240)f` elementary reversible gates and no additional +workspace. RESULT.json records exact X/CNOT/Toffoli counts rather than treating +this coarse upper bound as measured. For example b=32 gives, per spectator +lane, 5482752 X,1031936 CNOT and 442109184 Toffoli gates, versus 76032 X,950016 +CNOT and 380425984 Toffoli for the constructed clean comparison. These large +constructive counts make no speed or recursive-tariff affordability claim. + +## Mapping to PR3994, and why replacement stops here + +PR3994's full-state-cut theorem permits each completed cut an absolute defect +at most H2^(-beta-25). This single macro meets that allowance whenever +80 sqrt(f) Delta <= H2^(-beta-25). For power-of-two H, the sufficient choice +p >= beta+32+ceil(log2(sqrt(f))) meets it. This is an explicit module-to-cut +mapping, conditional on the actual caller placing this macro at that cut and +paying its time/space bill. It is not an improved selected stock coefficient. + +Local bijectivity does NOT preserve the provider's linear dirty-cleanup proof. +The exact source's `bw_transport.py` applies row-linear additions, scales and +operator composition; substituting a nonlinear rounded map is outside that +contract. For the actual rank-five L C_[5] R above, let h=s be real unit input +at coordinate0. The checked witness Q(h+s)-Q(h)-Q(s) has 24 nonzero complex +coordinates; coordinate0 is1 grid unit. Thus a dirty helper increment transformed +before and after adding s depends on h and is not Q(s). This is an actual +source-bound macro witness, not merely a generic nonlinear example. + +Destructive coordinate flooring is worse: even one C followed by its adjoint +and flooring fails to restore the input ((1,0),(0,0)); the verifier records its +round-trip result. Our lift restores it exactly, but the preceding additivity +failure remains. A full implementation must account for its nonlinear errors +and exact borrowed-bit cleanup jointly, or retain extra reversible information +in an affordable lifecycle. A single rank-five child charge is not evidence +that the explicit scalar circuit above fits the recursive tariff. We stop +implementation expansion at that missing actual caller/native budget. diff --git a/research/staged544-reversible-lattice-macro/README.md b/research/staged544-reversible-lattice-macro/README.md new file mode 100644 index 0000000000..65103a43d7 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/README.md @@ -0,0 +1,84 @@ +# Staged544 residual: replace one clean word with dirty reversible scratch + +This implements the actual rank-five residual for helper 277 in both pinned +PR3945 providers on a finite Gaussian lattice. Reversible numerical lifting and +finite-state bit circuits replace a destructive rounding step. One arbitrary +dirty `(b+1)`-bit workspace word is returned exactly, with no clean ancillary +bits in the explicit generalized-controlled-X circuit model. + +Compared with our explicitly constructed clean-accumulator implementation, this +removes `(b+1)` required clean bits and adds four real-word operations per C pair. +The comparison is **a clean-space tradeoff, not a speedup or a paid supplier +improvement**. Both implementations realize the same rounded map. The source +compiler is an exact operator evaluator; it does not provide this physical +finite-grid baseline. + +For one 512-coordinate spectator lane, the completed source-bound `L C_[5] R` +macro has 1280 pairs. Full dirty implementation:23040 real-word arithmetic +primitives,3792 real swaps,2304 real negations, one dirty word reusable serially. +The bit realization costs at most `10240b²+41584b+10240` NOT/generalized +controlled-X gates. The clean comparison costs 17920 word primitives and +`8960b²+35184b+10240` gates, with the same routing. The generalized gates are +also compiled into literal X/CNOT/Toffoli gates, borrowing only existing pair +bits and restoring them after each gate. At b=32, the dirty macro costs 442109184 +Toffolis per lane versus 380425984 for the clean comparison, plus separately +counted X/CNOT gates. Recursive tariff/owner admission remains unknown; this +concrete implementation is expensive. + +For `f` spectator lanes and grid spacing Delta, the completed Hilbert error is +at most `80 sqrt(f) Delta`. Every scratch bit is restored for **every** finite +data/scratch bit pattern. Numerical error claims additionally require the +proved no-wrap data range; scratch itself may overflow freely. The explicit +allowance maps this macro to PR3994's full-state logical-cut bound, retaining +the caller's tensor/range/lifecycle premises. + +**Why direct replacement stops:** the actual rounded rank-five macro is +nonlinear. For dirty helper and source `h=s=e0`, `Q(h+s)-Q(h)-Q(s)` has 24 +nonzero coordinates. Local reversible inversion therefore does not preserve +the whole provider's linear compensation/borrowed-buffer identities after +intervening arithmetic. No provider replacement, selected stock coefficient, +new kappa, or frontier change is claimed. + +## Reproduce + +Run `python3 -B verify.py` and `python3 -O -B verify.py` from this directory. +Default verification is read-only and uses only the standard library. Optional +`--print-result` prints recomputed mathematical evidence without writing files. +The repository registry is `python3 scripts/research_package.py --package +research/staged544-reversible-lattice-macro` from the repository root. + +Checks authenticate source bytes, bind helper 277 in both actual providers, +replay the credited PR3987 canonical-frame/recipe oracle on all 512 columns, +exhaust 279552 modular half-sum cases and 67584 pair states, and compare literal +bit circuits with the arithmetic specification on 17408 half-sum cases and 2048 +pair states. They also check actual full-macro dirty return/inversion, exact +Gaussian error bounds, the nonlinear witness, and meaningful source/parity/ +sign-extension/phase mutations. Finite tests support the parameterized proof; +they do not replace it or prove the full multiplication theorem. + +See PROOF.md for the derivation, RESULT.json for exact replay output, +LEDGER.json for the complete boundary/cost status and FROZEN-SOURCES.json for +immutable source pins. Exact predecessor notices are retained under frozen/. + +## Open next questions + +1. Bind the explicit bounded-fanin circuit to an affordable actual caller and + serial or parallel scratch lifecycle. The rank-five recursive charge alone + cannot pay the scalar circuit by declaration; optimize only after stating + the real allowance. +2. Resolve nonlinear dirty compensation across actual intervening arithmetic. + First replay the exhibited actual-macro witness through one concrete helper + lifetime with reversible recovery information fully charged. Do not infer + whole-word restoration from local invertibility. +3. Bind the actual caller's spectator dimension, dirty amplitude and budget to + the completed-error bound. Only then derive selected stock/tape coefficients. + +Credit Dugongue, dataisfire, Jeremy Kothe, Sagar Thakrar, roger-sato, Arham Tahir, +DreamingOfClouds, chafreaky, Cinna Davis, and the preserved native/owner/outer +lineage. Chris R / Clear1nsight with substantial OpenAI Codex assistance. No +independent human or proof-kernel review is asserted. + +The dirty borrowed-bit controlled-X decomposition is credited to +[Barenco et al., Lemma 7.2](https://arxiv.org/pdf/quant-ph/9503016), not presented +as a new gate theorem. Its finite implementation and application here are +checked independently of that paper's diagram. diff --git a/research/staged544-reversible-lattice-macro/RESULT.json b/research/staged544-reversible-lattice-macro/RESULT.json new file mode 100644 index 0000000000..5343e5915b --- /dev/null +++ b/research/staged544-reversible-lattice-macro/RESULT.json @@ -0,0 +1,164 @@ +{ + "half_exhaustive_cases": 279552, + "pair_exhaustive_cases": 67584, + "literal_bit_half_cases": 17408, + "literal_bit_pair_cases": 2048, + "credited_exact_canonical_recipe_columns": 512, + "rank5_full_cases": 24, + "rank5_max_error_squared_numerator_over_1024": 2212864, + "nonlinear_witness_input": "h=s=e0 real one grid unit", + "nonlinear_witness_first": [ + [ + 0, + [ + 1, + 0 + ] + ], + [ + 26, + [ + -2, + -1 + ] + ], + [ + 40, + [ + -1, + 1 + ] + ], + [ + 41, + [ + -1, + -1 + ] + ], + [ + 50, + [ + 0, + -1 + ] + ], + [ + 51, + [ + 0, + -1 + ] + ], + [ + 74, + [ + 1, + -1 + ] + ], + [ + 75, + [ + 1, + 0 + ] + ] + ], + "nonlinear_nonzero_coordinates": 24, + "naive_roundtrip": [ + [ + 0, + -1 + ], + [ + -1, + -1 + ] + ], + "routing": { + "left": { + "complex_swaps": 496, + "real_swaps": 1248, + "real_negations": 512, + "phase_histogram": [ + 128, + 128, + 128, + 128 + ], + "cycles": 16 + }, + "right": { + "complex_swaps": 504, + "real_swaps": 1264, + "real_negations": 512, + "phase_histogram": [ + 128, + 128, + 128, + 128 + ], + "cycles": 8 + } + }, + "pair_count_per_spectator": 1280, + "real_word_add_primitives_per_spectator": 23040, + "clean_comparison_word_add_primitives": 17920, + "total_real_negations_per_spectator": 2304, + "total_real_swaps_per_spectator": 3792, + "dirty_gate_polynomial_coefficients": [ + 10240, + 41584, + 10240 + ], + "clean_gate_polynomial_coefficients": [ + 8960, + 35184, + 10240 + ], + "dirty_scratch_bits": "b+1, restored; reused serially across all spectator lanes", + "error_bound": "80 sqrt(f) grid units for f spectator lanes", + "status": "PASS_FINITE_MACRO_NOT_PROVIDER_REPLACEMENT", + "dirty_ladder_full_states": 10912, + "elementary_full_pair_states": 2112, + "elementary_bill_per_spectator": { + "8": { + "dirty": { + "X": 389376, + "CNOT": 267392, + "Toffoli": 6765824 + }, + "constructed_clean": { + "X": 20736, + "CNOT": 246912, + "Toffoli": 5437184 + } + }, + "32": { + "dirty": { + "X": 5482752, + "CNOT": 1031936, + "Toffoli": 442109184 + }, + "constructed_clean": { + "X": 76032, + "CNOT": 950016, + "Toffoli": 380425984 + } + }, + "64": { + "dirty": { + "X": 21448960, + "CNOT": 2051328, + "Toffoli": 3557018880 + }, + "constructed_clean": { + "X": 149760, + "CNOT": 1887488, + "Toffoli": 3087619840 + } + } + }, + "bounded_fanin_upper_bound": "(6b+4)(10240b^2+41584b+10240)f elementary gates; no additional workspace" +} diff --git a/research/staged544-reversible-lattice-macro/SOURCES.json b/research/staged544-reversible-lattice-macro/SOURCES.json new file mode 100644 index 0000000000..3eaa7ce796 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/SOURCES.json @@ -0,0 +1,26 @@ +{ + "schema_version": 1, + "base_commit": "20ecf2891d80b5acf18d980b2164fb44ea7faa90", + "files": [ + { + "path": "certificates/selected-result.json", + "usage": "provenance", + "git_blob": "b1fea0c94436b236cc2b7d41a7be032811b94c81", + "sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "path": "docs/research/agent-task-catalog.json", + "usage": "provenance", + "git_blob": "67f085acd86acd7d4e03922d9cf4b26bca66fed5", + "sha256": "47b42433f5a85809a3aadd29c2c339da2c6ed728e4f7762df6b88bccb7874cf0" + } + ], + "external_snapshot": { + "manifest": "FROZEN-SOURCES.json", + "heads": [ + "91f81d131252db704f945891da1ea54e29d46b8b", + "fc536202fdaa924158789a5ef59ac079bbe21922" + ], + "relation": "Exact public predecessor bytes retained and authenticated; not asserted to be Git ancestors. PR3994 eb2ac25838a3d39ac8fd6acfa62b8b613c847629 completed-cut theorem reused with explicit premise." + } +} diff --git a/research/staged544-reversible-lattice-macro/TASK.json b/research/staged544-reversible-lattice-macro/TASK.json new file mode 100644 index 0000000000..7d71cd816a --- /dev/null +++ b/research/staged544-reversible-lattice-macro/TASK.json @@ -0,0 +1,89 @@ +{ + "schema_version": 1, + "task_id": "selected-stock-envelope", + "priority_revision": 6, + "base_commit": "20ecf2891d80b5acf18d980b2164fb44ea7faa90", + "original_card": { + "id": "selected-stock-envelope", + "question": "What explicit uniform stock envelope does the actual selected stopped producer supply at one bootstrap stage?", + "starting_points": [ + "research/selected-bootstrap-stock-audit/README.md", + "research/bootstrap-cutoff-time-space-split/README.md", + "certificates/selected-result.json", + "docs/research/community-efficient1000-review.md", + "research/stock-margin-chain/README.md" + ], + "methods": [ + "Derive a source-bound reserve recurrence at the actual selected atom widths, separating parent stock from completed inner borrowing.", + "Find an exact missing implication or counterexample to a proposed selected-stage stock envelope." + ], + "acceptance_gate": "Bind every coefficient and depth factor to the selected producer and state the width domain. Compare a proved envelope with the sufficient cutoff guard; a large numerical headroom or a historical m=120 coefficient is not a selected m=73 proof.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read #2972 stock-margin chain and the selected stock audit. The new source archive reports the remaining cutoff comparisons, but leaves every actual stock coefficient unresolved; it is not an independently validated reserve envelope.", + "scope": "Source-bound orientation only. Read the named package and review before relying on its local evidence; this command is not its replay or supplier admission." + }, + "first_experiment": "Choose one actual selected producer/stage and derive its parent reserve and depth coefficient from source. Check whether newer handoffs already cover that exact obligation. Stop with the missing implementation lemma if it cannot be bounded; do not rerun #2972 cutoff/headroom arithmetic as a new contribution.", + "bottleneck_link": "This reduces a concrete inherited implementation obligation without confusing unchanged kappa arithmetic with a completed theorem.", + "allowed_variations": [ + "One stage or one explicit reserve/depth implication.", + "An independently checked same-domain proof repair, retaining all remaining assumptions." + ], + "scope_change_triggers": [ + "Importing the historical 57604 or 252 allowance without a selected-producer binding.", + "Calling a conditional fit lemma a full outer-proof adoption.", + "Replacing an actual selected stock coefficient with cutoff comparisons or a conditional fit inequality." + ], + "overlap_terms": [ + "selected stock", + "stock envelope", + "bootstrap cutoff", + "1956", + "1965", + "1990", + "2972", + "stock-margin-chain", + "actual_stock_coefficient" + ], + "existing_checks": [ + { + "scope": "Retained stock audit identifies missing actual selected-stage coefficients; later cutoff-chain arithmetic does not supply them.", + "evidence": "docs/research/research-family-status.md#revision-6-handoffs-source-archives-awaiting-independent-validation", + "remaining": "Derive one actual reserve/depth coefficient from the selected producer.", + "status": "reviewed", + "source_commit": "836b19bfa309ceafbc8ee32a15e8c4b10dde7e11", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + } + ] + }, + "scope_status": "changed", + "actual_scope": "Finite bit-level realization of the actual helper277 rank5 residual on a Gaussian lattice, dirty workspace tradeoff against an explicitly constructed clean baseline, and actual macro nonadditivity obstruction to provider substitution.", + "scope_change_reason": "Explicit assigned staged544 physical precision follow-up to PR3994. This closes one finite macro arithmetic/scratch implementation; it does not derive selected m73 stock or uniform supplier admission.", + "bottleneck_link": "Connect completed-output error to an actual reversible arithmetic implementation and reject unsupported exact dirty-cleanup substitution.", + "budget_minutes": 60, + "stop_rule": "Finish one source-bound finite macro, full time/space/error ledger, and nonlinear admission discriminator; stop before a recursive replacement without caller budget.", + "outcome": "completed", + "author": "Chris R / Clear1nsight", + "ai_assistance": "Substantial OpenAI Codex assistance. Separate mathematical subtask within a coordinated multi-agent contribution batch; no independent human or proof-kernel review.", + "evidence": "RESULT.json, PROOF.md, LEDGER.json and VALIDATION.json", + "open_questions": [ + { + "question": "Can the finite bit circuit fit an actual recursive caller budget while preserving all dirty-helper cleanup?", + "why_it_matters": "Local reversible approximation alone does not preserve linear compensation after interleaved arithmetic.", + "first_step": "Bind one actual helper lifetime and recovery stock to the explicit nonadditivity witness and full bit bill.", + "blocked_by": "Caller range, tensor multiplicity, recursive tariff and nonlinear recovery contract." + } + ], + "checkpoint": { + "utc": "2026-10-19T08:43:57Z", + "canonical_main": "20ecf2891d80b5acf18d980b2164fb44ea7faa90", + "priority_revision": 6, + "fetch": "Root canonical shell fetch failed DNS; own GitHub connector confirmed main20ec and existing exact object used for new worktree. No successful shell fetch claim.", + "overlap": "702 open PR bodies complete7pages at08:39:35UTC; partial1166 discussions checked by root. No exhaustive novelty claim." + } +} diff --git a/research/staged544-reversible-lattice-macro/VALIDATION.json b/research/staged544-reversible-lattice-macro/VALIDATION.json new file mode 100644 index 0000000000..3050dba823 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/VALIDATION.json @@ -0,0 +1,61 @@ +{ + "status": "Scientific checks passed; repository registry/export/publication recorded after their actual runs", + "python": "3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]", + "platform": "Linux-7.0.0-38-generic-x86_64-with-glibc2.39", + "source_scope": "Actual pinned PR3945 words and native sources plus PR3987 exact recipe/oracle; all frozen hashes authenticated before science", + "commands": [ + "python3 -B verify.py", + "python3 -O -B verify.py" + ], + "bounded_same_team_review": "Root separately reviewed final PROOF.md and circuit.py: signed half identity, actual L/R binding, elementary ladder/negative controls/counts, range and cut mapping found consistent. Graph agent independently implemented modular and literal elementary-pair controls, including arbitrary dirty inputs and small-bit overflow boundaries. No independent human or proof-kernel review.", + "independent_graph_review": "round3-graph-moment-session/precision-review/REVIEW-RESULT.json and LITERAL-RESULT.json retained by coordinating session; not included/executed by default registry", + "failed_attempts": [ + "Result comparison initially compared Python tuples against JSON lists; normalized the entire evidence object before final verification.", + "Two prose patch anchors failed before applying; corrected against exact current text." + ], + "unrun": [ + "Complete provider replacement or whole-word rounded cleanup", + "Actual recursive tariff/owner/stock admission", + "Uniform all-size or selected-stage supplier theorem", + "Proof-kernel or human review" + ], + "registered_replay": { + "status": "PASS", + "normal_seconds": 4.017, + "optimized_seconds": 4.771, + "log": "registered-candidate.log" + }, + "git_free_replay": { + "seconds": 8.928, + "files": 25, + "read_only": true, + "Git_free": true, + "bytes_unchanged": true, + "runs": [ + { + "flags": [ + "-B" + ], + "exit": 0, + "stdout": "{\"status\": \"PASS_FINITE_MACRO_NOT_PROVIDER_REPLACEMENT\", \"seconds\": 4.474, \"half_cases\": 279552, \"pair_cases\": 67584, \"full_cases\": 24}\n", + "stderr": "" + }, + { + "flags": [ + "-O", + "-B" + ], + "exit": 0, + "stdout": "{\"status\": \"PASS_FINITE_MACRO_NOT_PROVIDER_REPLACEMENT\", \"seconds\": 4.158, \"half_cases\": 279552, \"pair_cases\": 67584, \"full_cases\": 24}\n", + "stderr": "" + } + ], + "scope": "25-file copy at test time; later CREDITS and documentation updates do not change scientific runtime; final exact copy verification follows" + }, + "latest_overlap": { + "utc": "2026-10-19T09:04:00Z", + "canonical_main": "20ecf2891d80b5acf18d980b2164fb44ea7faa90", + "open_pr_bodies": 718, + "coverage": "Root complete open-body refresh; Discussion coverage partial; no direct lattice-macro overlap identified." + } +} diff --git a/research/staged544-reversible-lattice-macro/VERIFY.json b/research/staged544-reversible-lattice-macro/VERIFY.json new file mode 100644 index 0000000000..518e31c074 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/VERIFY.json @@ -0,0 +1,28 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 180, + "checks": "Source-bound actual rank5 recipe; exhaustive modular/bit-state implementation, dirty returns, error bill, nonlinear and production mutation controls." + }, + { + "argv": [ + "{python}", + "-O", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 180, + "checks": "Same mathematical admission/rejection checks under optimized Python; explicit checks cannot disappear." + } + ] +} diff --git a/research/staged544-reversible-lattice-macro/bits.py b/research/staged544-reversible-lattice-macro/bits.py new file mode 100644 index 0000000000..d7aced0da5 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/bits.py @@ -0,0 +1,65 @@ +"""Literal ancilla-free generalized-controlled-X circuit simulator. + +Each counted step flips one bit under a conjunction of other bits (positive +or negative controls). This is an explicit gate alphabet, NOT a Toffoli count. +Arbitrary controlled-X decomposition into the supplier's native gates is open. +""" +def add(y,x,b,width=None,extend=False,inverse=False): + width=b if width is None else width + sources=[(j,j)for j in range(b)]+([(b,b-1)]if extend else []) + gates=[(j,k,s)for j,s in sources for k in range(width-1,j-1,-1)] + if inverse:gates.reverse() + for j,k,s in gates: + mask=((1<<(k-j))-1)<>s&1)and y&mask==mask:y^=1<>1,b,inverse=reverse);n+=k + d,k=add(d,c,b,b+1,True,not subtract);n+=k + d,k=add(d,a,b,b+1,True,True);n+=k + if not clean: + y,k=add(y,d>>1,b,inverse=not reverse);n+=k + y,k=parity_decrement(y,a,c,d,b,reverse);n+=k + return y,d,n + +def negate(x,b): + x^=(1<>c&1)==v for c,v in controls):state^=1<> (y.bit_length() - 1) & 1: x ^= y + if x: return False + return True +def Kop(G_cols): + """BW: K_G = perm(G) then diag(Q), Q = I + G^-T G^-1: PR2226's monomial() and the conjugator inside clifford_exact.canonical_frame.""" + G = transpose(tuple(G_cols), n); gi = inv(G, n) + Q = tuple((1 << i) ^ sum(parity(gi_i & gi_j) << j for j, gi_j in enumerate(transpose(gi, n))) for i, gi_i in enumerate(transpose(gi, n))) + return perm(n, G).then(diag(n, Q)) +def numeric_K(G_cols): + import numpy as np + pv, ph = bw_gauss.monomial(list(G_cols), n) + N = 1 << n; re = np.zeros((N, N), dtype=np.int64); im = np.zeros((N, N), dtype=np.int64) + unit = [(1, 0), (0, 1), (-1, 0), (0, -1)] + for x in range(N): re[pv[x], x], im[pv[x], x] = unit[ph[x]] + return re, im, 0 +def warp_ok(G_cols, rec): + """BW: the serialized monomial equals PR2226's exact numpy K_G on all 512 columns (indep. decode) and its op decodes to K_G exactly.""" + m = bw_gauss.recipe_matrix(rec, n) + if not bw_gauss.equal_scaled(numeric_K(G_cols), m): return False + dec = monomial_op(rec); ref = Kop(G_cols) + return dec.tab == ref.tab and dec.zero_state() == ref.zero_state() + +def main(): + c = json.load(gzip.open(sys.argv[1])); frames = c['frames']; v = c['v'] + starts = sorted({c['start'][r] for r in range(2 * v, len(c['start'])) if c['start'][r] != 0 and c['final'][r] == 1}) + # HPE: (entrance, terminal) pairs of helpers ending at a proper subspace; key 'E:U'. Inherited words have none. + ends = sorted({(c['start'][r], c['final'][r]) for r in range(2 * v, len(c['start'])) if c['final'][r] != 1}) + # COLD-HPE: e == 0 (a cold helper, entrance = bottom, T_0 = I) is allowed: the (0, U) recipe is keyed '0:U' + assert all(len(frames[u]) < n and _contains(frames[u], frames[e]) for e, u in ends) + cold_ends = [(e, u) for e, u in ends if e == 0] + recipes = {} + for f in starts: + U = frames[f]; rec, compiled = lower_child(S_of(U)) + recipes[str(f)] = dict(frame=f, vectors=list(U), entrance_rank=len(U), rank=rec['rank'], left=rec['left'], right=rec['right']) + for e, u in ends: + E, U = frames[e], frames[u]; rec, compiled = lower_child(S_of(E, U)) + recipes['%d:%d' % (e, u)] = dict(frame=e, terminal=u, vectors=list(E), terminal_vectors=list(U), entrance_rank=len(E), + terminal_rank=len(U), rank=rec['rank'], left=rec['left'], right=rec['right']) + # BW: monomial recipes of the warps K_G (anticipatory dirty borrowing, PR2226): one per operator, serialized like a wrapper monomial + warp_recipes = {} + for w in c.get('warps', []): + _, rec_k = mono_of(Kop(w['G_columns'])) + warp_recipes[str(w['op'])] = dict(op=w['op'], from_frame=w['from_frame'], to_frame=w['to_frame'], G_columns=list(w['G_columns']), K=rec_k) + Path(sys.argv[2]).write_text(json.dumps(dict(status='RESIDUAL_ADAPTER_RECIPES', recipes=recipes, warps=warp_recipes), sort_keys=True, separators=(',', ':')) + '\n') + # ---- independent decode of the serialized file + data_all = json.loads(Path(sys.argv[2]).read_text()); data = data_all['recipes'] + dot = lambda a, b: bin(a & b).count('1') & 1 + detail = [] + for f in starts: + rec = data[str(f)]; U = frames[f] + assert wrapped_ok(U, rec), ('wrapper product is not C_[w] x I', f) + detail.append(dict(frame=f, entrance_rank=len(U), residual_width=n - len(U), vectors=list(U), all_even_weight=all(bin(x).count('1') % 2 == 0 for x in U), + totally_isotropic=all(dot(a, b) == 0 for a in U for b in U))) + hdetail = [] + for e, u in ends: # HPE: independent decode, residual width = dim U - dim E + rec = data['%d:%d' % (e, u)]; E, U = frames[e], frames[u] + assert wrapped_ok(E, rec, U), ('HPE wrapper product is not C_[w] x I', e, u) + hdetail.append(dict(frame=e, terminal=u, entrance_rank=len(E), terminal_rank=len(U), residual_width=len(U) - len(E))) + controls = [] + def reject(name, fn): + f = starts[0]; rec = copy.deepcopy(data[str(f)]); fn(rec) + if wrapped_ok(frames[f], rec): raise AssertionError('mutated wrapper accepted: ' + name) + controls.append(name) + reject('wrong global phase', lambda r: r['right'].__setitem__('phase', (r['right']['phase'] + 1) % 4)) + reject('wrong translation', lambda r: r['left'].__setitem__('offset', r['left']['offset'] ^ 1)) + reject('wrong quadratic form', lambda r: r['right'].__setitem__('quadratic_rows', [x ^ 2 if i == 0 else x for i, x in enumerate(r['right']['quadratic_rows'])]) if False else r['right']['linear_Z4'].__setitem__(0, (r['right']['linear_Z4'][0] + 2) % 4)) + reject('sides swapped', lambda r: (r.__setitem__('left', r['right']), r.__setitem__('right', r['left']))) + reject('wrong width', lambda r: r.__setitem__('rank', r['rank'] + 1)) + if ends: # HPE controls on the first (E, U) pair + e, u = next((p for p in ends if p[0] != 0), ends[0]); rec0 = data['%d:%d' % (e, u)] # COLD-HPE: an entering pair if any (= ends[0] without cold ends) + def hreject(name, ok): + if ok: raise AssertionError('HPE mutation accepted: ' + name) + controls.append(name) + hreject('hpe: U-wrapper decoded against a FULL ending', wrapped_ok(frames[e], rec0)) + hreject('hpe: width misreported as 9 - dim E', wrapped_ok(frames[e], dict(rec0, rank=n - len(frames[e])), frames[u])) + other = next(f for f in range(len(frames)) if f != u and len(frames[f]) == len(frames[u]) and _contains(frames[f], frames[e])) + hreject('hpe: wrong terminal hyperplane', wrapped_ok(frames[e], rec0, frames[other])) + fe = next(((e2, u2) for e2, u2 in ends if str(e2) in data), None) + if fe: # an entrance shared with FULL-ended helpers: R_{E,FULL} must not serve as R_{E,U} + r2 = data['%d:%d' % fe] + hreject('hpe: pre wrapper resolved to the FULL recipe R_{E,FULL}', wrapped_ok(frames[fe[0]], dict(r2, right=data[str(fe[0])]['right']), frames[fe[1]])) + hreject('hpe: wrong global phase', wrapped_ok(frames[e], dict(rec0, left=dict(rec0['left'], phase=(rec0['left']['phase'] + 1) % 4)), frames[u])) + if cold_ends: # COLD-HPE controls on the first cold pair (0, U): factor_iff_pre says only R_{0,U} itself may precede + e, u = cold_ends[0]; recc = data['%d:%d' % (e, u)]; E, U = frames[e], frames[u] + ID = dict(matrix_rows=[1 << i for i in range(n)], offset=0, quadratic_rows=[0] * n, linear_Z4=[0] * n, phase=0) + assert monomial_op(ID).tab == identity(n) # the control's wrapper really is the identity + def creject(name, ok): + if ok: raise AssertionError('cold HPE mutation accepted: ' + name) + controls.append(name) + creject('cold hpe: identity pre wrapper instead of R_{0,U}', wrapped_ok(E, dict(recc, right=ID), U)) + creject('cold hpe: identity post wrapper instead of L_{0,U}', wrapped_ok(E, dict(recc, left=ID), U)) + creject('cold hpe: no wrappers (cold FULL convention L = R = I)', wrapped_ok(E, dict(recc, left=ID, right=ID), U)) + creject('cold hpe: U-wrapper decoded against a FULL ending', wrapped_ok(E, recc)) + creject('cold hpe: width misreported as 9', wrapped_ok(E, dict(recc, rank=n), U)) + other = next(f for f in range(len(frames)) if f != u and len(frames[f]) == len(frames[u])) + creject('cold hpe: wrong terminal hyperplane', wrapped_ok(E, recc, frames[other])) + creject('cold hpe: wrong global phase', wrapped_ok(E, dict(recc, right=dict(recc['right'], phase=(recc['right']['phase'] + 1) % 4)), U)) + ent = next((p for p in ends if p[0] != 0 and p[1] == u), None) + same = lambda x, y: monomial_op(x).tab == monomial_op(y).tab and monomial_op(x).zero_state() == monomial_op(y).zero_state() + if ent and not same(data['%d:%d' % ent]['right'], recc['right']): # an entering helper ending at the same U: its R_{E,U} must not serve as R_{0,U} + creject('cold hpe: pre wrapper resolved to an entering recipe R_{E,U}', wrapped_ok(E, dict(recc, right=data['%d:%d' % ent]['right']), U)) + wdetail = [] + for w in c.get('warps', []): # BW: independent decode of every warp recipe, then mutation controls on the first warp + rec = data_all['warps'][str(w['op'])] + assert rec['G_columns'] == w['G_columns'] + assert warp_ok(w['G_columns'], rec['K']), ('warp recipe differs from the exact monomial K_G', w['op']) + wdetail.append(dict(op=w['op'], from_frame=w['from_frame'], to_frame=w['to_frame'], columns_checked=1 << n)) + if c.get('warps'): + w0 = c['warps'][0]; k0 = data_all['warps'][str(w0['op'])]['K'] + def wreject(name, ok): + if ok: raise AssertionError('warp mutation accepted: ' + name) + controls.append(name) + wreject('warp: wrong global phase', warp_ok(w0['G_columns'], dict(k0, phase=(k0['phase'] + 1) % 4))) + wreject('warp: wrong translation', warp_ok(w0['G_columns'], dict(k0, offset=k0['offset'] ^ 1))) + wreject('warp: wrong linear phase', warp_ok(w0['G_columns'], dict(k0, linear_Z4=[(k0['linear_Z4'][0] + 2) % 4] + k0['linear_Z4'][1:]))) + wreject('warp: wrong quadratic form', warp_ok(w0['G_columns'], dict(k0, quadratic_rows=[k0['quadratic_rows'][0] ^ 2, k0['quadratic_rows'][1] ^ 1] + k0['quadratic_rows'][2:]))) + wreject('warp: recipe of another operator', warp_ok(w0['G_columns'], data_all['warps'][str(c['warps'][1]['op'])]['K'])) + wreject('warp: inverse recipe used as the warp', warp_ok(w0['G_columns'], mono_of(Kop(w0['G_columns']).adjoint())[1])) + G2 = list(w0['G_columns']); G2[0] ^= G2[1] + wreject('warp: wrong G (frame-changed column)', warp_ok(G2, k0)) + sing = list(w0['G_columns']); sing[1] = sing[0] + try: Kop(sing); raise SystemExit('non-invertible G accepted') + except (AssertionError, StopIteration, ValueError): controls.append('warp: non-invertible G') + res = dict(status='PASS_RESIDUAL_WRAPPERS_ARE_EXACT', frames=len(detail), **({'hyperplane_end_pairs': hdetail} if ends else {}), **({'cold_hyperplane_end_pairs': len(cold_ends)} if cold_ends else {}), wrappers_reject=controls, all_even_weight=all(d['all_even_weight'] for d in detail), **({'warp_recipes_exact_on_all_512_columns': wdetail} if wdetail else {}), + all_totally_isotropic=all(d['totally_isotropic'] for d in detail), detail=detail) + Path(sys.argv[3]).write_text(json.dumps(res, indent=1) + '\n') + print('Lemma A (exact): L^-1 S_E R^-1 = C_[w] x I for', len(detail), 'entrance frames, global phase included;', len(controls), 'wrapper mutations rejected; all-even-weight:', res['all_even_weight']) +if __name__ == '__main__': main() diff --git a/research/staged544-reversible-lattice-macro/frozen/bw_transport.py b/research/staged544-reversible-lattice-macro/frozen/bw_transport.py new file mode 100644 index 0000000000..08248542b1 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/frozen/bw_transport.py @@ -0,0 +1,416 @@ +"""Transport an explicit BORROW-WORD to the native canonical frame-id form, with warps, and replay it exactly. + +Anticipatory dirty borrowing is the construction of PR2226 (Cinna Davis, @1337isnot1337, with OpenAI Codex +assistance; Apache-2.0): a retiring helper's register is lent to a later helper through a monomial Clifford +logical reference change K_G ("warp"), the retired field's value being replaced by K_G z. The explicit +chronological BORROW-WORD (canonical coordinates, literal frames, warps, cold restoration, inverse cleanup +with private zero buffers) is the builder output of the borrowing work (P1/P2). This script is the +transport stage of the native chain (the analogue of hpe_audit_and_transport.py): it never trusts the builder. +It replays the program in the free operator algebra generated by the warps over every arbitrary input, +in BOTH orientations (forward and inverse-transpose), checks every frame chain and the paid profile, compacts +the helper registers to R' = R - k, and writes the native CANONICAL-WORD. + +usage: bw_transport.py BORROW-WORD.json[.gz] OUT_DIR +""" +if not __debug__: + raise RuntimeError('assertions must remain enabled') # every check of this stage is an assert +import argparse +import copy +import gzip +import hashlib +import json +import sys +import time +from collections import Counter +from fractions import Fraction as Q +from pathlib import Path + + +def read(path): + data = path.read_bytes() + return json.loads(gzip.decompress(data) if path.suffix == '.gz' else data) + + +def basis(vs): + pivots = {} + for x in vs: + for k in sorted(pivots, reverse=True): + if x >> k & 1: + x ^= pivots[k] + if x: + k = x.bit_length() - 1 + for j in pivots: + if pivots[j] >> k & 1: + pivots[j] ^= x + pivots[k] = x + return tuple(pivots[k] for k in sorted(pivots, reverse=True)) + + +def span(b): + s = {0} + for x in b: + s |= {t ^ x for t in s} + return frozenset(s) + + +def rank_of(vs): + return len(basis(vs)) + + +def solve_G(cols, h): + """G given as images of e_i; returns (invertible?, image-of-subspace function).""" + def lin(x): + out = 0 + for i, c in enumerate(cols): + if x >> i & 1: + out ^= c + return out + return lin, rank_of(cols) == h + + +# ---- free operator algebra over the warps ------------------------------------------------------------------ +def add_row(dst, src, c): + for key, value in list(src.items()): + z = dst.get(key, Q(0)) + c * value + if z: + dst[key] = z + elif key in dst: + del dst[key] + + +def warp_row(row, op): + out = {} + for (var, word), value in row.items(): + word = word[1:] if word and word[0] == -op else (op,) + word + out[var, word] = value + return out + + +def is_dyadic(q): + return q.denominator & (q.denominator - 1) == 0 + + +def gate_regs(e): + if e[0] == 'add': + return [e[1], e[2]] + if e[0] == 'scale': + return [e[1]] + raise AssertionError(e[0]) + + +def dual(e): + e = list(e) + if e[0] == 'add': + e[1], e[2] = e[2], e[1] + e[3] = -e[3] + elif e[0] == 'scale': + e[2], e[3] = e[3], e[2] + return e + + +def apply_gate(e, rows, back): + if back: + e = dual(e) + if e[0] == 'scale': + q = Q(e[2], e[3]) + assert q + rows[e[1]] = {j: q * x for j, x in rows[e[1]].items()} + else: + assert e[1] != e[2] + add_row(rows[e[1]], rows[e[2]], Q(e[3], e[4])) + + +def run(word_path, out): + t0 = time.monotonic() + word = read(word_path) + assert word['kind'] == 'BORROW-WORD' + v, h, R0 = word['report']['v'], word['report']['h'], word['report']['R'] + assert h == 9 and v == 112 + n0 = 2 * v + R0 + removed = sorted(word['removed']) + assert all(2 * v <= r < n0 for r in removed) and len(set(removed)) == len(removed) + k = len(removed) + kept = [r for r in range(n0) if r not in set(removed)] + newid = {r: i for i, r in enumerate(kept)} + n = len(kept) + R = R0 - k + assert n == 2 * v + R + Zbase = n0 # builder convention: zero buffer of restored c is register n0 + c + ports = word['ports'] + assert len(set(ports)) == v + full = tuple(1 << i for i in range(h - 1, -1, -1)) + frames, frame_ids = [(), full], {(): 0, full: 1} + + def fid(vectors): + frame = basis(vectors) + if frame not in frame_ids: + frame_ids[frame] = len(frames) + frames.append(frame) + return frame_ids[frame] + + def R_(r): # register -> new register (int) or ['Z', c] + if isinstance(r, list): + return r + if r >= Zbase: + return ['Z', newid[r - Zbase]] + return newid[r] + + start = [fid([p]) for p in ports] + [0] * (v + R) + for r, frame in word['start_extra'].items(): + assert 2 * v <= int(r) < n0 and int(r) not in set(removed) + start[newid[int(r)]] = fid(frame) + final = [1] * v + [fid(x for x in range(1, 1 << h) if (x & p).bit_count() % 2 == 0) for p in ports] + [1] * R + helper_final = {} + for r, frame in word['helper_final'].items(): + assert 2 * v <= int(r) < n0 and int(r) not in set(removed) + helper_final[newid[int(r)]] = fid(frame) + final[newid[int(r)]] = helper_final[newid[int(r)]] + zero_buffers = sorted(helper_final) # every restored (hyperplane-ended) helper is replaced by a private zero buffer in the FULL cleanup + + def gate(e): + e = copy.deepcopy(e) + # Four-low lifted-target port (PR2436 mechanism): literal A-phase warp after the entry adapters. + if e[0] == 'warp': + assert len(e) == 5 + return ['warp', R_(e[1]), e[2], fid(e[3]), fid(e[4])] + if e[0] == 'add': + e[1], e[2] = R_(e[1]), R_(e[2]) + else: + e[1] = R_(e[1]) + e[-1] = None if e[-1] is None else fid(e[-1]) + return e + + # warps: operator table; op id = position + 1; G given by images of the basis vectors + warps = [] + for i, (pos, lender, G, frm, to) in enumerate(word['warps']): + warps.append({'op': i + 1, 'B_pos': pos, 'lender': newid[lender], 'G_columns': list(G), + 'from_frame': fid(frm), 'to_frame': fid(to)}) + byp = {} + for w_ in warps: + byp.setdefault(w_['B_pos'], []).append(w_) + + def warp_event(r, op, f0, f1): + return ['warp', r, op, f0, f1] + + # compensation (zero frame): initial corrections first, as twisted additions t += c * W(s) + pre = [] + for term in word['initial_corrections']: + q = Q(term['coefficient']) + pre.append(['tadd', newid[term['target']], newid[term['source']], list(term['operator_word']), + q.numerator, q.denominator, 0]) + precondition = pre + [gate(e) for e in word['precondition']] # the formal initial corrections come first (PR2226 order) + compensation = [gate(e) for e in word['compensation']] + A = [gate(e) for e in word['A']] + cut = [gate(e) for e in word['cut']] + B = [] + for p in range(len(word['B']) + 1): + for w_ in sorted(byp.get(p, []), key=lambda x: x['op']): + B.append(warp_event(w_['lender'], w_['op'], w_['from_frame'], w_['to_frame'])) + if p < len(word['B']): + B.append(gate(word['B'][p])) + assert sum(1 for e in B if e[0] == 'warp') == len(warps) + tail = [gate(e) for e in word['restore']] + cleanup = [] + for e in word['cleanup']: + if e[0] == 'warp': + cleanup.append(warp_event(R_(e[1]), e[2], 1, 1)) + assert basis(e[3]) == full + else: + cleanup.append(gate(e)) + centers = [newid[r] for r in word['centers']] + center_frames = [fid(f) for f in word['center_frames']] + levels = {str(t): fid(f) for t, f in word['target_levels'].items()} + + canonical = dict(h=h, v=v, R=R, ports=ports, frames=frames, start=start, final=final, + precondition=precondition, compensation=compensation, A=A, cut=cut, B=B, tail=tail, + cleanup=cleanup, centers=centers, center_frames=center_frames, target_levels=levels, + warps=warps, zero_buffers=zero_buffers, removed=removed, helper_origin=kept[2 * v:], + borrow=dict(k=k, base=word.get('base'), original_helpers=R0)) + # ---- exact scalar replay in the free algebra over the warps (both orientations) ----------------------------------- + nz = len(zero_buffers) + + def regkey(r): + return tuple(r) if isinstance(r, list) else ('L', r) + + def expand_tadd(e): + _, t, s, wordops, a, b, f = e + ev = [warp_event(s, op, 0, 0) for op in reversed(wordops)] + ev.append(['add', t, s, a, b, 0]) + ev += [warp_event(s, -op, 0, 0) for op in wordops] + return ev + + def program(): + yield 'pre', [x for e in precondition + compensation for x in (expand_tadd(e) if e[0] == 'tadd' else [e])] + yield 'A', A + yield 'A', cut + yield 'B', B + yield 'tail', tail + yield 'cleanup', cleanup + + def fullprog(): + return [(part, e) for part, es in program() for e in es] + prog = fullprog() + for back in (False, True): + rows = {regkey(r): {(r, ()): Q(1)} for r in range(n)} + for c in zero_buffers: + rows[('Z', c)] = {} + for part, e in prog: + if e[0] == 'warp': + key = ('L', e[1]) if not isinstance(e[1], list) else tuple(e[1]) + rows[key] = warp_row(rows[key], e[2]) + else: + if e[0] == 'add': + src, dst = regkey(e[2]), regkey(e[1]) + a, b = e[3], e[4] + if back: + src, dst, a = dst, src, -a + assert src != dst + add_row(rows[dst], rows[src], Q(a, b)) + else: + key = regkey(e[1]) + a, b = (e[3], e[2]) if back else (e[2], e[3]) + q = Q(a, b) + assert q + rows[key] = {j: q * x for j, x in rows[key].items()} + expected = {regkey(r): {(r, ()): Q(1)} for r in range(n)} + for t in range(v): + if back: + expected[('L', t)][(v + t, ())] = Q(-1) + else: + expected[('L', v + t)][(t, ())] = Q(1) + for c in zero_buffers: + expected[('Z', c)] = {} + bad = [key for key in expected if rows[key] != expected[key]] + assert not bad, ('arbitrary-input endpoint (free warp algebra)', back, bad[:8]) + # dyadic primitives + for part, e in prog: + if e[0] == 'add': + assert is_dyadic(Q(e[3], e[4])) + elif e[0] == 'scale': + q = Q(e[2], e[3]) + a = abs(q.numerator) + assert is_dyadic(q) and a and a & (a - 1) == 0 + + wrapped_regs = {r for r in range(2 * v, n) if start[r] != 0 or final[r] != 1} # entering or hyperplane-ended helpers carry wrappers + # ---- frame chains, paid profile, edges, warps ------------------------------------------------------------------- + contains = lambda a, b: basis(frames[a] + frames[b]) == tuple(frames[b]) + cur = start.copy() + paid, edges = Counter(), set() + wsum = {w_['op']: w_ for w_ in warps} + G_of = {} + for w_ in warps: + lin, inv_ = solve_G(w_['G_columns'], h) + assert inv_, ('non-invertible G', w_['op']) + img = basis([lin(x) for x in frames[w_['from_frame']]]) + assert img == tuple(frames[w_['to_frame']]), ('G does not map the from frame onto the to frame', w_['op']) + assert len(frames[w_['from_frame']]) == len(frames[w_['to_frame']]) + G_of[w_['op']] = lin + warp_edges = set() + + def regs_of(e): + return [r for r in gate_regs(e) if not isinstance(r, list)] + + def climb(r, f): + old = cur[r] + assert contains(old, f), ('nonmonotone', r, old, f) + if old != f: + degree = len(frames[f]) - len(frames[old]) + paid[degree] += 1 + edges.add((old, f)) + cur[r] = f + + def do_warp(e): + _, r, op, f0, f1 = e + if isinstance(r, list): + assert r[0] == 'Z' + assert f0 == f1 == 1 + return + assert cur[r] == f0, ('warp frame mismatch', r, op, cur[r], f0) + a = abs(op) + lin = G_of[a] + if op > 0: + ok = basis([lin(x) for x in frames[f0]]) == tuple(frames[f1]) + else: + ok = basis([lin(x) for x in frames[f1]]) == tuple(frames[f0]) + assert ok, ('warp G does not carry the frame', op, f0, f1) + cur[r] = f1 + warp_edges.add((1 if op > 0 else -1, a, f0, f1)) + + # zero-frame phase + for e in precondition + compensation: + if e[0] == 'tadd': + assert start[e[2]] == 0 and start[e[1]] == 0 and e[-1] == 0 and e[2] not in set(wrapped_regs) and all(op != 0 for op in e[3]) + for ev in expand_tadd(e): + if ev[0] == 'warp': + do_warp(ev) # frame 0 -> 0: K_G itself is the physical operator + continue + for r in regs_of(e): + assert start[r] == 0 and e[-1] == 0, ('zero-frame precondition on a nonzero entrance', e) + for part in ('A', 'B'): + if part == 'B': + assert all(cur[r] == f for r, f in zip(centers, center_frames)) + assert all(cur[v + t] == levels.get(str(t), 0) for t in range(v)) + for r, frame in zip(centers, center_frames): + served = {levels.get(str(e[1] - v), 0) for e in cut if e[2] == r} + old = frame + for f in sorted(served, key=lambda f: -len(frames[f])): + assert contains(f, old) + if old != f: + paid[len(frames[old]) - len(frames[f])] += 1 + edges.add((old, f)) + edges.add((f, old)) + old = f + for e in (A if part == 'A' else B): + if e[0] == 'warp': + do_warp(e) + else: + for r in regs_of(e): + climb(r, e[-1]) + for e in tail: + for r in regs_of(e): + climb(r, e[-1]) + for r, f in enumerate(final): + climb(r, f) + for e in cleanup: + if e[0] == 'warp': + do_warp(e) + continue + for r in gate_regs(e): + if isinstance(r, list): + assert r[0] == 'Z' and r[1] in set(zero_buffers) and e[-1] == 1 + else: + assert final[r] == 1 and e[-1] == 1, ('cleanup on a non-FULL end', e) + assert all(len(frames[final[r]]) < h for r in zero_buffers) + assert set(zero_buffers) == set(helper_final) + rep = word['report'] + assert dict(paid) == {int(r): c for r, c in rep['local_profile'].items()}, ('paid profile differs', dict(paid), rep['local_profile']) + canonical['local_profile'] = dict(sorted(paid.items())) + canonical['edges'] = sorted(edges) + canonical['warp_edges'] = sorted(warp_edges) + out.mkdir(parents=True, exist_ok=False) + payload = json.dumps(canonical, sort_keys=True, separators=(',', ':')).encode() + (out / 'CANONICAL-WORD.json.gz').write_bytes(gzip.compress(payload, mtime=0)) + raw = word_path.read_bytes() + (out / 'FULL-WORD.json.gz').write_bytes(gzip.compress(gzip.decompress(raw) if word_path.suffix == '.gz' else raw, mtime=0)) + receipt = dict(status='PASS_BORROW_WORD_FREE_ALGEBRA_ALL_COLUMNS_AND_NATIVE_FRAMES', + input_content_sha256=hashlib.sha256(gzip.decompress(raw) if word_path.suffix == '.gz' else raw).hexdigest(), + canonical_content_sha256=hashlib.sha256(payload).hexdigest(), + live_columns_each_orientation=n, helpers=R, original_helpers=R0, removed_helpers=k, + zero_buffers=nz, warps=len(warps), warp_events=sum(e[0] == 'warp' for part, e in prog), + initial_corrections=len(word['initial_corrections']), + scalar_operations=len([1 for p, e in prog if e[0] != 'warp']), + local_profile=dict(sorted(paid.items())), local_rank_mass=sum(r * z for r, z in paid.items()), + widths=[len(frames[final[r]]) - len(frames[start[r]]) for r in range(2 * v, n)], + frames=len(frames), directed_edges=len(edges), warp_edge_classes=len(warp_edges), + seconds=time.monotonic() - t0, + scope='Fresh exact forward and inverse-transpose replay over a free noncommutative warp algebra on every arbitrary input, native frame chains, dyadic primitives, zero buffers returned to zero. Physical Clifford exactness of every warp is checked by the local replay and the phase recipes.') + (out / 'SCALAR-FRAME-AUDIT.json').write_text(json.dumps(receipt, indent=2) + '\n') + print(json.dumps({k_: x for k_, x in receipt.items() if k_ != 'widths'}, indent=2), flush=True) + + +if __name__ == '__main__': + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument('word', type=Path) + ap.add_argument('out', type=Path) + a = ap.parse_args() + run(a.word, a.out) diff --git a/research/staged544-reversible-lattice-macro/frozen/clifford_exact.py b/research/staged544-reversible-lattice-macro/frozen/clifford_exact.py new file mode 100644 index 0000000000..166841a037 --- /dev/null +++ b/research/staged544-reversible-lattice-macro/frozen/clifford_exact.py @@ -0,0 +1,149 @@ +"""Small exact Gaussian-dyadic Clifford compiler, independent of gx internals. +Paulis use i^p X^x Z^z. State vectors use integer Gaussian numerators / 2^d. +The tableau is supplemented by a literal circuit, so global phases are kept. +""" +from dataclasses import dataclass + +def parity(x):return x.bit_count()&1 +def rank(rows): + p={} + for x in rows: + while x: + b=x.bit_length()-1 + if b not in p:p[b]=x;break + x^=p[b] + return len(p) +def transpose(rows,n):return tuple(sum(((rows[j]>>i)&1)<>j&1);a[j],a[k]=a[k],a[j] + for i in range(n): + if i!=j and a[i]>>j&1:a[i]^=a[j] + assert [r&((1<>n for r in a) +def basis_extend(cols,n): + out=[] + for x in list(cols)+[1<len(out):out.append(x) + assert len(out)==n + return tuple(out) +def nullspace(rows,n): + a=list(rows);p=[];k=0 + for j in range(n): + t=next((i for i in range(k,len(a)) if a[i]>>j&1),None) + if t is None:continue + a[t],a[k]=a[k],a[t] + for i in range(len(a)): + if i!=k and a[i]>>j&1:a[i]^=a[k] + p.append(j);k+=1 + return tuple((1<>j)&1)<>i&1:out=pmul(out,T[i]) + for i in range(n): + if z>>i&1:out=pmul(out,T[n+i]) + return out +def compose(A,B):return tuple(apply(A,p) for p in B) +def inverse(T): + n=len(T)//2;cols=[x|(z<>n;u,v,p=apply(T,(x,z,0));assert (u,v)==identity(n)[j][:2];out.append((x,z,(-p)%4)) + return tuple(out) +def qvalue(Q,alpha,x,n): + return (sum(alpha[i] for i in range(n) if x>>i&1)+2*sum(parity((Q[i]>>(i+1))&(x>>(i+1))) for i in range(n) if x>>i&1))%4 +def mul_i(a,p): + x,y=a;p%=4 + return [(x,y),(-y,x),(-x,-y),(y,-x)][p] +@dataclass +class Op: + n:int + tab:tuple + circuit:list + def then(self,b): + assert self.n==b.n + return Op(self.n,compose(b.tab,self.tab),self.circuit+b.circuit) + def adjoint(self): + circ=[] + for e in reversed(self.circuit): + if e[0]=='P':circ.append(('P',inv(e[1],self.n))) + elif e[0]=='D':circ.append(('D',e[1],tuple((-x)%4 for x in e[2]))) + elif e[0]=='C':circ.append(('C',e[1],-e[2])) + elif e[0]=='phase':circ.append(('phase',(-e[1])%4)) + else:circ.append(e) + return Op(self.n,inverse(self.tab),circ) + def zero_state(self,basis=0): + N=1<>i)&1 for i in range(n)) + assert all(alpha[i]%2==(Q[i]>>i)&1 for i in range(n)) + return Op(n,tuple([(1<>i&1 else 0,1<>i&1 else 0) for i in range(n)]),[('C',q,sgn)]) +def xgate(n,b):return Op(n,tuple([(1<>i)&1)) for i in range(n)]),[('X',b)]) +def fourier(n,axes=None): + out=ident(n) + for i in range(n) if axes is None else axes:out=out.then(cgate(n,1<len(selected):picks.append(j);selected.append(x) + assert len(picks)==r and all(x>>r==0 for x in Bcols) + Br=transpose(selected,r);Bi=inv(Br,r);Dr=transpose([Dcols[j]&((1<>i&1] + q.append((sum(gram[i][i] for i in bits)+2*sum(gram[i][j]for i in bits for j in bits if i>j)&1)==((quad[j]>>i)&1)for i in range(N)for j in range(N)),'symmetric quadratic form') + need(all(alpha[i]%2==((quad[i]>>i)&1)for i in range(N)),'quadratic parity') + perm=[];phasev=[] + for x in range(SIZE): + perm.append(sum(((r&x).bit_count()%2)<>i&1] + phasev.append((phase+sum(alpha[i]for i in bits)+2*sum((quad[i]>>j)&1 for i in bits for j in bits if i0 else 2]+=1 + elif not r:phase_hist[1 if s>0 else 3]+=1 + digest.update(json.dumps([x,da,sorted(a.items())],separators=(',',':')).encode()) + return dict(columns=SIZE,nonzero_coefficients=support,gaussian_axis_phase_histogram=phase_hist,operator_sha256=digest.hexdigest()) + +def lift_cocycle(G,H): + """K_H K_G = K_(HG) Z_ell. Exact finite Z4 phase defect.""" + gp,gq=kernel(tuple(G));hp,hq=kernel(tuple(H)) + HG=tuple(lin(H,c)for c in G);cp,cq=kernel(HG) + defect=[(gq[x]+hq[gp[x]]-cq[x])%4 for x in range(SIZE)] + ell=sum((defect[1<>(b-1)&1 else x + +def half_accumulate(y,a,c,d,b,subtract=False,reverse=False,omit_carry=False): + """y += floor((signed(a) +/- signed(c))/2), restoring arbitrary dirty d. + + y,a,c have b bits; d has b+1 bits. Seven reversible arithmetic primitives: + four scratch adds/subtracts, two shifted target adds/subtracts, one + parity-controlled decrement. Sources a,c are unchanged, even when d wraps. + """ + m=(1<>1))&m + d=(d-cc)&dm; d=(d-aa)&dm + y=(y-direction*(d>>1))&m + if not omit_carry:y=(y-direction*((d&1)&((a^c)&1)))&m + return y,d + +def pair(x,y,d,b,inverse=False,omit_carry=False): + """C or inverse C approximation: two complex b-bit words; one dirty word. + + Exact inverse as a finite permutation on all 2^(5b+1) states. + Numerical C approximation requires the separately stated no-wrap bound. + """ + m=(1<>i&1] + perm.append(sum(((x&r).bit_count()%2)<>j)&1 for i in bits for j in bits if i>j&1:v[x],v[x^(1<>b)&mask);y=((state>>(2*b))&mask,(state>>(3*b))&mask);d=state>>(4*b) + a,z,dd=l.pair(x,y,d,b) + expected=a[0]|(a[1]<