diff --git a/research/selected-native-tensor-closure/NATIVE.json.gz b/research/selected-native-tensor-closure/NATIVE.json.gz new file mode 100644 index 0000000000..7eb40e7a8a Binary files /dev/null and b/research/selected-native-tensor-closure/NATIVE.json.gz differ diff --git a/research/selected-native-tensor-closure/PROOF.md b/research/selected-native-tensor-closure/PROOF.md new file mode 100644 index 0000000000..fffff67965 --- /dev/null +++ b/research/selected-native-tensor-closure/PROOF.md @@ -0,0 +1,411 @@ +# Exact native traces and the complete selected tensor interface + +Prepared for @CubeJerry with substantial OpenAI Codex assistance. Apache-2.0. +This is a source-bound algebraic certificate and a written universal argument. +It proves the exact-operator assertion labeled `native_all_columns` for the +pinned selected P104 native layer and its assembled caller. Physical +implementation, selected-rate dispatch, owned allocation/erasure and the other +framework premises remain separate. No admission record or kappa is changed. + +## 1. What must be composed + +The selected word is DreamingOfClouds' #6030 at canonical main +`7c49fe32c55de02c2c873655c804b16e4c3fef0a`. Its local certificate, the +all-forward P104 caller and the native tensor interpretation are different +objects. A dense equality at column width one cannot identify a sum of +different native group elements at all widths. Conversely, equality of two +*products* of unitary native gates is sufficient once every factor is lifted +columnwise and exterior scalar coefficients remain exterior. + +The local common-chart argument is already present in the P104 source and +#6635. #6043 independently checked every selected native operator densely. +#6546 supplies a numerical execution and tensor lift of the fixed local word, +and explicitly separates that from identifying recursive callers with it. +#5442 proves an all-width certificate for the different #5413 caller. +The contribution here is an independent exact trace acceptance mechanism and +its complete source-bound composition for the selected #6030 local word, +helpers, wrappers and all-forward caller. These predecessor identities are +credited, not asserted to be new lemmas. + +## 2. Exact traces of the native grammar + +Let the address dimension be n. Accepted primitive gates are an invertible +binary address permutation P_A, a binary translation X_v, a phase i^c, +a diagonal i^q(x), and + + C_v^s = ((1+s*i) I + (1-s*i) X_v)/2, s in {+1,-1}. + +Here q is a Z/4 polynomial with arbitrary linear coefficients and even mixed +coefficients. The source additionally requires its symmetric quadratic matrix +and diagonal-parity convention. The checker validates this grammar, every +binary inverse and every sign before using a trace. P_A and X_v permute an +orthonormal basis, diagonal phases have modulus one, and X_v is a self-adjoint +involution. On its +/- eigenspaces C_v^s has eigenvalues 1 and s*i. Thus every +accepted gate and every compared complete product is unitary, including its +normalization. Scalar ADD/COPY/SCALE programs are **not** passed to this test. + +Introduce n initial-address bits x and one binary branch t for each C gate. +The identity + + C_v^s = (1+s*i)/2 * sum_(t=0,1) i^(-s*t) X_v^t + +expresses every path amplitude as a known Gaussian dyadic scalar times +i^Q(x,t). Throughout the circuit each current address bit is an affine +Boolean form in x and previous branch variables. A phase gate contributes +only a quadratic polynomial modulo four: for a parity L=sum x_j mod2, + + L = sum x_j - 2 sum_(j=1 and an arbitrary spectator coefficient space S, write +L_f(U)=I_S tensor U^(tensor f), with the fixed address shuffle placing columns +in the source's slot order. Then + + L_f(UV)=L_f(U)L_f(V), L_f(U*)=L_f(U)*. + +This is a statement about full arrays, including arrays correlated across +columns and spectators: tensor basis vectors span the full space. It does +not require a pure-tensor input or zero spectator coordinates. + +Every accepted native equality is an equality between complete products. +Therefore each such equality lifts under L_f. A rank-r positive child lifts +to the identical elementary C on r*f selected binary axes. A monomial with +constant phase c contributes i^(c*f), and its remaining phase is the sum of +the one-column phase polynomials at all columns. A scalar coefficient a in a +register ADD or SCALE remains a, not a^f. In particular L_f(iI)=i^f I differs +from the exterior scalar iI in general. Likewise the width-one expansion of +C_v into two scalar-weighted translations is not an allowed termwise tensor +rewrite. The verifier tests both errors with exact width-two witnesses. + +The same argument extends a complete local address operator by identity to +any complement and conjugates it by any complete coordinate bijection. +Thus it supplies the algebraic input needed by #6878's occurrence-specific +full-field embeddings. It does not price those bijections or replace their +physical field-placement and ownership hypotheses. + +## 4. Complete caller join + +### Statement and hypotheses + +Fix exactly the WORD, RESULT, CONTROLLER, source chart definition, compiler +recipe payload and original port data pinned in SOURCES.json. Let f be any +positive integer. Each productive register contains an arbitrary vector in +S tensor (C^(2^145))^(tensor f), for any finite-dimensional coefficient space +S; equivalently one may use the source's 265 rows and its 120 unused identity +spectator rows. The 13,444 productive registers are independent inputs, not +copies or zero-filled helpers. Interpret native products by L_f, rational +register coefficients as exterior scalars, and INIT/CLEAR by the ideal owned +zero/reset operations in the source semantics. All coordinate maps below are +complete bijections, including their complementary coordinates. + +Under these hypotheses, the literal 18-forward-call supplier with its 16 +five-step wrappers, 15 thin queries, whole-idle jobs, scalar boundary programs +and whole-job adapters has the stated diagonal positive-Gaussian endpoint on +all 13,444 arbitrary productive inputs and returns its 29 local owned labels +to zero. Its paid and productive profiles are exactly those in the selected +RESULT. The proof is uniform in f and S. This is a theorem of the exact typed +algebraic program; it assumes ideal owned resets and native calls. It does not +establish an encoded tape implementation, an accelerated primitive tariff, +precision control, analytic recovery, or physical owned erasure. + +### Local chart induction + +Write Gamma_a for the full signed canonical chart associated with frame a. +The independent trace acceptance checks each selected native recipe as + + M_left G_r M_right = Gamma_b Gamma_a^*, + +where G_r is the product of positive elementary Gaussians on the first r +axes. This includes 2,886 distinct MOVE pairs, the additional whole-helper +pairs, and all 208 ordinary main adapters. The union has 2,922 pairs. The +identity is between full operators, so Section 3 gives its exact L_f lift. + +If a register's physical value is L_f(Gamma_a) z, a MOVE to b makes it +L_f(Gamma_b) z. ADD at a common current chart performs + + L_f(Gamma_a) z + c L_f(Gamma_a) w + = L_f(Gamma_a) (z+c w). + +SCALE is the same linearity identity; a COPY uses an owned zero target. +The coefficient c is retained outside L_f. All actual 18,404 ADD, 861 SCALE +and 23 COPY events satisfy their current-chart and ownership tests, rather +than relying on a declared common-chart convention. INIT establishes zero +and its recorded chart; CLEAR deletes only a currently owned value. This +last operation is an inherited ideal reset, not a deduction that arbitrary +nonzero data can be physically erased for free. + +The exact rational sparse replay starts with 799 independent formal inputs, +including the 29 owned entrance labels. After the 22,803 literal events it +checks every endpoint coefficient: the 770 public coordinates are unchanged +except Y_r -> Y_r+X_r at the 104 selected pairs; every owned entrance column +has been eliminated and every owned output is zero. There are 31 distinct +owned lifetimes, with peak 13. Finite verification determines this one fixed +word's rational identity. The preceding symbolic induction, rather than a +finite sweep of f values, proves that identity for all f and S. + +For each main port q put Q=C_q^+ and H_9=product_(j<9) C_(e_j)^+. +The actual ordinary main entry/exit recipes are checked against + + A_X = Gamma_initial-X Q^*, + A_Y = H_9 Q^* Gamma_final-Y^*. + +The source entrance frame of X is the one-vector frame [q], but its canonical +chart Gamma_initial-X need **not** equal the translation Gaussian Q. The +actual ordinary A_X above is therefore essential. The other two boundaries +are Gamma_initial-Y=I and Gamma_final-X=H_9. Combining the three nonzero rational endpoint paths with +these exact adapters gives, on the two main registers, + + F_0 = D_0 [[1,0],[Q^(-1),1]], D_0=H_9 Q^(-1). + +The checker verifies all three complete products separately at every port, +including their constant phases. The displayed 2-by-2 notation is a matrix +of native operators and exterior rational coefficients, not a matrix that +is itself tensor-powered. + +For every arbitrary helper, the chart endpoint is Gamma_b Gamma_a^*. +Apply M_right^* before the complete local word and M_left^* after it. Its +entire productive endpoint is then G_r. All 69 distinct helper boundary +types are checked as complete products; their multiplicities give all 562 +helper inputs. These normalizers are whole-job boundaries, not uncharged +adapters inserted at each recursive child. + +### Source raw contacts and arbitrary spectators + +The original raw construction uses 265 formal binary axes e_j. At stage s>0 +the actual route swaps the source's eight orthonormal q-complement vectors +b_i with its eight fresh axes e_(9+8(s-1)+i), and fixes q and the remaining +orthogonal complement. The source port data are checked to make +(q,b_0,...,b_7) an orthonormal basis. These eight disjoint orthonormal swaps +give a complete involutive orthogonal map R_s. The explicit binary formula +in caller_check.py is checked to perform exactly those swaps and fix q. + +A product of translation Gaussians has Fourier-character eigenvalue + + i^p(z), p(z)=sum_v c_v (v dot z mod2) (mod4). + +Its polynomial has linear and even mixed coefficients, and constant zero. +Polynomial equality therefore proves equality on every character; Fourier +characters form a basis. An even linear difference 2(t dot z) is exactly the +translation X_t, with absolute phase +1. The checker computes the complete +entry/exit translations and their inverses from these polynomials. Their +ordered payload equals the **already registered selected** route hash +`7f4f0ca768ffbc4f93dcff575592c4c67411f46b4289e45b73f715a2ad47b142`. + +This is more than comparing abstract frame labels. If a native convolution +path has phase p and the actual entry and exit maps are X_u P_R and X_v P_R, +their executed composition is + + X_v P_R A X_u P_R + = X_(v+R u) (P_R A P_R). + +Thus its eigenphase is p(R z)+2((v+R u) dot z). The checker uses the actual +four contact records to verify both diagonal paths as D_s and the cross +path as D_s Q^(-1), where D_0=H_9 Q^(-1) and, for s>0, D_s is the product +of the eight positive fresh-axis Gaussians. This checks 5,616 composed paths +through all 7,488 actual contacts, including spectator charts on entry and +exit. It does not only compare their marginal source/target phase profiles. + +Only stages 0,1,3,...,31,32 occur. All 120 rows of the other stages are fixed +by every actual contact and absent from its translations, main products and +idle products. Taking the nine source rows and the 17 retained eight-row +blocks identifies the actual 145-row supplier. This is a checked application +of the retained-row construction credited to #6878, not a new compression +claim. Every positive main/idle canonicalizer is explicitly completed on +all 145 retained coordinates; the unused 120 rows and arbitrary further +spectators are preserved as identity factors. Section 3 then transports +each equality through the complete occurrence embeddings in #6878. No +assumption about vanishing or independent spectator coordinates is used. + +The application to #6878 is source-compatible in a checkable sense. At its +head `41febf890fbbb852c6059d4c0cc8c593ae9dfa5c`, that package pins the same +CONTROLLER, original port data and caller implementation as SOURCES.json +here, with identical full SHA256 values. Its ordered retained set is +precisely the 145 indices just constructed, and its section 1 re-emits +positive canonicalizers with the selected positions followed by the full +retained complement, as done here. Its extension lemma takes a complete +ambient-m unit with endpoint G_r tensor I, uses a complete coordinate +bijection on entry and its inverse on return, and permits arbitrary +spectators. Those are exactly the operator and spectator hypotheses proved +here. Its compiler scalar contacts require routing entire participating +fields into a common coordinate order; our induction likewise uses exterior +scalars on complete aligned fields. Thus there is no model, width, phase or +scalar-type mismatch at that algebraic interface. The current package needs +no unmerged code to prove its own theorem. The larger compiler, ownership, +movement and cost premises of #6878 remain as stated there. + +### All-forward controller and whole-job completion + +Each physical LOCAL has forward orientation. The source's 16 reverse +interfaces use the literal five-event word + + Q_X^(-2), SIGNED_SWAP(X,Y), F_s, + Q_Y^(+2), SIGNED_SWAP(Y,X). + +With chronological action and SIGNED_SWAP(X,Y):(X,Y)->(Y,-X), this word +implements D_s [[1,-Q],[0,1]]. The minus sign is an exterior coefficient. +The equality Q^(+2)=Q^(-2)=X_q has absolute phase +1; it is checked at every +port. Each thin query realizes Q^(-1)=X_q Q by a positive rank-one Gaussian +conjugated through the complete port basis, plus its ordinary translation. +Its separate owned scratch label t has the explicit semantic macro + + INIT t=0; COPY t=X; apply Q^(-1) to t; ADD Y+=t; CLEAR t. + +It leaves X unchanged, replaces Y by Y+Q^(-1)X, and returns t to zero under +the stated ideal-reset semantics. The complete query basis and its inverse +restore the original full field coordinates before ADD. The scratch label +is outside the 29-label local owned bank and is reused only after CLEAR. +This makes the additional owned return explicit; it neither supplies a +physical erasure algorithm nor adds another paid native call. Each of the +15*104 thin queries still invokes one rank-one positive child. + +To verify the *actual* controller, source_algebra.py propagates each of the +32 final coordinate functionals backwards through every literal event and +both scalar boundary programs. Coefficients lie in the free Laurent ring + + Q[Q,Q^(-1),D_0,D_0^(-1),...,D_32,D_32^(-1)]. + +This is independent of the predecessor's forward row-matrix replay. It +checks all 1,024 entries of the resulting 32-by-32 operator and compares +the literal boundary programs with their stored matrices. There is no +Q^4=1 quotient that could conceal a central-power error. At every port the +native operators Q,D_s commute, since they are products of the commuting +translations X_v. Evaluation in this commutative operator algebra therefore +preserves the verified identity. Their columnwise lifts also commute, while +the rational coefficients stay exterior. Consequently the same exact raw +diagonal endpoint holds at every f and every spectator space. + +For each of the 3,328 main fields, the raw endpoint is Q^epsilon product D_s, +with epsilon in {+1,-1}. If epsilon=-1, its whole-job translation X_q changes +the Q exponent to +1. The polynomial check establishes equality to the +positive Gaussians on the complete recorded target axes. If stage 0 is +present, use the original nine coordinate axes; otherwise use q and its +eight-vector orthonormal complement. Append the selected fresh axes and +**all** other retained coordinates. The complete invertible map conjugates +this product to G_r, where r=1+8 times the number of selected stages. + +Each whole-idle product similarly receives one positive G_(8k) child with +its complete basis and the exactly calculated whole-job translation, where +k is the actual number of distinct stages in the window. All 3,120 fields +are checked, including the windows that contain stage 0. A rank-r child +becomes exactly rank r*f after the tensor lift; spectator coordinates remain +untouched. The raw positive query, main and idle normalizations are all +identities of full products, so no tensoring of a scalar-weighted sum occurs. + +Finally, every local call maps its 208 main public roles to the actual pair +of controller rows, its 562 arbitrary helpers to fresh public inputs, and +its 29 owned roles to the returned shared owned bank. These maps are checked +as injective on all 799 labels, and the thin scratch label is separate. +There are 3,328 arbitrary main and 18*562=10,116 arbitrary helper inputs. +The local gauge identity, complete whole-helper normalization, complete raw +caller identity and whole-job normalization prove the asserted direct-sum +endpoint, with no remaining unspecified local algebraic adapter. + +## 5. Accounting and limits + +This package leaves the selected bill unchanged: + +| Quantity | Exact count | +|---|---:| +| Arbitrary productive fields | 13,444 | +| Paid calls | 66,834 | +| Paid rank mass | 240,152 | +| Productive rank mass | 240,912 | +| Actual forward local calls | 18 | +| Five-step wrappers | 16 | +| Thin rank-one calls | 1,560 | +| Whole-idle calls | 3,120 | + +The complete paid profile is 18 times the selected local MOVE profile, plus +the 1,560 positive rank-one thin calls and the 3,120 whole-idle calls. The +productive profile is 18 times the 562-helper profile plus the complete main +endpoint profile. These profiles are compared exactly with selected RESULT, +including every multiplicity. This verifies algebraic accounting; it does +not reprice ordinary adapters, infer a physical runtime from a recipe, or +claim that the positive rank margin alone proves a multiplication bound. + +The selected record states `native_all_columns` as: retained native operators, +phase conventions, spectators and whole-job adapters work at every positive +column multiplicity. For the exact P104 objects and assembled caller pinned +here, that algebraic assertion is now the theorem of Sections 2--4. Its status +does not depend on a future maintainer admission or a physical dispatcher. +The theorem does not silently extend to a different upstream native family. + +The result supplies this proved algebraic endpoint to a later physical +dispatch theorem. That theorem must still realize every typed +native product, whole-field scalar operation and coordinate map on the +prescribed layouts, preserve or discharge the owned-reset semantics, and +charge source access, staging, restoration and recursive children at the +selected tariff. Existing physical monomial constructions #3055/#3087 and +old-controller #3385 are credited but do not automatically establish that +current combined tariff. The other framework assumptions remain explicit. +No selected record or accepted kappa is changed. **No new kappa.** diff --git a/research/selected-native-tensor-closure/README.md b/research/selected-native-tensor-closure/README.md new file mode 100644 index 0000000000..531a5f64d6 --- /dev/null +++ b/research/selected-native-tensor-closure/README.md @@ -0,0 +1,205 @@ +# Exact native traces and the selected all-column caller + +This package proves and independently checks the **algebraic** assertion +`native_all_columns` for the pinned selected #6030 P104 native layer and its +assembled caller, at every positive column width and with arbitrary spectator +factors. It joins every signed native recipe, +the complete local word, all 18 forward calls and 16 wrappers, and every +whole-job helper/main/idle adapter. It does **not** implement the selected-rate +physical dispatcher or discharge the complete five-assumption framework. +The all-column operator assertion is proved; physical realization and the +source's ideal owned-reset semantics remain distinct obligations. +**No new κ.** + +The accepted source remains canonical main +`7c49fe32c55de02c2c873655c804b16e4c3fef0a`, with conditional +κ = `781451/250000000`. No prior source, selected record, tariff or bill is +modified. [PROOF.md](PROOF.md) states the exact quantified theorem, proves the +trace algorithm and tensor interpretation, and gives the complete composition. + +## Result and evidence + +The new native acceptance mechanism computes the exact closed overlap +`tr(V*U)` as a constrained quadratic Gauss sum over binary variables. Checked +unitarity makes the value `2^9` equivalent to full operator equality. The +checker retains constant phases and Gaussian normalizations; it uses neither +a Pauli tableau, a distinguished input column, floating point, nor a dense +512-by-512 operator matrix. Quadratic elimination is polynomial in the finite +circuit description. This is a certificate-verification bound, not a +multiplication-runtime improvement. + +The caller verification keeps two different types of objects distinct: +native products are lifted columnwise, while rational coefficients of +register ADD/COPY/SCALE and signed swaps stay outside the tensor power. A +native constant phase becomes `i^(p*f)`; a register coefficient remains the +same coefficient. The proof does not infer an all-width identity by tensoring +a width-one sum of different native group elements. + +| Verified object | Complete coverage | +|---|---:| +| Distinct signed native/helper pairs | 2,922 | +| Distinct MOVE pairs within that union | 2,886 | +| Intrinsic main adapters | 208 | +| Complete local main paths | 312 | +| Distinct complete helper boundary types | 69 | +| Arbitrary helpers per local call | 562 | +| Local endpoint coefficients | 799 × 799 | +| Literal local events | 22,803 | +| Actual raw contacts | 7,488 | +| Composed contact/native/contact paths | 5,616 | +| Complete free-Laurent caller entries | 32 × 32 | +| Arbitrary main productive fields | 3,328 | +| Arbitrary helper productive fields | 10,116 | +| Whole-idle paid fields | 3,120 | + +The source-bound reverse-functional Laurent replay checks all 218 physical +controller events and both literal rational boundary programs. It uses the +free Laurent ring, with no `Q^4=1` quotient. The geometry check composes the +actual entry/native/exit maps, matches the selected raw-contact payload hash, +and explicitly fixes the 120 omitted spectator rows of the 265-row source. +Each main/idle positive basis is completed on all 145 retained rows. The +all-width proof then applies to every complete occurrence embedding, including +the embeddings supplied by #6878. + +The exact selected bill is unchanged: **13,444 productive fields, 66,834 paid +calls, paid rank mass 240,152 and productive rank mass 240,912**. The checker +reconstructs both complete profiles from the literal source events rather +than inferring a bound from this positive rank margin. Ordinary adapters, +source access, staging, physical erasure and restoration still require their +own implementation and charging theorems. + +## What is new, and what is already proved + +This is not a new local common-chart lemma or another dense native census. +The contribution is a different exact native acceptance mechanism together +with the **complete selected-source join** from those native equalities to +the assembled all-forward caller, including the exterior-scalar typing and +whole-job boundaries. + +| Predecessor or concurrent work | Already established; relationship here | +|---|---| +| #5442, `research/allwidth-caller-certificate/` | Group-algebra and tensor framework for the older #5413 caller. The product-lifting principle is credited. | +| #5974, `research/p104-allwidth-native-certificate/` | Full exact native verification for #5599 and the factorwise lift. Its native census is not repeated as a claimed new theorem. | +| #6043, `research/p104-6030-independent-audit/` | Independent dense verification of the current #6030 native inventory. The present trace method shares neither its dense mechanism nor its candidate compiler's tableau/anchor acceptance. | +| #6635 | Complete selected scalar common-chart census. The present typed induction uses that established mechanism and checks its composition with every MOVE. | +| #6293 and #6331 | The `i^(p*f)` phase convention and the obstruction to deleting native phases. The current width-two controls explicitly enforce those distinctions. | +| #6546, `research/selected-absolute-stochastic-caller/` | Concurrent direct stochastic local execution and a fixed-local all-width lift; its stated limitation is identification with complete recursive callers. The present package closes the algebraic assembled-caller join, without importing its unmerged code. | +| #6878, `research/selected-compiler-occurrence-layout/` | Complete occurrence-specific coordinate embeddings and retained-row geometry. This package supplies their native algebraic endpoint premise; it does not reprice or redevelop the embeddings. | + +At the frozen reconnaissance, #6546 was an open contribution at +`ff038070b8d122a43993f2b2524154323cc6b4d7`, and #6878 was an open contribution +at `41febf890fbbb852c6059d4c0cc8c593ae9dfa5c`. They are credited comparisons and +applications, **not runtime or source-import dependencies** of this package. +The proved tensor/naturality statement quantifies over any complete embedding; +the exact accepted inputs below all come from the pinned canonical main. + +The native/caller identities and raw phase construction in +`research/p104-productive-controller/` and the independent caller audit remain +credited source results. Existing physical compact, Gaussian-monomial and old +controller work #3055, #3087 and #3385 was checked during scope selection and +was not reimplemented. Its older tariffs do not automatically price the +current selected dispatcher. + +## Reproduction + +From the repository root, using only Python's standard library: + +```sh +python3 -I -B research/selected-native-tensor-closure/verify.py +``` + +Expected final marker: + +```text +PASS_SELECTED_NATIVE_TENSOR_CLOSURE {"kappa_changed": false, "native_pairs": 2922, "paid_calls": 66834, "productive_fields": 13444, "raw_contacts": 7488, "rejecting_controls": 20} +``` + +The registered replay also checks the generic trace engine in normal and +optimized Python and rebuilds the full native recipe artifact with the +credited source compiler: + +```sh +python3 -B scripts/research_package.py --package research/selected-native-tensor-closure +``` + +`SOURCES.json` records exact Git blob and SHA256 pins. Every live source input +is declared in `VERIFY.json`. The independent verifier authenticates the +selected word, result, controller, port data and mathematical source files +before parsing them; it imports no predecessor verifier or compiler. +`emit_recipes.py` alone imports the credited compiler to regenerate the +candidate artifact. Its complete recipe payload must reproduce the already +registered selected digest +`e22642923d5437c49e2d1dc79dd6b795503499d6f33615a1df3568f0b96164c1`. +The independent checker then accepts every complete emitted product by the +trace method. This producer/acceptor separation is deliberate. + +`RESULT.json` is deterministic and records the exact coverage, profile and +endpoint digests and every rejecting control. `--write` regenerates only this +new package's receipt. `emit_recipes.py --write` regenerates only this package's +small compressed candidate artifact; ordinary replay compares its full +decompressed contents instead. + +## Verification and negative controls + +The trace engine's independent dense-column oracle uses exact rational +arithmetic on 120 deterministic random small circuits. Additional checks +enumerate all 16,933 quadratic forms through four variables with zero constant +term, 480 affine systems, 480 affine substitutions, nonzero constant phases, +unitary inverses and a 300-variable symbolic trace. Fixed seeds are `7606030` +and `7606546`; these are bounded verifier tests, not an open-ended supplier +search. Ten trace grammar/operator controls reject malformed expected gates, +wrong phases and invalid gates, including cases that agree on the zero column. + +The source package has 20 separate controls. They reject source-byte and +registered-payload drift; a global `i` invisible to conjugation action; reversed +native factors; an omitted positive child; confusing a canonical rank-one +chart with the translation Gaussian on that vector; `i^p` used where `i^(p*f)` is +required; tensor-powering an exterior minus sign; tensoring a Gaussian sum +termwise; a wrong whole-helper normalizer; a scalar chart mismatch; reversed +MOVE orientation; aliased public roles; a missing wrapper translation or swap +sign; a wrong raw final exponent; a corruption on an arbitrary spectator +coordinate; and an omitted whole-job final translation. Mathematical fault +controls call the comparison mechanisms directly, so their rejection is not +merely an earlier source-hash failure. + +Both normal and `-O` execution are required by the registered manifest. The +package uses explicit checks rather than optimization-disabled assertions. +The finite tests support the checker implementation; the all-f and arbitrary +spectator conclusions come from the written theorem, not from sampling +column widths. This is not a proof-kernel formalization or independent human +acceptance. + +## Open next questions + +The structured versions are in [TASK.json](TASK.json). + +1. Bind this exact typed algebraic word to the selected-rate physical + dispatcher. Start with one full compiled occurrence, preserving the + distinction between native column phases and exterior scalar field + coefficients, and account for every adapter, complete field, recursive + child and return operation. This is blocked by the remaining physical + implementation and charging obligations, not by a missing local chart + identity. +2. Compose the resulting implementation with the owned-stream and precision + contracts. Start with a complete source-owned call/return that realizes + the 29-label local owned bank and separate thin scratch field, without + treating the ideal CLEAR in this algebraic proof as a physical erasure + algorithm. The required ownership and rounding premises remain explicit. + +## Attribution and license + +Prepared for **@CubeJerry**, with substantial **OpenAI Codex** assistance in +research, derivation, implementation and adversarial checks. The lead research +reviewer checked the Gauss-sum derivation and the complete typed composition; +that is an AI-assisted mathematical review, not a separate formal proof. + +Credit DreamingOfClouds for the selected #6030 change; David Arias for the +coalesced source word, Cinna Davis for private reuse, the native representations +and the Laurent controller, +Gareth Davidson for their composition, and Ali Romman for the P104 caller and +independent source audits. The native compiler, source constructions and +proof framework retain their existing contributors' credit. Relevant earlier +and concurrent mechanisms are identified above rather than claimed anew. +Apache-2.0, following the repository license. No predecessor source is copied +or modified; the compressed artifact contains deterministically emitted +recipe data authenticated against the selected registration. diff --git a/research/selected-native-tensor-closure/RESULT.json b/research/selected-native-tensor-closure/RESULT.json new file mode 100644 index 0000000000..2545b90099 --- /dev/null +++ b/research/selected-native-tensor-closure/RESULT.json @@ -0,0 +1,154 @@ +{ + "all_size_status": "PROOF.md proves the typed algebraic implication for every positive f and arbitrary spectator factors; finite replay is the exact selected-source premise", + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "complete_caller": { + "all_1024_laurent_entries_checked": true, + "controller_events": 218, + "endpoint_sha256": "4ba0b7b54172171102343f81f03f2dac7753ffd184cdffcbe62c8b9d6b1dc0bf", + "five_step_forward_wrappers": 16, + "forward_local_calls": 18, + "literal_boundary_events": 145, + "method": "reverse linear-functional substitution; no finite-order quotient of Q", + "thin_queries_per_port": 15 + }, + "limitations": [ + "ideal owned reset semantics remain assumed", + "physical selected-rate dispatcher not implemented", + "compiler, precision_tape and analytic_recovery not discharged", + "No new kappa" + ], + "local_gauge": { + "arbitrary_public_columns": 770, + "events": 22803, + "full_endpoint_coefficients": 638401, + "gauge_endpoint_sha256": "3a9a39e842438b4575689b5233c0d9237b4863b71f8f1939c757607fe4d35325", + "opcode_counts": { + "ADD": 18404, + "CLEAR": 31, + "COPY": 23, + "INIT": 31, + "MOVE": 3453, + "SCALE": 861 + }, + "owned_entrance_columns_erased": 29, + "owned_lifetimes": 31, + "paid_profile": { + "1": 2219, + "2": 457, + "3": 496, + "4": 100, + "5": 163, + "6": 11, + "7": 6, + "8": 1 + }, + "peak_owned": 13, + "rows": 799, + "rule": "chart coefficients are formal inverse/forward products; every scalar remains exterior" + }, + "native_trace": { + "arbitrary_helpers": 562, + "central_squares": 104, + "complete_main_paths": 312, + "complete_trace_digest": "dcb7308d7925b139d4547247eae4955b58445155bda7ac93d7c3b18d479078a5", + "distinct_move_pairs": 2886, + "distinct_native_pairs": 2922, + "helper_normalized_pairs": 69, + "helper_profile": { + "1": 14, + "2": 8, + "3": 4, + "4": 107, + "5": 14, + "6": 2, + "7": 9, + "8": 19, + "9": 385 + }, + "main_adapters": 208, + "maximum_closed_trace_branches": 18, + "method": "exact constrained quadratic Gauss sum; no tableau or distinguished column", + "selected_recipe_payload_sha256": "e22642923d5437c49e2d1dc79dd6b795503499d6f33615a1df3568f0b96164c1" + }, + "negative_controls": { + "MOVE_reversed_source_and_target": "current native source and ownership at 9896", + "aliased_local_public_role": "all productive owners", + "caller_exterior_swap_sign_lost": "full free-Laurent reverse output 8", + "caller_missing_central_translation": "full free-Laurent reverse output 8", + "caller_wrong_raw_diagonal_Q_exponent": "full free-Laurent reverse output 0", + "canonical_rank_one_chart_mistaken_for_C_q": "omitted nontrivial intrinsic main adapter: exact unitary overlap trace (256, 0, 0)", + "contact_corrupts_arbitrary_spectator_row": "nonidentity spectator action", + "exterior_minus_incorrectly_tensor_powered": "exterior sign squared: exact unitary overlap trace (-262144, 0, 0)", + "main_whole_job_final_translation_omitted": "omitted X_q final raw endpoint correction", + "native_constant_i_not_raised_to_column_width": "wrong i^(p*f): exact unitary overlap trace (0, -262144, 0)", + "native_global_i_preserving_conjugation_action": "lost absolute phase: exact unitary overlap trace (0, 512, 0)", + "native_left_right_order": "reversed native factors: exact unitary overlap trace (128, 0, 0)", + "native_missing_positive_child": "omitted native Gaussian: exact unitary overlap trace (256, -256, 0)", + "registered_recipe_payload_drift": "full selected recipe payload hash", + "scalar_chart_mismatch": "scalar current chart", + "source_drift:research/p104-helper470-twin-rung-removal/WORD.json.gz": "Rejected before parsing or execution", + "source_drift:research/p104-productive-controller/caller.py": "Rejected before parsing or execution", + "tensor_of_sum_replaced_by_sum_of_tensors": "tensoring a Gaussian expansion termwise: exact unitary overlap trace (2, 0, 0)", + "whole_helper_pre_normalizer_not_inverted": "wrong whole-helper entry: exact unitary overlap trace (16, 0, 0)", + "zero_column_agrees_but_quadratic_operator_differs": "missing controlled sign: exact unitary overlap trace (2, 0, 0)" + }, + "ownership_and_invoice": { + "field_maps_sha256": "0cc409ad6083dedf325df5bd452ed58f84d579f5664e48a519a86ab2e15bdd33", + "fresh_helper_inputs": 10116, + "limits": "ideal source ownership only; allocation, physical erasure and retained backing remain premises", + "local_owned_labels": 29, + "main_arbitrary_inputs": 3328, + "paid_calls": 66834, + "paid_rank_mass": 240152, + "productive_inputs": 13444, + "separate_thin_owned_label": 13473, + "target_rank_mass": 240912 + }, + "schema": "selected-native-tensor-closure-result/1", + "source_sha256": { + "research/p104-caller-independent-audit/capsule/outputs/p104-caller-route-audit-v2-20261025/sources/DATA-PHASES.json": "c5916ff312678f12aba403847643fbbc29f643acec60bdf836fa56cd3e8251fa", + "research/p104-helper470-twin-rung-removal/RESULT.json": "84fcbe2a0b64307b5703c363408042bdd91555b0419509aa50daa43b3b1924ad", + "research/p104-helper470-twin-rung-removal/WORD.json.gz": "7834725d9e34ee846a9ccc615221ea81e0201613938afa185d2eda0c9a6c232f", + "research/p104-native-channel/vendor/clifford_exact.py": "2982ead07721e83358dc67c6f49c2b4c16a236a6bebdfd72f58221be1f5d0962", + "research/p104-productive-controller/CONTROLLER.json": "a84f6bbd547379597464e56c420cc665f96bc43a9a1351eed4b7cd0fce3cc4b9", + "research/p104-productive-controller/caller.py": "300d40043953e4f6aecfde8f2d1004b8ad6dc5a79ec3c7666c9908c2466c91c8", + "research/p104-productive-controller/local.py": "878734dfd64c4b9d362d0ae476cc5c2a19fe93e48b7378763b23f3e0dd0a5a71" + }, + "status": "PASS_SELECTED_NATIVE_TENSOR_CLOSURE", + "whole_job_algebra": { + "complete_idle_endpoints": 3120, + "complete_main_endpoints": 3328, + "complete_raw_contacts": 7488, + "composed_native_paths": 5616, + "full_coordinate_bijections": 4888, + "idle_boundary_sha256": "3b493ec6281025ba31b1a66b682d33292b58f99c982461f68018f340c8bbb677", + "idle_profile": { + "16": 416, + "24": 416, + "32": 416, + "40": 416, + "48": 416, + "56": 416, + "64": 416, + "72": 208 + }, + "limits": "algebraic whole-field bijections; physical scheduling and charged realization remain separate", + "main_boundary_sha256": "57d64f0cbbd7430e780837e64f8bd7336df73c88de52adbe91f8204b62770afd", + "main_profile": { + "17": 416, + "25": 416, + "33": 416, + "41": 416, + "49": 416, + "57": 416, + "65": 416, + "73": 208, + "145": 208 + }, + "omitted_identity_spectator_rows": 120, + "retained_source_rows": 145, + "source_dimension": 265, + "source_route_payload_sha256": "7f4f0ca768ffbc4f93dcff575592c4c67411f46b4289e45b73f715a2ad47b142", + "thin_query_boundaries": 104 + } +} diff --git a/research/selected-native-tensor-closure/SOURCES.json b/research/selected-native-tensor-closure/SOURCES.json new file mode 100644 index 0000000000..57558383d3 --- /dev/null +++ b/research/selected-native-tensor-closure/SOURCES.json @@ -0,0 +1,60 @@ +{ + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "files": [ + { + "git_blob": "3404fbdd5e7529a0674eef26114b5071e4586cec", + "path": "docs/research/agent-task-catalog.json", + "sha256": "ead6cdc9d0af6d58e8a49744d8ec8c7c15e13d2ba93c276c434bcf9b51b93a81", + "usage": "provenance" + }, + { + "git_blob": "d59b5035e7b4cbaa9d688a1d32dd0d6eb79c466a", + "path": "certificates/selected-result.json", + "sha256": "9b8d0eea95b3bf0dfcb7938a732a6439b87a2685dec2a5ab9e525b3b34debbfa", + "usage": "provenance" + }, + { + "git_blob": "22f9ab02d1b73ea0aa4b07ce445a14cc2602c760", + "path": "research/p104-helper470-twin-rung-removal/WORD.json.gz", + "sha256": "7834725d9e34ee846a9ccc615221ea81e0201613938afa185d2eda0c9a6c232f", + "usage": "input" + }, + { + "git_blob": "e4a03118d585fb80c9ac932281b528ac394ccc5f", + "path": "research/p104-helper470-twin-rung-removal/RESULT.json", + "sha256": "84fcbe2a0b64307b5703c363408042bdd91555b0419509aa50daa43b3b1924ad", + "usage": "input" + }, + { + "git_blob": "cc539db709cf7a6c42872c4380902736ad453af3", + "path": "research/p104-productive-controller/CONTROLLER.json", + "sha256": "a84f6bbd547379597464e56c420cc665f96bc43a9a1351eed4b7cd0fce3cc4b9", + "usage": "input" + }, + { + "git_blob": "d9a4f84211182ca200c081ea061d724c8a2cfb70", + "path": "research/p104-caller-independent-audit/capsule/outputs/p104-caller-route-audit-v2-20261025/sources/DATA-PHASES.json", + "sha256": "c5916ff312678f12aba403847643fbbc29f643acec60bdf836fa56cd3e8251fa", + "usage": "input" + }, + { + "git_blob": "166841a037f069249f6f7f6dedb89248812f59e2", + "path": "research/p104-native-channel/vendor/clifford_exact.py", + "sha256": "2982ead07721e83358dc67c6f49c2b4c16a236a6bebdfd72f58221be1f5d0962", + "usage": "input" + }, + { + "git_blob": "dbb3d56a4f5b733bb0c32a91249d1f6a7e1ab5d2", + "path": "research/p104-productive-controller/local.py", + "sha256": "878734dfd64c4b9d362d0ae476cc5c2a19fe93e48b7378763b23f3e0dd0a5a71", + "usage": "input" + }, + { + "git_blob": "6ac5e735691555ecafe2afbcff71edd923178113", + "path": "research/p104-productive-controller/caller.py", + "sha256": "300d40043953e4f6aecfde8f2d1004b8ad6dc5a79ec3c7666c9908c2466c91c8", + "usage": "input" + } + ], + "schema_version": 1 +} diff --git a/research/selected-native-tensor-closure/TASK.json b/research/selected-native-tensor-closure/TASK.json new file mode 100644 index 0000000000..0251f7fb6a --- /dev/null +++ b/research/selected-native-tensor-closure/TASK.json @@ -0,0 +1,88 @@ +{ + "actual_scope": "Prove and independently certify the selected #6030 algebraic native-to-18-call-caller implication for every positive column width, arbitrary spectators, signed phases and complete whole-job adapters.", + "ai_assistance": "Substantial OpenAI Codex assistance in derivation, implementation and adversarial review; no claim of independent human or proof-kernel acceptance.", + "author": "@CubeJerry", + "base_commit": "7c49fe32c55de02c2c873655c804b16e4c3fef0a", + "bottleneck_link": "native_all_columns at the actual selected caller, with owned reset, physical selected-rate dispatch, compiler, precision_tape and analytic_recovery premises explicitly retained.", + "evidence": "PROOF.md and RESULT.json; full source-bound deterministic normal/optimized replay, exact Gauss-sum validation, complete recipe regeneration and rejecting phase/order/typing/endpoint/source controls.", + "open_questions": [ + { + "blocked_by": "Selected-rate physical native and adapter realization, complete call/return accounting and current precision/storage contracts.", + "first_step": "Bind one full compiler occurrence to the actual call schedule, preserving exterior scalar coefficients and all complete coordinate maps; charge every introduced operation.", + "question": "Can the exact typed selected algebraic word be bound to a physical dispatcher at the selected accelerated tariff?", + "why_it_matters": "This package establishes native/caller equality but does not implement or price source access, staging, monomials and recursive returns." + }, + { + "blocked_by": "The retained owned-erasure and precision_tape framework obligations; this package deliberately assumes ideal owned reset semantics.", + "first_step": "Construct one complete call/return with all 29 local owned labels and the separate thin scratch field, including retained information, initialization, rounding and returned ownership.", + "question": "Can the actual owned-stream and numerical contracts be composed with every owned lifetime of this selected caller?", + "why_it_matters": "Ideal INIT/CLEAR algebra does not prove physically valid erasure or control finite-precision errors." + } + ], + "original_card": { + "acceptance_gate": "Identify the proposition and what would change downstream; do not equate a finite replay with a universal 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." + ], + "bottleneck_link": "Judge the actual current supplier contract and complete signed target/paid bill; frozen-profile ceilings require an applicability proof.", + "existing_checks": [ + { + "evidence": "research/unconditional-batched-crt/README.md", + "remaining": "Independent proof audit of one caller-bound all-size implication; all other premises remain explicit.", + "scope": "PR #4100: proposed unconditional construction and finite checks, without independent acceptance.", + "selected_record_sha256": "bb2eaa58647b353f88d0aec2eafb9d30df1be53589231b23e12ceef3e4bad129", + "source_commit": "337d04939571a637aeab54a0f58f54fde811663a", + "status": "author-checked" + }, + { + "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.", + "scope": "Selected PR5599: complete helper-subspace construction and independent caller replay; five framework assumptions remain.", + "selected_record_sha256": "2a0220e866417774606e0f991e41b9c1d26b1f43b97857238cf478dbc7d330b5", + "source_commit": "09dd0965711ca7eeb169057a420abab1c9052137", + "status": "reviewed" + } + ], + "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.", + "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." + }, + "id": "uniform-transfer-audit", + "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." + ], + "overlap_terms": [ + "native_all_columns", + "owned_erasure", + "compiler", + "precision_tape", + "analytic_recovery" + ], + "question": "Can one of the selected record's five inherited assumptions be proved at its actual caller?", + "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." + ], + "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" + ] + }, + "outcome": "completed", + "schema_version": 1, + "scope_change_reason": "The card asks for one quantified inherited implication. Earlier dense censuses and the scalar common-chart lemma were already proved; this scope isolates the complete selected assembled-caller join and checks native operators by a distinct exact closed-trace method.", + "scope_status": "refined", + "stop_rule": "Complete the exact pinned native, local, raw-contact, free-Laurent and whole-job inventories; stop if their all-width interpretation cannot be proved without tensoring exterior scalar sums. No open-ended parameter search.", + "task_id": "uniform-transfer-audit", + "time_budget_minutes": 180 +} diff --git a/research/selected-native-tensor-closure/VERIFY.json b/research/selected-native-tensor-closure/VERIFY.json new file mode 100644 index 0000000000..4d06e71495 --- /dev/null +++ b/research/selected-native-tensor-closure/VERIFY.json @@ -0,0 +1,69 @@ +{ + "commands": [ + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/verify.py" + ], + "checks": "Complete exact selected-source native/caller/whole-job certificate and all 20 rejecting controls", + "timeout_seconds": 120 + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "-O", + "{package}/verify.py" + ], + "checks": "Complete exact selected-source native/caller/whole-job certificate and all 20 rejecting controls under optimized Python", + "timeout_seconds": 120 + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/test_gauss_trace.py" + ], + "checks": "Independent dense rational oracle, exhaustive small Gauss sums, affine substitution and malformed-gate/operator controls", + "timeout_seconds": 60 + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "-O", + "{package}/test_gauss_trace.py" + ], + "checks": "Independent dense rational oracle, exhaustive small Gauss sums, affine substitution and malformed-gate/operator controls under optimized Python", + "timeout_seconds": 60 + }, + { + "argv": [ + "{python}", + "-I", + "-B", + "{package}/emit_recipes.py" + ], + "checks": "Regenerate every complete native recipe and intrinsic adapter with the pinned credited compiler; require exact selected payload hash and full decompressed candidate bytes", + "timeout_seconds": 600 + } + ], + "inputs": [ + "research/p104-helper470-twin-rung-removal/WORD.json.gz", + "research/p104-helper470-twin-rung-removal/RESULT.json", + "research/p104-productive-controller/CONTROLLER.json", + "research/p104-caller-independent-audit/capsule/outputs/p104-caller-route-audit-v2-20261025/sources/DATA-PHASES.json", + "research/p104-native-channel/vendor/clifford_exact.py", + "research/p104-productive-controller/local.py", + "research/p104-productive-controller/caller.py" + ], + "python": "3.12", + "requirements": [], + "schema_version": 1, + "status": "ready" +} diff --git a/research/selected-native-tensor-closure/caller_check.py b/research/selected-native-tensor-closure/caller_check.py new file mode 100644 index 0000000000..23ef0969bb --- /dev/null +++ b/research/selected-native-tensor-closure/caller_check.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Exact source contacts and whole-job positive endpoints, with no old imports.""" +from __future__ import annotations + +from collections import Counter +from functools import lru_cache +import hashlib +import json + +from gauss_trace import Quadratic, adjoint, equal, require +from native_check import transpose + + +DIMENSION = 265 +AXES = tuple(1 << i for i in range(DIMENSION)) + + +def terms(entries): + coefficients = Counter() + for axis, value in entries: + require(type(axis) is int and 0 < axis < 1 << DIMENSION and type(value) is int, 'spectral term domain') + coefficients[axis] += value + return tuple(sorted((axis, value % 4) for axis, value in coefficients.items() if value % 4)) + + +@lru_cache(maxsize=None) +def phase(entries): + polynomial = Quadratic.zero(DIMENSION) + for axis, coefficient in entries: + polynomial.add_affine(coefficient, (axis, 0)) + return tuple(polynomial.linear), frozenset(polynomial.pairs), polynomial.constant + + +def apply(columns, value): + result = 0 + while value: + low = value & -value + result ^= columns[low.bit_length()-1] + value ^= low + return result + + +def positive(vectors): + return terms((axis, 1) for axis in vectors) + + +def stage_terms(stage, q): + require(type(stage) is int and 0 <= stage <= 32, 'controller stage domain') + return terms([(axis, 1) for axis in AXES[:9]]+[(q, -1)]) if stage == 0 else positive(AXES[9+8*(stage-1):9+8*stage]) + + +def orthogonal_base(q, recipe): + basis = tuple(recipe['idle_children'][0]['orthogonal_axes'][:8]) + complete = (q,)+basis + require(len(set(complete)) == 9 and all(type(v) is int and 0 < v < 512 for v in complete), + 'complete nine-axis port basis') + require(all((a & b).bit_count() % 2 == int(i == j) + for i, a in enumerate(complete) for j, b in enumerate(complete)), 'orthonormal port basis') + return basis + + +def route(stage, q, basis): + """Swap eight orthonormal pairs; fix their orthogonal complement.""" + if stage == 0: + return AXES + fresh = AXES[9+8*(stage-1):9+8*stage] + differences = tuple(a ^ b for a, b in zip(basis, fresh, strict=True)) + columns = tuple(axis ^ apply(differences, sum(((axis & v).bit_count() % 2) << j + for j, v in enumerate(differences))) for axis in AXES) + require(all(apply(columns, a) == b and apply(columns, b) == a + for a, b in zip(basis, fresh, strict=True)), 'actual eight swaps') + require(apply(columns, q) == q and all(apply(columns, columns[j]) == AXES[j] for j in range(DIMENSION)), + 'complete involutive route and central port') + # The checked two orthonormal families are disjoint. Their eight swaps and + # fixed orthogonal complement prove orthogonality, without a 265^2 replay. + return columns + + +def contact(before, after, columns): + moved = terms((apply(columns, axis), coefficient) for axis, coefficient in before) + left, right = phase(moved), phase(after) + require(left[1:] == right[1:], 'contact full mixed and constant phase') + difference = tuple((b-a) % 4 for a, b in zip(left[0], right[0], strict=True)) + require(all(value in (0, 2) for value in difference), 'contact even linear residual') + translation = sum((value//2) << j for j, value in enumerate(difference)) + correction = [(translation, 2)] if translation else [] + require(phase(terms(list(moved)+correction)) == right, 'complete forward contact') + inverse = apply(columns, translation) + backward = [(apply(columns, axis), coefficient) for axis, coefficient in after] + if inverse: + backward.append((inverse, 2)) + require(phase(terms(backward)) == phase(before), 'complete inverse contact') + return {'translation': translation, 'inverse_translation': inverse} + + +def transformed_path(local, entry, exit_, columns): + """Exit * native * entry, including both actual address translations.""" + translation = exit_['translation'] ^ apply(columns, entry['translation']) + entries = [(apply(columns, axis), coefficient) for axis, coefficient in local] + if translation: + entries.append((translation, 2)) + return phase(terms(entries)) + + +def complete_positive_basis(base, active, retained): + """Return a complete coordinate map, including all spectator columns.""" + require(len(base) == 9 and len(set(active)) == len(active) + and all(type(j) is int and 0 <= j < DIMENSION for j in active), 'positive coordinate selection') + require(all((a & b).bit_count() % 2 == int(i == j) + for i, a in enumerate(base) for j, b in enumerate(base)), 'complete orthogonal local basis') + require(set(active) <= set(retained), 'positive job uses retained source rows') + order = (tuple(active)+tuple(j for j in retained if j not in set(active)) + +tuple(j for j in range(DIMENSION) if j not in set(retained))) + require(sorted(order) == list(range(DIMENSION)), 'all spectator coordinates retained') + columns = tuple(base)+AXES[9:] + return tuple(columns[j] for j in order) + + +def check_caller(word, controller, phase_source, source_result): + recipes = {entry['q']: entry for entry in phase_source['recipes']} + require(len(recipes) == len(phase_source['recipes']) and set(word['ports']) <= set(recipes), 'original source port data') + bases = {q: orthogonal_base(q, recipes[q]) for q in word['ports']} + local_stages = sorted(event[1] for event in controller['physical_events'] if event[0] == 'LOCAL') + require(local_stages == [0]+list(range(1, 32, 2))+[32], 'all selected actual stages') + retained = tuple(range(9))+tuple(j for stage in local_stages if stage + for j in range(9+8*(stage-1), 9+8*stage)) + require(len(retained) == len(set(retained)) == controller['ambient_rank'], 'actual 145-row retained support') + retained_mask = sum(1 << j for j in retained) + contacts = [] + paths = 0 + endpoint_records = [] + main_profile, idle_profile = Counter(), Counter() + for _, stage, pair, backward in (event for event in controller['physical_events'] if event[0] == 'LOCAL'): + require(not backward, 'actual forward source supplier') + spectators = positive(AXES[9:9+8*stage]) + for q in word['ports']: + columns = route(stage, q, bases[q]) + raw_x = ((q, 1),) if stage == 0 else positive(AXES[:9+8*(stage-1)]) + raw_y = () if stage == 0 else terms(list(raw_x)+[(q, -1)]) + entry_x = terms(list(spectators)+[(q, 1)]) + entry_y = spectators + exit_x = terms(list(spectators)+[(axis, 1) for axis in AXES[:9]]) + exit_y = terms(list(exit_x)+[(q, -1)]) + out_x = positive(AXES[:9+8*stage]) + out_y = terms(list(out_x)+[(q, -1)]) + maps = [contact(a, b, columns) for a, b in + ((raw_x, entry_x), (raw_y, entry_y), (exit_x, out_x), (exit_y, out_y))] + require(all(columns[j] == AXES[j] for j in range(DIMENSION) if j not in retained) + and all((item['translation'] | item['inverse_translation']) & ~retained_mask == 0 for item in maps), + 'all actual contacts fix omitted spectator rows') + expected = phase(stage_terms(stage, q)) + d0 = stage_terms(0, q) + require(transformed_path(d0, maps[0], maps[2], columns) == expected, 'executed X diagonal D_s') + require(transformed_path(d0, maps[1], maps[3], columns) == expected, 'executed Y diagonal D_s') + require(transformed_path(terms(list(d0)+[(q, -1)]), maps[0], maps[3], columns) + == phase(terms(list(stage_terms(stage, q))+[(q, -1)])), 'executed cross D_s Q inverse') + require(sum(columns[j] != AXES[j] for j in range(DIMENSION)) <= 17 + and all(item['translation'].bit_count() <= 17 and item['inverse_translation'].bit_count() <= 17 + for item in maps), 'source seventeen-axis contacts') + contacts.append([stage, q, maps]) + paths += 3 + digest = hashlib.sha256(json.dumps(contacts, separators=(',', ':')).encode()).hexdigest() + require(digest == source_result['physical_caller']['route_payload_sha256'], 'complete selected raw contact payload') + + for q in word['ports']: + # A rank-one positive query plus its full ordinary normalizer gives Q^-1. + query_basis = transpose((q,)+bases[q]) + query = (('P', tuple(query_basis)),) + equal(9, adjoint(query)+(('C', 1, 1),)+query+(('X', q),), (('C', q, -1),), 'complete positive thin query') + for output, diagonal in enumerate(controller['diagonal']): + qp, selected = diagonal[0], diagonal[1:] + require(qp in (-1, 1) and len(selected) == 33 and set(selected) <= {0, 1}, 'complete raw endpoint exponent grammar') + raw = terms([(q, qp)]+[entry for stage, yes in enumerate(selected) if yes for entry in stage_terms(stage, q)]) + active = list(range(9)) if selected[0] else [0] + active += [j for stage in range(1, 33) if selected[stage] for j in range(9+8*(stage-1), 9+8*stage)] + base = AXES[:9] if selected[0] else (q,)+bases[q] + canonicalizer = complete_positive_basis(base, active, retained) + wanted = canonicalizer[:len(active)] + translation = q if qp == -1 else 0 + corrected = terms(list(raw)+([(translation, 2)] if translation else [])) + require(phase(corrected) == phase(positive(wanted)), 'entire main endpoint with final translation') + require(len(wanted) == 1+8*sum(selected), 'complete productive main rank') + main_profile[len(wanted)] += 1 + endpoint_records.append([q, output, len(wanted), translation, list(canonicalizer)]) + idle_endpoints = [] + for event_index, event in enumerate(controller['physical_events']): + if event[0] != 'IDLE': + continue + stages = event[2] + require(stages and len(stages) == len(set(stages)) and set(stages) <= set(range(33)), 'entire idle window') + for q in word['ports']: + raw = terms(entry for stage in stages for entry in stage_terms(stage, q)) + active = list(range(1, 9)) if 0 in stages else [] + active += [j for stage in stages if stage for j in range(9+8*(stage-1), 9+8*stage)] + canonicalizer = complete_positive_basis((q,)+bases[q], active, retained) + wanted = positive(canonicalizer[:len(active)]) + adapter = contact(wanted, raw, AXES) + require(len(active) == 8*len(stages), 'positive whole-idle rank') + idle_profile[len(active)] += 2 + idle_endpoints.append([event_index, q, len(active), adapter, list(canonicalizer)]) + registered = source_result['physical_caller'] + require(dict(main_profile) == {int(k): v for k, v in registered['main_targets'].items()}, 'selected main output census') + require(dict(idle_profile) == {int(k): v for k, v in registered['whole_idle_jobs'].items()}, 'selected whole-idle census') + return {'source_dimension': DIMENSION, 'retained_source_rows': len(retained), 'omitted_identity_spectator_rows': DIMENSION-len(retained), + 'complete_raw_contacts': 4*len(contacts), 'composed_native_paths': paths, + 'source_route_payload_sha256': digest, 'thin_query_boundaries': len(word['ports']), + 'complete_main_endpoints': sum(main_profile.values()), 'main_profile': dict(sorted(main_profile.items())), + 'complete_idle_endpoints': sum(idle_profile.values()), 'idle_profile': dict(sorted(idle_profile.items())), + 'full_coordinate_bijections': len(endpoint_records)+len(idle_endpoints), + 'main_boundary_sha256': hashlib.sha256(json.dumps(endpoint_records, separators=(',', ':')).encode()).hexdigest(), + 'idle_boundary_sha256': hashlib.sha256(json.dumps(idle_endpoints, separators=(',', ':')).encode()).hexdigest(), + 'limits': 'algebraic whole-field bijections; physical scheduling and charged realization remain separate'} diff --git a/research/selected-native-tensor-closure/controls.py b/research/selected-native-tensor-closure/controls.py new file mode 100644 index 0000000000..b20e5a434a --- /dev/null +++ b/research/selected-native-tensor-closure/controls.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Mathematical faults rejected independently of provenance-hash failures.""" +from __future__ import annotations + +from copy import deepcopy + +from gauss_trace import adjoint, equal, require +from native_check import check_native, frame, gaussian, lowered, monomial +from source_algebra import free_laurent, local_gauge, ownership_and_invoice +from caller_check import AXES, contact, orthogonal_base, phase, positive, route, stage_terms, terms, transformed_path + + +def lift(n, f, circuit, repeat_constant=True): + """Small checked test witness, not a replacement for the universal proof.""" + dimension = n*f + out = [] + for column in range(f): + offset = n*column + for gate in circuit: + kind = gate[0] + if kind == 'P': + rows = [1 << j for j in range(dimension)] + rows[offset:offset+n] = [row << offset for row in gate[1]] + out.append(('P', tuple(rows))) + elif kind == 'D': + rows, linear = [0]*dimension, [0]*dimension + rows[offset:offset+n] = [row << offset for row in gate[1]] + linear[offset:offset+n] = gate[2] + out.append(('D', tuple(rows), tuple(linear))) + elif kind in ('X', 'C'): + out.append((kind, gate[1] << offset)+gate[2:]) + else: + require(kind == 'phase', 'witness native gate') + if repeat_constant or column == 0: + out.append(gate) + return tuple(out) + + +def run(word, result, candidates, controller, phase_source): + rejected = {} + + def reject(name, action): + try: + action() + except ValueError as error: + rejected[name] = str(error) + return + raise ValueError('negative control accepted: '+name) + + records = {(a, b): recipe for a, b, recipe in candidates['pairs']} + # These are actual source pairs, chosen once after locating nondegenerate + # faults. They are fixed regression witnesses, not a continuing search. + a, b = 0, 249 + recipe = records[a, b] + expected = adjoint(frame(tuple(word['frames'][a])))+frame(tuple(word['frames'][b])) + actual = lowered(recipe) + equal(9, actual, expected, 'native control baseline') + reject('native_global_i_preserving_conjugation_action', + lambda: equal(9, actual+(('phase', 1),), expected, 'lost absolute phase')) + reject('native_left_right_order', + lambda: equal(9, monomial(recipe['left'])+gaussian(recipe['rank'])+monomial(recipe['right']), + expected, 'reversed native factors')) + reject('native_missing_positive_child', + lambda: equal(9, monomial(recipe['right'])+monomial(recipe['left']), expected, 'omitted native Gaussian')) + equal(18, lift(9, 2, actual), lift(9, 2, expected), 'actual two-column native baseline') + reject('native_constant_i_not_raised_to_column_width', + lambda: equal(18, lift(9, 2, actual, repeat_constant=False), lift(9, 2, expected), 'wrong i^(p*f)')) + require(any(event[0] == 'SIGNED_SWAP' for event in controller['physical_events']), 'actual exterior minus source') + reject('exterior_minus_incorrectly_tensor_powered', + lambda: equal(18, lift(9, 2, (('phase', 2),)), (('phase', 2),), 'exterior sign squared')) + reject('tensor_of_sum_replaced_by_sum_of_tensors', + lambda: equal(2, (('C', 3, 1),), (('C', 1, 1), ('C', 2, 1)), 'tensoring a Gaussian expansion termwise')) + reject('zero_column_agrees_but_quadratic_operator_differs', + lambda: equal(2, (), (('D', (2, 1), (0, 0)),), 'missing controlled sign')) + + a, b = 3, 117 + helper = records[a, b] + helper_path = adjoint(frame(tuple(word['frames'][a])))+frame(tuple(word['frames'][b])) + equal(9, adjoint(monomial(helper['right']))+helper_path+adjoint(monomial(helper['left'])), + gaussian(helper['rank']), 'whole-helper control baseline') + reject('whole_helper_pre_normalizer_not_inverted', + lambda: equal(9, monomial(helper['right'])+helper_path+adjoint(monomial(helper['left'])), + gaussian(helper['rank']), 'wrong whole-helper entry')) + + changed = deepcopy(candidates) + changed['pairs'][0][2]['left']['phase'] = (changed['pairs'][0][2]['left']['phase']+1) % 4 + reject('registered_recipe_payload_drift', lambda: check_native(word, result, changed)) + changed_word = deepcopy(word) + scalar = next(event for event in changed_word['program'] if event[0] == 'ADD') + scalar[-1] = (scalar[-1]+1) % len(word['frames']) + reject('scalar_chart_mismatch', lambda: local_gauge(changed_word, result)) + changed_word = deepcopy(word) + move = next(event for event in changed_word['program'] if event[0] == 'MOVE') + move[2], move[3] = move[3], move[2] + reject('MOVE_reversed_source_and_target', lambda: local_gauge(changed_word, result)) + changed_word = deepcopy(word) + changed_word['live'][-1] = changed_word['live'][0] + reject('aliased_local_public_role', lambda: ownership_and_invoice(changed_word, controller, result)) + + changed_controller = deepcopy(controller) + changed_controller['physical_events'].remove(next(event for event in changed_controller['physical_events'] if event[0] == 'Q_POWER')) + reject('caller_missing_central_translation', lambda: free_laurent(changed_controller)) + changed_controller = deepcopy(controller) + next(event for event in changed_controller['physical_events'] if event[0] == 'SIGNED_SWAP')[0] = 'SWAP' + reject('caller_exterior_swap_sign_lost', lambda: free_laurent(changed_controller)) + changed_controller = deepcopy(controller) + changed_controller['diagonal'][0][0] *= -1 + reject('caller_wrong_raw_diagonal_Q_exponent', lambda: free_laurent(changed_controller)) + + q = word['ports'][0] + reject('canonical_rank_one_chart_mistaken_for_C_q', + lambda: equal(9, frame(tuple(word['frames'][word['initial'][word['live'][0]]])), + (('C', q, 1),), 'omitted nontrivial intrinsic main adapter')) + port_recipe = next(item for item in phase_source['recipes'] if item['q'] == q) + basis = orthogonal_base(q, port_recipe) + stage = 1 + columns = route(stage, q, basis) + spectators = positive(AXES[9:17]) + entry = contact(positive(AXES[:9]), terms(list(spectators)+[(q, 1)]), columns) + exit_ = contact(terms(list(spectators)+[(axis, 1) for axis in AXES[:9]]), positive(AXES[:17]), columns) + desired = phase(stage_terms(stage, q)) + require(transformed_path(stage_terms(0, q), entry, exit_, columns) == desired, 'actual contact control baseline') + changed_exit = dict(exit_) + changed_exit['translation'] ^= AXES[264] + reject('contact_corrupts_arbitrary_spectator_row', + lambda: require(transformed_path(stage_terms(0, q), entry, changed_exit, columns) == desired, + 'nonidentity spectator action')) + diagonal = next(term for term in controller['diagonal'] if term[0] == -1) + raw = terms([(q, -1)]+[item for s, yes in enumerate(diagonal[1:]) if yes for item in stage_terms(s, q)]) + corrected = phase(terms(list(raw)+[(q, 2)])) + reject('main_whole_job_final_translation_omitted', + lambda: require(phase(raw) == corrected, 'omitted X_q final raw endpoint correction')) + return rejected diff --git a/research/selected-native-tensor-closure/emit_recipes.py b/research/selected-native-tensor-closure/emit_recipes.py new file mode 100644 index 0000000000..4cd1b96d90 --- /dev/null +++ b/research/selected-native-tensor-closure/emit_recipes.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Rebuild the selected candidate recipes with the credited source compiler. + +This is a candidate producer, not the independent acceptance checker. The +complete payload must match the already registered selected recipe digest. +""" +from __future__ import annotations + +from functools import lru_cache +import gzip +import hashlib +import importlib.util +import json +from pathlib import Path +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +WORD = ROOT/'research/p104-helper470-twin-rung-removal/WORD.json.gz' +RESULT = ROOT/'research/p104-helper470-twin-rung-removal/RESULT.json' +COMPILER = ROOT/'research/p104-native-channel/vendor/clifford_exact.py' + + +def need(ok, message): + if not ok: + raise ValueError(message) + + +def canonical(value): + return json.dumps(value, sort_keys=True, separators=(',', ':')).encode() + + +def produce(): + need(hashlib.sha256(WORD.read_bytes()).hexdigest() == '7834725d9e34ee846a9ccc615221ea81e0201613938afa185d2eda0c9a6c232f', + 'selected word pin') + need(hashlib.sha256(COMPILER.read_bytes()).hexdigest() == '2982ead07721e83358dc67c6f49c2b4c16a236a6bebdfd72f58221be1f5d0962', + 'candidate compiler pin') + need(hashlib.sha256(RESULT.read_bytes()).hexdigest() == '84fcbe2a0b64307b5703c363408042bdd91555b0419509aa50daa43b3b1924ad', + 'selected result pin') + word = json.loads(gzip.decompress(WORD.read_bytes())) + result = json.loads(RESULT.read_bytes()) + spec = importlib.util.spec_from_file_location('credited_candidate_compiler', COMPILER) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + # The candidate producer is deliberately the source implementation. All + # acceptance, including absolute phases, uses gauss_trace independently. + @lru_cache(None) + def chart(index): + return module.canonical_frame(9, tuple(word['frames'][index])) + main = set(word['live']) | {r+112 for r in word['live']} + pairs = {(event[2], event[3]) for event in word['program'] if event[0] == 'MOVE'} + pairs |= {(word['initial'][r], word['final'][r]) for r in range(word['public']) if r not in main} + records = [] + for i, (a, b) in enumerate(sorted(pairs)): + recipe, _ = module.lower_child(chart(a).adjoint().then(chart(b))) + records.append([a, b, recipe]) + if i % 250 == 0: + print('candidate_pairs', i, len(pairs), flush=True) + adapters = [] + for role, q in zip(word['live'], word['ports'], strict=True): + entry = module.cgate(9, q, 1).adjoint().then(chart(word['initial'][role])) + exit_ = chart(word['final'][role+112]).adjoint().then(module.cgate(9, q, -1).then(module.fourier(9))) + for kind, op in (('input', entry), ('output', exit_)): + recipe, _ = module.lower_child(op) + adapters.append({'kind': kind, 'role': role, 'port': q, 'recipe': recipe}) + payload = records+[item['recipe'] for item in adapters] + digest = hashlib.sha256(canonical(payload)).hexdigest() + need(digest == result['native']['recipe_payload_sha256'], 'complete payload equals selected registered recipes') + return {'schema': 'selected-native-tensor-closure/1', 'pairs': records, 'adapters': adapters, + 'source_word_sha256': hashlib.sha256(WORD.read_bytes()).hexdigest(), 'recipe_payload_sha256': digest} + + +def main(): + value = produce() + raw = canonical(value)+b'\n' + target = HERE/'NATIVE.json.gz' + if '--write' in sys.argv: + target.write_bytes(gzip.compress(raw, compresslevel=9, mtime=0)) + else: + need(gzip.decompress(target.read_bytes()) == raw, 'complete regenerated payload bytes') + print('PASS_SELECTED_NATIVE_RECIPE_EMISSION', value['recipe_payload_sha256']) + + +if __name__ == '__main__': + with tempfile.TemporaryDirectory(prefix='native-candidate-pycache-') as cache: + sys.pycache_prefix = cache + sys.dont_write_bytecode = True + main() diff --git a/research/selected-native-tensor-closure/gauss_trace.py b/research/selected-native-tensor-closure/gauss_trace.py new file mode 100644 index 0000000000..f232a11bf5 --- /dev/null +++ b/research/selected-native-tensor-closure/gauss_trace.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +"""Exact circuit traces by constrained quadratic Gauss sums. + +No Clifford tableau, distinguished input column, floating point, or dense +operator matrix is used. See PROOF.md. Apache-2.0. +""" +from __future__ import annotations + +from dataclasses import dataclass +from itertools import combinations + + +def require(ok: bool, reason: str) -> None: + if not ok: + raise ValueError(reason) + + +def bits(mask: int) -> list[int]: + out = [] + while mask: + low = mask & -mask + out.append(low.bit_length() - 1) + mask ^= low + return out + + +def gaussian_mul(a: tuple[int, int], b: tuple[int, int]) -> tuple[int, int]: + x, y = a + z, w = b + return x*z-y*w, x*w+y*z + + +def unit(power: int) -> tuple[int, int]: + return ((1, 0), (0, 1), (-1, 0), (0, -1))[power % 4] + + +@dataclass +class Quadratic: + """c + sum a_i x_i + 2 sum_(i Quadratic: + require(type(n) is int and n >= 0, 'quadratic variable count') + return cls([0]*n, set()) + + def copy(self) -> Quadratic: + return Quadratic(self.linear[:], self.pairs.copy(), self.constant) + + def toggle(self, i: int, j: int) -> None: + require(0 <= i < len(self.linear) and 0 <= j < len(self.linear), 'quadratic index') + if i == j: + self.linear[i] = (self.linear[i]+2) % 4 + return + pair = (min(i, j), max(i, j)) + if pair in self.pairs: + self.pairs.remove(pair) + else: + self.pairs.add(pair) + + def add_affine(self, coefficient: int, form: tuple[int, int]) -> None: + """Add coefficient times a Boolean affine parity, modulo four.""" + mask, constant = form + require(mask >= 0 and mask >> len(self.linear) == 0 and constant in (0, 1), 'affine form domain') + coefficient %= 4 + if coefficient == 0: + return + support = bits(mask) + self.constant = (self.constant+coefficient*constant) % 4 + signed = coefficient*(1-2*constant) + for i in support: + self.linear[i] = (self.linear[i]+signed) % 4 + if coefficient % 2: + for i, j in combinations(support, 2): + self.toggle(i, j) + + def add_product(self, a: tuple[int, int], b: tuple[int, int]) -> None: + """Add twice the product of two Boolean affine forms, modulo four.""" + x, c = a + y, d = b + require(x >= 0 and y >= 0 and (x | y) >> len(self.linear) == 0 and c in (0, 1) and d in (0, 1), + 'quadratic product domain') + self.constant = (self.constant+2*c*d) % 4 + for i in bits((y if c else 0) ^ (x if d else 0)): + self.linear[i] = (self.linear[i]+2) % 4 + for i in bits(x): + for j in bits(y): + self.toggle(i, j) + + def substitute(self, forms: list[tuple[int, int]], n: int) -> Quadratic: + require(len(forms) == len(self.linear), 'complete substitution') + out = Quadratic.zero(n) + out.constant = self.constant + for coefficient, form in zip(self.linear, forms, strict=True): + out.add_affine(coefficient, form) + for i, j in sorted(self.pairs): + out.add_product(forms[i], forms[j]) + return out + + def value(self, x: int) -> int: + require(type(x) is int and 0 <= x < 1 << len(self.linear), 'quadratic assignment') + return (self.constant+sum(a for i, a in enumerate(self.linear) if x >> i & 1) + +2*sum((x >> i & 1)*(x >> j & 1) for i, j in self.pairs)) % 4 + + +def gauss_sum(poly: Quadratic) -> tuple[int, int]: + """Return sum_x i^poly(x) exactly using one- and two-variable pivots.""" + q = poly.copy() + active = set(range(len(q.linear))) + factor = (1, 0) + while active: + odd = next((i for i in sorted(active) if q.linear[i] % 2), None) + if odd is not None: + a = q.linear[odd] + neighbours = 0 + retained = set() + for i, j in q.pairs: + if odd == i: + neighbours ^= 1 << j + elif odd == j: + neighbours ^= 1 << i + else: + retained.add((i, j)) + q.pairs = retained + q.linear[odd] = 0 + active.remove(odd) + z = unit(a) + factor = gaussian_mul(factor, (1+z[0], z[1])) + q.add_affine(-a, (neighbours, 0)) + continue + if q.pairs: + i, j = min(q.pairs) + require(i in active and j in active, 'elimination support invariant') + u = v = 0 + retained = set() + for a, b in q.pairs: + if (a, b) == (i, j): + continue + if i == a: + u ^= 1 << b + elif i == b: + u ^= 1 << a + elif j == a: + v ^= 1 << b + elif j == b: + v ^= 1 << a + else: + retained.add((a, b)) + require((u | v) & ((1 << i) | (1 << j)) == 0, 'two-pivot complement') + ci, cj = q.linear[i]//2, q.linear[j]//2 + q.pairs = retained + q.linear[i] = q.linear[j] = 0 + active.remove(i) + active.remove(j) + q.add_product((u, ci), (v, cj)) + factor = (2*factor[0], 2*factor[1]) + continue + if any(q.linear[i] == 2 for i in active): + return 0, 0 + require(all(q.linear[i] == 0 for i in active), 'isolated even phases') + size = 1 << len(active) + factor = factor[0]*size, factor[1]*size + active.clear() + require(not q.pairs and not any(q.linear), 'complete quadratic elimination') + return gaussian_mul(factor, unit(q.constant)) + + +def affine_solution(n: int, equations: list[tuple[int, int]]) -> tuple[list[tuple[int, int]], int] | None: + """RREF parametrization of every solution, with each free assignment once.""" + rows = [[mask, rhs] for mask, rhs in equations] + require(all(mask >= 0 and mask >> n == 0 and rhs in (0, 1) for mask, rhs in rows), 'linear equation domain') + pivots = [] + k = 0 + for j in range(n): + at = next((i for i in range(k, len(rows)) if rows[i][0] >> j & 1), None) + if at is None: + continue + rows[k], rows[at] = rows[at], rows[k] + for i in range(len(rows)): + if i != k and rows[i][0] >> j & 1: + rows[i][0] ^= rows[k][0] + rows[i][1] ^= rows[k][1] + pivots.append(j) + k += 1 + if any(mask == 0 and rhs for mask, rhs in rows): + return None + free = [j for j in range(n) if j not in set(pivots)] + positions = {j: i for i, j in enumerate(free)} + forms = [(0, 0)]*n + for j, i in positions.items(): + forms[j] = (1 << i, 0) + for pivot, (mask, rhs) in zip(pivots, rows, strict=False): + require(mask & sum(1 << j for j in pivots) == 1 << pivot, 'RREF pivot isolation') + forms[pivot] = (sum(1 << positions[j] for j in free if mask >> j & 1), rhs) + return forms, len(free) + + +def binary_inverse(rows: tuple[int, ...]) -> tuple[int, ...]: + n = len(rows) + require(n > 0 and all(type(row) is int and 0 <= row < 1 << n for row in rows), 'binary matrix domain') + augmented = [row | (1 << (n+i)) for i, row in enumerate(rows)] + for j in range(n): + k = next((i for i in range(j, n) if augmented[i] >> j & 1), None) + require(k is not None, 'singular address matrix') + augmented[j], augmented[k] = augmented[k], augmented[j] + for i in range(n): + if i != j and augmented[i] >> j & 1: + augmented[i] ^= augmented[j] + require([row & ((1 << n)-1) for row in augmented] == [1 << i for i in range(n)], 'binary inverse endpoint') + return tuple(row >> n for row in augmented) + + +def adjoint(circuit: tuple[tuple, ...]) -> tuple[tuple, ...]: + out = [] + for gate in reversed(circuit): + kind = gate[0] + if kind == 'P': + out.append(('P', binary_inverse(tuple(gate[1])))) + elif kind == 'D': + out.append(('D', tuple(gate[1]), tuple(-a % 4 for a in gate[2]))) + elif kind == 'C': + out.append(('C', gate[1], -gate[2])) + elif kind == 'phase': + out.append(('phase', -gate[1] % 4)) + else: + require(kind == 'X', 'adjoint gate vocabulary') + out.append(gate) + return tuple(out) + + +def circuit_trace(n: int, circuit: tuple[tuple, ...]) -> tuple[int, int, int]: + """Trace numerator real/imaginary and power-of-two denominator. + + All accepted gates are unitary by their checked syntax and invertible + address maps. The trace construction works at arbitrary n. + """ + require(type(n) is int and n > 0, 'positive circuit dimension') + addresses = [(1 << i, 0) for i in range(n)] + q = Quadratic.zero(n) + factor = (1, 0) + denominator = 0 + for gate in circuit: + kind = gate[0] + if kind == 'P': + require(len(gate) == 2 and len(gate[1]) == n, 'permutation arity') + rows = tuple(gate[1]) + binary_inverse(rows) + following = [] + for row in rows: + mask = constant = 0 + for j in bits(row): + mask ^= addresses[j][0] + constant ^= addresses[j][1] + following.append((mask, constant)) + addresses = following + elif kind == 'X': + require(len(gate) == 2 and type(gate[1]) is int and 0 <= gate[1] < 1 << n, 'translation domain') + addresses = [(mask, constant ^ (gate[1] >> i & 1)) for i, (mask, constant) in enumerate(addresses)] + elif kind == 'phase': + require(len(gate) == 2 and type(gate[1]) is int and 0 <= gate[1] < 4, 'phase domain') + q.constant = (q.constant+gate[1]) % 4 + elif kind == 'D': + require(len(gate) == 3 and len(gate[1]) == len(gate[2]) == n, 'diagonal arity') + rows, linear = gate[1:] + require(all(type(row) is int and 0 <= row < 1 << n for row in rows), 'quadratic matrix domain') + require(all(type(a) is int and 0 <= a < 4 for a in linear), 'quadratic linear phase domain') + require(all((rows[i] >> j & 1) == (rows[j] >> i & 1) for i in range(n) for j in range(n)), + 'symmetric source quadratic') + require(all((linear[i] & 1) == (rows[i] >> i & 1) for i in range(n)), 'source diagonal parity') + for coefficient, form in zip(linear, addresses, strict=True): + q.add_affine(coefficient, form) + for i in range(n): + for j in range(i+1, n): + if rows[i] >> j & 1: + q.add_product(addresses[i], addresses[j]) + else: + require(kind == 'C' and len(gate) == 3 and type(gate[1]) is int and 0 < gate[1] < 1 << n + and type(gate[2]) is int and gate[2] in (-1, 1), 'Gaussian gate domain') + direction, sign = gate[1:] + variable = 1 << len(q.linear) + q.linear.append(-sign % 4) + addresses = [(mask ^ (variable if direction >> i & 1 else 0), constant) + for i, (mask, constant) in enumerate(addresses)] + factor = gaussian_mul(factor, (1, sign)) + denominator += 1 + constraints = [(mask ^ (1 << i), constant) for i, (mask, constant) in enumerate(addresses)] + solved = affine_solution(len(q.linear), constraints) + if solved is None: + return 0, 0, 0 + forms, free = solved + result = gaussian_mul(factor, gauss_sum(q.substitute(forms, free))) + real, imag = result + while denominator and real % 2 == 0 and imag % 2 == 0: + real //= 2 + imag //= 2 + denominator -= 1 + return real, imag, denominator + + +def validate(n: int, circuit: tuple[tuple, ...]) -> None: + """Validate original syntax before an adjoint can normalize any field.""" + require(type(n) is int and n > 0, 'positive circuit dimension') + for gate in circuit: + require(type(gate) in (tuple, list) and len(gate) > 0, 'gate record') + kind = gate[0] + if kind == 'P': + require(len(gate) == 2 and len(gate[1]) == n, 'permutation arity') + binary_inverse(tuple(gate[1])) + elif kind == 'X': + require(len(gate) == 2 and type(gate[1]) is int and 0 <= gate[1] < 1 << n, 'translation domain') + elif kind == 'phase': + require(len(gate) == 2 and type(gate[1]) is int and 0 <= gate[1] < 4, 'phase domain') + elif kind == 'C': + require(len(gate) == 3 and type(gate[1]) is int and 0 < gate[1] < 1 << n + and type(gate[2]) is int and gate[2] in (-1, 1), 'Gaussian gate domain') + else: + require(kind == 'D' and len(gate) == 3 and len(gate[1]) == len(gate[2]) == n, 'diagonal arity') + rows, linear = gate[1:] + require(all(type(row) is int and 0 <= row < 1 << n for row in rows), 'quadratic matrix domain') + require(all(type(a) is int and 0 <= a < 4 for a in linear), 'quadratic linear phase domain') + require(all((rows[i] >> j & 1) == (rows[j] >> i & 1) for i in range(n) for j in range(n)), + 'symmetric source quadratic') + require(all((linear[i] & 1) == (rows[i] >> i & 1) for i in range(n)), 'source diagonal parity') + + +def equal(n: int, actual: tuple[tuple, ...], expected: tuple[tuple, ...], label: str) -> tuple[int, int, int]: + validate(n, expected) + trace = circuit_trace(n, actual+adjoint(expected)) + require(trace == (1 << n, 0, 0), label+': exact unitary overlap trace '+str(trace)) + return trace diff --git a/research/selected-native-tensor-closure/native_check.py b/research/selected-native-tensor-closure/native_check.py new file mode 100644 index 0000000000..a771f88464 --- /dev/null +++ b/research/selected-native-tensor-closure/native_check.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Source-native acceptance using the independent exact trace mechanism.""" +from __future__ import annotations + +from collections import Counter +from functools import lru_cache +import hashlib +import json + +from gauss_trace import adjoint, binary_inverse, equal, require + + +def canonical(value) -> bytes: + return json.dumps(value, sort_keys=True, separators=(',', ':')).encode() + + +def transpose(rows: tuple[int, ...]) -> tuple[int, ...]: + return tuple(sum(((row >> j) & 1) << i for i, row in enumerate(rows)) for j in range(len(rows))) + + +def span(vectors: list[int] | tuple[int, ...], n: int = 9) -> frozenset[int]: + out = {0} + for value in vectors: + require(type(value) is int and 0 < value < 1 << n and value not in out, 'independent binary frame') + out |= {x ^ value for x in tuple(out)} + return frozenset(out) + + +def extended_columns(vectors: tuple[int, ...], n: int) -> tuple[int, ...]: + """The source's ordered greedy extension, reimplemented without imports.""" + result, reached = [], {0} + for value in vectors+tuple(1 << i for i in range(n)): + if value not in reached: + result.append(value) + reached |= {x ^ value for x in tuple(reached)} + require(len(result) == n and len(reached) == 1 << n, 'complete source frame extension') + return tuple(result) + + +def gaussian(rank: int) -> tuple[tuple, ...]: + return tuple(('C', 1 << i, 1) for i in range(rank)) + + +@lru_cache(maxsize=None) +def frame(vectors: tuple[int, ...], n: int = 9) -> tuple[tuple, ...]: + span(vectors, n) + rank = len(vectors) + if rank == 0: + return () + if rank == n: + return gaussian(n) + matrix = transpose(extended_columns(vectors, n)) + inverse_columns = transpose(binary_inverse(matrix)) + quadratic = tuple((1 << i) ^ sum(((a & b).bit_count() % 2) << j + for j, b in enumerate(inverse_columns)) + for i, a in enumerate(inverse_columns)) + linear = tuple((row >> i) & 1 for i, row in enumerate(quadratic)) + conjugator = (('P', matrix), ('D', quadratic, linear)) + return adjoint(conjugator)+gaussian(rank)+conjugator + + +def monomial(record: dict) -> tuple[tuple, ...]: + require(type(record) is dict and set(record) == {'matrix_rows', 'offset', 'quadratic_rows', 'linear_Z4', 'phase'}, + 'complete monomial record') + matrix = tuple(record['matrix_rows']) + quadratic = tuple(record['quadratic_rows']) + linear = tuple(record['linear_Z4']) + require(len(matrix) == len(quadratic) == len(linear) == 9, 'source monomial dimension') + binary_inverse(matrix) + return (('D', quadratic, linear), ('P', matrix), ('X', record['offset']), ('phase', record['phase'])) + + +def lowered(record: dict) -> tuple[tuple, ...]: + require(type(record) is dict and set(record) == {'rank', 'left', 'right'}, 'complete lowered record') + rank = record['rank'] + require(type(rank) is int and 0 <= rank <= 9, 'source child rank') + if rank == 0: + require(record['right'] is None, 'rank-zero right convention') + return monomial(record['left']) + return monomial(record['right'])+gaussian(rank)+monomial(record['left']) + + +def inventory(word: dict) -> tuple[set[tuple[int, int]], list[int], list[tuple[str, int, int]]]: + main = set(word['live']) | {r+112 for r in word['live']} + helpers = [r for r in range(word['public']) if r not in main] + pairs = {(event[2], event[3]) for event in word['program'] if event[0] == 'MOVE'} + pairs |= {(word['initial'][r], word['final'][r]) for r in helpers} + adapters = [(kind, r, q) for r, q in zip(word['live'], word['ports'], strict=True) + for kind in ('input', 'output')] + return pairs, helpers, adapters + + +def check_native(word: dict, source_result: dict, candidates: dict, progress=False) -> dict: + pairs, helpers, adapter_ids = inventory(word) + require(set(candidates) == {'schema', 'pairs', 'adapters', 'source_word_sha256', 'recipe_payload_sha256'}, + 'complete native candidate envelope') + require(candidates['schema'] == 'selected-native-tensor-closure/1', 'candidate schema') + require(candidates['source_word_sha256'] == '7834725d9e34ee846a9ccc615221ea81e0201613938afa185d2eda0c9a6c232f', + 'candidate source word binding') + records = {(a, b): record for a, b, record in candidates['pairs']} + require(len(records) == len(candidates['pairs']) and set(records) == pairs, 'exact MOVE/helper recipe coverage') + require(all(set(item) == {'kind', 'role', 'port', 'recipe'} for item in candidates['adapters']), + 'complete main adapter records') + require([(item['kind'], item['role'], item['port']) for item in candidates['adapters']] == adapter_ids, + 'complete ordered main adapter coverage') + payload = candidates['pairs']+[item['recipe'] for item in candidates['adapters']] + digest = hashlib.sha256(canonical(payload)).hexdigest() + require(digest == source_result['native']['recipe_payload_sha256'] == candidates['recipe_payload_sha256'], + 'full selected recipe payload hash') + charts = [frame(tuple(vectors)) for vectors in word['frames']] + max_branches = 0 + traces = [] + for count, (a, b) in enumerate(sorted(pairs)): + expected = adjoint(charts[a])+charts[b] + actual = lowered(records[a, b]) + require(records[a, b]['rank'] == abs(len(word['frames'][a])-len(word['frames'][b])), 'paid or helper source rank') + trace = equal(9, actual, expected, f'frame pair {a}:{b}') + max_branches = max(max_branches, sum(g[0] == 'C' for g in actual+expected)) + traces.append([a, b, *trace]) + if progress and count % 500 == 0: + print('trace_pairs', count, len(pairs), flush=True) + adapters = {} + for item in candidates['adapters']: + kind, r, q = item['kind'], item['role'], item['port'] + if kind == 'input': + expected = (('C', q, -1),)+charts[word['initial'][r]] + else: + expected = adjoint(charts[word['final'][r+112]])+(('C', q, -1),)+gaussian(9) + require(item['recipe']['rank'] == 0, 'ordinary intrinsic adapter') + actual = lowered(item['recipe']) + equal(9, actual, expected, f'main {kind} {r}') + adapters[kind, r] = actual + + # Join the logical endpoint X'=X, Y'=Y+X to all three canonical paths. + main_paths = 0 + for r, q in zip(word['live'], word['ports'], strict=True): + ix, iy = word['initial'][r], word['initial'][r+112] + ox, oy = word['final'][r], word['final'][r+112] + require(word['frames'][ix] == [q] and word['frames'][iy] == [] and len(word['frames'][ox]) == 9, + 'actual main entrance and full source exit') + entry, exit_ = adapters['input', r], adapters['output', r] + d0 = (('C', q, -1),)+gaussian(9) + paths = [ + (entry+adjoint(charts[ix])+charts[ox], d0, 'source diagonal'), + (adjoint(charts[iy])+charts[oy]+exit_, d0, 'target diagonal'), + (entry+adjoint(charts[ix])+charts[oy]+exit_, (('C', q, -1),)+d0, 'positive cross'), + ] + for actual, expected, name in paths: + equal(9, actual, expected, f'local {name} {r}') + main_paths += 1 + equal(9, (('C', q, 1), ('C', q, 1)), (('X', q),), 'central square absolute phase') + + helper_pairs = {(word['initial'][r], word['final'][r]) for r in helpers} + helper_profile = Counter() + for a, b in sorted(helper_pairs): + rec = records[a, b] + require(rec['rank'] > 0, 'positive productive helper') + complete = adjoint(monomial(rec['right']))+adjoint(charts[a])+charts[b]+adjoint(monomial(rec['left'])) + equal(9, complete, gaussian(rec['rank']), f'complete helper normalization {a}:{b}') + for r in helpers: + helper_profile[records[word['initial'][r], word['final'][r]]['rank']] += 1 + require(dict(sorted(helper_profile.items())) == {int(k): v for k, v in source_result['native']['helpers'].items()}, + 'selected arbitrary helper census') + return {'distinct_native_pairs': len(pairs), 'distinct_move_pairs': len({(e[2], e[3]) for e in word['program'] if e[0] == 'MOVE'}), + 'main_adapters': len(adapters), 'complete_main_paths': main_paths, 'central_squares': len(word['ports']), + 'helper_normalized_pairs': len(helper_pairs), 'arbitrary_helpers': len(helpers), 'helper_profile': dict(sorted(helper_profile.items())), + 'maximum_closed_trace_branches': max_branches, 'complete_trace_digest': hashlib.sha256(canonical(traces)).hexdigest(), + 'selected_recipe_payload_sha256': digest, 'method': 'exact constrained quadratic Gauss sum; no tableau or distinguished column'} diff --git a/research/selected-native-tensor-closure/source_algebra.py b/research/selected-native-tensor-closure/source_algebra.py new file mode 100644 index 0000000000..597ccfbd2d --- /dev/null +++ b/research/selected-native-tensor-closure/source_algebra.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Complete current-word gauge, ownership and free-Laurent certificates.""" +from __future__ import annotations + +from collections import Counter +from fractions import Fraction +import hashlib + +from gauss_trace import require +from native_check import canonical, span + + +def add_scaled(dst, src, factor): + for key, value in tuple(src.items()): + updated = dst.get(key, 0)+factor*value + if updated: + dst[key] = updated + else: + dst.pop(key, None) + + +def local_gauge(word: dict, source_result: dict) -> dict: + public, owned = word['public'], word['owned_fields'] + require((public, owned) == (770, 29), 'selected public/owned counts') + total = public+owned + require(len(word['initial']) == len(word['final']) == public, 'complete local boundaries') + spaces = [span(vectors) for vectors in word['frames']] + rows = [{i: Fraction(1)} for i in range(total)] + current = word['initial'][:]+[None]*owned + live_owned = set() + paid = Counter() + counts = Counter() + peak = lifetimes = 0 + for index, event in enumerate(word['program']): + kind, target = event[:2] + require(type(target) is int and 0 <= target < total, 'local target range') + counts[kind] += 1 + if kind == 'MOVE': + require(len(event) == 5, 'MOVE grammar') + _, _, old, new, private = event + require(type(private) is bool and current[target] == old and (target in live_owned) == private, + f'current native source and ownership at {index}') + require(spaces[new] < spaces[old] if private else spaces[old] < spaces[new], 'proper nested MOVE') + paid[abs(len(word['frames'][new])-len(word['frames'][old]))] += 1 + current[target] = new + elif kind == 'INIT': + require(len(event) == 3 and target >= public and target not in live_owned, 'fresh owned INIT') + live_owned.add(target) + rows[target] = {} + current[target] = event[2] + peak = max(peak, len(live_owned)) + lifetimes += 1 + elif kind == 'CLEAR': + require(len(event) == 3 and target in live_owned and current[target] == event[2], 'owned CLEAR at current chart') + live_owned.remove(target) + rows[target] = {} + current[target] = None + else: + require(kind in ('ADD', 'SCALE', 'COPY') and len(event) == (4 if kind == 'SCALE' else 5), 'scalar grammar') + coefficient, chart = Fraction(event[-2]), event[-1] + require(coefficient != 0 and current[target] == chart, 'scalar current chart') + require(coefficient.denominator & (coefficient.denominator-1) == 0, 'dyadic exterior coefficient') + if kind == 'SCALE': + rows[target] = {origin: coefficient*value for origin, value in rows[target].items()} + else: + source = event[2] + require(type(source) is int and 0 <= source < total and source != target and current[source] == chart, + 'exact common-chart source') + if kind == 'COPY': + require(target in live_owned and rows[target] == {}, 'COPY into reached owned zero') + rows[target] = {origin: coefficient*value for origin, value in rows[source].items()} + else: + add_scaled(rows[target], rows[source], coefficient) + require(not live_owned and current[:public] == word['final'] and current[public:] == [None]*owned, + 'all current charts and ownership returned') + for target, row in enumerate(rows): + expected = {target: Fraction(1)} if target < public else {} + if target-112 in word['live']: + expected[target-112] = Fraction(1) + require(row == expected, f'complete symbolic gauge endpoint {target}') + expected = source_result['local'] + require({int(k): v for k, v in expected['paid'].items()} == dict(paid), 'selected paid occurrences') + require((peak, lifetimes) == (expected['peak_owned_fields'], expected['owned_lifetimes']), 'actual owned chronology') + encoded = [[[origin, str(coefficient)] for origin, coefficient in sorted(row.items())] for row in rows] + return {'events': len(word['program']), 'opcode_counts': dict(sorted(counts.items())), 'rows': total, + 'arbitrary_public_columns': public, 'owned_entrance_columns_erased': owned, + 'full_endpoint_coefficients': total*total, 'owned_lifetimes': lifetimes, 'peak_owned': peak, + 'paid_profile': dict(sorted(paid.items())), 'gauge_endpoint_sha256': hashlib.sha256(canonical(encoded)).hexdigest(), + 'rule': 'chart coefficients are formal inverse/forward products; every scalar remains exterior'} + + +ZERO = (0,)*34 + + +def shift(poly, exponent, factor=1): + require(len(exponent) == 34, 'all Laurent variables present') + return {tuple(a+b for a, b in zip(term, exponent, strict=True)): factor*value + for term, value in poly.items() if factor*value} + + +def event_pullback(weights, event): + """Substitute the actual forward assignment into a final linear form.""" + kind = event[0] + if kind in ('LOCAL', 'QUERY_SHEAR'): + _, stage, pair, backward = event + require(type(backward) is bool, 'literal controller orientation') + x, y = 2*pair, 2*pair+1 + if backward: + x, y = y, x + d = ((0,)+tuple(int(j == stage) for j in range(33))) if kind == 'LOCAL' else ZERO + cross = (1 if backward else -1,)+(0,)*33 + wx, wy = shift(weights[x], d), shift(weights[y], d) + add_scaled(wx, shift(wy, cross), -1 if backward else 1) + weights[x], weights[y] = wx, wy + elif kind == 'IDLE': + require(len(set(event[2])) == len(event[2]), 'no repeated idle stage') + d = (0,)+tuple(int(j in event[2]) for j in range(33)) + for row in (2*event[1], 2*event[1]+1): + weights[row] = shift(weights[row], d) + elif kind == 'Q_POWER': + require(event[2] in (-2, 2), 'ordinary even central power') + weights[event[1]] = shift(weights[event[1]], (event[2],)+(0,)*33) + elif kind == 'ADD': + add_scaled(weights[event[2]], weights[event[1]], Fraction(event[3])) + elif kind == 'SCALE': + weights[event[1]] = shift(weights[event[1]], ZERO, Fraction(event[2])) + elif kind == 'SWAP': + weights[event[1]], weights[event[2]] = weights[event[2]], weights[event[1]] + else: + require(kind == 'SIGNED_SWAP', 'controller gate vocabulary') + weights[event[1]], weights[event[2]] = shift(weights[event[2]], ZERO, -1), weights[event[1]] + + +def free_laurent(controller: dict) -> dict: + require((controller['kind'], controller['pairs'], controller['ambient_rank']) == ('complex', 16, 145), 'selected controller type') + for side in ('left', 'right'): + for output in range(32): + weights = [{ZERO: Fraction(int(row == output))} if row == output else {} for row in range(32)] + for event in reversed(controller['boundaries'][side+'_program']): + event_pullback(weights, event) + expected = [{ZERO: Fraction(c)} if Fraction(c) else {} for c in controller['boundaries'][side][output]] + require(weights == expected, 'literal '+side+' boundary matrix') + program = controller['boundaries']['right_program']+controller['physical_events']+controller['boundaries']['left_program'] + outputs = [] + for output in range(32): + weights = [{ZERO: Fraction(1)} if row == output else {} for row in range(32)] + for event in reversed(program): + event_pullback(weights, event) + expected = [{tuple(controller['diagonal'][output]): Fraction(1)} if row == output else {} for row in range(32)] + require(weights == expected, f'full free-Laurent reverse output {output}') + outputs.append([output, controller['diagonal'][output], '1']) + sites = [] + local_count = query_count = 0 + for i, event in enumerate(controller['physical_events']): + if event[0] == 'QUERY_SHEAR': + query_count += 1 + if event[0] != 'LOCAL': + continue + _, stage, pair, backward = event + require(not backward, 'all actual suppliers forward') + local_count += 1 + if stage in controller['wrapper_sites']: + x, y = 2*pair, 2*pair+1 + require(controller['physical_events'][i-2:i+3] == [ + ['Q_POWER', x, -2], ['SIGNED_SWAP', x, y], event, + ['Q_POWER', y, 2], ['SIGNED_SWAP', y, x]], 'literal five-step reverse interface') + sites.append(stage) + require(sites == controller['wrapper_sites'] and len(sites) == 16 and local_count == 18 and query_count == 15, + 'complete all-forward sites and thin calls') + return {'controller_events': len(controller['physical_events']), 'literal_boundary_events': len(program)-len(controller['physical_events']), + 'all_1024_laurent_entries_checked': True, 'forward_local_calls': local_count, 'thin_queries_per_port': query_count, + 'five_step_forward_wrappers': len(sites), 'endpoint_sha256': hashlib.sha256(canonical(outputs)).hexdigest(), + 'method': 'reverse linear-functional substitution; no finite-order quotient of Q'} + + +def ownership_and_invoice(word: dict, controller: dict, source_result: dict) -> dict: + main_roles = set(word['live']) | {r+112 for r in word['live']} + helpers = [r for r in range(word['public']) if r not in main_roles] + calls = [e for e in controller['physical_events'] if e[0] == 'LOCAL'] + mains = 32*len(word['live']) + productives = mains+len(calls)*len(helpers) + maps = [] + for call, event in enumerate(calls): + pair = event[2] + mapping = {r: (2*pair)*len(word['live'])+j for j, r in enumerate(word['live'])} + mapping.update({r+112: (2*pair+1)*len(word['live'])+j for j, r in enumerate(word['live'])}) + mapping.update({r: mains+call*len(helpers)+j for j, r in enumerate(helpers)}) + require(set(mapping) == set(range(word['public'])) and len(set(mapping.values())) == word['public'], + 'actual distinct local public owners') + mapping.update({r: productives+r-word['public'] for r in range(word['public'], word['public']+word['owned_fields'])}) + require(len(set(mapping.values())) == word['public']+word['owned_fields'], 'owned bank disjoint from all public inputs') + maps.append([mapping[r] for r in range(word['public']+word['owned_fields'])]) + paid = Counter({int(k): len(calls)*v for k, v in source_result['local']['paid'].items()}) + targets = Counter({int(k): len(calls)*v for k, v in source_result['local']['helpers'].items()}) + for event in controller['physical_events']: + if event[0] == 'QUERY_SHEAR': + paid[1] += len(word['ports']) + elif event[0] == 'IDLE': + paid[8*len(event[2])] += 2*len(word['ports']) + for diagonal in controller['diagonal']: + targets[1+8*sum(diagonal[1:])] += len(word['ports']) + cost = source_result['complete_cost'] + require(dict(paid) == {int(k): v for k, v in cost['paid'].items()}, 'complete paid profile unchanged') + require(dict(targets) == {int(k): v for k, v in cost['targets'].items()}, 'complete productive profile unchanged') + require(sum(targets.values()) == productives == 13444, 'all productive owners') + return {'main_arbitrary_inputs': mains, 'fresh_helper_inputs': len(calls)*len(helpers), 'productive_inputs': productives, + 'local_owned_labels': word['owned_fields'], 'separate_thin_owned_label': productives+word['owned_fields'], + 'paid_calls': sum(paid.values()), 'paid_rank_mass': sum(r*n for r, n in paid.items()), + 'target_rank_mass': sum(r*n for r, n in targets.items()), 'field_maps_sha256': hashlib.sha256(canonical(maps)).hexdigest(), + 'limits': 'ideal source ownership only; allocation, physical erasure and retained backing remain premises'} diff --git a/research/selected-native-tensor-closure/test_gauss_trace.py b/research/selected-native-tensor-closure/test_gauss_trace.py new file mode 100644 index 0000000000..11d945e72b --- /dev/null +++ b/research/selected-native-tensor-closure/test_gauss_trace.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Independent bounded oracles and rejecting controls for gauss_trace.py.""" +from __future__ import annotations + +from fractions import Fraction +from itertools import combinations, product +import json +from pathlib import Path +import random +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from gauss_trace import Quadratic, adjoint, affine_solution, circuit_trace, equal, gauss_sum, require + + +def exhaustive_quadratics() -> int: + count = 0 + for n in range(5): + edges = list(combinations(range(n), 2)) + for linear in product(range(4), repeat=n): + for mask in range(1 << len(edges)): + q = Quadratic(list(linear), {edge for j, edge in enumerate(edges) if mask >> j & 1}) + real = imag = 0 + for x in range(1 << n): + v = (sum(linear[j]*((x >> j) & 1) for j in range(n)) + +2*sum(((x >> a) & 1)*((x >> b) & 1) for a, b in q.pairs)) % 4 + real += (1, 0, -1, 0)[v] + imag += (0, 1, 0, -1)[v] + require(gauss_sum(q) == (real, imag), 'exhaustive quadratic sum') + count += 1 + return count + + +def affine_and_substitution() -> dict[str, int]: + rng = random.Random(7606030) + systems = substitutions = 0 + for n in range(8): + for _ in range(60): + equations = [(rng.randrange(1 << n), rng.randrange(2)) for __ in range(rng.randrange(n+3))] + expected = {x for x in range(1 << n) + if all((x & mask).bit_count() % 2 == rhs for mask, rhs in equations)} + solved = affine_solution(n, equations) + if solved is None: + actual = set() + else: + forms, free = solved + values = [sum((((mask & t).bit_count() % 2)^c) << j for j, (mask, c) in enumerate(forms)) + for t in range(1 << free)] + require(len(set(values)) == len(values), 'unique affine enumeration') + actual = set(values) + require(actual == expected, 'complete affine solution set') + systems += 1 + for _ in range(60): + q = Quadratic([rng.randrange(4) for __ in range(n)], + {pair for pair in combinations(range(n), 2) if rng.randrange(2)}, rng.randrange(4)) + free = rng.randrange(7) + forms = [(rng.randrange(1 << free), rng.randrange(2)) for __ in range(n)] + changed = q.substitute(forms, free) + for t in range(1 << free): + x = sum((((mask & t).bit_count() % 2)^c) << j for j, (mask, c) in enumerate(forms)) + require(changed.value(t) == q.value(x), 'complete affine quadratic substitution') + substitutions += 1 + return {'affine_systems': systems, 'affine_substitutions': substitutions} + + +def dense_trace(n: int, circuit: tuple[tuple, ...]) -> tuple[Fraction, Fraction]: + """Separate direct column propagation; only used at n<=4.""" + size = 1 << n + total = [Fraction(0), Fraction(0)] + for column in range(size): + real = [Fraction(int(x == column)) for x in range(size)] + imag = [Fraction(0) for _ in range(size)] + for gate in circuit: + kind = gate[0] + ar, ai = [Fraction(0) for _ in range(size)], [Fraction(0) for _ in range(size)] + if kind == 'C': + q, sign = gate[1:] + for x in range(size): + y = x ^ q + ar[x] = (real[x]-sign*imag[x]+real[y]+sign*imag[y])/2 + ai[x] = (imag[x]+sign*real[x]+imag[y]-sign*real[y])/2 + else: + for x in range(size): + y, power = x, 0 + if kind == 'P': + y = sum(((row & x).bit_count() % 2) << j for j, row in enumerate(gate[1])) + elif kind == 'X': + y ^= gate[1] + elif kind == 'phase': + power = gate[1] + else: + require(kind == 'D', 'dense oracle gate') + power = sum(a for j, a in enumerate(gate[2]) if x >> j & 1) + power += 2*sum(1 for a in range(n) for b in range(a+1, n) + if (x >> a & 1) and (x >> b & 1) and (gate[1][a] >> b & 1)) + a, b = real[x], imag[x] + ar[y], ai[y] = ((a, b), (-b, a), (-a, -b), (b, -a))[power % 4] + real, imag = ar, ai + total[0] += real[column] + total[1] += imag[column] + return total[0], total[1] + + +def dense_circuits() -> int: + rng = random.Random(7606546) + count = 0 + for n in range(1, 5): + for _ in range(30): + gates = [] + for __ in range(1+rng.randrange(18)): + kind = rng.randrange(5) + if kind == 0: + gates.append(('C', rng.randrange(1, 1 << n), (-1, 1)[rng.randrange(2)])) + elif kind == 1: + gates.append(('X', rng.randrange(1 << n))) + elif kind == 2: + gates.append(('phase', rng.randrange(4))) + elif kind == 3: + rows = [1 << j for j in range(n)] + for ___ in range(2*n): + a, b = rng.randrange(n), rng.randrange(n) + if a != b: + rows[a] ^= rows[b] + gates.append(('P', tuple(rows))) + else: + linear = tuple(rng.randrange(4) for __ in range(n)) + rows = [((a % 2) << j) for j, a in enumerate(linear)] + for a, b in combinations(range(n), 2): + if rng.randrange(2): + rows[a] ^= 1 << b + rows[b] ^= 1 << a + gates.append(('D', tuple(rows), linear)) + circuit = tuple(gates) + got = circuit_trace(n, circuit) + expected = dense_trace(n, circuit) + require((Fraction(got[0], 1 << got[2]), Fraction(got[1], 1 << got[2])) == expected, + 'Gauss trace equals separate dense-column oracle') + equal(n, circuit+adjoint(circuit), (), 'literal inverse') + count += 1 + require(circuit_trace(300, (('C', 1, 1),)) == (1 << 299, 1 << 299, 0), + '300-axis symbolic Gaussian trace') + return count + + +def rejecting_controls() -> int: + attempts = [ + lambda: equal(1, (('phase', 1),), (), 'wrong global phase'), + lambda: equal(1, (('D', (0,), (2,)),), (), 'input phase invisible on zero'), + lambda: equal(1, (('C', 1, 1),), (('C', 1, -1),), 'wrong child direction'), + lambda: equal(1, (('X', 1), ('D', (1,), (1,))), (('D', (1,), (1,)), ('X', 1)), 'wrong order'), + lambda: circuit_trace(2, (('P', (1, 1)),)), + lambda: circuit_trace(1, (('C', 1, 0),)), + lambda: circuit_trace(2, (('D', (2, 0), (0, 0)),)), + lambda: circuit_trace(1, (('scale', 2),)), + lambda: equal(1, (), (('phase', 4),), 'expected phase before normalization'), + lambda: equal(1, (), (('phase', 0, 'discarded'),), 'expected arity before adjoint'), + ] + for run in attempts: + try: + run() + except ValueError: + continue + raise ValueError('trace negative control accepted') + return len(attempts) + + +def main() -> None: + result = {'all_quadratics_through_four_variables': exhaustive_quadratics(), + **affine_and_substitution(), 'independent_dense_circuits': dense_circuits(), + 'rejecting_controls': rejecting_controls(), 'seed': [7606030, 7606546]} + print('PASS_GAUSS_TRACE', json.dumps(result, sort_keys=True)) + + +if __name__ == '__main__': + main() diff --git a/research/selected-native-tensor-closure/verify.py b/research/selected-native-tensor-closure/verify.py new file mode 100644 index 0000000000..e70c3d3fbe --- /dev/null +++ b/research/selected-native-tensor-closure/verify.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Source-bound selected native tensor closure; see PROOF.md for all-size proof. + +Prepared for @CubeJerry with substantial OpenAI Codex assistance. Apache-2.0. +""" +from __future__ import annotations + +import argparse +import gzip +import hashlib +import json +from pathlib import Path +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path.insert(0, str(HERE)) +# Direct replay also avoids reading stale preexisting package bytecode. The +# repository's registered runner supplies its own private cache as well. +_cache = tempfile.TemporaryDirectory(prefix='native-tensor-closure-pycache-') +sys.pycache_prefix = _cache.name +sys.dont_write_bytecode = True + +from gauss_trace import require +from native_check import check_native +from source_algebra import free_laurent, local_gauge, ownership_and_invoice +from caller_check import check_caller +from controls import run as negative_controls + + +BASE = '7c49fe32c55de02c2c873655c804b16e4c3fef0a' +PINS = { + 'research/p104-helper470-twin-rung-removal/WORD.json.gz': '7834725d9e34ee846a9ccc615221ea81e0201613938afa185d2eda0c9a6c232f', + 'research/p104-helper470-twin-rung-removal/RESULT.json': '84fcbe2a0b64307b5703c363408042bdd91555b0419509aa50daa43b3b1924ad', + 'research/p104-productive-controller/CONTROLLER.json': 'a84f6bbd547379597464e56c420cc665f96bc43a9a1351eed4b7cd0fce3cc4b9', + 'research/p104-caller-independent-audit/capsule/outputs/p104-caller-route-audit-v2-20261025/sources/DATA-PHASES.json': 'c5916ff312678f12aba403847643fbbc29f643acec60bdf836fa56cd3e8251fa', + 'research/p104-native-channel/vendor/clifford_exact.py': '2982ead07721e83358dc67c6f49c2b4c16a236a6bebdfd72f58221be1f5d0962', + 'research/p104-productive-controller/local.py': '878734dfd64c4b9d362d0ae476cc5c2a19fe93e48b7378763b23f3e0dd0a5a71', + 'research/p104-productive-controller/caller.py': '300d40043953e4f6aecfde8f2d1004b8ad6dc5a79ec3c7666c9908c2466c91c8', +} + + +def authenticate(path, data): + require(path in PINS and hashlib.sha256(data).hexdigest() == PINS[path], 'source byte pin: '+path) + return data + + +def run(): + raw = {path: authenticate(path, (ROOT/path).read_bytes()) for path in PINS} + word = json.loads(gzip.decompress(raw['research/p104-helper470-twin-rung-removal/WORD.json.gz'])) + source_result = json.loads(raw['research/p104-helper470-twin-rung-removal/RESULT.json']) + controller = json.loads(raw['research/p104-productive-controller/CONTROLLER.json']) + phase_source = json.loads(raw['research/p104-caller-independent-audit/capsule/outputs/p104-caller-route-audit-v2-20261025/sources/DATA-PHASES.json']) + candidates = json.loads(gzip.decompress((HERE/'NATIVE.json.gz').read_bytes())) + local = local_gauge(word, source_result) + native = check_native(word, source_result, candidates) + laurent = free_laurent(controller) + caller = check_caller(word, controller, phase_source, source_result) + invoice = ownership_and_invoice(word, controller, source_result) + controls = negative_controls(word, source_result, candidates, controller, phase_source) + for path in ('research/p104-helper470-twin-rung-removal/WORD.json.gz', 'research/p104-productive-controller/caller.py'): + try: + authenticate(path, raw[path]+b' ') + except ValueError: + controls['source_drift:'+path] = 'Rejected before parsing or execution' + else: + raise ValueError('source mutation accepted: '+path) + return { + 'schema': 'selected-native-tensor-closure-result/1', + 'status': 'PASS_SELECTED_NATIVE_TENSOR_CLOSURE', + 'base_commit': BASE, + 'source_sha256': PINS, + 'local_gauge': local, + 'native_trace': native, + 'complete_caller': laurent, + 'whole_job_algebra': caller, + 'ownership_and_invoice': invoice, + 'negative_controls': dict(sorted(controls.items())), + 'all_size_status': 'PROOF.md proves the typed algebraic implication for every positive f and arbitrary spectator factors; finite replay is the exact selected-source premise', + 'limitations': ['ideal owned reset semantics remain assumed', 'physical selected-rate dispatcher not implemented', + 'compiler, precision_tape and analytic_recovery not discharged', 'No new kappa'], + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--write', action='store_true', help='write the deterministic new-package result receipt') + args = parser.parse_args() + result = run() + path = HERE/'RESULT.json' + encoded = (json.dumps(result, sort_keys=True, indent=2)+'\n').encode() + if args.write: + path.write_bytes(encoded) + else: + require(path.read_bytes() == encoded, 'complete deterministic result receipt') + print(result['status'], json.dumps({ + 'native_pairs': result['native_trace']['distinct_native_pairs'], + 'raw_contacts': result['whole_job_algebra']['complete_raw_contacts'], + 'productive_fields': result['ownership_and_invoice']['productive_inputs'], + 'paid_calls': result['ownership_and_invoice']['paid_calls'], + 'rejecting_controls': len(result['negative_controls']), 'kappa_changed': False, + }, sort_keys=True)) + + +if __name__ == '__main__': + try: + main() + finally: + _cache.cleanup()