diff --git a/research/clifford-chart-contraction/INPUT.json b/research/clifford-chart-contraction/INPUT.json new file mode 100644 index 0000000000..c81be4f7e5 --- /dev/null +++ b/research/clifford-chart-contraction/INPUT.json @@ -0,0 +1 @@ +{"initial":2310346608841204225,"circuit":[]} diff --git a/research/clifford-chart-contraction/PROOF.md b/research/clifford-chart-contraction/PROOF.md new file mode 100644 index 0000000000..875f4a18b4 --- /dev/null +++ b/research/clifford-chart-contraction/PROOF.md @@ -0,0 +1,59 @@ +# A compact observation at the width-13 identity decoder + +## Producer and observation + +Fix four qubits per register, thirteen registers, and the identity-coefficient row of apoursh's #7800 at **fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e**. The 104-bit computational address is the 52-bit row followed by the 52-bit column. Our producer is Ali Romman's #5704 signature constructor at width 104. Its chart has independent 104-bit columns of a linear map $D$, an offset $o$, a quadratic phase $q$ modulo four with even mixed terms, and an absolute scalar $c=(a+ib)/2^e$. It gives $Y[o+Dx]=c i^{q(x)}$ for each binary $x$ and zero elsewhere. A sum of producer charts costs a separate contraction per chart. The input contains no decomposition into the decoded Clifford columns. Global circuit phases are retained. Additions inside vector or mask arguments below are over the binary field. + +Split a raw address linearly as $(S,V)$. The low twelve nibbles of $S$ are the XORs of adjacent nibbles for the six row pairs and then the six column pairs. The high nibble is the XOR of the singleton row and column. $V$ comprises the second nibble in each pair, then the row singleton. This is invertible because a pair can be reconstructed from its XOR and second nibble, and the column singleton equals the row singleton plus their XOR. The published row has 22 shift keys $s$ with zero high nibble. Its value at address $(s,v)$ is + +$$2^{-12}\sum_{(w,n)\text{ at }s} n(-1)^{w\cdot v}.$$ + +The frozen compiler returns 4,265 terms with total absolute numerator 12,800. Other shifts have weight zero. This is a linear evaluation of $Y$ without conjugating $c$. [#7800 raw cost and weight formula](https://github.com/apoursh/integer-mult-bounds/blob/fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e/research/clifford-sparse-row/COST.md) + +## All shifts share the same phase spectrum + +Eliminate $SD$ once. Write $K$ for a matrix of independent kernel columns and $d$ for its column count. For a consistent shift take any witness $t$ with $SDt=s+So$. The producer parameters over that shift are precisely $t+Ku$. Inconsistent shifts contribute zero. The map $VDK$ is injective because $(S,V)$ is invertible and $DK$ is injective. Thus $d\le52$, even for a producer of full rank 104. + +Let $B$ be the binary symmetric polar matrix defined by + +$$q(x+y)=q(x)+q(y)-q(0)+2x^TBy\pmod4.$$ + +Its diagonal gives the linear coefficients modulo two, and its off-diagonal entries are half the mixed coefficients. Set $p(u)=q(Ku)-q(0)$, $v_t=V(o+Dt)$, and $F(m)=\sum_u i^{p(u)}(-1)^{m\cdot u}$. Then term $(w,n)$ contributes exactly + +$$\frac{cn}{4096}\,i^{q(t)}(-1)^{w\cdot v_t} F\big(K^TBt+(VDK)^Tw\big).$$ + +This identifies one quadratic polynomial $p$ shared by all 4,265 frequencies across all 22 address buckets. + +Let $H$ be the polar matrix of $p$. For $z\in\ker H$, $p(z)$ is even by applying the polar identity to $x=y=z$. Moreover $p(z)/2$ is linear on the radical. Choose $m_0$ satisfying $m_0\cdot z=p(z)/2$ on a basis of the radical. The solutions form exactly $m_0+\operatorname{im}H$, since $H$ is symmetric. A shift by $z$ in the sum for $F(m)$ proves it vanishes outside this affine space. For $m=m_0+Hv$, shift the summation variable by $v$ to obtain + +$$F(m)=i^{-p(v)}(-1)^{m_0\cdot v} F(m_0).$$ + +This is independent of the preimage $v$. In fact $|F(m_0)|^2=2^{d+\dim\ker H}$. In the square, pair indices $u$ and $u+z$. Summing over $u$ kills all $z$ outside the radical and the anchor cancels the remaining phases. Only $F(m_0)$ requires the credited #5727 Gauss-sum routine. Its input is $p(u)+2m_0\cdot u$. All other nonzero values are Gaussian-unit rotations of its output. An empty shift intersection skips the Gauss sum entirely. + +A single **weighted Walsh cell** with independent mask rows $M$, signature $b$, and numerator $n$ is covered by the same algorithm. Replace its bucket terms by $(M^Tw,n(-1)^{b\cdot w})$ for all $w$ on the signature bits and multiply the denominator by $2^{\operatorname{rank} M}$. This is the binary character formula for the indicator $Mv=b$. + +## General cost in the declared input model + +The public command reads its JSON circuit file once and reports the exact byte count $L$. It builds the signature through the unchanged #5704 gate implementation, whose circuit-dependent work and gate restrictions carry over. The contraction begins at that returned chart. An observation already supplied as a chart needs its offset, scalar, independent columns and phase terms read once into working memory. Converting an arbitrary dense array to a chart is a separate problem. The unchanged #7800 program generates the 4,265 fixed terms once. A packed representation can store each frequency in 52 bits and each signed weight in nine (the absolute maximum is 128), plus 22 keys and bucket lengths. Python containers have additional object overhead. + +Let $r\le104$ be the chart rank. Use words wide enough for a 104-bit binary mask. One pivot elimination of $SD$, one for $H$, and one linear system for $m_0$ suffice apart from the internals of the single scalar Gauss routine. A per-shift witness gives $v_t$, $q(t)$ and the twist $K^TBt$. Each term then takes at most $d$ parity products to project its frequency, $d$ pivot steps, and one phase evaluation on at most $1+d+\binom d2$ monomials, plus constant overhead. With the retained substitution-based implementation, a conservative total word-operation bound after row compilation and chart production is + +$$O\big(r^2(d+1)^2+(d+1)^5+22(r+1)^2+4265(d+1)^2\big).$$ + +For the middle term the retained scalar routine eliminates at most $d$ variables. A generic substitution visits at most quadratically many old terms and expands each into at most quadratically many new ones. Peak dynamic working storage beyond the fixed compiled source tables is $O((r+1)^2+(d+1)^2+4265)$ mask/coefficient words, plus the Gaussian integers. The algorithm avoids enumeration of the $2^d$ coordinates. The unit-rotation accumulator has components at most 12,800 in absolute value. Each component of the Gauss result has absolute value at most $2^d$. Before reducing the final denominator $2^{e+12}$, each output numerator has absolute value at most $2^{d+1}12800(|a|+|b|)$, including multiplication by the producer scalar. The procedure reads the chart without mutation and can release the transient arrays on return. + +## A priced active cell on a phase-mask tape + +For each of the six adjacent register pairs, call the free second row and column nibbles $r_j,s_j$. On all $2^{104}$ raw addresses $A$ supply the normalized amplitude + +$$Y_h[A]=2^{-52}(-1)^{\sum_{j=1}^6r_j\cdot s_j+h\cdot A},\qquad h\in\mathbb F_2^{104}.$$ + +These are actual #5704 outputs. Apply the positive translation root on each coordinate, then a diagonal phase cancelling the independent root phases and introducing the shown quadratic pairs and linear sign. The accumulated root scalar is $(1+i)^{104}/2^{104}=2^{-52}$. At $h=0$ exchanging a coupled second register with its uncoupled neighbor changes an amplitude. Every tensor power in the decoded alphabet is permutation-invariant, so this observation is outside their entire linear span. + +Choose the source bucket with shifts $(0,0,0,0,0,4)$ on both sides, and signature 2 in its three masks (compiled values in *cell_tape.py*). The weight of this cell is $128/4096=1/32$. For each of the eight indicator frequencies $w$, the effective free-variable frequency is the XOR of $M^Tw$ and the restriction of $h$ to the free coordinates. Write its first 24 bits as $\alpha$, the next 24 as $\beta$, and its singleton as $\gamma$. Each pair contributes $16(-1)^{\alpha_j\cdot\beta_j}$ by Fourier orthogonality on one nibble. The singleton contributes 16 if $\gamma=0$ and zero otherwise. Including the $1/8$ from the indicator leaves the fixed denominator $2^{32}$. The numerator is a signed sum of at most eight units. + +On a read-only binary tape supply the 104 bits of $h$ directly, in the order consumed. For each pair and bit, an adjacent quartet $(a,b,c,d)$ holds the two row and two column phase bits. The final eight symbols give the two phase bits of each singleton bit. On the corresponding free coordinates $h$ adds $a+b,c+d$, and on the shift it adds $a x'_j+c x_j$. Expanding $(\alpha+a+b)(\beta+c+d)$ in one coordinate changes $\alpha\beta$ by $(a+b)(c+d)+(a+b)\beta+(c+d)\alpha$. For each quartet this plus the shift phase is an eight-bit flip mask on the eight signs. The fixed table has 24 rows of 16 one-byte masks. Four singleton XORs select one of 16 one-byte eligibility masks. A one-byte initial phase mask includes the eight indicator and constant Fourier signs. The entire fixed lookup payload is **401 bytes** (384+16+1). + +One evaluation reads exactly **104 binary symbols**, moves its input head **104 positions forward and 104 back**, writes zero input symbols, and emits an integer in $[-8,8]$ with implicit denominator $2^{32}$. With a fixed controller the mutable data include an eight-bit sign register, up to four quartet/singleton bits and a temporary incoming/partial bit. The final eligibility byte and five-bit signed output can reuse that space. Reserving these registers separately takes 26 bits (8+4+1+8+5). The fixed arithmetic uses 24 table lookups and byte XORs, one eligibility lookup, and a byte intersection, two population counts, a shift and a subtraction for the output. This is a read-only input track plus fixed local controller and ROM model. The loop counters in the executable simulate a fixed finite schedule. Clearing the local registers after copying the output restores the scratch. The 208 count prices input-head motion with no external scratch head. The producer supplies the phase bits in the stated order. The test encoder starts from a mask in a random-access word. A differently ordered caller tape entails an extra conversion. Reversible gate or selected-multiplier costs remain open. + +At $h=0$ the cell gives $2^{-31}$. For the complete row on this input the same six-pair factorization and singleton selection, applied to all 4,265 raw frequencies, independently give $2^{-29}$. The chart algorithm handles this example with $d=52$, one Gauss evaluation and 603 supported frequencies. All 22 shifts are reached. The verifier also checks 137 phase masks against the general single-cell algorithm with exact head restoration. diff --git a/research/clifford-chart-contraction/README.md b/research/clifford-chart-contraction/README.md new file mode 100644 index 0000000000..40ecb5419c --- /dev/null +++ b/research/clifford-chart-contraction/README.md @@ -0,0 +1,36 @@ +# One Gauss sum for a compact width-13 Clifford observation + +Given a compact 104-bit observation from Ali Romman's absolute-phase Clifford circuit simulator, this package evaluates the complete identity-coefficient row of #7800 with **at most one quadratic Gauss sum**, on at most 52 binary variables. The row's 4,265 signed terms share 22 affine address sets. All have the same linear directions. Their Fourier coefficients therefore reduce to rotations of one value, including for observations outside the Clifford-mixture span. [Proof and cost model](PROOF.md) + +| Exact test | Result | +|---|---:| +| Full row on a normalized, explicitly off-image observation with support $2^{104}$ | $2^{-29}$ | +| Single active cell on that observation | $2^{-31}$ | +| Same cell on a family specified by 104 binary phase-mask symbols | 104 reads, 208 head moves, input head restored | +| Fixed lookup data for this tape consumer | 401 bytes | + +The off-image example has unequal amplitudes on two inputs related by a register swap, which every vector in the Clifford-column span preserves. A separate product of six four-bit Fourier sums checks the full result. The tape count applies to one identified cell with the phase bits supplied in the declared layout. For general circuit-produced observations the package instead accounts for the chart arithmetic, precision and working storage. A selected-multiplier input supplying such a chart remains an open obligation. There is no change to κ. + +## Replay and use + +Run from the repository root with CPython 3.12 and its standard library. + +~~~sh +python3.12 -B scripts/research_package.py --package research/clifford-chart-contraction +python3.12 -I -B research/clifford-chart-contraction/verify.py +python3.12 -I -B research/clifford-chart-contraction/verify.py --tape +python3.12 -I -B research/clifford-chart-contraction/contract.py research/clifford-chart-contraction/INPUT.json +~~~ + +The last example returns exactly **−1/32** for the first nonzero probe in #7800. The JSON takes a #5704 gate array in `circuit` and an optional nonnegative 104-bit computational address in `initial`. It produces the chart, evaluates the row, and reports the exact real/imaginary rational parts, input byte count, and producer/consumer counters. In Python, `contract(state)` accepts an engine signature directly. `one_cell` evaluates one explicitly weighted Walsh cell. Proof-relevant source bytes are authenticated at startup. [Frozen source index](RETAINED.json) + +The verifier compares all 4,233 frequency values for all admissible phases with zero constant through dimension three against literal enumeration. It exercises 22 source-produced small-support circuits (one in each shift), four normalized 13-fold Clifford columns including global phase, the full-support off-image fixture, and 137 phase masks on the priced cell. The checks are finite evidence supplementing the general proof. + +## Sources and credit + +apoursh prepared this package with substantial OpenAI Codex and separate agent assistance, under Apache-2.0. apoursh's #7800 supplies the signed decoder row and its access problem, building on #7799 and the Clifford/Bell, spectral and Pauli lineage of Ali Romman, Nick Petalas and alephnan. Ali Romman's #5727 supplies the exact Gauss routine and affine solver, and #5704 supplies the compact circuit producer. Quadratic stabilizer simulation and Fourier transforms of quadratic phases are classical. The frozen source retains the original attribution and Apache license. [Signed decoder row](https://github.com/CrocSwap/integer-mult-bounds/pull/7800) · [Exact contractions](https://github.com/CrocSwap/integer-mult-bounds/pull/5727) · [Circuit signature](https://github.com/CrocSwap/integer-mult-bounds/pull/5704) · [Original notices](source/engine/source/PR5704-NOTICE.md) · [Public claim](https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19754144) + +## Open next questions + +1. Does a named multiplication supplier naturally expose this phase mask or a bounded sum of these charts? Bind one producer's actual output bytes and address order, quantify chart count and acquisition, and price restoring its working state. +2. Can several target coefficients share a single elimination on a concrete producer? First derive the target's shift equations and absolute phases, then compare their kernel and polar form with the identity target's. Other coefficient rows need their own source binding. diff --git a/research/clifford-chart-contraction/RETAINED.json b/research/clifford-chart-contraction/RETAINED.json new file mode 100644 index 0000000000..520317e651 --- /dev/null +++ b/research/clifford-chart-contraction/RETAINED.json @@ -0,0 +1,74 @@ +[ + { + "local": "source/engine/INPUTS.json", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/INPUTS.json", + "sha256": "c62bd55fd36c136ba2ec34f6d91ed481497932fadc7134d0b7e5c10009fd588c", + "git_blob": "f9d4fd920651b002370ffb5084dbef2abaa5ed44" + }, + { + "local": "source/engine/contractions.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/contractions.py", + "sha256": "a2fc065d6f293ddcffe5b6eec7fff0fdf57c8e3d4c6be355bd92e87d3f1865ef", + "git_blob": "76c807deceea0b1a6b64b50735253959b07c144d" + }, + { + "local": "source/engine/source/LICENSE", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/source/LICENSE", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64" + }, + { + "local": "source/engine/source/PR5698-NOTICE.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/source/PR5698-NOTICE.md", + "sha256": "1f55b3e4bb80a60611b1fca0622da5a99fe7877446f03d0edd1dc8f3a5abadd2", + "git_blob": "56712e3195faf8c83319100065183b8b2488809d" + }, + { + "local": "source/engine/source/PR5704-NOTICE.md", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/source/PR5704-NOTICE.md", + "sha256": "a77adc71861e3b9c73c703c5db5b671f61a1101d85d14cca08547e21d6d8dce4", + "git_blob": "b96b400e5ca04b3a9003a8b2c70a2461972d39d7" + }, + { + "local": "source/engine/source/PR5704-quadratic.py", + "repository": "CrocSwap/integer-mult-bounds", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "path": "research/clifford-exact-contractions/source/PR5704-quadratic.py", + "sha256": "d406584aed1479b75c387bc964b9e797b2f4f75e5f8c6bbea00df07f7d590a91", + "git_blob": "ce3c86ec07fd5767741e02ff0c88b93ba9164fb4" + }, + { + "local": "source/row/bell_reads.py", + "repository": "apoursh/integer-mult-bounds", + "commit": "fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e", + "path": "research/clifford-sparse-row/bell_reads.py", + "sha256": "44942462cd7778d23042bf827fb313d0e7acf99aa5b9793e411503e83d3421b7", + "git_blob": "32b2ed2a94dc77d04709fedb420bf0ffd6d74f73" + }, + { + "local": "source/row/compile_row.py", + "repository": "apoursh/integer-mult-bounds", + "commit": "fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e", + "path": "research/clifford-sparse-row/compile_row.py", + "sha256": "4e6420f6dcccfd76d64a3b14d94dbdd4803bfd780c921a225d8f29b5d9f0565b", + "git_blob": "daf35d6a26993ed00cfc25a9e16c9136fba2a275" + }, + { + "local": "source/row/raw_row.py", + "repository": "apoursh/integer-mult-bounds", + "commit": "fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e", + "path": "research/clifford-sparse-row/raw_row.py", + "sha256": "40fb7b900409d1908e01683830f44670417338412753ba77a37ea203f94aafa7", + "git_blob": "1787feb76acf78e3fd314bf3e0ecbe6cb2432316" + } +] diff --git a/research/clifford-chart-contraction/SOURCES.json b/research/clifford-chart-contraction/SOURCES.json new file mode 100644 index 0000000000..ed2a846b4d --- /dev/null +++ b/research/clifford-chart-contraction/SOURCES.json @@ -0,0 +1,48 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "files": [ + { + "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" + } + ], + "cited_research": [ + { + "pr": 5704, + "author": "aliromman", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "title": "Make complete Clifford replay 5.17x faster with exact quadratic states", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/5704" + }, + { + "pr": 5727, + "author": "aliromman", + "head": "8b74ecd0eea26d95b400e56435d35fbd261dc49b", + "title": "Add exact phase-sensitive Clifford contractions and attained finite-span errors", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/5727" + }, + { + "pr": 7799, + "author": "apoursh", + "head": "7f08a74037788311cc6b7da27297b25f1b188e45", + "title": "Prove the sharp Gaussian-dyadic four-qubit Clifford tensor width is 13 (no κ)", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/7799" + }, + { + "pr": 7800, + "author": "apoursh", + "head": "fdc90699f4a64139ed6d84cdbf9a606ff0ccd32e", + "title": "Compile the width-13 Clifford decoder into 4,265 Bell reads and certify its dense input cost (no κ)", + "url": "https://github.com/CrocSwap/integer-mult-bounds/pull/7800" + } + ] +} diff --git a/research/clifford-chart-contraction/TASK.json b/research/clifford-chart-contraction/TASK.json new file mode 100644 index 0000000000..15de4eb6d7 --- /dev/null +++ b/research/clifford-chart-contraction/TASK.json @@ -0,0 +1,99 @@ +{ + "schema_version": 1, + "base_commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "task_id": "uniform-transfer-audit", + "original_card": { + "id": "uniform-transfer-audit", + "question": "Can one of the selected record's five inherited assumptions be proved at its actual caller?", + "starting_points": [ + "docs/research/current-priorities.md", + "docs/research/research-family-status.md", + "certificates/selected-result.json", + "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md" + ], + "methods": [ + "Construct and independently check one source-bound instance of the stated first experiment.", + "Seek an exact counterexample or target-specific complete-budget obstruction to that same proposed change." + ], + "acceptance_gate": "Identify the proposition and what would change downstream; do not equate a finite replay with a universal proof.", + "first_step": { + "command": [ + "python3", + "-B", + "scripts/research_selected_baseline.py" + ], + "expected": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "inspect": "Read revision 8, the selected review and live exact-source handoffs. Then follow this card's bounded first_experiment.", + "scope": "Source-bound orientation only, not a supplier replay or theorem proof." + }, + "first_experiment": "Choose one assumption ID (native_all_columns, owned_erasure, compiler, precision_tape, analytic_recovery), one quantified implication and exact dependency closure. Check current handoffs, including #5625 row reentry and #5707 root-prefix lowering, without treating their partial scope as the whole theorem. Prove or falsify that implication with a caller-bound argument; stop at the chosen obligation. Finite tests or root digits do not discharge an all-size statement.", + "bottleneck_link": "Judge the actual current supplier contract and complete signed target/paid bill; frozen-profile ceilings require an applicability proof.", + "allowed_variations": [ + "One exact source head, helper/cut region or quantified proposition and changed hypothesis; check live handoffs first. Different seeds are not different scopes." + ], + "scope_change_triggers": [ + "Changing source head, helper/cut domain, operation alphabet or caller boundary without recording the new scope.", + "Treating an archived proposal or local numerical pass as complete supplier admission." + ], + "overlap_terms": [ + "native_all_columns", + "owned_erasure", + "compiler", + "precision_tape", + "analytic_recovery" + ], + "existing_checks": [ + { + "scope": "PR #4100: proposed unconditional construction and finite checks, without independent acceptance.", + "evidence": "research/unconditional-batched-crt/README.md", + "remaining": "Independent proof audit of one caller-bound all-size implication; all other premises remain explicit.", + "status": "author-checked", + "source_commit": "337d04939571a637aeab54a0f58f54fde811663a", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129" + }, + { + "scope": "Selected PR5599: complete helper-subspace construction and independent caller replay; five framework assumptions remain.", + "evidence": "docs/research/pr-intake-evidence/pr5599-completion/PROOF-REVIEW.md", + "remaining": "The next experiment must identify uncovered source-specific work. Successor archive intake does not transfer this admission.", + "status": "reviewed", + "source_commit": "09dd0965711ca7eeb169057a420abab1c9052137", + "selected_record_sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5" + } + ] + }, + "priority_revision": 8, + "selection_nonce": "59773a6650a00991f368359a9b9baf50", + "scope_key": "58d0403e3078b2c5ae8a", + "scope_status": "changed", + "actual_scope": "Contract the width-13 identity row of #7800 directly against an absolute-phase affine-quadratic observation from the #5704 circuit producer.", + "scope_change_reason": "The concrete handoff asks whether the finite readout can consume encoded observations. This changes the input contract of the dense-read analysis and scopes the work to one output.", + "bottleneck_link": "Determines when the 151 × 2^47 dense probes can be replaced by a calculation on an already encoded observation, and identifies which preparation and restoration costs still apply.", + "stop_rule": "Give the input equations, evaluate a full-size encoded observation and an active cell, and check the phase, normalization and acquisition model.", + "outcome": "completed", + "author": "apoursh", + "ai_assistance": "Substantial OpenAI Codex assistance in derivation, implementation and review.", + "evidence": "The proof, compact contraction, encoded circuit fixtures, literal low-rank comparisons and the retained source manifest.", + "claim": "https://github.com/CrocSwap/integer-mult-bounds/discussions/1166#discussioncomment-19754144", + "open_questions": [ + { + "question": "Which multiplication supplier exposes an observation in these coordinates?", + "why_it_matters": "Producing the compact input can dominate the arithmetic on a supplied chart.", + "first_step": "Identify a named producer and bind the phase mask or chart count, address ordering and clean-up cost.", + "blocked_by": "The present fixture has its own circuit source and no proven connection to the selected multiplier." + }, + { + "question": "Can one reuse the same elimination for several transported output rows of a specified readout?", + "why_it_matters": "A single recovered coefficient does not price an entire coefficient vector.", + "first_step": "Compile a second transported row, write its shift and frequency maps, and measure which operations can actually be shared.", + "blocked_by": "Transport can change the linear maps on the input support and the physical source must supply its encoding." + } + ], + "overlap": "Read the #1163 coordination guide, the live #1166 handoffs and recent pull requests. Searched all PR states for Clifford widths, Gram spectra and Gauss contractions, and checked related source PRs. The local overlap helper used an incomplete sparse checkout and an older cache.", + "upstream_refresh": { + "date_utc": "2026-11-19", + "commit": "e54523517d0f03e58352e647c403a5af3e525a57", + "selected_orientation": "PASS_RESEARCH_BASELINE_BINDINGS_ONLY", + "context": "Priority revision 8 references #5599. The selected record points to #7000.", + "before_submission": "Fetched canonical main again and verified the same base and selected record." + } +} diff --git a/research/clifford-chart-contraction/VERIFY.json b/research/clifford-chart-contraction/VERIFY.json new file mode 100644 index 0000000000..769f9da174 --- /dev/null +++ b/research/clifford-chart-contraction/VERIFY.json @@ -0,0 +1,65 @@ +{ + "schema_version": 1, + "status": "ready", + "python": "3.12", + "requirements": [], + "inputs": [], + "commands": [ + { + "argv": [ + "{python}", + "-E", + "-s", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Gauss transport, literal small-support inputs and the fully supported 104-bit circuit; includes 137 active-cell tape masks and restoration" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-O", + "-W", + "error", + "-B", + "{package}/verify.py" + ], + "timeout_seconds": 120, + "checks": "Gauss transport, literal small-support inputs and the fully supported 104-bit circuit with optimized Python; includes 137 active-cell tape masks and restoration" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-W", + "error", + "-B", + "{package}/contract.py", + "{package}/INPUT.json" + ], + "timeout_seconds": 120, + "checks": "Public JSON circuit example through the command-line entry point" + }, + { + "argv": [ + "{python}", + "-E", + "-s", + "-O", + "-W", + "error", + "-B", + "{package}/contract.py", + "{package}/INPUT.json" + ], + "timeout_seconds": 120, + "checks": "Public JSON circuit example through the command-line entry point with optimized Python" + } + ] +} diff --git a/research/clifford-chart-contraction/cell_tape.py b/research/clifford-chart-contraction/cell_tape.py new file mode 100644 index 0000000000..379c5eb9bf --- /dev/null +++ b/research/clifford-chart-contraction/cell_tape.py @@ -0,0 +1,78 @@ +"""A fixed active cell on a compact, phase-modulated observation; Apache-2.0.""" +from fractions import Fraction +from contract import apply, parity + +SHIFTS = (0, 0, 0, 0, 0, 4) * 2 +MASKS = (0x48210048210, 0x1048210148210, 0x2048210248210) +SIGNATURE = 2 + + +def compile_cell(): + frequencies = [apply(MASKS, w) for w in range(8)] + initial = sum((parity(w & SIGNATURE) ^ parity((f & ((1 << 24)-1)) & (f >> 24))) << w + for w, f in enumerate(frequencies)) + lookup = [] + for j in range(24): + output_shift = (SHIFTS[j//4] >> (j%4)) & 1 + input_shift = (SHIFTS[6+j//4] >> (j%4)) & 1 + row = [] + for quad in range(16): + a, b, c, d = ((quad >> k) & 1 for k in range(4)) + r, s = a ^ b, c ^ d + common = (a & output_shift) ^ (c & input_shift) ^ (r & s) + row.append(sum((common ^ (r & (f >> (24+j))) ^ (s & (f >> j))) << w + for w, f in enumerate(frequencies))) + lookup.append(row) + eligible = [sum((f >> 48 == s) << w for w, f in enumerate(frequencies)) for s in range(16)] + return initial, lookup, eligible + + +TABLE = compile_cell() + + +def phase_mask_symbols(mask): + """Input encoder used in tests; the consumer itself reads only the tape.""" + tape = [] + for j in range(24): + right = 4*(11 - 2*(j//4)) + j%4 + for bit in (52+right+4, 52+right, right+4, right): + tape.append((mask >> bit) & 1) + for bit in range(4): + tape.extend(((mask >> (52+bit)) & 1, (mask >> bit) & 1)) + return bytes(tape) + + +class Tape: + """One read-only binary input track, a movable head, and counted motion.""" + def __init__(self, symbols): + if len(symbols) != 104: + raise ValueError("A phase mask has 104 bits") + self.symbols = symbols + self.position = self.reads = self.moves = 0 + + def take(self): + symbol = self.symbols[self.position] + if symbol not in (0, 1): + raise ValueError("Expected a binary symbol") + self.reads += 1 + self.moves += 1 + self.position += 1 + return symbol + + def restore(self): + self.moves += self.position + self.position = 0 + + +def evaluate(tape): + phase, blocks, eligible = TABLE + for table in blocks: + quad = sum(tape.take() << j for j in range(4)) + phase ^= table[quad] + singleton = 0 + for j in range(4): + singleton |= (tape.take() ^ tape.take()) << j + active = eligible[singleton] + value = active.bit_count() - 2 * (phase & active).bit_count() + tape.restore() + return Fraction(value, 1 << 32) diff --git a/research/clifford-chart-contraction/contract.py b/research/clifford-chart-contraction/contract.py new file mode 100644 index 0000000000..11df2cef14 --- /dev/null +++ b/research/clifford-chart-contraction/contract.py @@ -0,0 +1,195 @@ +"""Contract #7800's identity row with a #5704 affine-quadratic observation. + +apoursh with substantial OpenAI Codex assistance. Apache-2.0. +""" +from collections import Counter, defaultdict +from fractions import Fraction +from hashlib import sha256 +import json +from functools import cache +from pathlib import Path +import sys + +HERE = Path(__file__).resolve().parent +for record in json.loads((HERE / "RETAINED.json").read_text()): + if sha256((HERE / record["local"]).read_bytes()).hexdigest() != record["sha256"]: + raise ValueError("Changed retained source: " + record["local"]) +sys.path[:0] = [str(HERE / "source" / "engine"), str(HERE / "source" / "row")] +from contractions import Q, gauss, solution +from raw_row import RAW_DENOMINATOR, iter_reads, label_sum, pack, split_address + + +def parity(bits): + return bits.bit_count() & 1 + + +def transpose(columns, vector): + return sum(parity(column & vector) << j for j, column in enumerate(columns)) + + +def apply(columns, vector): + out = 0 + for j in Q.bits(vector): + out ^= columns[j] + return out + + +class BinaryMap: + """One elimination: a kernel basis and a right inverse on the image.""" + def __init__(self, columns): + self.pivots = {} + self.kernel = [] + for j, column in enumerate(columns): + word, witness = column, 1 << j + while word: + bit = word.bit_length() - 1 + if bit not in self.pivots: + self.pivots[bit] = (word, witness) + break + pivot, preimage = self.pivots[bit] + word ^= pivot + witness ^= preimage + if not word: + self.kernel.append(witness) + + def preimage(self, word): + witness = 0 + while word: + pivot = self.pivots.get(word.bit_length() - 1) + if pivot is None: + return None + word ^= pivot[0] + witness ^= pivot[1] + return witness + + +def polar(dimension, phase): + columns = [0] * dimension + for mask, coefficient in phase.items(): + if mask.bit_count() == 2: + a, b = Q.bits(mask) + columns[a] ^= 1 << b + columns[b] ^= 1 << a + elif mask and coefficient & 1: + columns[mask.bit_length() - 1] ^= mask + return columns + + +class Spectrum: + """Return a Fourier coefficient as a rotation of one exact Gauss sum.""" + def __init__(self, dimension, phase): + self.phase = phase + self.map = BinaryMap(polar(dimension, phase)) + equations = [] + for r in self.map.kernel: + q = Q.value(phase, r) + Q.need(q % 2 == 0, "An element of the radical has even phase") + equations.append((r, q // 2)) + _, forms = solution(dimension, equations) + self.origin = sum((form & 1) << j for j, form in enumerate(forms)) + twisted = dict(phase) + Q.affine(twisted, self.origin << 1, 2) + self.value = gauss(dimension, twisted) + Q.need(self.value != (0, 0), "Nonzero Fourier anchor") + + def rotation(self, frequency): + u = self.map.preimage(self.origin ^ frequency) + if u is None: + return None + return (2 * parity(self.origin & u) - Q.value(self.phase, u)) % 4 + + +def address_parts(address): + """Linear map from raw 104 bits to (52 shift bits, 52 free bits).""" + row, col = divmod(address, 1 << 52) + r, c = split_address(row), split_address(col) + pairs = r[:-1] + c[:-1] + shifts = [a ^ b for a, b in zip(pairs[::2], pairs[1::2], strict=True)] + return pack([*shifts, r[-1] ^ c[-1]]), pack([*pairs[1::2], r[-1]]) + + +@cache +def read_plan(): + plan = defaultdict(list) + for read in iter_reads(): + labels = read.output_labels + read.input_labels + singleton = label_sum(labels) + Q.need(singleton < 16 and read.correction_i == 0, "Identity trace convention") + shift = pack([t >> 4 for t in labels]) + frequency = pack([*(t & 15 for t in labels), singleton]) + plan[shift].append((frequency, read.numerator)) + return {s: tuple(terms) for s, terms in sorted(plan.items())} + + +def contract(state, plan=None, denominator=RAW_DENOMINATOR): + """Linear (unconjugated) observation contraction on a signature() output. + + A plan maps a packed shift to (frequency, signed integer weight) pairs. + Each weight has the stated common denominator. + """ + n, offset, cols, terms, real, imag, exponent = state + Q.need(n == 104, "This row consumes a 104-bit state") + if plan is None: + plan = read_plan() + shift0, point0 = address_parts(offset) + parts = [address_parts(c) for c in cols] + support = BinaryMap(s for s, _ in parts) + points = [v for _, v in parts] + intersections = [] + for shift, table in plan.items(): + witness = support.preimage(shift ^ shift0) + if witness is not None: + intersections.append((witness, table)) + counts = Counter(buckets=len(intersections), dimension=len(support.kernel), gauss=0) + if not intersections: + return (Fraction(0), Fraction(0)), dict(counts) + + kernel = support.kernel + phase = dict(terms) + restricted = Q.substitute(phase, [transpose(kernel, 1 << j) << 1 for j in range(len(cols))]) + restricted.pop(0, None) + spectrum = Spectrum(len(kernel), restricted) + counts["gauss"] = 1 + polar_cols = polar(len(cols), phase) + point_directions = [apply(points, k) for k in kernel] + total = [0, 0] + for witness, table in intersections: + point = point0 ^ apply(points, witness) + twist = transpose(kernel, apply(polar_cols, witness)) + constant = Q.value(phase, witness) + for frequency, weight in table: + counts["terms"] += 1 + exponent_i = spectrum.rotation(twist ^ transpose(point_directions, frequency)) + if exponent_i is None: + continue + counts["supported"] += 1 + angle = (constant + 2 * parity(point & frequency) + exponent_i) % 4 + total[angle % 2] += weight if angle < 2 else -weight + numerator = Q.multiply((real, imag), Q.multiply(spectrum.value, total)) + return tuple(Fraction(x, denominator << exponent) for x in numerator), dict(counts) + + +def one_cell(state, shifts, masks, signature, numerator): + """Contract the actual weight numerator/4096 on a single Walsh cell.""" + frequencies = [(apply(masks, w), numerator * (-1)**parity(w & signature)) + for w in range(1 << len(masks))] + return contract(state, {pack(shifts): frequencies}, RAW_DENOMINATOR << len(masks)) + + +def main(): + """Evaluate a literal #5704 circuit on one computational basis input.""" + import argparse + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("input", type=Path, help="JSON with circuit and optional initial address") + args = parser.parse_args() + data = args.input.read_bytes() + request = json.loads(data) + counters = {} + state = Q.signature(104, request["circuit"], initial=request.get("initial", 0), counters=counters) + result, execution = contract(state) + print(json.dumps({"real": str(result[0]), "imag": str(result[1]), "input_bytes": len(data), + "producer": counters, "consumer": execution}, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/research/clifford-chart-contraction/source/engine/INPUTS.json b/research/clifford-chart-contraction/source/engine/INPUTS.json new file mode 100644 index 0000000000..f9d4fd9206 --- /dev/null +++ b/research/clifford-chart-contraction/source/engine/INPUTS.json @@ -0,0 +1,72 @@ +[ + { + "local": "PR5704-quadratic.py", + "origin": "research/exact-clifford-quadratic-replay/quadratic.py", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "d406584aed1479b75c387bc964b9e797b2f4f75e5f8c6bbea00df07f7d590a91", + "git_blob": "ce3c86ec07fd5767741e02ff0c88b93ba9164fb4" + }, + { + "local": "PR5704-PROOF.md", + "origin": "research/exact-clifford-quadratic-replay/PROOF.md", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "e5039414a02e36cdeab82fb9803fc4de0c3e0f3997e8812ef9d227e5d417ec91", + "git_blob": "559f9f4b207783c6eb908450b63eed3431594c22" + }, + { + "local": "PR5704-NOTICE.md", + "origin": "research/exact-clifford-quadratic-replay/NOTICE.md", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "a77adc71861e3b9c73c703c5db5b671f61a1101d85d14cca08547e21d6d8dce4", + "git_blob": "b96b400e5ca04b3a9003a8b2c70a2461972d39d7" + }, + { + "local": "PR5526-PROOF.md", + "origin": "research/clifford-pointwise-faithfulness/PROOF.md", + "head": "df0137efd35e11b4445734bf612bdd4c7ebc330c", + "sha256": "45483e4b5f604a5e70602c5caaa4394d4a0d0d1a6d0b6e8a93b836d50b23f764", + "git_blob": "465009d9d1b6947e80e6f1e868022f47ddab1f3c" + }, + { + "local": "clifford_exact.py", + "origin": "research/exact-clifford-quadratic-replay/source/source/clifford_exact.py", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "2982ead07721e83358dc67c6f49c2b4c16a236a6bebdfd72f58221be1f5d0962", + "git_blob": "166841a037f069249f6f7f6dedb89248812f59e2" + }, + { + "local": "prune_native.py", + "origin": "research/exact-clifford-quadratic-replay/source/source/prune_native.py", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "f2b37c183a10922eabc8e0436b426a08866430e96bd0adc7e178951c7fbb5257", + "git_blob": "8c3e11b2408fa96eefa3ebe7952d1b11b90b772b" + }, + { + "local": "PHYSICAL.json", + "origin": "research/exact-clifford-quadratic-replay/source/PHYSICAL.json", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "f78ba861d23ff33f2c9ffeca8c3ab6a7f1ec906f38adff5d325c13efb187c7c3", + "git_blob": "375b30b8c7aa16df521deaec04f16d1af8532abd" + }, + { + "local": "CONSTRUCTION.json.gz", + "origin": "research/exact-clifford-quadratic-replay/source/CONSTRUCTION.json.gz", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "00d13d7774adf087f93bc58d4c5860e296f8408c0ee25a4db254a056f8da7dec", + "git_blob": "31c6d481dd8b32e30d3c137bd2561a59a9d9fcc0" + }, + { + "local": "PR5698-NOTICE.md", + "origin": "research/exact-clifford-quadratic-replay/source/NOTICE.md", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "1f55b3e4bb80a60611b1fca0622da5a99fe7877446f03d0edd1dc8f3a5abadd2", + "git_blob": "56712e3195faf8c83319100065183b8b2488809d" + }, + { + "local": "LICENSE", + "origin": "research/exact-clifford-quadratic-replay/source/source/LICENSE", + "head": "daa4d9dbd102d2a3677afc5614c56466bd2cf3a2", + "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4", + "git_blob": "261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64" + } +] diff --git a/research/clifford-chart-contraction/source/engine/contractions.py b/research/clifford-chart-contraction/source/engine/contractions.py new file mode 100644 index 0000000000..76c807dece --- /dev/null +++ b/research/clifford-chart-contraction/source/engine/contractions.py @@ -0,0 +1,236 @@ +"""Exact Clifford contractions with absolute phase. Apache-2.0. + +Classical affine-support and quadratic Gauss-sum methods. Prepared by +Ali Romman with substantial OpenAI Codex assistance. +""" +from fractions import Fraction +from hashlib import sha256 +import importlib.util +import json +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parent + + +def load_source(name, filename): + records = json.loads((ROOT / 'INPUTS.json').read_text()) + record = next(x for x in records if x['local'] == filename) + path = ROOT / 'source' / filename + if sha256(path.read_bytes()).hexdigest() != record['sha256']: + raise ValueError('Changed frozen input: ' + filename) + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +Q = load_source('contraction_quadratic', 'PR5704-quadratic.py') + + +def add(a, b): + return a[0] + b[0], a[1] + b[1] + + +def conjugate(a): + return a[0], -a[1] + + +def power(a, exponent): + Q.need(type(exponent) is int and exponent >= 0, 'Nonnegative integral exponent') + result = (1, 0) + while exponent: + if exponent & 1: + result = Q.multiply(result, a) + a = Q.multiply(a, a) + exponent >>= 1 + return result + + +def solution(n, equations): + """Return every binary solution as affine coordinate forms, or None.""" + rows = {} + for mask, rhs in equations: + Q.validate_integer(mask, 1 << n, 'Equation variable mask') + Q.validate_integer(rhs, 2, 'Equation right side') + while mask: + pivot = mask.bit_length() - 1 + if pivot not in rows: + rows[pivot] = (mask, rhs) + break + other, value = rows[pivot] + mask ^= other + rhs ^= value + if not mask and rhs: + return None + free = [j for j in range(n) if j not in rows] + forms = [0] * n + for k, j in enumerate(free): + forms[j] = 1 << (k + 1) + for pivot in sorted(rows): + mask, rhs = rows[pivot] + forms[pivot] = rhs + for j in Q.bits(mask ^ (1 << pivot)): + forms[pivot] ^= forms[j] + return len(free), forms + + +def gauss(n, poly): + """Return sum_x i**q(x) as an exact Gaussian integer.""" + Q.need(type(n) is int and n >= 0, 'Nonnegative Gauss dimension') + for mask, coefficient in poly.items(): + Q.validate_integer(mask, 1 << n, 'Phase variable mask') + Q.need(type(coefficient) is int and 0 < coefficient < 4, + 'Canonical nonzero phase coefficient') + Q.need(mask.bit_count() <= 2 and (mask.bit_count() != 2 or coefficient == 2), + 'Only even quadratic terms') + poly = dict(poly) + scalar = (1, 0) + while n: + last = 1 << (n - 1) + a = poly.pop(last, 0) + linear = 0 + for mask in list(poly): + if mask & last: + linear ^= mask ^ last + del poly[mask] + n -= 1 + if a & 1: + scalar = Q.multiply(scalar, (1, 1 if a == 1 else -1)) + Q.affine(poly, linear << 1, -a) + elif linear: + resolved = solution(n, [(linear, a // 2)]) + Q.need(resolved is not None, 'A nonzero linear form takes both values') + n, forms = resolved + poly = Q.substitute(poly, forms) + scalar = (2 * scalar[0], 2 * scalar[1]) + elif a: + return (0, 0) + else: + scalar = (2 * scalar[0], 2 * scalar[1]) + return Q.multiply_i(scalar, poly.get(0, 0)) + + +def inner(left, right): + """Return the exact inner product of two valid engine states. + + Inputs come from signature or choi. Arbitrary serialized states are not + admitted without the source engine's construction contract. + """ + n, offset, cols, terms, a, b, den = left + m, other, cols2, terms2, c, d, den2 = right + Q.need(n == m, 'Equal state dimensions') + r = len(cols) + allcols = cols + cols2 + equations = [(sum(((v >> i) & 1) << j for j, v in enumerate(allcols)), + ((offset ^ other) >> i) & 1) for i in range(n)] + resolved = solution(len(allcols), equations) + if resolved is None: + return Fraction(0), Fraction(0) + dimension, forms = resolved + phase = Q.substitute(dict(terms2), forms[r:]) + for mask, coefficient in Q.substitute(dict(terms), forms[:r]).items(): + Q.term(phase, mask, -coefficient) + total = Q.multiply(Q.multiply((a, -b), (c, d)), gauss(dimension, phase)) + return Fraction(total[0], 1 << (den + den2)), Fraction(total[1], 1 << (den + den2)) + + +def choi(n, circuit): + """Return a normalized Choi state, retaining one common Bell phase.""" + Q.need(type(n) is int and n >= 0, 'Nonnegative circuit width') + preparation = [('C', (1 << j) | (1 << (n + j)), 1) for j in range(n)] + preparation.append(('D', tuple(1 << j if j < n else 0 for j in range(2 * n)), + (1,) * n + (0,) * n)) + expanded = [] + for gate in circuit: + # Validate the original arity and domain before extension. + Q.signature(n, [gate]) + kind = gate[0] + if kind == 'P': + expanded.append(('P', tuple(gate[1]) + tuple(1 << j for j in range(n, 2 * n)))) + elif kind == 'D': + expanded.append(('D', tuple(gate[1]) + (0,) * n, tuple(gate[2]) + (0,) * n)) + else: + expanded.append(gate) + return Q.signature(2 * n, preparation + expanded) + + +def trace(n, circuit): + result = inner(choi(n, []), choi(n, circuit)) + return result[0] * (1 << n), result[1] * (1 << n) + + +def kernel(states): + """Return normalized trace(U_i^* U_j) for valid equal-width circuits.""" + return [[inner(a, b) for b in states] for a in states] + + +def residual_norm(gram, coefficients, width): + """Return ||sum c_i U_i^(tensor width)||_HS^2 / d^width.""" + Q.need(type(width) is int and width > 0, 'Positive tensor width') + size = len(coefficients) + Q.need(len(gram) == size and all(len(row) == size for row in gram), 'Gram dimensions') + result = (Fraction(0), Fraction(0)) + for i, a in enumerate(coefficients): + for j, b in enumerate(coefficients): + result = add(result, Q.multiply(Q.multiply(conjugate(a), b), power(gram[i][j], width))) + Q.need(result[1] == 0 and result[0] >= 0, 'A valid Gram norm is real and nonnegative') + return result[0] + + +def decide(n, circuits, coefficients): + """Apply the credited four-width theorem to one fixed expanded residual.""" + Q.need(len(circuits) == len(coefficients), 'One fixed coefficient per circuit') + for a in coefficients: + Q.need(len(a) == 2 and all(type(x) in (int, Fraction) for x in a), + 'Exact rational real and imaginary coefficients') + gram = kernel([choi(n, c) for c in circuits]) + first = 4 * n + 4 if n else 1 + norms = [residual_norm(gram, coefficients, f) for f in range(first, first + 4)] + return dict(widths=list(range(first, first + 4)), norms=norms, + all_positive_widths_zero=all(x == 0 for x in norms)) + + +def divide(a, b): + scale = b[0] ** 2 + b[1] ** 2 + Q.need(scale != 0, 'Nonzero complex pivot') + value = Q.multiply(a, conjugate(b)) + return Fraction(value[0]) / scale, Fraction(value[1]) / scale + + +def best_approximation(states, target, width): + """Minimize the normalized squared residual in the supplied finite span. + + Coefficients may depend on this width. Dependent columns are permitted. + This operation does not admit a physical readout or new native queries. + """ + Q.need(type(width) is int and width > 0, 'Positive tensor width') + size = len(states) + gram = kernel(states + [target]) + matrix = [[power(gram[i][j], width) for j in range(size)] + + [power(gram[i][size], width)] for i in range(size)] + pivots = [] + for col in range(size): + row = next((r for r in range(len(pivots), size) if matrix[r][col] != (0, 0)), None) + if row is None: continue + k = len(pivots) + matrix[k], matrix[row] = matrix[row], matrix[k] + pivot = matrix[k][col] + matrix[k] = [divide(x, pivot) for x in matrix[k]] + for r in range(size): + if r != k: + factor = matrix[r][col] + matrix[r] = [add(x, Q.multiply((-factor[0], -factor[1]), y)) + for x, y in zip(matrix[r], matrix[k])] + pivots.append(col) + Q.need(all(row[-1] == (0, 0) for row in matrix[len(pivots):]), 'Consistent Gram normal equations') + coefficients = [(Fraction(0), Fraction(0))] * size + for row, col in enumerate(pivots): coefficients[col] = matrix[row][-1] + residual = residual_norm(gram, [(-x, -y) for x, y in coefficients] + [(1, 0)], width) + # Orthogonality is an independently inspectable optimum certificate. + for i in range(size): + value = (Fraction(0), Fraction(0)) + for j in range(size): value = add(value, Q.multiply(power(gram[i][j], width), coefficients[j])) + Q.need(value == power(gram[i][size], width), 'Exact residual orthogonality') + return dict(coefficients=coefficients, squared_residual=residual, span_rank=len(pivots)) diff --git a/research/clifford-chart-contraction/source/engine/source/LICENSE b/research/clifford-chart-contraction/source/engine/source/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/research/clifford-chart-contraction/source/engine/source/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/clifford-chart-contraction/source/engine/source/PR5698-NOTICE.md b/research/clifford-chart-contraction/source/engine/source/PR5698-NOTICE.md new file mode 100644 index 0000000000..56712e3195 --- /dev/null +++ b/research/clifford-chart-contraction/source/engine/source/PR5698-NOTICE.md @@ -0,0 +1,9 @@ +# Attribution + +Ali Romman with substantial OpenAI Codex assistance. Apache-2.0. + +Dugongue PR5687 supplies the actual two-line C coframe proposal and its complete profile, source interpretation and moment/tail proof. The native-dual-suppliers source supplies the actual restriction, native maps and main normalizers. Preserve Cao Yifan PR4610/4470, Cinna Davis and the native/frame/helper/ROW/controller lineage, DaysSky, Nick Petalas, Ryanson Jonathan, zxv, Jacob Alan Sussman, and every retained phase, scalar, compiler, precision, stock and analytic notice. + +Seventeen source files are retained byte for byte. Their original comments and attribution remain unchanged. INPUTS.json and SOURCES.json give exact commits, paths, Git objects and SHA256 hashes. Dinic's integral flow algorithm and the submodular graph-cut construction are classical methods, not new mathematics claimed here. + +The new work is the complete 423-frame binary optimization, four additional folds, exact emitted physical program and phase certificates, finite optimality headroom bound, stronger full gain, and charged higher-moment transfer. No global literature priority, independent human acceptance or new kappa is claimed. diff --git a/research/clifford-chart-contraction/source/engine/source/PR5704-NOTICE.md b/research/clifford-chart-contraction/source/engine/source/PR5704-NOTICE.md new file mode 100644 index 0000000000..b96b400e5c --- /dev/null +++ b/research/clifford-chart-contraction/source/engine/source/PR5704-NOTICE.md @@ -0,0 +1,33 @@ +# Attribution + +Ali Romman with substantial OpenAI Codex assistance. Apache-2.0. + +The affine-support and quadratic-phase representation is classical stabilizer +simulation. Credit Jeroen Dehaene and Bart De Moor, Physical Review A 68, 042318 +(2003), and the phase-sensitive stabilizer literature, including Bravyi, Browne, +Calpin, Campbell, Gosset and Howard (arXiv:1808.00128). The proof gives a direct +induction for this exact Gaussian-dyadic gate grammar. No discovery or optimal +simulation-complexity claim is made. + +Charles Bethin PR662 supplies the byte-exact table evaluator and prior runtime +work. Its retained NOTICE credits icekylinx, DreamingOfClouds, chafreaky, Jeremy +Kothe and the prior Clifford/wrapper/compiler lineage. Its source and notice +are frozen in tables/. They are used as a comparison engine and finite oracle. + +Ali Romman PR5698 supplies the complete actual restricted-C coframe construction, +source replay and proof checks. Its 32 package files and all nested notices are +frozen in source/. replay.py and verify_source.py are explicitly marked derived +copies with only source paths and state-equality calls changed. Preserve +Dugongue PR5687, Cao Yifan PR4610/4470, Cinna Davis, DaysSky, Nick Petalas, +Ryanson Jonathan, zxv, Jacob Alan Sussman and all native/helper/phase/ROW/controller, +compiler, precision and stock attribution in those retained files. + +BigCactusLabs PR702 and Joshua Snider's cold-wrapper quadratic certificate are +related independent finite amplitude/phase audits. Their scopes and credit are +separate from this implementation. No source contribution is reassigned here. + +The new contribution is the exact polynomial-state engine, explicit full-source +integration, proof-check preservation binding, independent representation tests, +all-actual-state cross-check and complete same-fixture runtime evidence. There +is no change to the mathematical construction, selected result or physical bill. +No independent human review or proof-kernel acceptance is claimed. diff --git a/research/clifford-chart-contraction/source/engine/source/PR5704-quadratic.py b/research/clifford-chart-contraction/source/engine/source/PR5704-quadratic.py new file mode 100644 index 0000000000..ce3c86ec07 --- /dev/null +++ b/research/clifford-chart-contraction/source/engine/source/PR5704-quadratic.py @@ -0,0 +1,283 @@ +"""Exact affine-support states for the retained Gaussian-dyadic gate grammar. + +The method is classical stabilizer simulation. This implementation keeps the +absolute Gaussian-integer scalar. Ali Romman with substantial OpenAI Codex +assistance. Apache-2.0. +""" + + +def need(condition, message): + if not condition: + raise ValueError(message) + + +def bits(mask): + while mask: + bit = mask & -mask + yield bit.bit_length() - 1 + mask ^= bit + + +def term(poly, mask, value): + value = (poly.get(mask, 0) + value) % 4 + if value: + poly[mask] = value + else: + poly.pop(mask, None) + + +def affine(poly, form, coefficient): + """Add a coefficient times an affine Boolean form, modulo four.""" + coefficient %= 4 + if not coefficient: + return + constant = form & 1 + term(poly, 0, coefficient * constant) + signed = coefficient * (1 - 2 * constant) + indices = list(bits(form >> 1)) + for i in indices: + term(poly, 1 << i, signed) + if coefficient & 1: + for k, i in enumerate(indices): + for j in indices[k + 1:]: + term(poly, (1 << i) | (1 << j), 2) + + +def product(poly, left, right): + """Add twice the product of two affine Boolean forms.""" + a, b = left & 1, right & 1 + u, v = list(bits(left >> 1)), list(bits(right >> 1)) + term(poly, 0, 2 * a * b) + if b: + for i in u: + term(poly, 1 << i, 2) + if a: + for j in v: + term(poly, 1 << j, 2) + for i in u: + for j in v: + term(poly, (1 << i) | (1 << j), 2) + + +def substitute(poly, forms): + result = {} + for mask, coefficient in poly.items(): + if not mask: + term(result, 0, coefficient) + elif mask.bit_count() == 1: + affine(result, forms[mask.bit_length() - 1], coefficient) + else: + need(mask.bit_count() == 2 and coefficient == 2, + 'A phase must have only even quadratic terms') + i, j = bits(mask) + product(result, forms[i], forms[j]) + return result + + +def value(poly, argument): + return sum(c for mask, c in poly.items() if argument & mask == mask) % 4 + + +def basis(columns): + """Return reduced binary columns with their original coordinates.""" + rows = {} + for j, column in enumerate(columns): + vector, coordinates = column, 1 << j + while vector: + pivot = vector.bit_length() - 1 + if pivot not in rows: + rows[pivot] = (vector, coordinates) + break + other, witness = rows[pivot] + vector ^= other + coordinates ^= witness + need(vector != 0, 'Support columns must be independent') + for pivot in sorted(rows): + vector, witness = rows[pivot] + for other in sorted(rows): + if other > pivot and rows[other][0] >> pivot & 1: + x, y = rows[other] + rows[other] = (x ^ vector, y ^ witness) + return rows + + +def coordinates(rows, vector): + result = 0 + for pivot in sorted(rows, reverse=True): + if vector >> pivot & 1: + column, witness = rows[pivot] + vector ^= column + result ^= witness + return None if vector else result + + +def multiply_i(pair, power): + a, b = pair + return ((a, b), (-b, a), (-a, -b), (b, -a))[power % 4] + + +def multiply(left, right): + a, b = left + c, d = right + return a * c - b * d, a * d + b * c + + +def normalize(pair, denominator): + need(pair != (0, 0), 'A unitary state cannot be zero') + while denominator and not ((pair[0] | pair[1]) & 1): + pair = (pair[0] // 2, pair[1] // 2) + denominator -= 1 + return pair, denominator + + +def matrix_vector(rows, vector): + return sum(((row & vector).bit_count() & 1) << j for j, row in enumerate(rows)) + + +def validate_integer(value_, limit, message): + need(type(value_) is int and 0 <= value_ < limit, message) + + +def signature(n, circuit, initial=0, counters=None): + """Return a canonical exact state without an exponential vector. + + A state is scalar times i^q(z) at offset xor columns*z. The columns + remain independent. The returned tuple describes every amplitude. + """ + need(type(n) is int and n >= 0, 'The width must be a nonnegative integer') + validate_integer(initial, 1 << n, 'Initial basis index') + columns, offset, poly = [], initial, {} + scalar, denominator = (1, 0), 0 + counts = counters if counters is not None else {} + + def count(key): + counts[key] = counts.get(key, 0) + 1 + + for gate in circuit: + need(isinstance(gate, (tuple, list)) and gate, 'Nonempty gate record') + kind = gate[0] + r = len(columns) + if kind == 'P': + need(len(gate) == 2 and len(gate[1]) == n, 'Permutation dimensions') + rows = gate[1] + for row in rows: + validate_integer(row, 1 << n, 'Binary permutation row') + basis(rows) + offset = matrix_vector(rows, offset) + columns = [matrix_vector(rows, x) for x in columns] + elif kind == 'X': + need(len(gate) == 2, 'Translation record') + validate_integer(gate[1], 1 << n, 'Translation mask') + offset ^= gate[1] + elif kind == 'phase': + need(len(gate) == 2 and type(gate[1]) is int, 'Global phase record') + term(poly, 0, gate[1]) + elif kind == 'D': + need(len(gate) == 3 and len(gate[1]) == len(gate[2]) == n, + 'Diagonal dimensions') + rows, linear = gate[1], gate[2] + for i in range(n): + validate_integer(rows[i], 1 << n, 'Binary diagonal row') + need(type(linear[i]) is int and linear[i] % 2 == (rows[i] >> i & 1), + 'Diagonal parity lift') + for j in range(i): + need((rows[i] >> j & 1) == (rows[j] >> i & 1), + 'Symmetric diagonal matrix') + forms = [(offset >> i & 1) | + sum((column >> i & 1) << (j + 1) for j, column in enumerate(columns)) + for i in range(n)] + for i, coefficient in enumerate(linear): + affine(poly, forms[i], coefficient) + for j in bits(rows[i] >> (i + 1)): + product(poly, forms[i], forms[i + 1 + j]) + elif kind == 'C': + need(len(gate) == 3 and type(gate[2]) is int and gate[2] in (-1, 1), + 'Translation-root record and sign') + q, sign = gate[1:] + validate_integer(q, 1 << n, 'Translation-root mask') + witness = coordinates(basis(columns), q) + scalar = multiply(scalar, (1, sign)) + denominator += 1 + term(poly, 1 << r, -sign) + if witness is None: + columns.append(q) + count('independent_root') + else: + # The last variable has zero output after this substitution. + forms = [(1 << (i + 1)) | (((witness >> i) & 1) << (r + 1)) + for i in range(r)] + [1 << (r + 1)] + poly = substitute(poly, forms) + last = 1 << r + coefficient = poly.pop(last, 0) + neighbours = 0 + for mask in list(poly): + if mask & last: + need(mask.bit_count() == 2 and poly[mask] == 2, + 'Dependent-root quadratic term') + neighbours ^= mask ^ last + del poly[mask] + if coefficient & 1: + scalar = multiply(scalar, (1, 1 if coefficient == 1 else -1)) + affine(poly, neighbours << 1, -coefficient) + count('odd_elimination') + else: + scalar = (2 * scalar[0], 2 * scalar[1]) + constant = coefficient // 2 + if neighbours: + pivot = (neighbours & -neighbours).bit_length() - 1 + free = [i for i in range(r) if i != pivot] + forms = [0] * r + for j, i in enumerate(free): + forms[i] = 1 << (j + 1) + forms[pivot] = constant | sum( + 1 << (j + 1) for j, i in enumerate(free) if neighbours >> i & 1) + poly = substitute(poly, forms) + if constant: + offset ^= columns[pivot] + columns = [columns[i] ^ (columns[pivot] if neighbours >> i & 1 else 0) + for i in free] + count('even_restriction') + else: + need(constant == 0, 'A unitary root cannot annihilate the state') + count('even_free') + scalar, denominator = normalize(scalar, denominator) + else: + raise ValueError('Unknown gate: ' + str(kind)) + need(len(columns) <= n, 'Support dimension cannot exceed width') + counts['peak_support_rank'] = max(counts.get('peak_support_rank', 0), len(columns)) + + rows = basis(columns) + reduced_offset, shift = offset, 0 + for pivot in sorted(rows, reverse=True): + if reduced_offset >> pivot & 1: + column, witness = rows[pivot] + reduced_offset ^= column + shift ^= witness + ordered = [rows[p] for p in sorted(rows)] + forms = [(shift >> i & 1) | sum(((witness >> i) & 1) << (j + 1) + for j, (_, witness) in enumerate(ordered)) for i in range(len(columns))] + poly = substitute(poly, forms) + scalar = multiply_i(scalar, poly.pop(0, 0)) + scalar, denominator = normalize(scalar, denominator) + return (n, reduced_offset, tuple(x for x, _ in ordered), tuple(sorted(poly.items())), + scalar[0], scalar[1], denominator) + + +def amplitude(state, index): + n, offset, columns, terms, real, imag, denominator = state + validate_integer(index, 1 << n, 'Amplitude index') + argument = coordinates(basis(columns), index ^ offset) + if argument is None: + return (0, 0), 0 + pair = multiply_i((real, imag), value(dict(terms), argument)) + return pair, denominator + + +def equal_operators(left, right): + """Compare valid retained Clifford objects, including absolute phase. + + Their tableaus must be derived from their circuits by the retained exact + constructors. An arbitrary supplied tableau is not a valid input contract. + """ + return (left.n == right.n and left.tab == right.tab and + signature(left.n, left.circuit) == signature(right.n, right.circuit)) diff --git a/research/clifford-chart-contraction/source/row/bell_reads.py b/research/clifford-chart-contraction/source/row/bell_reads.py new file mode 100644 index 0000000000..32b2ed2a94 --- /dev/null +++ b/research/clifford-chart-contraction/source/row/bell_reads.py @@ -0,0 +1,128 @@ +"""Emit the phase-corrected Bell measurements for the compiled Clifford row. + +Use --emit for the identity fibre in order. Labels have four low Z bits +and four high X bits. apoursh with substantial OpenAI Codex assistance. +Apache-2.0. Phase correction is from PR7799. +""" +import argparse +from functools import cache +import json +from typing import NamedTuple + +from compile_row import DENOMINATOR, IDENTITY, SEED, apply, iter_terms, pairing + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def parity(value): + return value.bit_count() % 2 + + +def q0(v): + return parity((v >> 4) & v) + + +def transvection(axis, vector): + return vector ^ (axis if pairing(axis, vector) else 0) + + +def decompose(matrix): + """Write a symplectic map as a sequence of transvections in application order.""" + columns = list(matrix) + corrections = [] + for i, target in enumerate(IDENTITY): + source = columns[i] + if source == target: + continue + if pairing(source, target): + axes = (source ^ target,) + else: + middle = next(v for v in range(256) + if pairing(v, source) and pairing(v, target) + and all(pairing(source ^ v, fixed) == 0 for fixed in IDENTITY[:i])) + axes = (source ^ middle, middle ^ target) + for axis in axes: + columns = [transvection(axis, v) for v in columns] + corrections.append(axis) + require(tuple(columns) == IDENTITY, "transvection reduction failed") + return tuple(reversed(corrections)) + + +def step(axis, v, bell): + """Phase exponent modulo four of a transvection on one unphased Weyl label.""" + out = transvection(axis, v) + exponent = 0 + if out != v: + exponent = 1 + q0(axis) + 2 * parity((axis & 15) & (v >> 4)) + if bell: + if q0(axis): + exponent += 1 + else: + exponent += 2 + 2 * parity((out & 15) & (axis >> 4)) + out ^= axis + return out, exponent % 4 + + +def label_sum(labels): + total = 0 + for label in labels: + total ^= label + return total + + +@cache +def transported_seed(matrix): + """Return the six output labels and the seed's transport phase exponent.""" + labels = list(SEED) + weight = label_sum(SEED) + phase = 0 + for axis in decompose(matrix): + next_weight, gamma = step(axis, weight, False) + values = [step(axis, label, True) for label in labels] + labels = [value for value, _ in values] + phase += sum(theta for _, theta in values) - gamma + weight = next_weight + # Independent affine check. q(Sv+b)=q(v) fixes the offset b uniquely. + offset = labels[0] + require(all(q0(apply(matrix, u) ^ offset) == q0(u) for u in (0, *IDENTITY)), + "Bell offset violates transpose parity") + require(all(label == apply(matrix, v) ^ offset for v, label in zip(SEED, labels, strict=True)) + and weight == label_sum(labels), "misordered symplectic transport") + return tuple(labels), phase % 4 + + +class Read(NamedTuple): + numerator: int + input_labels: tuple[int, ...] + output_labels: tuple[int, ...] + correction_i: int + + +def iter_reads(target=IDENTITY): + """Weight is numerator/DENOMINATOR. Multiply the corrected singleton by i^correction_i.""" + for term in iter_terms(target): + i, phase_i = transported_seed(term.input_map) + j, phase_j = transported_seed(term.output_map) + yield Read(term.numerator, i, j, (phase_i - phase_j) % 4) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--emit", action="store_true", help="emit one JSON object per identity-fibre read") + args = parser.parse_args() + pairs = set() + for read in iter_reads(): + pair = read.input_labels, read.output_labels + require(pair not in pairs, "repeated literal Bell address") + pairs.add(pair) + if args.emit: + print(json.dumps(dict(read._asdict(), denominator=DENOMINATOR))) + if not args.emit: + print(f"PASS_BELL_READS distinct_pairs={len(pairs)}") + + +if __name__ == "__main__": + main() diff --git a/research/clifford-chart-contraction/source/row/compile_row.py b/research/clifford-chart-contraction/source/row/compile_row.py new file mode 100644 index 0000000000..daf35d6a26 --- /dev/null +++ b/research/clifford-chart-contraction/source/row/compile_row.py @@ -0,0 +1,247 @@ +"""Compile the shear-character certificate in PR7799 into signed Bell reads. + +Binary vectors have four low Z bits and four high X bits, least significant +bit for qubit one. A matrix is the tuple of images of the standard basis. +apoursh, with substantial OpenAI Codex and separate agent assistance. +Apache-2.0. The seed, character cases and plane selection are from PR7799. +""" +import argparse +from collections import Counter, defaultdict +from functools import cache +from itertools import combinations, combinations_with_replacement +import json +from typing import NamedTuple + + +IDENTITY = tuple(1 << i for i in range(8)) +DENOMINATOR = 1024 +SEED = (0, 1, 2, 4, 8, 128) +UPPER = tuple(combinations_with_replacement(range(4), 2)) + + +class Term(NamedTuple): + numerator: int + input_map: tuple[int, ...] + output_map: tuple[int, ...] + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def apply(columns, vector): + result = 0 + while vector: + bit = vector & -vector + result ^= columns[bit.bit_length() - 1] + vector ^= bit + return result + + +def compose(left, right): + return tuple(apply(left, v) for v in right) + + +def pairing(u, v): + return (((u >> 4) & v) ^ ((v >> 4) & u)).bit_count() % 2 + + +def span(basis): + points = [0] + for v in basis: + points += [u ^ v for u in points] + return points + + +def is_symplectic(matrix): + return (len(matrix) == 8 and all(isinstance(v, int) and 0 <= v < 256 for v in matrix) + and all(pairing(matrix[i], matrix[j]) == pairing(IDENTITY[i], IDENTITY[j]) + for i, j in combinations(range(8), 2))) + + +@cache +def shear(mask): + """Send (z,x) to (z+B x,x), with B's upper triangle given by mask.""" + result = list(IDENTITY) + for index, (i, j) in enumerate(UPPER): + if mask & (1 << index): + result[4 + i] ^= 1 << j + if i != j: + result[4 + j] ^= 1 << i + return tuple(result) + + +def pair_mask(u, v): + return sum(((((u >> i) & (v >> j)) ^ ((u >> j) & (v >> i))) & 1) << k + for k, (i, j) in enumerate(UPPER)) + + +def quadratic_address(v): + return sum(1 << k for k, (i, j) in enumerate(UPPER) if v & (1 << i) and v & (1 << j)) + + +def select_plane(ch): + # Match the deterministic binary ordering used by the PR7799 verifier. + values = tuple((ch & quadratic_address(v)).bit_count() % 2 for v in range(16)) + + def polar(u, v): + return values[u] ^ values[v] ^ values[u ^ v] + + if any(all(polar(v, b) == 0 for b in (1, 2, 4, 8)) for v in range(1, 16)): + return next(w for w in combinations(range(1, 16), 3) + if len(set(span(w))) == 8 and all(polar(i, j) == 0 for i, j in combinations(w, 2))) + r = next(v for v in range(1, 16) if values[v] == 0) + hyperplane = [u for u in range(16) if polar(r, u) == 0] + z2 = next(v for v in hyperplane if v not in (0, r)) + dual = next(x for x in range(1, 16) if all((x & v).bit_count() % 2 == 0 for v in hyperplane)) + return r, z2, dual << 4 + + +def canonical_basis(points): + basis = [] + for v in sorted(points): + if v not in span(basis): + basis.append(v) + return tuple(basis) + + +def extend_basis(w): + z = list(w) + z.append(next(v for v in range(1, 256) if v not in span(z) and all(pairing(v, u) == 0 for u in z))) + x = [] + for i in range(4): + x.append(next(v for v in range(1, 256) + if all(pairing(v, u) == int(i == j) for j, u in enumerate(z)) + and all(pairing(v, b) == 0 for b in x))) + matrix = tuple(z + x) + require(is_symplectic(matrix), "plane transporter is not symplectic") + return matrix + + +def walsh(characters): + values = [0] * 1024 + for ch in characters: + values[ch] = 1 + step = 1 + while step < len(values): + for start in range(0, len(values), 2 * step): + for i in range(start, start + step): + j = i + step + values[i], values[j] = values[i] + values[j], values[i] - values[j] + step *= 2 + return values + + +def normalizer_representatives(w, p_basis): + if len(p_basis) == 3: + return [0] + dual = next(v for v in w if v >> 4) + p = span(p_basis) + representatives = {} + for mask in range(1024): + b_dual = apply(shear(mask), dual) ^ dual + key = min(b_dual ^ u for u in p) + representatives.setdefault(key, mask) + require(len(representatives) == 4, "mixed-plane normalizer index") + return sorted(representatives.values()) + + +def iter_terms(target=IDENTITY): + """Yield numerator / DENOMINATOR weights on transported coset *sums*. + + Apply the source and target transporters to SEED via the affine Bell + action and undo the singleton/transport phases as specified in PROOF.md. + The weighted sum of those 16-by-16 blocks is the target's fibre matrix + on the image of the observation map. Target defaults to the identity. + """ + require(is_symplectic(target), "invalid target symplectic matrix") + by_plane = defaultdict(list) + for ch in range(1024): + by_plane[canonical_basis(span(select_plane(ch)))].append(ch) + for w, chars in sorted(by_plane.items()): + pure = tuple(z for z in w if z < 16) + h = span(tuple(pair_mask(u, v) for u, v in combinations(pure, 2))) + representatives = normalizer_representatives(w, pure) + g = extend_basis(w) + values = walsh(chars) + divisor = 4 if len(pure) == 2 else 1 + for delta, value in enumerate(values): + if not value or delta != min(delta ^ offset for offset in h): + continue + require(value % divisor == 0, "coefficient needs a finer denominator") + for b in representatives: + right = compose(shear(b), g) + left = compose(target, compose(shear(delta ^ b), g)) + yield Term(value // divisor, right, left) + + +def seed_subgroup(): + hats = [pair_mask(1 << i, 1 << j) for i, j in combinations(range(3), 2)] + return tuple(shear(mask) for mask in span(hats)) + + +@cache +def inverse(matrix): + # Binary symplectic inverse from the images of a paired basis. + return tuple(sum(pairing(matrix[i ^ 4], u) << i for i in range(8)) for u in IDENTITY) + + +def bell_tuple(matrix): + # q(L v)=q(v) gives = q(u)+q(S^-1 u), hence b from the + # images of basis vectors under the inverse. q(e_j)=0. + inv = inverse(matrix) + offset = 0 + for j in range(8): + v = inv[j ^ 4] + offset |= (((v >> 4) & v).bit_count() % 2) << j + return tuple(apply(matrix, v) ^ offset for v in SEED) + + +def check(target): + accum = Counter() + seen = set() + terms = list(iter_terms(target)) + subgroup = seed_subgroup() + for weight, right, left in terms: + products = {compose(left, compose(c, inverse(right))) for c in subgroup} + key = frozenset(products) + require(len(products) == 8 and key not in seen, "repeated or malformed coset") + seen.add(key) + for item in products: + accum[item] += weight + require({k: v for k, v in accum.items() if v} == {target: DENOMINATOR}, + "signed coset sum is not the single target") + require(len(accum) == 8304, "expanded union size") + mass_by_input = Counter() + for term in terms: + mass_by_input[bell_tuple(term.input_map)] += abs(term.numerator) + require(Counter(mass_by_input.values()) == {128: 29, 192: 10, 224: 8, 240: 8, 288: 12}, + "absolute coefficient mass by input") + require(8 * sum(m*m for m in mass_by_input.values()) * 64 == 1319 * DENOMINATOR**2, + "simultaneous squared norm bound") + numerators = [term.numerator for term in terms] + require(len(terms) == 4265 and sum(abs(w) for w in numerators) == 12800, + "row sparsity or absolute mass") + require(sum(w*w for w in numerators) == DENOMINATOR**2 // 8, "squared row mass") + require(any(w % 2 for w in numerators), "denominator 1024 not attained") + return len(accum) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--emit", action="store_true", help="emit the identity row as JSON lines") + args = parser.parse_args() + if args.emit: + for term in iter_terms(): + print(json.dumps(term._asdict(), separators=(",", ":"))) + return + covered = check(IDENTITY) + # Hadamard on each qubit swaps the two coordinate registers. + require(check(IDENTITY[4:] + IDENTITY[:4]) == covered, "translated support") + print(f"PASS_COMPRESSED_CLIFFORD_ROW terms=4265 group_terms=34120 union={covered}" + " denominator=1024 absolute_mass=25/2 squared_mass=1/8 row_norm_squared=2^45") + + +if __name__ == "__main__": + main() diff --git a/research/clifford-chart-contraction/source/row/raw_row.py b/research/clifford-chart-contraction/source/row/raw_row.py new file mode 100644 index 0000000000..1787feb76a --- /dev/null +++ b/research/clifford-chart-contraction/source/row/raw_row.py @@ -0,0 +1,284 @@ +"""Exact computational-basis coefficients of the compiled identity decoder. + +A row or column address is a 52-bit integer, with the first register in +the most significant nibble. A returned numerator has denominator 4096. +apoursh, with substantial OpenAI Codex assistance. Apache-2.0. +""" +import argparse +from collections import Counter, defaultdict +from dataclasses import dataclass +from functools import cache +from itertools import islice +import json + +from bell_reads import iter_reads, label_sum +from compile_row import DENOMINATOR + + +BITS = 52 +RAW_DENOMINATOR = 4 * DENOMINATOR + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def pack(nibbles): + return sum(nibble << (4 * i) for i, nibble in enumerate(nibbles)) + + +def split_address(address): + if not isinstance(address, int) or not 0 <= address < 1 << BITS: + raise ValueError("row and column must be unsigned 52-bit addresses") + return tuple((address >> (4 * j)) & 15 for j in reversed(range(13))) + + +@dataclass(frozen=True) +class Bucket: + masks: tuple[int, ...] + numerators: tuple[int, ...] + + def signature(self, point): + return sum(((mask & point).bit_count() % 2) << j for j, mask in enumerate(self.masks)) + + def point_at(self, signature, index): + """Unrank the free bits, then solve the parity equations by leading bit.""" + pivots = sorted((mask.bit_length()-1, j) for j, mask in enumerate(self.masks)) + pivot_bits = {bit for bit, _ in pivots} + point = 0 + for bit in range(BITS): + if bit not in pivot_bits: + point |= (index & 1) << bit + index >>= 1 + for bit, j in pivots: + target = (signature >> j) & 1 + value = target ^ ((self.masks[j] & point).bit_count() % 2) + point |= value << bit + return point + + +def make_bucket(terms): + masks = [] + pivots = {} + weights = Counter() + for frequency, weight in terms: + address = 0 + while frequency: + bit = frequency.bit_length()-1 + if bit not in pivots: + pivots[bit] = len(masks) + masks.append(frequency) + j = pivots[bit] + frequency ^= masks[j] + address ^= 1 << j + weights[address] += weight + # Orthogonality of the independent masks makes every sign pattern attainable. + table = [weights[i] for i in range(1 << len(masks))] + step = 1 + while step < len(table): + for start in range(0, len(table), 2 * step): + for i in range(start, start + step): + a, b = table[i], table[i+step] + table[i], table[i+step] = a+b, a-b + step *= 2 + return Bucket(tuple(masks), tuple(table)) + + +@cache +def raw_plan(): + terms = defaultdict(list) + for read in iter_reads(): + labels = read.output_labels + read.input_labels + shifts = tuple(t >> 4 for t in labels) + singleton = label_sum(labels) + require(singleton < 16, "identity trace is not diagonal in this term") + require(read.correction_i == 0, "identity term has an unexpected phase") + frequency = pack([*(t & 15 for t in labels), singleton]) + terms[shifts].append((frequency, read.numerator)) + return {key: make_bucket(value) for key, value in sorted(terms.items())} + + +def coefficient_numerator(row, column): + r, c = split_address(row), split_address(column) + if r[-1] != c[-1]: + return 0 + pairs = r[:-1] + c[:-1] + shifts = tuple(a ^ b for a, b in zip(pairs[::2], pairs[1::2], strict=True)) + bucket = raw_plan().get(shifts) + if bucket is None: + return 0 + point = pack((*pairs[1::2], r[-1])) + return bucket.numerators[bucket.signature(point)] + + +def matrix_addresses(shifts, point): + addresses = [] + singleton = (point >> 48) & 15 + for start in (0, 6): + address = 0 + for index in range(start, start+6): + v = (point >> (4*index)) & 15 + address = (address << 8) | ((v ^ shifts[index]) << 4) | v + addresses.append((address << 4) | singleton) + return tuple(addresses) + + +def probe_at(index): + """One nonzero coordinate, in deterministic bucket/signature/free-bit order.""" + if not isinstance(index, int) or index < 0: + raise ValueError("probe index must be a nonnegative integer") + for shifts, bucket in raw_plan().items(): + size = 1 << (BITS-len(bucket.masks)) + for signature, numerator in enumerate(bucket.numerators): + if numerator != 0: + if index < size: + point = bucket.point_at(signature, index ^ (index >> 1)) + row, col = matrix_addresses(shifts, point) + return row, col, numerator + index -= size + raise ValueError("probe index outside the nonzero support") + + +def cell_geometry(shifts, bucket): + def address(signature, index): + row, column = matrix_addresses(shifts, bucket.point_at(signature, index)) + return (row << BITS) | column + + origin = address(0, 0) + directions = [origin ^ address(0, 1 << j) for j in range(BITS - len(bucket.masks))] + return address, directions + + +def iter_probes(): + """Stream the exact nonzero support of the identity row in probe_at order.""" + for shifts, bucket in raw_plan().items(): + address, directions = cell_geometry(shifts, bucket) + size = 1 << len(directions) + for signature, numerator in enumerate(bucket.numerators): + if not numerator: + continue + pointer = address(signature, 0) + for i in range(size): + row, col = divmod(pointer, 1 << BITS) + yield row, col, numerator + if i + 1 < size: + # Consecutive reflected Gray words flip this one free bit. + delta = i + 1 + pointer ^= directions[(delta & -delta).bit_length() - 1] + + +def first_last_addresses(): + """Extrema of the nonzero row on a row-major tape, over affine Walsh cells.""" + first, last = 1 << (2*BITS), -1 + for shifts, bucket in raw_plan().items(): + address, generators = cell_geometry(shifts, bucket) + pivots = {} + for v in generators: + while v: + bit = v.bit_length() - 1 + if bit not in pivots: + pivots[bit] = v + break + v ^= pivots[bit] + require(len(pivots) == BITS - len(bucket.masks), "address map lost a free bit") + directions = [pivots[bit] for bit in sorted(pivots, reverse=True)] + for i, n in enumerate(bucket.numerators): + if not n: + continue + lo = hi = address(i, 0) + for direction in directions: + lo = min(lo, lo ^ direction) + hi = max(hi, hi ^ direction) + first, last = min(first, lo), max(last, hi) + return first, last + + +def check_diagonal_columns(): + # For U=Z^z, the raw column is supported on equal row and column + # addresses. There r=s for every pair, leaving 24 pair bits and one + # free singleton. Push these free bits through the parity equations. + outputs = [0] * 16 + for shifts, bucket in raw_plan().items(): + require(shifts[:6] == shifts[6:], "diagonal fixture shift layout") + image = {0} + for bit in range(24): + basis_point = (1 << bit) | (1 << (bit+24)) + character = bucket.signature(basis_point) + image |= {s ^ character for s in image} + multiplicity = 2**24 // len(image) + shift_sum = label_sum(shifts[:6]) + for singleton in range(16): + offset = bucket.signature(singleton << 48) + total = sum(bucket.numerators[s ^ offset] for s in image) * multiplicity + for z in range(16): + sign = (-1) ** (((shift_sum ^ singleton) & z).bit_count() % 2) + outputs[z] += sign * total + require(outputs == [RAW_DENOMINATOR * 4**13] + [0]*15, + "normalized diagonal Clifford recovery from raw address weights") + + +def check(): + counts = Counter() + cells = 0 + checked = 0 + plan = raw_plan() + for shifts, bucket in plan.items(): + size = 1 << (BITS - len(bucket.masks)) + cells += len(bucket.numerators) + for signature, n in enumerate(bucket.numerators): + counts[n] += size + for index in (0, size-1): + point = bucket.point_at(signature, index) + require(bucket.signature(point) == signature, "unranking a Walsh class") + require(coefficient_numerator(*matrix_addresses(shifts, point)) == n, + "raw address lookup mismatch") + checked += 1 + expected = {0: 77827831060496384, 128: 10133099161583616, -128: 10133099161583616, + 512: 492581209243648, -512: 492581209243648} + require(counts == expected and len(plan) == 22, "raw coefficient multiplicities") + support = sum(count for n, count in counts.items() if n) + require(support == 151 * 2**47, "raw query bill") + require(sum(n*n*count for n,count in counts.items()) == RAW_DENOMINATOR**2 * 2**45, + "computational and Bell row norms disagree") + for index in (0, 1, support//2, support-2, support-1): + row, col, n = probe_at(index) + require(n == coefficient_numerator(row, col) and n != 0, "nonzero-support unranking") + require(list(islice(iter_probes(), 64)) == [probe_at(i) for i in range(64)], + "stream order disagrees with indexed access") + check_diagonal_columns() + first, last = first_last_addresses() + require(first == 0x00000000000210000000000021 and first + last == (1 << (2*BITS)) - 1, + "row-major tape extrema") + for address in (first, last): + require(coefficient_numerator(*divmod(address, 1 << BITS)) != 0, "inactive tape endpoint") + print(f"PASS_RAW_IDENTITY_ROW buckets={len(plan)} Walsh_cells={cells}" + f" boundary_lookups={checked} nonzero_coordinates={support} squared_norm=2^45" + f" first={first:026x} last={last:026x}") + + +def integer(text): + return int(text, 0) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + action = parser.add_mutually_exclusive_group() + action.add_argument("--entry", type=integer, nargs=2, metavar=("ROW", "COLUMN")) + action.add_argument("--probe-index", type=integer, + help="unrank one nonzero coordinate, starting at zero") + args = parser.parse_args() + if args.entry is not None: + row, col = args.entry + numerator = coefficient_numerator(row, col) + elif args.probe_index is not None: + row, col, numerator = probe_at(args.probe_index) + else: + check() + return + print(json.dumps({"row": row, "column": col, "numerator": numerator, + "denominator": RAW_DENOMINATOR})) + + +if __name__ == "__main__": + main() diff --git a/research/clifford-chart-contraction/verify.py b/research/clifford-chart-contraction/verify.py new file mode 100644 index 0000000000..e025e43e70 --- /dev/null +++ b/research/clifford-chart-contraction/verify.py @@ -0,0 +1,210 @@ +"""Exact tests for the compact width-13 identity-row consumer; Apache-2.0.""" +import argparse +from fractions import Fraction +from itertools import combinations, product +from pathlib import Path +from random import Random +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from cell_tape import MASKS, SHIFTS, SIGNATURE, Tape, evaluate, phase_mask_symbols +from contract import Q, Spectrum, apply, contract, one_cell, parity, read_plan +from raw_row import RAW_DENOMINATOR, coefficient_numerator, matrix_addresses, raw_plan + + +def require(ok, message): + if not ok: + raise ValueError(message) + + +def direct_spectrum(n, phase, w): + counts = [0] * 4 + for x in range(1 << n): + counts[(Q.value(phase, x) + 2 * parity(w & x)) % 4] += 1 + return counts[0] - counts[2], counts[1] - counts[3] + + +def spectrum_tests(): + cases = 0 + for n in range(4): + pair_masks = [(1 << i) | (1 << j) for i, j in combinations(range(n), 2)] + for linear in product(range(4), repeat=n): + for edges in range(1 << len(pair_masks)): + phase = {1 << i: a for i, a in enumerate(linear) if a} + phase.update({term: 2 for j, term in enumerate(pair_masks) if edges >> j & 1}) + spectrum = Spectrum(n, phase) + for w in range(1 << n): + angle = spectrum.rotation(w) + value = (0, 0) if angle is None else Q.multiply_i(spectrum.value, angle) + require(value == direct_spectrum(n, phase, w), "Fourier sign or radical") + cases += 1 + return cases + + +def raw_address(shifts, point): + r, c = matrix_addresses(shifts, point) + return (r << 52) | c + + +def literal(state, selected=None): + _, origin, cols, terms, a, b, den = state + total = [0, 0] + for x in range(1 << len(cols)): + address = origin ^ apply(cols, x) + row, col = divmod(address, 1 << 52) + if selected is not None and address not in selected: + continue + weight = coefficient_numerator(row, col) + unit = Q.multiply_i((a, b), Q.value(dict(terms), x)) + for j in range(2): + total[j] += weight * unit[j] + return tuple(Fraction(z, RAW_DENOMINATOR << den) for z in total) + + +def small_circuits(): + rng = Random(7800) + plan = raw_plan() + count = nonzero = 0 + for ix, (shifts, bucket) in enumerate(plan.items()): + sig = next(i for i, w in enumerate(bucket.numerators) if w) + first = raw_address(shifts, bucket.point_at(sig, 0)) + varied = [raw_address(shifts, bucket.point_at(sig, 1 << j)) ^ first for j in range(4)] + other = next((sig ^ (1 << j) for j in range(len(bucket.masks))), sig) + if other != sig: + varied.append(raw_address(shifts, bucket.point_at(other, 0)) ^ first) + varied.extend([1, 1 << 38]) # change singleton XOR and a Bell shift + circuit = [('C', d, rng.choice((-1, 1))) for d in varied] + circuit.append(('phase', ix)) + # Apply a real quadratic coupling and arbitrary powers of i in raw coordinates. + rows = [1 << j for j in range(104)] + rows[32] ^= 1 << 65 + rows[65] ^= 1 << 32 + circuit.append(('D', rows, [rng.choice((1, 3)) for _ in rows])) + state = Q.signature(104, circuit, initial=first) + actual, _ = contract(state) + require(actual == literal(state), "Small-support literal full contraction") + valid = {raw_address(shifts, bucket.point_at(sig, j)) for j in range(16)} + partial, _ = one_cell(state, shifts, bucket.masks, sig, bucket.numerators[sig]) + # Get the expected cell independently by filtering raw coordinates, including + # cases in which a changed shift happens to remain in another active bucket. + require(partial == literal(state, valid), "Single active cell") + count += 1 + nonzero += actual != (0, 0) + require(nonzero > 0, "Small fixtures must detect genuine outputs") + return count, nonzero + + +def bell_column(extra=()): + # Prepare the 52 equality pairs and cancel the translation roots' local phases. + roots = [('C', (1 << j) | (1 << (j + 52)), 1) for j in range(52)] + rows = [1 << j if j < 52 else 0 for j in range(104)] + circuit = roots + [('D', rows, [1] * 52 + [0] * 52), ('phase', 2), *extra] + return Q.signature(104, circuit) + + +def full_columns(): + shift = sum(1 << (52 + 4*j) for j in range(13)) + cz = [0] * 104 + for j in range(13): + a = 52 + 4*j + cz[a] |= 1 << (a+1) + cz[a+1] |= 1 << a + observations = [ + (bell_column(), (1, 0)), + (bell_column([('phase', 1)]), (0, 1)), + (bell_column([('X', shift)]), (0, 0)), + (bell_column([('D', cz, [0]*104)]), (0, 0)), + ] + counts = [] + for state, expected in observations: + result, stats = contract(state) + require(result == expected, "Literal normalized Clifford tensor column") + counts.append(stats) + return counts + + +def coupled_state(mask=0): + # The address has 13 nibbles on each side. Couple corresponding second + # nibbles in the six Bell pairs; the remaining singleton has no coupling. + rows = [1 << j for j in range(104)] + for pair in range(6): + for bit in range(4): + j = 4*(11-2*pair)+bit + rows[j] |= 1 << (j+52) + rows[j+52] |= 1 << j + return Q.signature(104, [('C', 1 << j, 1) for j in range(104)] + + [('D', rows, [1+2*((mask >> j) & 1) for j in range(104)])]) + + +def independent_coupled(): + # For frequency nibbles a,b the two 4-bit free words r,s have sum + # of (-1)^(r.s+a.r+b.s) equal to 16*(-1)^(a.b). The singleton + # contributes 16 or zero according to its four frequency bits. + total = 0 + for terms in read_plan().values(): + for freq, weight in terms: + if freq >> 48: + continue + left, right = (freq & ((1<<24)-1)), (freq >> 24) & ((1<<24)-1) + total += weight * (-1)**parity(left & right) + return Fraction(total * 16**7, RAW_DENOMINATOR << 52) + + +def tape_tests(): + bucket = raw_plan()[SHIFTS] + weight = bucket.numerators[SIGNATURE] + require(bucket.masks == MASKS and weight == 128, "Fixed cell must match the raw compiler") + rng = Random(104) + samples = [0, *[1 << j for j in range(104)], *(rng.getrandbits(104) for _ in range(32))] + outputs = set() + for mask in samples: + symbols = phase_mask_symbols(mask) + tape = Tape(symbols) + received = evaluate(tape) + if mask == 0: + require(received == Fraction(1, 1 << 31), "Unmodulated exact cell") + require((tape.reads, tape.moves, tape.position, tape.symbols) == (104, 208, 0, symbols), + "One complete forward read and a restored input head") + # Compare with the general chart algorithm on every phase mask sampled. + got, _ = one_cell(coupled_state(mask), SHIFTS, MASKS, SIGNATURE, weight) + require(got == (received, 0), "Tape consumer and the general chart contraction disagree") + outputs.add(received) + require(len(outputs) >= 3, "Cell controls need both signs and zero") + return len(samples) + + +def main(): + import json + request = json.loads((Path(__file__).parent / "INPUT.json").read_text()) + example = Q.signature(104, request["circuit"], initial=request["initial"]) + require(contract(example)[0] == (Fraction(-1, 32), 0), "Published circuit example") + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--tape", action="store_true", help="Run the independent input-tape checks") + args = parser.parse_args() + if args.tape: + print(f"PASS_ACTIVE_CELL_TAPE masks={tape_tests()} reads=104 moves=208 " + "restored_position=0 fixed_lookup_bytes=401") + return + cases = spectrum_tests() + small, nonzero = small_circuits() + stats = full_columns() + tapes = tape_tests() + state = coupled_state() + require(len(state[2]) == 104, "Full-support fixture") + # Swapping register 2 with the singleton exchanges these two inputs. + first = (1 << 44) | (1 << 96) + second = 1 | (1 << 52) + require(Q.amplitude(state, first) == ((-1, 0), 52) and + Q.amplitude(state, second) == ((1, 0), 52), "Off-image register-swap witness") + coupled, counts = contract(state) + analytic = independent_coupled() + require(coupled == (analytic, 0) and analytic != 0, "104-bit Fourier pair factorization") + require(counts['buckets'] == 22 and counts['gauss'] == 1 and counts['terms'] == 4265, + "All buckets must share a single Gauss sum") + print(f"PASS_CHART_CONTRACTION Fourier_values={cases} small_circuits={small} " + f"small_nonzero={nonzero} normalized_columns={len(stats)} " + f"tape_masks={tapes} tape_reads=104 tape_moves=208 full_support=2^104 output={analytic} counts={counts}") + + +if __name__ == '__main__': + main()