From d48a8453d8f118acdf93d810f59f002a7c7a7b0c Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sun, 15 Nov 2026 11:48:50 +0800 Subject: [PATCH 1/5] Add the Watrous learning route and source-bound hosted mathematics checks --- .github/workflows/hosted-math.yml | 65 +++ README.md | 8 +- learning/README.md | 18 + learning/anchor.md | 78 +++ learning/milestones.md | 431 ++++++++++++++ learning/story.md | 183 ++++++ llms.txt | 1 + references/bibliography.bib | 7 + verification/README.md | 8 +- .../hosted_math/capture_hosted_math.cjs | 549 ++++++++++++++++++ .../hosted_math/check_rendered_math.py | 370 ++++++++++++ .../hosted_math/probe_hosted_math.cjs | 146 +++++ 12 files changed, 1861 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/hosted-math.yml create mode 100644 learning/README.md create mode 100644 learning/anchor.md create mode 100644 learning/milestones.md create mode 100644 learning/story.md create mode 100644 verification/hosted_math/capture_hosted_math.cjs create mode 100644 verification/hosted_math/check_rendered_math.py create mode 100644 verification/hosted_math/probe_hosted_math.cjs diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml new file mode 100644 index 0000000..a8c9ae1 --- /dev/null +++ b/.github/workflows/hosted-math.yml @@ -0,0 +1,65 @@ +name: Hosted mathematics + +on: + pull_request: + paths: + - '**.md' + - 'verification/hosted_math/**' + - '.github/workflows/hosted-math.yml' + +permissions: + contents: read + +concurrency: + group: hosted-math-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + capture: + if: github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-24.04 + timeout-minutes: 20 + env: + CAPTURE_REVISION: ${{ github.event.pull_request.head.sha }} + steps: + - name: Check out the exact proposed source + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ env.CAPTURE_REVISION }} + persist-credentials: false + - name: Set up Node + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '22' + - name: Install the capture runtime + run: | + npm install --prefix "$RUNNER_TEMP/math-runtime" playwright@1.56.1 mathjax-full@3.2.1 + node "$RUNNER_TEMP/math-runtime/node_modules/playwright/cli.js" install --with-deps chromium + - name: Probe a representative page + continue-on-error: true + run: | + export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" + node verification/hosted_math/probe_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --page science/moment_frontier.md \ + --output "$RUNNER_TEMP/hosted-probe" + - name: Compare every hosted mathematical expression + run: | + export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" + node verification/hosted_math/capture_hosted_math.cjs \ + --root "$GITHUB_WORKSPACE" \ + --repository "$GITHUB_REPOSITORY" \ + --revision "$CAPTURE_REVISION" \ + --output "$RUNNER_TEMP/hosted-math" + - name: Retain the actual captures and comparison report + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: hosted-math-${{ env.CAPTURE_REVISION }} + path: | + ${{ runner.temp }}/hosted-math + ${{ runner.temp }}/hosted-probe + if-no-files-found: error + retention-days: 14 diff --git a/README.md b/README.md index 170b5b7..7523cc1 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ For loss $\ell_h(x)=1-\operatorname{Tr}[\Pi_h(x)\rho_x]$ and fixed tilt $a>0$, m R_a(h)=\frac{1}{a}\log\left(\frac{1}{M}\sum_{x=1}^{M}e^{a\ell_h(x)}\right). ``` -Let $\Gamma_r(a)$ be the largest logarithmic separation between exponential moments of two distributions on $[0,1]$ whose first $r$ moments agree. Equivalently, it is the best multiplicative distortion of a degree-$r$ polynomial envelope of $e^{au}$; the scalar approximation duality is inherited and credited in the [moment account](science/moment_frontier.md). +Let $\kappa_r(a)$ be the largest ratio between exponential moments of two distributions on $[0,1]$ whose first $r$ moments agree, and set $\Gamma_r(a)=a^{-1}\log\kappa_r(a)$. Equivalently, $\kappa_r(a)$ is the best multiplicative distortion of a degree-$r$ polynomial envelope of $e^{au}$; the scalar approximation duality is inherited and credited in the [moment account](science/moment_frontier.md). For every fixed integer $k\ge1$, at accuracies strictly between adjacent thresholds, @@ -21,7 +21,7 @@ N_{\mathrm{worst}}(M) =\Theta_{a,\varepsilon,H,\delta}\!\left(M^{1-1/k}\right). ``` -Here $H$ is the fixed finite number of hypotheses, the failure target satisfies $0<\delta<1/2$, and $M$ tends to infinity while the other parameters remain fixed. The upper bound holds for every such class; a particular two-hypothesis class on two-qubit outputs witnesses the worst-case lower bound. Arbitrary collective quantum measurements are allowed. +Here $H\ge2$ is a fixed finite cap on the number of hypotheses, the failure target satisfies $0<\delta<1/2$, and $M$ tends to infinity while the other parameters remain fixed. The upper bound holds for every such class; a particular two-hypothesis class on two-qubit outputs witnesses the worst-case lower bound. Arbitrary collective quantum measurements are allowed. | Same-context observations that become necessary | Passive source exponent | |---|---:| @@ -44,6 +44,10 @@ At $a=1$, the first three thresholds are approximately $0.12330156$, $0.01029531 Start with the [scientific route](science/README.md), or go directly to the [model](science/model.md), [moment thresholds](science/moment_frontier.md), [passive sampling theorem and proof](science/passive_frontier.md), and [replay and resource account](science/replay_and_resources.md). The [interpretation](science/interpretation.md) explains what the frontier changes in quantum learning. The [related-work comparison](references/related_work.md) separates the result from established ensemble, classical moment and multi-observation methods. +## Learn the project + +The [learning route](learning/README.md) starts with a concrete two-context example, connects Watrous's *The Theory of Quantum Information* (2018) to the project notation, and follows a shared map of exactly 30 milestones from the data model to the theorem and its resource limits. + ## Meaning and scope A nonlinear objective depends on within-context outcome probabilities, rather than only their mean across contexts. Better accuracy can require higher same-context occupancies. Passive sampling must wait for these coincidences; selected-input replay supplies them directly and removes the support-size factor. diff --git a/learning/README.md b/learning/README.md new file mode 100644 index 0000000..3b8e515 --- /dev/null +++ b/learning/README.md @@ -0,0 +1,18 @@ +# Learning route + +Start with [the story](story.md): two hypotheses can have the same mean loss while a tilted objective prefers one, and the accuracy required of that preference determines which repeated contexts the source must supply. + +The project uses one educational anchor: John Watrous, *The Theory of Quantum Information* (2018). [The anchor and notation bridge](anchor.md) identifies the relevant sections and connects states, measurements and distinguishability to this learning model. It also identifies the classical approximation and collision arguments supplied locally rather than covered by the book. + +[The common 30-milestone map](milestones.md) records the understanding targets and their dependencies. Its 12 background milestones assemble the model; its 18 narrative milestones connect the example, proof mechanisms, theorem and resource interpretation. The map is a guide to the project, not a requirement to read the entire anchor first. + +| Reading purpose | Route | +| --- | --- | +| See the task and main mechanism | [Story](story.md), then milestones M13–M27 | +| Translate quantum-information notation | [Anchor bridge](anchor.md), with M01–M12 | +| Follow the complete common map | [Milestones M01–M30](milestones.md) | +| Check exact statements and proofs | [Scientific account](../science/README.md) | +| Check imported ingredients and scientific comparisons | [Related work](../references/related_work.md) | +| Inspect numerical checks | [Verification](../verification/README.md) | + +The canonical theorem, assumptions and limits are in the scientific account. The learning route preserves its distinction between proper PAC selection and expected regret, between passive data and replay, and between a quantum-data access frontier and a quantum processing advantage. diff --git a/learning/anchor.md b/learning/anchor.md new file mode 100644 index 0000000..92c9d9a --- /dev/null +++ b/learning/anchor.md @@ -0,0 +1,78 @@ +# Watrous and the bridge to this project + +The sole educational anchor is **John Watrous, *The Theory of Quantum Information*, Cambridge University Press (2018)**, [publisher DOI](https://doi.org/10.1017/9781316848142). The [author's book page](https://cs.uwaterloo.ca/~watrous/TQI/) provides the manuscript and errata. The manuscript is linked rather than reproduced here. Section numbers below were checked against its author-hosted contents and chapters. + +The useful route is selective. Chapter 1 supplies mathematical language, Chapter 2 supplies the physical data and measurement model, and Chapter 3 supplies the operational meaning of indistinguishable training states. The local moment and collision arguments then connect these foundations to nonlinear-risk learning. + +## A short source route + +| Anchor location | Foundation to take from it | Project connection | +| --- | --- | --- | +| [Chapter 1](https://cs.uwaterloo.ca/~watrous/TQI/TQI.1.pdf), §§1.1.1–1.1.3 | Finite-dimensional spaces, tensor products, positive operators and norms | Registers, diagonal witness states and tensor-copy expansions; M01, M04 | +| Chapter 1, §1.2.1, especially Carathéodory's theorem (Theorem 1.9) | Compactness, convex combinations and finite-dimensional convex hulls | Moment vectors and finitely supported extremizers; M11, M14–M15 | +| Chapter 1, §1.2.2 | Expectations and elementary probability notation | Conditional loss, sampled contexts and bounded statistics; M03, M07, M09 | +| [Chapter 2](https://cs.uwaterloo.ca/~watrous/TQI/TQI.2.pdf), §§2.1.1–2.1.2 | Classical registers and density operators | The classical–quantum source and its fixed conditional table; M01, M05 | +| Chapter 2, §2.2.1 and §§2.3.1–2.3.2 | Channels, measurement probabilities and projective measurements | Known hypothesis measurements and arbitrary processing of supplied data; M02, M10 | +| [Chapter 3](https://cs.uwaterloo.ca/~watrous/TQI/TQI.3.pdf), §3.1.1, especially Theorem 3.4 | Binary state discrimination and the trace norm | Turning equality of the entire averaged dataset into a lower bound for every learner; M10, M21–M23 | + +The optional binary-effect implementation in [the passive proof](../science/passive_frontier.md) also uses the dilation viewpoint of Chapter 2, §2.3.2, Theorem 2.42. It is not needed for the immediate-measurement construction. + +## Notation translation + +Watrous uses matrix notation rather than Dirac notation. The project uses both. + +| Book notation | Project notation or role | +| --- | --- | +| A complex Euclidean space such as $\mathcal X$ | A finite-dimensional register space, here $\mathsf Q\cong\mathbb C^d$ | +| $\mathrm D(\mathcal X)$ | The density operators, written $\mathcal D(\mathsf Q)$ here | +| $u u^*$ and $E_{x,x}=e_xe_x^*$ | $\lvert u\rangle\langle u\rvert$ and $\lvert x\rangle\langle x\rvert$ | +| A measurement $\mu$ with outcome operator $\mu(1)$ | The loss outcome operator $I-\Pi_h(x)$ | +| $\langle A,\rho\rangle=\operatorname{Tr}(A^*\rho)$ | $\operatorname{Tr}[(I-\Pi_h(x))\rho_x]=\ell_h(x)$ for the Hermitian loss projector | +| $\lVert A\rVert_1$ | The same trace norm; our trace distance is $D(\rho,\sigma)=\tfrac12\lVert\rho-\sigma\rVert_1$ | + +## From registers to the source + +The context is a readable classical register. A table $x\mapsto\rho_x$ defines + +$$ +\Omega_\rho=\frac1M\sum_{x=1}^M +\lvert x\rangle\langle x\rvert\otimes\rho_x. +$$ + +Its block-diagonal form means a context label is sampled with probability $1/M$ and its associated state is supplied. The table is unknown but fixed. Receiving another example means another independent source preparation, not a coherent query to that table. Reading the context does not supply a preparation circuit or the ability to choose the next context. These are local modeling assumptions, made explicit in [the model](../science/model.md); they are not consequences of the density-operator formalism. + +Measuring $I-\Pi_h(x)$ produces a bit $Y$ with conditional mean $\ell_h(x)$. If the same context supplies $j$ independent specimens, the product of the $j$ loss bits has conditional mean $\ell_h(x)^j$. This is the first bridge from tensor-product copies to the classical moments required by the nonlinear objective. + +## From indistinguishable states to a learning converse + +The lower bound constructs two priors over fixed tables. Under either prior, consider the density operator of **all** labeled training registers. When no context occurs $k$ times, matching moments make these operators exactly equal. This statement concerns the complete quantum input, not just the outcomes of a preferred hypothesis measurement. + +If the exceptional collision event has probability $q$, the two averaged training states $\omega_0,\omega_1$ satisfy + +$$ +D(\omega_0,\omega_1)\le q. +$$ + +For equal prior probabilities, Watrous's Theorem 3.4 bounds every binary decision by + +$$ +p_{\mathrm{correct}}\le\frac12+\frac14 +\lVert\omega_0-\omega_1\rVert_1 +\le\frac{1+q}{2}. +$$ + +An entire adaptive learning computation ending in a binary hypothesis choice defines such a measurement on its supplied data. It therefore cannot evade this bound. The local proof must still show that typical frozen tables have opposite risk-minimizing hypotheses with a gap exceeding the requested tolerance. [The passive proof](../science/passive_frontier.md) supplies that concentration step. State indistinguishability alone does not establish the risk gap. + +## What the local account adds to the book + +The exponential-loss approximation problem and the generalized birthday calculation are additional **classical** machinery. The bridge is: + +1. Repeated loss measurements estimate moments of the conditional probability. +2. A degree-$k$ envelope $e^{au}\le P(u)\le\kappa_k(a)e^{au}$ turns those moments into a surrogate risk with distortion $\Gamma_k(a)$. +3. The dual moment pair makes a larger gap invisible below the necessary repetition level. +4. Uniform-context occupancy supplies, and limits, that repetition level at $M^{1-1/k}$ samples. +5. Concentration and proper hypothesis selection connect these facts to a PAC guarantee for each fixed table. + +The complete derivations are [the moment frontier](../science/moment_frontier.md) and [the passive frontier](../science/passive_frontier.md), corresponding to M14–M27 in [the map](milestones.md). This machinery is not attributed to Watrous. + +The primary proof dependencies are separate research citations: [Adibi–Krysta, Appendix I](https://arxiv.org/abs/2610.28999) for exact relative-approximation duality; [Brun](https://arxiv.org/abs/quant-ph/0401067) for multi-copy polynomial observables; and classical [population-parameter inference](https://arxiv.org/abs/1709.02707), [multi-observation learning](https://proceedings.mlr.press/v89/frongillo19a.html) and [collision estimation](https://arxiv.org/abs/1408.1000) for the surrounding methods. These are attribution and proof pointers, not additional educational anchors. [Related work](../references/related_work.md) delimits the comparison. diff --git a/learning/milestones.md b/learning/milestones.md new file mode 100644 index 0000000..7484c84 --- /dev/null +++ b/learning/milestones.md @@ -0,0 +1,431 @@ +# Thirty milestones for quantum learning repeatability + +This map connects the source model, the exact moment thresholds, and the matching passive-sampling theorem. Its sole educational anchor is **John Watrous, *The Theory of Quantum Information* (2018)**, especially Chapters 1–3. The [anchor bridge](anchor.md) identifies the relevant textbook foundations. The project supplies its own approximation, probability, and learning arguments; those arguments are not attributed to the textbook. + +The allocation is **12 background/preliminaries milestones and 18 narrative/innovation milestones**. The background moves from an individual state and measurement to the full statistical learning experiment. The narrative moves from a small equal-mean example through the scalar and quantum proof mechanisms to the complete sample law, its resource requirements, and its limits. This allocation leaves most of the map for the connection that the project establishes while making its data-access assumptions understandable before the theorem appears. + +Each milestone records a conceptual target and its source dependencies. The map covers the load-bearing ideas, rather than every specialist lemma. Scientific claims and complete proofs remain in the [canonical scientific account](../science/README.md). + +## Background and preliminaries — local objects to the complete experiment + +### M01 — A conditional quantum state + +**Phase:** Background/preliminaries. + +**Central question:** What does the source assign to one classical context? + +**Understanding target:** Interpret a density operator as the complete state supplied at a fixed context, including the possibility of a mixed state. Distinguish the state from a preparation description and from a measurement outcome. + +**Dependencies and story role:** This is the local starting point; no earlier milestone is required. It introduces the object that remains fixed whenever its context is revisited. + +**Conceptual connection:** The table entry $\rho_x$ is a physical statistical object, not a classical list of its matrix entries given to the learner. + +**Sources:** Watrous, Chapter 2, “Basic notions of quantum information,” for states; [model](../science/model.md), “Source and hypotheses.” + +### M02 — A known projector and its Born loss + +**Phase:** Background/preliminaries. + +**Central question:** How does a known measurement hypothesis assign a loss to an unknown state? + +**Understanding target:** Read $\ell_h(x)=1-\operatorname{Tr}[\Pi_h(x)\rho_x]$ as a probability in $[0,1]$. Distinguish knowledge of a hypothesis measurement from knowledge of its probability on the unknown source. + +**Dependencies and story role:** Uses M01 and adds the local measurement through which a hypothesis is evaluated. + +**Conceptual connection:** Projector-valued hypotheses make the learning task concrete without giving the learner a preparation oracle or a description of $\rho_x$. + +**Sources:** Watrous, Chapters 1–2, for operators, trace, and measurements; [model](../science/model.md), “Source and hypotheses” and “Tilted population risk.” + +### M03 — One specimen and a conditional mean + +**Phase:** Background/preliminaries. + +**Central question:** Which information does one binary measurement outcome supply about its context? + +**Understanding target:** Separate the observed bit $Y$ from the conditional probability $\ell_h(x)=\mathbb E[Y\mid X=x]$. Explain why applying a nonlinear function to the bit need not estimate that function of the probability. + +**Dependencies and story role:** Uses M02. It isolates the local statistical distinction that eventually creates the repetition cost. + +**Conceptual connection:** The objective concerns variation of conditional Born means across contexts, while measurements provide random outcomes within contexts. + +**Sources:** Watrous, Chapter 1, for probability and expectation, and Chapter 2, for outcome probabilities; [model](../science/model.md), “Tilted population risk.” + +### M04 — Independent copies and tensor products + +**Phase:** Background/preliminaries. + +**Central question:** What changes when the source supplies several independent specimens at the same context? + +**Understanding target:** Interpret $\rho_x^{\otimes r}$ as repeated independent preparation. Distinguish this access from one specimen, a correlated multi-system state, or a procedure that clones an unknown received state. + +**Dependencies and story role:** Uses M01–M03. It joins the state and outcome descriptions into the local repeated-observation experiment. + +**Conceptual connection:** Independent conditional preparations are what make products of measurement outcomes encode powers of a Born probability. + +**Sources:** Watrous, Chapters 1–2, for tensor products and composite registers; [model](../science/model.md), “Three access models” and “Moments and full quantum information.” + +### M05 — Classical labels and a frozen quantum source + +**Phase:** Background/preliminaries. + +**Central question:** How are random context labels and their fixed conditional states combined into training data? + +**Understanding target:** Read the classical-quantum source $M^{-1}\sum_x|x\rangle\langle x|\otimes\rho_x$ and its independent repetitions. Explain that the table is fixed even though the sampled label changes, and that revisiting a label does not redraw its hidden table entry. + +**Dependencies and story role:** Uses M01 and M04. It moves from one context to the full source without yet specifying a learning objective. + +**Conceptual connection:** Fixed conditional states permit useful repeated labels; uniform random labels determine how long such repetitions take to obtain. + +**Sources:** Watrous, Chapter 2, for classical and quantum registers; [model](../science/model.md), “Source and hypotheses.” + +### M06 — Passive, grouped, and replay access + +**Phase:** Background/preliminaries. + +**Central question:** Which kinds of repetition can a source actually supply? + +**Understanding target:** Distinguish a naturally repeated passive label, an arrival containing a fixed number of same-context copies, and an interface that can re-prepare a sampled context on request. Keep a cap per arrival separate from the total copies accumulated after later visits. + +**Dependencies and story role:** Uses M04–M05. It fixes the source capability before comparing algorithms or sample counts. + +**Conceptual connection:** A stronger source can remove a waiting cost; it does not follow merely from the learner having a quantum processor. + +**Sources:** Watrous, Chapter 2, for preparation and register operations; [model](../science/model.md), “Three access models”; [replay and resources](../science/replay_and_resources.md), “Conditional replay is an additional source capability.” + +### M07 — Mean risk and tilted population risk + +**Phase:** Background/preliminaries. + +**Central question:** What does a positive tilt ask the learner to resolve beyond the mean loss? + +**Understanding target:** Interpret $R_a(h)=a^{-1}\log\mathbb E_x e^{a\ell_h(x)}$ for $a>0$, its mean-loss limit, and its emphasis on larger conditional losses. Preserve the order of the conditional mean, exponential, context average, and logarithm. + +**Dependencies and story role:** Uses M03 and M05. It connects the local measurement probability to the global objective. + +**Conceptual connection:** The additional nonlinear dependence is the feature whose resolution will be indexed by the moment thresholds. + +**Sources:** Watrous, Chapter 1, for expectation and convexity foundations; [model](../science/model.md), “Tilted population risk”; [interpretation](../science/interpretation.md), “The target is a nonlinear function of a probability.” + +### M08 — Proper selection and the accuracy convention + +**Phase:** Background/preliminaries. + +**Central question:** What counts as a successful learning output in this project? + +**Understanding target:** Explain proper selection from the supplied finite class, population excess risk, and the PAC failure probability. Distinguish the excess of the returned hypothesis from expected regret and from the nonlinear risk of a measurement outside the class. + +**Dependencies and story role:** Uses M02 and M07. It specifies the decision and guarantee against which the converse and construction will be compared. + +**Conceptual connection:** A lower bound for proper selection does not automatically apply to unrestricted improper prediction, and a bound on expected regret is not a PAC guarantee. + +**Sources:** Watrous, Chapter 1, for probability and randomized decisions; [model](../science/model.md), “Learning guarantee and quantifiers” and “PAC excess and expected regret are different.” + +### M09 — Same-context products reveal moments + +**Phase:** Background/preliminaries. + +**Central question:** Why do repeated conditional observations supply powers of a probability? + +**Understanding target:** Explain $\mathbb E[\prod_{i=1}^{j}Y_i\mid x]=\ell_h(x)^j$ under conditional independence, then average over contexts. Recognize the first $r$ loss moments as accessible from grouped $r$-copy examples. + +**Dependencies and story role:** Uses M03–M04 and M07. It converts physical repetition into the scalar information used by approximation theory. + +**Conceptual connection:** Products of observations connect tensor-copy access to moments of the distribution of conditional losses. + +**Sources:** Watrous, Chapters 1–2, for independent random variables and composite systems; [model](../science/model.md), “Moments and full quantum information”; [moment frontier](../science/moment_frontier.md), “From an envelope to a learning guarantee.” + +### M10 — Indistinguishability before any measurement + +**Phase:** Background/preliminaries. + +**Central question:** What kind of equality defeats every collective learning strategy? + +**Understanding target:** Distinguish equality of selected scalar statistics from equality of the full supplied density operators. Explain why identical training states have identical outcome laws under every allowed measurement, and how trace distance controls distinguishing success when equality holds only on a high-probability event. + +**Dependencies and story role:** Uses M02, M04–M05. It supplies the measurement-independent language required for the converse. + +**Conceptual connection:** The proof permits arbitrary quantum processing; it obtains its bound by comparing inputs rather than restricting the learner's measurement choices. + +**Sources:** Watrous, Chapter 3, “Similarity and distance among states and channels,” for state discrimination and trace distance; [passive frontier](../science/passive_frontier.md), “Equality before a k-fold repeat.” + +### M11 — Moments and a positive polynomial envelope + +**Phase:** Background/preliminaries. + +**Central question:** How can finitely many moments control a nonlinear exponential mean? + +**Understanding target:** Interpret a degree-$r$ polynomial as a linear combination of the moments in M09. Understand the pointwise envelope $e^{au}\le p(u)\le K e^{au}$ as a multiplicative comparison that survives averaging. + +**Dependencies and story role:** Uses M07 and M09. It introduces the classical approximation interface that links repetition to risk accuracy. + +**Conceptual connection:** The envelope's positivity is a statement about its values on $[0,1]$; it does not assert that every coefficient or every associated measurement operator is positive. + +**Sources:** Watrous, Chapter 1, for linear functionals, norms, and convexity foundations; [moment frontier](../science/moment_frontier.md), “Equivalent positive polynomial envelope” and “Relative approximation, strictness, and convergence.” The project supplies the approximation argument. + +### M12 — The complete learning experiment + +**Phase:** Background/preliminaries. + +**Central question:** Which assumptions must be held together before the repeatability frontier has a definite meaning? + +**Understanding target:** Assemble the fixed unknown state table, known uniform support, finite class-size cap, positive loss tilt, proper PAC decision, passive source access, and unrestricted quantum processing. Distinguish sample complexity from the cost of implementing a known measurement. + +**Dependencies and story role:** Integrates M01–M11 and completes the background phase. It identifies the whole experiment to which the narrative applies. + +**Conceptual connection:** The contribution concerns the information supplied by this source at a requested accuracy; changing its access, output model, or limiting regime changes the problem. + +**Sources:** Watrous, Chapters 1–3, for the combined register, measurement, and discrimination framework; [model](../science/model.md); [scientific route](../science/README.md). + +## Narrative and innovation — local mechanisms to the full frontier + +### M13 — Equal mean losses can favor different hypotheses + +**Phase:** Narrative/innovation. + +**Central question:** What does the smallest useful example reveal about nonlinear risk? + +**Understanding target:** Compare a hypothesis with losses $0$ and $1$ at equally likely contexts to one with constant loss $1/2$. Explain why their means agree while positive-tilt risks differ, and why the single-outcome substitution from M03 misses this distinction. + +**Dependencies and story role:** Uses M07, M11–M12. It begins the narrative with a concrete need for information beyond the first moment. + +**Conceptual connection:** A variance-sensitive decision creates the foothold for a quantitative moment hierarchy; the example alone is not the full converse. + +**Sources:** Watrous, Chapters 1–2, for expectation and Born probabilities; [story](story.md); [moment frontier](../science/moment_frontier.md), “The one-copy value and small-tilt hierarchy.” + +### M14 — Moment twins define the unresolved risk gap + +**Phase:** Narrative/innovation. + +**Central question:** How large can a tilted-risk difference remain when the first $r$ moments agree? + +**Understanding target:** Interpret $\kappa_r(a)$ as the largest ratio of exponential means over matching-moment laws and $\Gamma_r(a)=a^{-1}\log\kappa_r(a)$ as the corresponding risk gap. Explain why exchanging the two laws removes a sign ambiguity. + +**Dependencies and story role:** Uses M09, M11 and M13. It replaces an isolated example by the exact scalar quantity that will control the theorem. + +**Conceptual connection:** The hidden distinction is quantified in the same loss units as the requested PAC tolerance. + +**Sources:** Watrous, Chapter 1, for probability measures and linear expectation foundations; [moment frontier](../science/moment_frontier.md), “A sharp moment-ratio constant.” + +### M15 — The converse and the envelope are dual descriptions + +**Phase:** Narrative/innovation. + +**Central question:** Why does the largest moment-twin gap equal the best positive polynomial-envelope distortion? + +**Understanding target:** Follow the easy integration inequality and the converse finite-grid linear-program argument, including the compactness step that produces a continuum envelope. Identify this scalar duality as inherited mathematics, not a new quantum effect. + +**Dependencies and story role:** Uses M11 and M14. It makes one exact threshold serve both the lower and upper proofs. + +**Conceptual connection:** Matching moments erase every degree-$r$ polynomial difference, while a positive envelope bounds what remains of the exponential objective. + +**Sources:** Watrous, Chapter 1, for finite-dimensional linear and convex foundations; [moment frontier](../science/moment_frontier.md), Theorem 1 and its explicit attribution; [related work](../references/related_work.md), “Classical conditional learning and approximation theory.” + +### M16 — The explicit first threshold + +**Phase:** Narrative/innovation. + +**Central question:** What accuracy can first-moment information support at a fixed tilt? + +**Understanding target:** Explain the extremal constant-loss and endpoint-Bernoulli laws at a common mean, the maximizing mean, and the explicit value of $\Gamma_1(a)$. Recognize its logarithmic Specht-ratio origin and its leading behavior $a/8$. + +**Dependencies and story role:** Uses M13–M15. It turns the abstract frontier into a concrete scale for the first change in passive sample behavior. + +**Conceptual connection:** The small-tilt regime is an accuracy comparison, rather than a statement that every nonzero tilt already forces support-dependent samples. + +**Sources:** Watrous, Chapter 1, for convexity and expectation foundations; [moment frontier](../science/moment_frontier.md), Proposition 3; [interpretation](../science/interpretation.md), “The target is a nonlinear function of a probability.” + +### M17 — More moments reduce the ambiguity + +**Phase:** Narrative/innovation. + +**Central question:** How do successive repetition levels change the threshold sequence? + +**Understanding target:** Explain positivity, strict decrease, and convergence of $\Gamma_r(a)$, and the role of relative approximation in those properties. Interpret the fixed-degree small-tilt asymptotic while keeping that limit separate from the fixed-parameter support-size limit. + +**Dependencies and story role:** Uses M14–M16. It establishes that adjacent accuracy intervals form a genuine ordered hierarchy. + +**Conceptual connection:** Higher moments provide progressively finer control of the nonlinear objective; they do not create a uniform joint-limit theorem in all parameters. + +**Sources:** Watrous, Chapter 1, for norms and finite-dimensional linear algebra; [moment frontier](../science/moment_frontier.md), Propositions 2 and 4. The project supplies the approximation, weighted-alternation and shifted-Chebyshev arguments. + +### M18 — A signed polynomial is a bounded estimator + +**Phase:** Narrative/innovation. + +**Central question:** How is an envelope implemented without treating its coefficients as probabilities? + +**Understanding target:** Construct the polynomial statistic from products of same-context loss bits. Explain its unbiased expectation and coefficient-norm bound, and distinguish a bounded Hermitian observable from a positive effect or projector. + +**Dependencies and story role:** Uses M02, M09 and M15. It supplies a physically valid upper-bound primitive. + +**Conceptual connection:** Pointwise positivity of the scalar polynomial does not justify an uncharged binary measurement; a shift, rescaling, or dilation has its own implementation and accuracy obligations. + +**Sources:** Watrous, Chapters 1–2, for operator norms, effects, and measurements; [passive frontier](../science/passive_frontier.md), “A signed polynomial is an observable, not automatically an effect”; [moment frontier](../science/moment_frontier.md), “From an envelope to a learning guarantee.” + +### M19 — One envelope distortion is enough for selection + +**Phase:** Narrative/innovation. + +**Central question:** How does minimizing a surrogate yield the required proper-risk decision? + +**Understanding target:** Follow the chain comparing the selected exponential mean, its polynomial mean, and the optimal hypothesis's polynomial mean. Explain why the distortion enters once as $\Gamma_r(a)$, with a separate estimation slack, rather than twice. + +**Dependencies and story role:** Uses M08, M15 and M18. It connects local estimation to the actual learning output. + +**Conceptual connection:** An estimator is useful here because it preserves a near-optimal decision at the stated tolerance, not merely because it approximates a scalar function. + +**Sources:** Watrous, Chapter 1, for inequalities and probabilistic estimation; [moment frontier](../science/moment_frontier.md), “From an envelope to a learning guarantee”; [passive frontier](../science/passive_frontier.md), “Finite estimates and a fixed sample budget.” + +### M20 — Two frozen worlds encode opposite decisions + +**Phase:** Narrative/innovation. + +**Central question:** How can scalar moment twins become legitimate quantum learning sources? + +**Understanding target:** Build the two-qubit diagonal product-state table from latent probabilities drawn once per context. Identify the two constant commuting projector hypotheses and the swapped worlds in which their optimal choices differ. + +**Dependencies and story role:** Uses M01–M02, M05 and M14. It starts the converse by constructing an allowed source rather than assuming a restriction on measurements. + +**Conceptual connection:** A random table prior is a proof device; each table sampled from it is fixed during the learner's experiment. + +**Sources:** Watrous, Chapter 2, for diagonal states and tensor-product registers; [passive frontier](../science/passive_frontier.md), “Two moment-matched worlds”; [moment frontier](../science/moment_frontier.md), “Why the same constant is unavoidable.” + +### M21 — Low occupancy hides the entire training state + +**Phase:** Narrative/innovation. + +**Central question:** Why can no collective quantum measurement distinguish the two worlds before sufficient repetitions occur? + +**Understanding target:** Explain why entries of an $s$-copy conditional state are degree-$s$ polynomials in its latent probability. Use the matching moments and independence between frozen context entries to obtain equality of the complete prior-averaged training states when every occupancy is small enough. + +**Dependencies and story role:** Uses M04, M10 and M20. It provides the measurement-independent core of the lower bound. + +**Conceptual connection:** Equality of all supplied quantum information is stronger than equality of the particular loss moments used by the upper algorithm. + +**Sources:** Watrous, Chapters 2–3, for composite states and operational indistinguishability; [passive frontier](../science/passive_frontier.md), “Equality before a k-fold repeat.” + +### M22 — The first informative collision sets a lower scale + +**Phase:** Narrative/innovation. + +**Central question:** At what sample scale can a context first occur often enough to expose the hidden distinction? + +**Understanding target:** Interpret the bound $\Pr(\text{a k-fold repeat})\leq\binom nk M^{1-k}$ for $k\geq2$. Derive the scale $M^{1-1/k}$ and explain how a rare bad-label event bounds distinguishing advantage. + +**Dependencies and story role:** Uses M05, M10 and M21. It turns full-state equality into a support-dependent information bound. + +**Conceptual connection:** The familiar collision exponent enters through random source labels, not through a limit on quantum circuit power. + +**Sources:** Watrous, Chapter 1, for probability bounds, and Chapter 3, for state discrimination; [passive frontier](../science/passive_frontier.md), “Equality before a k-fold repeat.” + +### M23 — From a prior comparison to a fixed-source PAC lower bound + +**Phase:** Narrative/innovation. + +**Central question:** Why does the argument establish a failure for a fixed unknown source, rather than a different resampling model? + +**Understanding target:** Combine concentration of the table's exponential means, a strict risk gap above $\epsilon$, and the world-identification bound. Explain how averaging a purported guarantee over table priors leads to a contradiction and therefore to a violating deterministic table. + +**Dependencies and story role:** Uses M08 and M20–M22. It closes the lower proof under the original task's quantifiers. + +**Conceptual connection:** Concentration controls the target decision, while indistinguishability controls the observations; both are needed to transfer a moment-twin prior into a proper-learning converse. + +**Sources:** Watrous, Chapter 1, for probability foundations, and Chapter 3, for distinguishing success; [passive frontier](../science/passive_frontier.md), “Fixed-table risks and the PAC contradiction,” for the concentration argument. + +### M24 — A collision batch succeeds at the matching scale + +**Phase:** Narrative/innovation. + +**Central question:** Is the lower collision scale also enough to obtain a useful repeated context? + +**Understanding target:** Follow the first- and second-moment calculation for the number of equal-label $k$-subsets in a batch of order $M^{1-1/k}$. Explain why overlap terms vanish at fixed $k$ and why the chance of success stays bounded away from zero. + +**Dependencies and story role:** Uses M22. It begins the constructive half at the same support exponent as the converse. + +**Conceptual connection:** A constant batch-success probability supplies repeated conditional observations without requesting a context or discarding their acquisition cost. + +**Sources:** Watrous, Chapter 1, for expectations and probability inequalities; [passive frontier](../science/passive_frontier.md), “A constant-probability k-collision.” The specific occupancy proof is supplied there. + +### M25 — Extraction preserves the right context law + +**Phase:** Narrative/innovation. + +**Central question:** Why does a selected repeated context represent the original uniform population? + +**Understanding target:** Explain label-permutation symmetry, outcome-independent selection, and independent data batches. Distinguish uniformity of labels from symmetry of unknown states, and explain why selected groups remain IID for each fixed source table. + +**Dependencies and story role:** Uses M05, M09 and M24. It verifies the statistical interface between collision finding and risk estimation. + +**Conceptual connection:** A repeated context is useful only if its selection law matches the risk's averaging law; nonuniform context distributions do not inherit this property automatically. + +**Sources:** Watrous, Chapters 1–2, for conditional probability and independent preparations; [passive frontier](../science/passive_frontier.md), “Uniformity and independence are preserved”; [interpretation](../science/interpretation.md), “Replay changes source access.” + +### M26 — Confidence and the full fixed sample budget + +**Phase:** Narrative/innovation. + +**Central question:** How are enough useful groups obtained within a prescribed total budget? + +**Understanding target:** Separate collision-batch failures from errors in the bounded polynomial estimates. Explain the fixed number of batches, the confidence allocation across hypotheses, and why every source output is counted even when it yields no selected group. + +**Dependencies and story role:** Uses M18–M19 and M24–M25. It completes the upper construction as a fixed-budget learning algorithm rather than an expected waiting-time argument. + +**Conceptual connection:** The theorem's constant may depend on the tilt, class cap, confidence, degree, and threshold margin even though its power of $M$ is sharp. + +**Sources:** Watrous, Chapter 1, for probability notation; [passive frontier](../science/passive_frontier.md), “Finite estimates and a fixed sample budget,” for bounded-variable concentration and confidence bookkeeping; [replay and resources](../science/replay_and_resources.md), “Physical and computational resources.” + +### M27 — The accuracy-dependent passive staircase + +**Phase:** Narrative/innovation. + +**Central question:** How do the exact thresholds and the collision scale combine into one theorem? + +**Understanding target:** Explain why $\Gamma_k(a)<\epsilon<\Gamma_{k-1}(a)$ gives worst-case sample complexity $\Theta(M^{1-1/k})$. State the fixed-parameter limiting order, the confidence and proper-selection conditions, and the distinction between an upper bound for every finite class and a lower bound witnessed by one two-hypothesis class. + +**Dependencies and story role:** Integrates M14–M26. It is the global synthesis of the main scientific proof. + +**Conceptual connection:** Required risk precision selects the needed moment level; passive repetition then assigns its source-cost exponent. Neither half alone establishes the complete law. + +**Sources:** Watrous, Chapters 1–3, for the combined probability, quantum-input, and discrimination framework; [passive frontier](../science/passive_frontier.md), theorem and “What the theorem establishes”; [interpretation](../science/interpretation.md), “Accuracy determines the required repetition level.” + +### M28 — Grouped access has an accuracy floor, with distinct decision metrics + +**Phase:** Narrative/innovation. + +**Central question:** What remains ambiguous when each random arrival already supplies $r$ copies? + +**Understanding target:** Explain the support-independent PAC boundary at $\Gamma_r(a)$, why later natural visits prevent it from being an eternal impossibility for a fixed finite support, and why the worst-case expected-regret factor $1-1/H$ describes a different guarantee. + +**Dependencies and story role:** Uses M06, M08, M15, M19 and M23. It places the passive staircase inside the broader access comparison without changing the output metric silently. + +**Conceptual connection:** The number supplied per event, the support over which uniformity is required, and the decision criterion jointly determine the meaning of a copy threshold. + +**Sources:** Watrous, Chapters 1–3, for randomized decisions, composite states, and discrimination; [moment frontier](../science/moment_frontier.md), “Why the same constant is unavoidable” and “Expected regret has a different exact floor”; [replay and resources](../science/replay_and_resources.md), “A finite replica cap removes the support dependence above its threshold.” + +### M29 — Replay and random depth change the source bill + +**Phase:** Narrative/innovation. + +**Central question:** What does deliberate repetition remove, and which preparation costs remain? + +**Understanding target:** Explain how replay bypasses collision waiting, how the Poisson product identity estimates the exponential with random depth, and why a finite expected count differs from a hard copy cap. Account for the initial specimen even when the random depth is zero, giving expected preparations $a+e^{-a}$ under the stated natural-event interface. + +**Dependencies and story role:** Uses M04, M06, M09 and M28. It completes the source-access comparison with its physical preparation obligations. + +**Conceptual connection:** A repeated-input capability can alter support dependence without cloning a specimen or providing free data loading; the probability-generating-function identity is inherited classical machinery. + +**Sources:** Watrous, Chapters 1–2, for probability, expectation, and preparation/register foundations; [replay and resources](../science/replay_and_resources.md), “An exact exponential estimator with random replica depth,” “The initial specimen is still charged,” and “Finite-depth truncation.” The project supplies and attributes the Poisson construction. + +### M30 — The full scientific consequence and its boundaries + +**Phase:** Narrative/innovation. + +**Central question:** What can now be concluded about quantum learning from passive data, and which conclusions require a different theorem? + +**Understanding target:** Give a connected account of the exact accuracy thresholds, the matched support exponent, the impossibility of a collective-processing shortcut, and the fixed-class immediate-measurement upper bound. Keep source copies, classical records, optional quantum storage, and known measurement circuits visible. State the limits at critical accuracies, nonuniform or drifting sources, structured families, improper outputs, and joint parameter limits. + +**Dependencies and story role:** Integrates M12 and M27–M29, with the preceding proof mechanisms and access comparisons. It completes the narrative as one scientific contribution. + +**Conceptual connection:** The result is a quantitative law about available conditional information and requested decision precision. Its commuting lower-bound witness and classical statistical ingredients delimit the claim; they do not establish a quantum processing speedup or a hardware crossover. + +**Sources:** Watrous, Chapters 1–3, as the common quantum-information foundation; [interpretation](../science/interpretation.md); [replay and resources](../science/replay_and_resources.md), “Physical and computational resources” and “Interpretation limits”; [related work](../references/related_work.md), “Scope and limitation.” diff --git a/learning/story.md b/learning/story.md new file mode 100644 index 0000000..710bf58 --- /dev/null +++ b/learning/story.md @@ -0,0 +1,183 @@ +# When learning accuracy requires repeated contexts + +An experiment has two equally likely settings. Two candidate measurements each have mean loss $1/2$. The first works perfectly at one setting and always fails at the other; the second has loss probability $1/2$ at both settings. + +| Context | Loss of $h_1$ | Loss of $h_2$ | +| --- | ---: | ---: | +| $x=1$ | $0$ | $1/2$ | +| $x=2$ | $1$ | $1/2$ | + +Mean loss ties them. A criterion that puts extra weight on settings with high loss prefers $h_2$. This small example introduces the question: how much conditional information must a data source supply before a learner can resolve that preference at a specified accuracy? + +## A complete quantum realization + +Write $\tau_u=\operatorname{diag}(1-u,u)$ for a qubit state. Use the two-qubit source table + +$$ +\rho_1=\tau_0\otimes\tau_{1/2},\qquad +\rho_2=\tau_1\otimes\tau_{1/2}, +$$ + +and the known projectors + +$$ +\Pi_1=\lvert0\rangle\langle0\rvert\otimes I,\qquad +\Pi_2=I\otimes\lvert0\rangle\langle0\rvert. +$$ + +For hypothesis $h$, the loss at context $x$ is + +$$ +\ell_h(x)=1-\operatorname{Tr}[\Pi_h(x)\rho_x]. +$$ + +The state table and projectors give exactly the displayed losses. Measuring the complementary projector $I-\Pi_h(x)$ produces a loss bit with that probability. These notions connect to Watrous's states and measurements through [the anchor bridge](anchor.md). + +For positive tilt $a$, define the population risk + +$$ +R_a(h)=\frac1a\log\left(\frac12 +e^{a\ell_h(1)}+\frac12e^{a\ell_h(2)}\right). +$$ + +Direct substitution gives + +$$ +R_a(h_2)=\frac12,\qquad +R_a(h_1)=\frac12+\frac1a\log\cosh(a/2). +$$ + +At $a=1$ the gap is about $0.12011451$. The extra cost comes from variation between contexts, despite equal means. This example illustrates the objective; the support-size lower bound below uses many contexts and specially matched frozen-table priors. + +## A probability and one observed bit are different objects + +Suppose an arrival at context $x$ gives one state, and measuring it gives a bit $Y$ with mean $\ell_h(x)$. Exponentiating that bit yields + +$$ +\mathbb E[e^{aY}\mid x] +=1+(e^a-1)\ell_h(x). +$$ + +The target instead contains $e^{a\ell_h(x)}$. The first quantity is affine in the loss probability, and the second is nonlinear. Exponentiating an outcome therefore does not solve the conditional-probability estimation problem. + +If the source prepares $j$ independent specimens at the same context, their loss bits satisfy + +$$ +\mathbb E[Y_1\cdots Y_j\mid x]=\ell_h(x)^j. +$$ + +Repeated preparations reveal higher moments. Passive data can supply such repetitions when a context reappears, but the learner cannot request them. The project asks which repeat order is actually necessary for the requested excess-risk tolerance. + +## A scalar threshold measures the missing information + +Let $\mu$ and $\nu$ be probability distributions of a loss value $u\in[0,1]$. Matching their first $r$ moments means + +$$ +\int u^j\,d\mu(u)=\int u^j\,d\nu(u) +\quad(0\le j\le r). +$$ + +Define + +$$ +\kappa_r(a)= +\max_{\mu,\nu\ \mathrm{matching\ through}\ r} +\frac{\int e^{au}\,d\mu(u)} +{\int e^{au}\,d\nu(u)},\qquad +\Gamma_r(a)=\frac1a\log\kappa_r(a). +$$ + +Thus $\Gamma_r(a)$ is the largest possible tilted-risk gap that remains compatible with those moments. An inherited approximation duality gives an equivalent envelope: + +$$ +\kappa_r(a)=\min\left\{K:\ \exists P,\ \deg P\le r,\quad +e^{au}\le P(u)\le K e^{au}\quad(0\le u\le1)\right\}. +$$ + +One scalar quantity controls both sides of the argument: indistinguishable moment pairs give a lower bound, and a polynomial envelope gives a learner. The local derivation and attribution are in [the moment frontier](../science/moment_frontier.md). + +The thresholds satisfy $1=\Gamma_0(a)>\Gamma_1(a)>\cdots>0$ and tend to zero. The first value is the classical logarithmic Specht ratio, + +$$ +\Gamma_1(a)=\frac1a\log\frac{e^a-1}{a} +-\frac1a+\frac1{e^a-1}. +$$ + +It is approximately $a/8$ at small tilt. The two-context example does not attain this maximum for every $a$: the sharp value optimizes over all admissible loss distributions with the same mean. + +## The accuracy–support theorem + +Now let the source have a known uniform support of $M$ contexts and an arbitrary unknown **fixed** state $\rho_x$ at each context. Each draw independently supplies a uniformly random label $x$ and one fresh specimen of $\rho_x$. There are at most $H$ known projector hypotheses. The learner must return one of those hypotheses: this is proper selection. + +Fix $a>0$, $H\ge2$, $0<\delta<1/2$ and an integer $k\ge1$. If + +$$ +\Gamma_k(a)<\varepsilon<\Gamma_{k-1}(a), +$$ + +then the worst-case fixed-budget sample complexity for + +$$ +\Pr\left[ +R_a(\widehat h)-\min_hR_a(h)\le\varepsilon +\right]\ge1-\delta +$$ + +is + +$$ +\mathsf N^*(M) +=\Theta_{a,\varepsilon,H,\delta,k}(M^{1-1/k}) +\qquad(M\to\infty). +$$ + +The upper bound holds for every supplied class of size at most $H$. One particular pair of commuting projectors on two qubits witnesses the lower bound. It is not a lower bound for every class. All displayed parameters except $M$ are fixed; constants need not be uniform near a threshold or when other parameters grow. + +At $a=1$, the strict tolerance intervals illustrate the staircase: + +| Tolerance | Source-cost dependence | +| --- | --- | +| $0.12330156\ldots<\varepsilon<1$ | $\Theta(1)$ | +| $0.01029531\ldots<\varepsilon<0.12330156\ldots$ | $\Theta(M^{1/2})$ | +| $0.00064456\ldots<\varepsilon<0.01029531\ldots$ | $\Theta(M^{2/3})$ | + +Endpoint equalities are not covered. These decimal values illustrate the analytically defined thresholds; numerical grids are not the proof. + +## Why collective quantum processing cannot remove the cost + +For the lower bound, choose loss distributions that match through degree $k-1$ but have a tilted-risk gap greater than $\varepsilon$. Draw latent loss parameters independently at each context and freeze them. One world makes the first coordinate better; the other swaps the coordinate priors. + +For a diagonal qubit $\tau_u$, every entry of $\tau_u^{\otimes s}$ is a polynomial of degree at most $s$ in $u$. Until a context occurs $k$ times, moment matching therefore makes the **complete prior-averaged training state** identical between the two worlds. This is stronger than saying the learner's chosen measurement has equal mean. + +With $n$ passive draws, a union bound gives + +$$ +\Pr[\text{some context appears at least }k\text{ times}] +\le {n\choose k}M^{1-k}. +$$ + +Below the scale $M^{1-1/k}$, the two full input states are almost indistinguishable. Watrous's binary discrimination theorem then limits every possible final hypothesis choice, including one produced by collective measurements and adaptive processing. Concentration of the frozen-table risks makes the preferred hypotheses genuinely opposite with high prior probability. Averaging any claimed guarantee over these fixed-table priors yields a contradiction. The source is fixed after its initial draw; the construction does not redraw its hidden parameters on each visit. + +## Why the same power is sufficient + +For one hypothesis at a time, measure every arriving specimen immediately and cache its context and loss bit. A batch of order $M^{1-1/k}$ draws contains a $k$-fold repeat with probability bounded away from zero. Select a repeated context using only its labels, symmetrically across labels, and retain its first $k$ outcomes. + +Uniform context sampling makes the selected context exactly uniform. Independent successful batches give independent effective repeated-context examples. A degree-$k$ envelope can be estimated by products of their loss bits. Its coefficients may be signed; boundedness permits statistical estimation even though the estimator is not a binary effect. + +Minimizing the estimated envelope surrogate loses at most $\Gamma_k(a)$ plus statistical slack. The strict inequality $\Gamma_k(a)<\varepsilon$ leaves room for that slack. A fixed number of independent batches, with their failures included in $\delta$, proves the matching fixed-budget upper bound. [The passive proof](../science/passive_frontier.md) gives the extraction and concentration details. + +## Replay and the meaning of the resource + +If the source can deliberately prepare $k$ independent copies at a sampled context, the learner obtains effective groups directly. For fixed tolerance above $\Gamma_k(a)$, the number of groups can be independent of $M$. Every initial and repeated specimen is still charged. This capability is independent preparation from the source, not cloning a received unknown state. + +Random replica depth is another interface choice. With $K\sim\operatorname{Poisson}(a)$, the loss-bit product has mean $e^{a(\ell_h(x)-1)}$. The identity is inherited Bernoulli-factory machinery. If a natural arrival always prepares an initial specimen, the physical count is $\max\{1,K\}$, with mean $a+e^{-a}$, rather than $a$. A finite expected count with an unbounded tail is different from a deterministic cap. + +The [resource account](../science/replay_and_resources.md) also charges discarded passive arrivals, classical caches, measurement circuits and any quantum waiting memory. + +## What the result establishes + +This is a quantum-data access theorem with a classical statistical core. Commuting states already force the lower bound, and immediate individual measurements attain the support exponent for fixed $H$. It establishes no quantum processing advantage or general runtime speedup. + +The PAC requirement concerns the excess of the hypothesis actually returned. Expected regret is a different criterion and has a different sharp moment-limited factor. Improper predictions outside the supplied class, nonuniform contexts, evolving or smooth state tables, critical threshold equalities and joint parameter limits require separate analysis. + +The conclusion is quantitative: a chosen nonlinear-risk accuracy determines which repeated conditional observations the source must supply. The settled [30-milestone map](milestones.md) connects this story to the proofs: M01–M12 assemble the model; M13–M19 explain the scalar frontier; M20–M27 establish the passive theorem; M28–M30 locate replay, metrics, resources and scope. diff --git a/llms.txt b/llms.txt index c6bdde3..795844c 100644 --- a/llms.txt +++ b/llms.txt @@ -10,6 +10,7 @@ Authoritative routes: - Meaning, examples and unresolved parameter boundaries: science/interpretation.md - Inherited tools and closest scientific comparisons: references/related_work.md - Reproduction and finite-check limits: verification/README.md +- Concrete story, selected Watrous (2018) bridge and common 30-milestone map: learning/README.md Essential distinctions: - One copy per passive arrival does not forbid natural recurrence of the same context. diff --git a/references/bibliography.bib b/references/bibliography.bib index ae7a44c..e365065 100644 --- a/references/bibliography.bib +++ b/references/bibliography.bib @@ -1,3 +1,10 @@ +@book{Watrous2018, + author = {Watrous, John}, + title = {The Theory of Quantum Information}, + publisher = {Cambridge University Press}, year = {2018}, + doi = {10.1017/9781316848142}, + url = {https://cs.uwaterloo.ca/~watrous/TQI/} +} @article{FanizzaQuekRosati2024, author = {Fanizza, Marco and Quek, Yihui and Rosati, Matteo}, title = {Learning Quantum Processes Without Input Control}, diff --git a/verification/README.md b/verification/README.md index 70c372c..94de734 100644 --- a/verification/README.md +++ b/verification/README.md @@ -2,7 +2,13 @@ The verifier checks the numerical threshold values and finite mechanisms used by the repeatability account. It compares independently specified moment and polynomial optimization problems, constructs explicit matching-moment source states, verifies the copy observable, and counts context collisions. The analytic statements and their quantifiers remain in the scientific account. -## Run +## Hosted mathematics + +The pull-request workflow compares the exact proposed Markdown with its actual GitHub rendering at widths 1440 and 760. It runs only for same-repository pull requests with `contents: read`, no persisted checkout credential and no secret inputs. The source-bound structural report, HTML and screenshots are retained for visual inspection. A passing structural comparison does not replace proof review or visual inspection. Artifacts have a limited retention period. + +The collector and source comparator are in `hosted_math/`. The workflow first probes one representative proof page, then checks every tracked Markdown page. Its artifact name identifies the exact proposed source commit. + +## Run the finite checks From the repository root, using Python 3.12: diff --git a/verification/hosted_math/capture_hosted_math.cjs b/verification/hosted_math/capture_hosted_math.cjs new file mode 100644 index 0000000..6f36ee0 --- /dev/null +++ b/verification/hosted_math/capture_hosted_math.cjs @@ -0,0 +1,549 @@ +#!/usr/bin/env node +'use strict'; +// Read-only collector for the real GitHub host. See ../references/hosted-rendering.md. +// Importing this module has no network effects; dependencies load only in run(). +const fs = require('node:fs'); +const path = require('node:path'); +const cp = require('node:child_process'); +const crypto = require('node:crypto'); +const VIEWPORTS = [{width:1440,height:1000}, {width:760,height:1000}]; +const RENDER_TIMEOUT_MS = 30000; +const sha256 = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); + +function argumentsFor(argv) { + const args = {pages:[], python:'python3'}; + for (let i=0; i['.','..'].includes(p))) throw new Error('Use exact owner/name'); + if (!/^[a-f0-9]{40}$/.test(args.revision)) throw new Error('Use a full lowercase commit SHA'); + if (new Set(args.pages).size!==args.pages.length || args.pages.some(p=>!safePath(p))) throw new Error('Use unique safe page paths'); + return args; +} +function safePath(p) { + return typeof p==='string' && p.length>0 && !p.includes('\\') && !p.includes('\0') && + !p.startsWith('/') && p.split('/').every(x=>x && x!=='.' && x!=='..'); +} +function git(root, argv) { + return cp.execFileSync('git',['--no-replace-objects',...argv],{cwd:root,encoding:'utf8',maxBuffer:32*1024*1024}); +} +function pinnedPages(args) { + const commit=git(args.root,['rev-parse',args.revision+'^{commit}']).trim(); + if (commit!==args.revision) throw new Error('Revision does not identify the supplied commit'); + const files=git(args.root,['ls-tree','-r','--name-only','-z',commit]).split('\0').filter(Boolean); + const pages=args.pages.length?args.pages:files.filter(p=>/\.(md|markdown|mdown|mkdn|mkd)$/i.test(p)); + if (!pages.length || pages.some(p=>!safePath(p) || !files.includes(p))) throw new Error('No pages or a page is absent from the pinned tree'); + // Git symlinks are not rendered Markdown source and must not be followed. + for (const p of pages) { + const item=git(args.root,['ls-tree',commit,'--',p]); + if (!/^100644 blob |^100755 blob /.test(item)) throw new Error('Page must be a regular tracked file: '+p); + } + return {pages,tree:git(args.root,['rev-parse',commit+'^{tree}']).trim()}; +} +function mathCompiler() { + const {mathjax}=require('mathjax-full/js/mathjax.js'); + const {TeX}=require('mathjax-full/js/input/tex.js'); + const {SVG}=require('mathjax-full/js/output/svg.js'); + const {liteAdaptor}=require('mathjax-full/js/adaptors/liteAdaptor.js'); + const {RegisterHTMLHandler}=require('mathjax-full/js/handlers/html.js'); + const {AllPackages}=require('mathjax-full/js/input/tex/AllPackages.js'); + const {SerializedMmlVisitor}=require('mathjax-full/js/core/MmlTree/SerializedMmlVisitor.js'); + const {STATE}=require('mathjax-full/js/core/MathItem.js'); + RegisterHTMLHandler(liteAdaptor()); + const doc=mathjax.document('',{InputJax:new TeX({packages:AllPackages,tags:'none'}),OutputJax:new SVG({fontCache:'none'})}); + const visitor=new SerializedMmlVisitor(); + return (tex,display)=>visitor.visitTree(doc.convert(tex,{display,end:STATE.CONVERT})); +} + +// Self-contained function executed inside the hosted page, also exercised by the +// local-browser regression fixture. It never injects styling or renders TeX there. +function inspectArticle(root, expected) { + function canonical(e, inherited='') { + const tag=e.localName; + if (['annotation','annotation-xml','mspace'].includes(tag)) return []; + const variant=e.getAttribute('mathvariant') || inherited; + if (['mi','mo','mn','mtext','ms'].includes(tag)) { + const text=e.textContent.trim(); + return text?[[tag,text,variant]]:[]; + } + // Preserve each structural child slot: flattening numerator and denominator + // together would confuse (a+b)/c with a/(b+c), and similarly for scripts. + const children=[...e.children].filter(c=>!['annotation','annotation-xml','mspace'].includes(c.localName)) + .map(c=>canonical(c,variant)); + if (['math','mrow','mstyle','semantics'].includes(tag)) return children.flat(); + const semantic={}; + for (const name of ['notation','accent','accentunder','linethickness','bevelled','open','close','separators']) if(e.hasAttribute(name)) semantic[name]=e.getAttribute(name); + // A table cell is an inferred row (a sequence), not a fixed-arity operator. + // GitHub inserts empty mrow alignment nodes; ignore those inside the cell + // while preserving the cell and row themselves, including empty cells. + return [[tag,semantic,tag==='mtd'?children.flat():children]]; + } + function plain(math) { + const copy=math.cloneNode(true); + for (const e of copy.querySelectorAll('annotation,annotation-xml')) e.remove(); + return copy.textContent; + } + function geometry(math, host) { + const boxes=[...math.querySelectorAll('mi,mo,mn,mtext,ms')].map(e=>e.getBoundingClientRect()).filter(b=>b.width && b.height); + if (!boxes.length) return {measurable:false}; + const left=Math.min(...boxes.map(b=>b.left)),right=Math.max(...boxes.map(b=>b.right)); + const top=Math.min(...boxes.map(b=>b.top)),bottom=Math.max(...boxes.map(b=>b.bottom)); + const width=right-left,height=bottom-top; + return {measurable:true,width,height,available_width:root.clientWidth, + overflow:width>root.clientWidth+4,collapsed:height>Math.max(200,3*width),host_width:host.getBoundingClientRect().width}; + } + let hosts=[...root.querySelectorAll('math-renderer')]; + // Some host versions expose native MathML without a custom-element wrapper. + if (!hosts.length) hosts=[...root.querySelectorAll('math')].filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + const pageErrors=[...root.querySelectorAll('merror,[data-mjx-error],.katex-error,math-renderer .flash-error')] + .map(e=>e.textContent.trim() || 'empty renderer error'); + const math=hosts.map((host,i)=>{ + const nodes=host.localName==='math'?[host]:[...host.querySelectorAll('math')].filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + const errors=[]; + if(nodes.length!==1) errors.push('Expected one accessible MathML representation; found '+nodes.length); + const actual=nodes[0],want=expected[i]; + let expectedSignature=null,actualSignature=null; + if(actual) actualSignature=JSON.stringify(canonical(actual)); + if(want) { + const parsed=new DOMParser().parseFromString(want.mml,'application/xml'); + if(parsed.querySelector('parsererror,merror')) errors.push('Source compiler returned invalid/error MathML'); + else expectedSignature=JSON.stringify(canonical(parsed.documentElement)); + } + if(!want) errors.push('Unexpected extra hosted expression'); + const match=!!actual && !!expectedSignature && expectedSignature===actualSignature; + if(!match) errors.push('Source-to-host MathML structure mismatch'); + const measure=actual?geometry(actual,host):{measurable:false}; + if(want && ['math-fence','dollar-display'].includes(want.kind) && (!measure.measurable || measure.overflow || measure.collapsed)) + errors.push('Display geometry is unmeasurable, overflowing or collapsed'); + return {rendered:!!actual,errors,text_source:'mathml',text:actual?plain(actual):'', + source_sha256:want?.source_sha256,structural_match:match, + expected_signature:expectedSignature,actual_signature:actualSignature,geometry:measure}; + }); + return {errors:pageErrors,math}; +} + +// Self-contained, read-only page probe. Presence of a custom-element placeholder +// is not readiness; wait for the accessible representation used by inspection. +function hostedMathReadiness(root, expectedCount) { + const errors=[...root.querySelectorAll('merror,[data-mjx-error],.katex-error,math-renderer .flash-error')] + .map(e=>e.textContent.trim() || 'empty renderer error'); + let hosts=[...root.querySelectorAll('math-renderer')]; + if(!hosts.length) hosts=[...root.querySelectorAll('math')] + .filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + let usable=0; + for(const host of hosts) { + const nodes=host.localName==='math'?[host]:[...host.querySelectorAll('math')] + .filter(e=>!e.parentElement?.closest('math,annotation,annotation-xml')); + if(nodes.length!==1) continue; + const copy=nodes[0].cloneNode(true); + for(const annotation of copy.querySelectorAll('annotation,annotation-xml')) annotation.remove(); + if(copy.textContent.trim() && copy.querySelector('mi,mo,mn,mtext,ms')) usable++; + } + return {ready:errors.length===0 && hosts.length===expectedCount && usable===expectedCount, + errors,expected_hosts:expectedCount,observed_hosts:hosts.length,usable_hosts:usable}; +} + +async function waitForHostedMath(article, expectedCount, options={}) { + const timeoutMs=options.timeoutMs ?? RENDER_TIMEOUT_MS, intervalMs=options.intervalMs ?? 100; + if(!Number.isFinite(timeoutMs) || timeoutMs<=0 || timeoutMs>RENDER_TIMEOUT_MS || + !Number.isFinite(intervalMs) || intervalMs<=0 || intervalMs>timeoutMs || + !Number.isInteger(expectedCount) || expectedCount<0) + throw new Error('Invalid bounded hosted-math readiness wait'); + // Clock/delay injection is for deterministic offline adapters; production uses + // a monotonic clock and an explicitly bounded poll budget. + const now=options.now || (()=>performance.now()); + const delay=options.delay || (ms=>new Promise(resolve=>setTimeout(resolve,ms))); + const started=now(), maxPolls=Math.ceil(timeoutMs/intervalMs)+1; + let state; + for(let poll=0;poll{timer=setTimeout(()=>reject(new Error( + 'Hosted mathematics readiness evaluation exceeded its bounded budget')),evaluationBudget)}), + ]); + } finally {clearTimeout(timer);} + if(state.errors.length) throw new Error('Hosted mathematics renderer error: '+state.errors.join('; ')); + if(state.ready) return state; + const remaining=timeoutMs-(now()-started); + if(remaining<=0 || poll===maxPolls-1) break; + await delay(Math.min(intervalMs,remaining)); + } + // This is a verification failure, not evidence of a transport interruption + // eligible for blind capture resume. Missing/malformed hosts never pass. + throw new Error('Hosted mathematics readiness failed after '+timeoutMs+' ms: expected '+expectedCount+ + ' hosts; observed '+state?.observed_hosts+'; usable '+state?.usable_hosts); +} + +function classifyFailure(error) { + const message=String(error); + if (/ERR_BLOCKED_BY_ADMINISTRATOR|blocked by.*policy|URLBlocklist|policy denied/i.test(message)) return 'policy_denied'; + if (/HTTP (401|403)|redirected away|sign.in|authentication/i.test(message)) return 'access_required'; + if (/Cannot find module|Executable doesn't exist|browser executable/i.test(message)) return 'capability_unavailable'; + if (/HTTP (429|5[0-9]{2})|ERR_NAME_NOT_RESOLVED|ENOTFOUND|ERR_CONNECTION|ERR_EMPTY_RESPONSE|ERR_INTERNET_DISCONNECTED|ECONNRESET|Timeout|timed out/i.test(message)) return 'transport_failure'; + return 'verification_failure'; +} +function writeJSON(filename, value) {fs.writeFileSync(filename,JSON.stringify(value,null,2)+'\n');} +function artifact(directory, relative, kind) { + const bytes=fs.readFileSync(path.join(directory,relative)); + return {path:relative,sha256:sha256(bytes),size_bytes:bytes.length,kind}; +} +function boundReport(inventory, tree, viewports, artifacts, failures, at) { + const boundaries=inventory.pages.map(p=>{ + const counts=viewports.map(v=>v.boundaries?.find(b=>b.path===p.path)?.captured_hosts); + return {path:p.path,url:p.url,revision:inventory.revision,source_sha256:p.source_sha256, + source_expressions:p.expressions.length, + captured_hosts:counts.length===VIEWPORTS.length && counts.every(n=>Number.isInteger(n) && n===counts[0])?counts[0]:null}; + }); + const wanted=inventory.pages.reduce((n,p)=>n+p.expressions.length,0); + failures=[...failures]; + if(JSON.stringify(viewports.map(v=>({width:v.width,height:v.height})))!==JSON.stringify(VIEWPORTS)) + failures.push('Missing, duplicate or unexpected viewport coverage'); + for(const viewport of viewports) { + if(JSON.stringify((viewport.boundaries||[]).map(b=>b.path))!==JSON.stringify(inventory.pages.map(p=>p.path))) + failures.push(viewport.width+': page coverage differs from inventory'); + for(const source of inventory.pages) { + const boundary=viewport.boundaries?.find(b=>b.path===source.path); + if(!boundary || boundary.source_sha256!==source.source_sha256 || boundary.revision!==inventory.revision || + boundary.url!==source.url || boundary.source_expressions!==source.expressions.length || boundary.captured_hosts!==source.expressions.length) + failures.push(viewport.width+': incomplete source/host coverage for '+source.path); + } + } + const structural=viewports.length===VIEWPORTS.length && viewports.every(v=>v.structural_matches===wanted); + const pass=!failures.length && structural && viewports.length===VIEWPORTS.length && viewports.every(v=>v.status==='pass'); + return {schema_version:1,kind:'hosted_math',repository:inventory.repository,revision:inventory.revision,tree, + renderer_profile:'github',captured_at:at,capture_method:'playwright-github',status:pass?'pass':'fail', + required_pages:inventory.pages.map(p=>p.path),boundaries,viewports,artifacts,failures, + structural_comparison:{status:structural?'pass':'fail',expressions_checked:structural?wanted:0}, + visual_review_required:true, + limits:'Observed GitHub MathML structure, counts, labels, relations and bounded geometry only. No independent scientific proof, exhaustive pixel review, host authenticity certificate or cross-browser guarantee.'}; +} + +// Resume is an explicit new attempt against identical source and execution inputs. +// Receipts bind observations, not authenticity: the final visual review is separate. +const RESUME_MAX_AGE_MS = 24*60*60*1000; +const MAX_EVIDENCE_BYTES = 32*1024*1024; +function safeEvidenceFile(directory, relative) { + if(!safePath(relative)) throw new Error('Unsafe evidence path: '+relative); + const root=path.resolve(directory); + if(fs.lstatSync(root).isSymbolicLink() || !fs.statSync(root).isDirectory()) + throw new Error('Evidence root must be a regular directory'); + let current=root; + for(const component of relative.split('/')) { + current=path.join(current,component); + if(fs.lstatSync(current).isSymbolicLink()) throw new Error('Symlink evidence is not reusable: '+relative); + } + const stat=fs.statSync(current); + if(!stat.isFile() || stat.size>MAX_EVIDENCE_BYTES) throw new Error('Evidence must be a bounded regular file: '+relative); + return current; +} +function readBoundArtifact(directory, descriptor) { + if(!descriptor || typeof descriptor.path!=='string' || !/^[a-f0-9]{64}$/.test(descriptor.sha256) || + !Number.isInteger(descriptor.size_bytes) || descriptor.size_bytes<0) + throw new Error('Malformed evidence artifact descriptor'); + const bytes=fs.readFileSync(safeEvidenceFile(directory,descriptor.path)); + if(bytes.length!==descriptor.size_bytes || sha256(bytes)!==descriptor.sha256) + throw new Error('Evidence artifact hash/size mismatch: '+descriptor.path); + return bytes; +} +function observationTime(value, now=Date.now()) { + const parsed=typeof value==='string' && /(?:Z|[+-]\d{2}:\d{2})$/.test(value)?Date.parse(value):NaN; + if(!Number.isFinite(parsed) || parsed>now || now-parsed>RESUME_MAX_AGE_MS) + throw new Error('Capture observation is stale, future-dated or lacks a timezone'); + return parsed; +} +function pageKey(page, viewport) {return viewport.width+'x'+viewport.height+':'+page;} +function capturePassed(source, item) { + return item && item.path===source.path && item.url===source.url && + item.revision===source.revision && item.source_sha256===source.source_sha256 && + Array.isArray(item.errors) && item.errors.length===0 && Array.isArray(item.math) && + item.math.length===source.expressions.length && item.math.every((m,index)=> + m.rendered===true && Array.isArray(m.errors) && m.errors.length===0 && m.structural_match===true && + m.source_sha256===source.expressions[index].source_sha256 && + typeof m.expected_signature==='string' && m.expected_signature.length>0 && + m.expected_signature===m.actual_signature); +} +function sessionBinding(inventory, tree, expectedBytes, contractBytes, runtime, helper, diagnosticOnly=false, inventoryBytes=null) { + return {repository:inventory.repository,revision:inventory.revision,tree, + inventory_sha256:sha256(inventoryBytes || Buffer.from(JSON.stringify(inventory,null,2)+'\n')), + expected_sha256:sha256(expectedBytes),contract_sha256:sha256(contractBytes),has_contract:contractBytes.toString('utf8')!=='null', + collector_sha256:sha256(fs.readFileSync(__filename)),checker_sha256:sha256(fs.readFileSync(helper)), + runtime,viewports:VIEWPORTS,purpose:diagnosticOnly?'diagnostic':'release_verification'}; +} +function newSession(binding, at) { + return {schema_version:1,kind:'hosted_math_session',binding,started_at:at,updated_at:at, + completed:[],failures:[]}; +} +function saveSession(output, session) { + const temporary=path.join(output,'capture-state.json.tmp'); + writeJSON(temporary,session);fs.renameSync(temporary,path.join(output,'capture-state.json')); +} +function loadResume(directory, binding, inventory, now=Date.now()) { + const bytes=fs.readFileSync(safeEvidenceFile(directory,'capture-state.json')); + const session=JSON.parse(bytes.toString('utf8')); + if(session.schema_version!==1 || session.kind!=='hosted_math_session' || + JSON.stringify(session.binding)!==JSON.stringify(binding)) + throw new Error('Resume source, scope, contract, collector/checker or runtime binding differs'); + if(!Array.isArray(session.failures) || session.failures.some(f=>f.category!=='transport_failure')) + throw new Error('Resume refused after a nontransient, policy or access failure; preserve that attempt and resolve its actual cause'); + if(!Array.isArray(session.completed)) throw new Error('Malformed completed-capture receipts'); + const sourceByPath=new Map(inventory.pages.map(p=>[p.path,{...p,revision:inventory.revision}])); + const reusable=new Map(); + for(const descriptor of session.completed) { + const receiptBytes=readBoundArtifact(directory,descriptor.receipt); + const receipt=JSON.parse(receiptBytes.toString('utf8')); + const source=sourceByPath.get(receipt.path); + const viewport=VIEWPORTS.find(v=>v.width===receipt.viewport?.width && v.height===receipt.viewport?.height); + if(!source || !viewport || receipt.schema_version!==1 || receipt.kind!=='hosted_math_page' || receipt.status!=='pass' || + receipt.repository!==inventory.repository || receipt.revision!==inventory.revision || + receipt.tree!==binding.tree || receipt.source_sha256!==source.source_sha256 || + receipt.key!==pageKey(source.path,viewport) || !capturePassed(source,receipt.capture) || + receipt.capture.observed_at!==receipt.observed_at || !Array.isArray(receipt.artifacts)) + throw new Error('Invalid or mismatched passing page receipt'); + observationTime(receipt.observed_at,now); + if(descriptor.key!==receipt.key || reusable.has(receipt.key)) throw new Error('Duplicate or mismatched page receipt key'); + const prefix=String(inventory.pages.findIndex(p=>p.path===source.path)+1).padStart(4,'0')+'-'+viewport.width; + if(descriptor.receipt.path!==prefix+'-receipt.json') throw new Error('Unexpected page receipt artifact path'); + const expectedArtifacts=new Map([ + [prefix+'-source.json','page_source_inventory'],[prefix+'-capture.json','page_hosted_capture'], + [prefix+'-result.json','page_math_result'],[prefix+'.html','hosted_html'],[prefix+'.png','screenshot']]); + if(binding.has_contract) expectedArtifacts.set(prefix+'-contract.json','page_text_contract'); + const artifactPaths=new Set(); + const payloads=receipt.artifacts.map(a=>{ + if(artifactPaths.has(a.path) || expectedArtifacts.get(a.path)!==a.kind) throw new Error('Duplicate or unexpected receipt artifact path'); + artifactPaths.add(a.path);return {descriptor:a,bytes:readBoundArtifact(directory,a)}; + }); + if(artifactPaths.size!==expectedArtifacts.size) throw new Error('Incomplete page artifact set'); + const resultArtifact=payloads.find(a=>a.descriptor.kind==='page_math_result'); + const captureArtifact=payloads.find(a=>a.descriptor.kind==='page_hosted_capture'); + const sourceArtifact=payloads.find(a=>a.descriptor.kind==='page_source_inventory'); + const result=resultArtifact?JSON.parse(resultArtifact.bytes.toString('utf8')):null; + const capture=captureArtifact?JSON.parse(captureArtifact.bytes.toString('utf8')):null; + const sourceInventory=sourceArtifact?JSON.parse(sourceArtifact.bytes.toString('utf8')):null; + if(result?.status!=='pass' || !Array.isArray(result.failures) || result.failures.length || + result.repository!==inventory.repository || result.revision!==inventory.revision || + result.captured_at!==receipt.observed_at || result.boundaries?.length!==1 || + result.boundaries[0].path!==source.path || result.boundaries[0].url!==source.url || + result.boundaries[0].revision!==inventory.revision || result.boundaries[0].source_expressions!==source.expressions.length || + result.boundaries[0].source_sha256!==source.source_sha256 || + result.boundaries[0].captured_hosts!==source.expressions.length || + result.expressions_checked!==source.expressions.length || + capture?.pages?.length!==1 || JSON.stringify(capture.pages[0])!==JSON.stringify(receipt.capture) || + capture.schema_version!==1 || capture.capture_method!=='playwright-github' || capture.renderer_profile!=='github' || + capture.captured_at!==receipt.observed_at || capture.repository!==inventory.repository || + capture.revision!==inventory.revision || + JSON.stringify(sourceInventory)!==JSON.stringify({...inventory,pages:[inventory.pages.find(p=>p.path===source.path)]}) || + !payloads.some(a=>a.descriptor.path===receipt.capture.artifacts?.html && a.descriptor.kind==='hosted_html') || + !payloads.some(a=>a.descriptor.path===receipt.capture.artifacts?.screenshot && a.descriptor.kind==='screenshot')) + throw new Error('Missing or inconsistent passing page evidence'); + reusable.set(receipt.key,{receipt,descriptor,receiptBytes,payloads, + provenance:{source_directory:path.resolve(directory),session_sha256:sha256(bytes), + receipt_sha256:descriptor.receipt.sha256,observed_at:receipt.observed_at}}); + } + return {reusable,previous_attempt:{directory:path.resolve(directory),session_sha256:sha256(bytes), + started_at:session.started_at,updated_at:session.updated_at,failures:session.failures}}; +} +function runTextCheck(args, helper, output, inventoryFile, captureFile, resultFile, contractFile=null) { + const command=[helper,'check','--inventory',path.join(output,inventoryFile),'--capture',path.join(output,captureFile), + '--output',path.join(output,resultFile)]; + if(contractFile) command.push('--contract',path.join(output,contractFile)); + const check=cp.spawnSync(args.python,command,{encoding:'utf8'}); + if(check.error || !fs.existsSync(path.join(output,resultFile))) + throw new Error('Math checker did not produce a result: '+(check.error||check.stderr)); + return JSON.parse(fs.readFileSync(path.join(output,resultFile),'utf8')); +} +function savePageReceipt(args, helper, output, session, inventory, source, viewport, item, prefix, contract) { + const capture={schema_version:1,repository:args.repository,revision:args.revision,renderer_profile:'github', + captured_at:item.observed_at,capture_method:'playwright-github',pages:[item]}; + const invFile=prefix+'-source.json',captureFile=prefix+'-capture.json',resultFile=prefix+'-result.json'; + writeJSON(path.join(output,invFile),{...inventory,pages:[source]}); + writeJSON(path.join(output,captureFile),capture); + const pageContract=contract?{...contract,expressions:contract.expressions.filter(e=>e.path===source.path)}:null; + const contractFile=pageContract?prefix+'-contract.json':null; + if(pageContract) writeJSON(path.join(output,contractFile),pageContract); + const result=runTextCheck(args,helper,output,invFile,captureFile,resultFile,contractFile); + const files=[artifact(output,invFile,'page_source_inventory'),artifact(output,captureFile,'page_hosted_capture'), + artifact(output,resultFile,'page_math_result')]; + if(contractFile) files.push(artifact(output,contractFile,'page_text_contract')); + for(const [kind,name] of [['hosted_html',item.artifacts?.html],['screenshot',item.artifacts?.screenshot]]) + if(name) files.push(artifact(output,name,kind)); + if(result.status!=='pass' || !capturePassed({...source,revision:args.revision},item)) + return {passed:false,result,artifacts:files}; + const receipt={schema_version:1,kind:'hosted_math_page',status:'pass',repository:args.repository, + revision:args.revision,tree:session.binding.tree,path:source.path,source_sha256:source.source_sha256, + viewport,key:pageKey(source.path,viewport),observed_at:item.observed_at,capture:item,artifacts:files}; + const filename=prefix+'-receipt.json';writeJSON(path.join(output,filename),receipt); + const descriptor={key:receipt.key,receipt:artifact(output,filename,'page_receipt')}; + session.completed.push(descriptor);session.updated_at=new Date().toISOString();saveSession(output,session); + return {passed:true,result,artifacts:[...files,descriptor.receipt],receipt}; +} +async function captureHostedPage(context, source, expected, prefix, output, readinessOptions={}) { + const page=await context.newPage(); + const item={path:source.path,url:source.url,revision:source.revision,source_sha256:source.source_sha256,errors:[],math:[]}; + try { + const response=await page.goto(source.url,{waitUntil:'domcontentloaded',timeout:60000}); + if(response?.status()!==200) throw new Error('HTTP '+response?.status()); + if(page.url()!==source.url) throw new Error('Browser redirected away from exact pinned source URL'); + const article=page.locator('article.markdown-body').first(); + await article.waitFor({state:'visible',timeout:30000}); + await page.evaluate(async()=>{ + for(let y=0,steps=0;ysetTimeout(r,50)); + } + window.scrollTo(0,0); + }); + await waitForHostedMath(article,expected.length,readinessOptions); + Object.assign(item,await article.evaluate(inspectArticle,expected)); + const html=prefix+'.html',png=prefix+'.png'; + fs.writeFileSync(path.join(output,html),await page.content()); + await page.screenshot({path:path.join(output,png),fullPage:true,timeout:30000}); + item.artifacts={html,screenshot:png}; + item.observed_at=new Date().toISOString(); + return item; + } finally {await page.close();} +} +async function defaultRuntime() { + const {chromium}=require('playwright'); + const runtime={node:process.version,playwright:require('playwright/package.json').version, + mathjax:require('mathjax-full/package.json').version}; + const compile=mathCompiler(),browser=await chromium.launch({headless:true}); + runtime.browser=browser.version();return {browser,compile,runtime}; +} +async function run(args, adapters={}) { + const output=path.resolve(args.output); + if(fs.existsSync(output) && (fs.lstatSync(output).isSymbolicLink() || fs.readdirSync(output).length)) + throw new Error('Use an empty output directory; preserve earlier failed evidence'); + fs.mkdirSync(output,{recursive:true}); + const pinned=pinnedPages(args),helper=path.join(__dirname,'check_rendered_math.py'); + cp.execFileSync(args.python,[helper,'inventory','--root',args.root,'--repository',args.repository, + '--revision',args.revision,...pinned.pages.flatMap(p=>['--page',p]),'--output',path.join(output,'math-source.json')],{stdio:'pipe'}); + const inventory=JSON.parse(fs.readFileSync(path.join(output,'math-source.json'),'utf8')); + const at=new Date().toISOString(),failures=[],artifacts=[artifact(output,'math-source.json','source_inventory')],viewports=[]; + const contractBytes=args.contract?fs.readFileSync(path.resolve(args.contract)):Buffer.from('null'); + const contract=args.contract?JSON.parse(contractBytes.toString('utf8')):null; + if(args.contract && (!contract || !Array.isArray(contract.expressions) || contract.schema_version!==1)) throw new Error('Invalid text contract'); + if(args.contract) { + fs.writeFileSync(path.join(output,'math-contract.json'),contractBytes); + artifacts.push(artifact(output,'math-contract.json','text_contract')); + } + let browser,session,runtime={},resume={reusable:new Map()},fatal=false; + const pageProvenance=[]; + try { + // A policy/access failure is detected from the durable state before a new browser is started. + if(args.resumeFrom) { + const prior=JSON.parse(fs.readFileSync(safeEvidenceFile(args.resumeFrom,'capture-state.json'),'utf8')); + if(!Array.isArray(prior.failures) || prior.failures.some(f=>f.category!=='transport_failure')) + throw new Error('Resume refused after a nontransient, policy or access failure'); + } + const loaded=await (adapters.loadRuntime || defaultRuntime)(); + browser=loaded.browser; + runtime={...loaded.runtime,python:cp.execFileSync(args.python,['-c','import sys; print(sys.version)'],{encoding:'utf8'}).trim()}; + const expected=Object.fromEntries(inventory.pages.map(p=>[p.path,p.expressions.map(e=>({...e, + mml:loaded.compile(e.tex,['math-fence','dollar-display'].includes(e.kind))}))])); + writeJSON(path.join(output,'expected-mathml.json'),expected); + artifacts.push(artifact(output,'expected-mathml.json','expected_mathml')); + session=newSession(sessionBinding(inventory,pinned.tree,fs.readFileSync(path.join(output,'expected-mathml.json')), + contractBytes,runtime,helper,args.diagnosticOnly===true,fs.readFileSync(path.join(output,'math-source.json'))),at); + if(args.resumeFrom) { + resume=loadResume(args.resumeFrom,session.binding,inventory); + session.previous_attempt=resume.previous_attempt; + } + saveSession(output,session); + for(const viewport of VIEWPORTS) { + const context=await browser.newContext({viewport,deviceScaleFactor:1,colorScheme:'light'}); + const capture={schema_version:1,repository:args.repository,revision:args.revision,renderer_profile:'github', + captured_at:at,capture_method:'playwright-github',pages:[]}; + try { + for(let index=0;indexp.observed_at).filter(Boolean).sort((a,b)=>Date.parse(a)-Date.parse(b)); + capture.captured_at=observed[0] || at; + const captureFile='math-capture-'+viewport.width+'.json',resultFile='math-result-'+viewport.width+'.json'; + writeJSON(path.join(output,captureFile),capture);artifacts.push(artifact(output,captureFile,'hosted_capture')); + const result=runTextCheck(args,helper,output,'math-source.json',captureFile,resultFile,args.contract?'math-contract.json':null); + artifacts.push(artifact(output,resultFile,'math_result')); + failures.push(...result.failures.map(f=>viewport.width+': '+f)); + const matches=capture.pages.reduce((n,p)=>n+p.math.filter(m=>m.structural_match && !m.errors.length).length,0); + viewports.push({...viewport,status:result.status,structural_matches:matches,capture_path:captureFile,result_path:resultFile,boundaries:result.boundaries}); + if(fatal) break; + } + } catch(error) { + const category=classifyFailure(error);failures.push(category+': '+String(error)); + if(session) { + session.failures.push({category,reason:String(error),observed_at:new Date().toISOString()}); + session.updated_at=new Date().toISOString();saveSession(output,session); + } + } finally {if(browser) await browser.close();} + if(session) artifacts.push(artifact(output,'capture-state.json','capture_session')); + const observations=pageProvenance.map(p=>p.observed_at).sort((a,b)=>Date.parse(a)-Date.parse(b)); + const report={...boundReport(inventory,pinned.tree,viewports,artifacts,failures,observations[0] || at),runtime, + report_assembled_at:new Date().toISOString(),page_provenance:pageProvenance,diagnostic_only:args.diagnosticOnly===true}; + if(session?.previous_attempt) report.previous_attempt=session.previous_attempt; + writeJSON(path.join(output,'hosted-report.json'),report); + console.log(JSON.stringify({status:report.status,report:path.join(output,'hosted-report.json'),sha256:sha256(fs.readFileSync(path.join(output,'hosted-report.json'))),pages:report.required_pages.length,failures:report.failures.length,reused_pages:pageProvenance.filter(p=>p.reused).length})); + return report.status==='pass'?0:1; +} +module.exports={argumentsFor,safePath,pinnedPages,mathCompiler,inspectArticle,hostedMathReadiness,waitForHostedMath,classifyFailure,artifact,boundReport,VIEWPORTS,run, + safeEvidenceFile,readBoundArtifact,observationTime,pageKey,capturePassed,sessionBinding,newSession,saveSession,loadResume, + runTextCheck,savePageReceipt,captureHostedPage,RESUME_MAX_AGE_MS,RENDER_TIMEOUT_MS}; +if(require.main===module) { + (async()=>{ + const args=argumentsFor(process.argv.slice(2)); + if(args.help) {console.log('capture_hosted_math.cjs --root REPO --repository owner/name --revision FULLSHA --output EMPTY_DIR [--page PATH ...] [--contract JSON] [--python python3] [--resume-from PRIOR_EVIDENCE_DIR]');return;} + process.exitCode=await run(args); + })().catch(error=>{console.error(String(error));process.exitCode=2;}); +} diff --git a/verification/hosted_math/check_rendered_math.py b/verification/hosted_math/check_rendered_math.py new file mode 100644 index 0000000..1d3bf98 --- /dev/null +++ b/verification/hosted_math/check_rendered_math.py @@ -0,0 +1,370 @@ +#!/usr/bin/env python3 +r"""Check captured mathematical text against pinned GitHub Markdown source. + +Usage (Python 3.10+, standard library only): + check_rendered_math.py inventory --root REPO --repository owner/name \ + --revision FULL_COMMIT --page README.md --page science/results.md \ + --output math-source.json + check_rendered_math.py check --inventory math-source.json \ + --capture math-capture.json [--contract math-contract.json] [--output result.json] + +Inventory reads Git objects at the requested commit, not the working tree. +It recognizes math fences, $`...`$, $$...$$ and single-dollar inline math, +excluding ordinary code fences/spans. This is a bounded Markdown scanner, +not the hosting renderer's parser. Inspect its inventory before capture. + +Capture schema (collect actual full accessible math text in document order): + {"schema_version": 1, "repository": "owner/name", "revision": "40 hex", + "renderer_profile": "github", "captured_at": "ISO-8601 with timezone", + "capture_method": "how the actual hosted DOM was inspected", + "pages": [{"path": "README.md", "url": "exact pinned inventory URL", + "revision": "40 hex", "source_sha256": "inventory source hash", + "errors": [], "math": [{"rendered": true, "errors": [], + "text_source": "mathml", "text": "full text, not a sample"}]}]} +Allowed text_source values: mathml, mathjax-assistive, katex-accessibility, +renderer-accessibility. Extract one accessible representation per host; +exclude TeX annotation nodes and duplicate visual/accessibility copies. +Native MathML is valid. Empty math lists are valid for math-free pages. + +Optional contract strengthens content checks without pretending to translate +arbitrary TeX. Each entry selects a path/index (1-based) and source_sha256 +(the expression hash in inventory), with expected_text and/or required_text: + {"schema_version": 1, "expressions": [{"path": "README.md", "index": 1, + "source_sha256": "expression hash", "required_text": ["d", "(C1)"], + "expected_text": "|A|", "le": "≤", "leq": "≤", "ge": "≥", "geq": "≥", + "ne": "≠", "neq": "≠", "in": "∈", "notin": "∉", "subset": "⊂", + "subseteq": "⊆", "supset": "⊃", "supseteq": "⊇", "approx": "≈", + "simeq": "≃", "equiv": "≡", "propto": "∝", "cong": "≅", "sim": "∼", + "to": "→", "rightarrow": "→", "Rightarrow": "⇒", "implies": "⇒", + "mapsto": "↦", "leftrightarrow": "↔", "Leftrightarrow": "⇔", "iff": "⇔", +} +RELATION_SYMBOLS = set("<>=") | set(RELATIONS.values()) +COMMAND = re.compile(r"\\([A-Za-z]+)") +LABEL = re.compile(r"\\tag(\*)?\{([^{}]+)\}|\\text\{\s*\(([^{}()]+)\)\s*\}") +FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})([^\n]*)\n?$") +SHA = re.compile(r"[0-9a-f]{40}") +TEXT_SOURCES = {"mathml", "mathjax-assistive", "katex-accessibility", "renderer-accessibility"} + + +def digest(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def compact(text: str) -> str: + return "".join(c for c in unicodedata.normalize("NFKC", text) + if not c.isspace() and unicodedata.category(c) != "Cf") + + +def escaped(text: str, index: int) -> bool: + backslashes = 0 + while index > 0 and text[index - 1] == "\\": + backslashes += 1 + index -= 1 + return bool(backslashes % 2) + + +def tex_body(text: str) -> str: + """Drop unescaped TeX comments; do not expand user macros.""" + return "\n".join(line[:next((i for i, c in enumerate(line) + if c == "%" and not escaped(line, i)), len(line))] + for line in text.splitlines()) + + +def relations(tex: str) -> dict[str, int]: + expanded = COMMAND.sub(lambda m: RELATIONS.get(m.group(1), m.group(0)), tex_body(tex)) + return dict(sorted(Counter(c for c in expanded if c in RELATION_SYMBOLS).items())) + + +def labels(tex: str) -> list[str]: + return [compact(tag if star else f"({tag or text})") + for star, tag, text in LABEL.findall(tex_body(tex))] + + +def expressions(source: str) -> list[dict]: + """Return ordered source spans; reject unterminated recognized delimiters.""" + found: list[dict] = [] + + def add(tex: str, offset: int, end: int, kind: str) -> None: + found.append({"line_start": source.count("\n", 0, offset) + 1, + "line_end": source.count("\n", 0, end) + 1, + "kind": kind, "tex": tex, "source_sha256": digest(tex), + "relations": relations(tex), "labels": labels(tex)}) + + def prose(start: int, end: int) -> None: + i = start + while i < end: + if source[i] == "$" and not escaped(source, i): + opener, closer, kind = ("$`", "`$", "github-inline") if source.startswith("$`", i) else ( + ("$$", "$$", "dollar-display") if source.startswith("$$", i) + else ("$", "$", "dollar-inline")) + j = source.find(closer, i + len(opener), end) + while j >= 0 and escaped(source, j): + j = source.find(closer, j + len(closer), end) + if j < 0 or (kind == "dollar-inline" and "\n" in source[i:j]): + raise ValueError(f"unclosed {kind} at line {source.count(chr(10), 0, i) + 1}") + add(source[i + len(opener):j], i, j + len(closer) - 1, kind) + i = j + len(closer) + elif source[i] == "`" and not escaped(source, i): + n = 1 + while i + n < end and source[i + n] == "`": + n += 1 + j = source.find("`" * n, i + n, end) + i = j + n if j >= 0 else i + n + else: + i += 1 + + lines = source.splitlines(keepends=True) + offset = start = i = 0 + while i < len(lines): + match = FENCE.match(lines[i]) + if not match: + offset += len(lines[i]) + i += 1 + continue + prose(start, offset) + marker, info = match.groups() + begin = offset + offset += len(lines[i]) + body_start = offset + i += 1 + while i < len(lines): + closing = FENCE.match(lines[i]) + if closing and closing[1][0] == marker[0] and len(closing[1]) >= len(marker) and not closing[2].strip(): + break + offset += len(lines[i]) + i += 1 + if i == len(lines): + raise ValueError(f"unclosed code fence at line {source.count(chr(10), 0, begin) + 1}") + if info.strip() == "math": + add(source[body_start:offset], begin, offset, "math-fence") + offset += len(lines[i]) + i += 1 + start = offset + prose(start, len(source)) + for index, item in enumerate(found, 1): + item["index"] = index + return found + + +def safe_path(path: str) -> bool: + return isinstance(path, str) and bool(path) and "\\" not in path and not PurePosixPath(path).is_absolute() and all( + part not in {"", ".", ".."} for part in path.split("/")) + + +def make_inventory(repository: str, revision: str, sources: dict[str, str]) -> dict: + if not isinstance(repository, str) or not isinstance(revision, str) or not re.fullmatch( + r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository) or not SHA.fullmatch(revision): + raise ValueError("use owner/name and an exact lowercase 40-character commit SHA") + if not isinstance(sources, dict) or not sources or not all( + safe_path(p) and isinstance(s, str) for p, s in sources.items()): + raise ValueError("supply at least one safe repository-relative page path") + return {"schema_version": 1, "repository": repository, "revision": revision, + "renderer_profile": "github", "pages": [ + {"path": path, "url": f"https://github.com/{repository}/blob/{revision}/{quote(path, safe='/')}", + "source_sha256": digest(source), "source_text": source, "expressions": expressions(source)} + for path, source in sources.items()]} + + +def validate(inventory: dict, capture: dict, contract: dict | None = None) -> dict: + """Return failures rather than equating a passing text check with readiness.""" + failures: list[str] = [] + boundaries: list[dict] = [] + exceptions: list[dict] = [] + if not isinstance(inventory, dict) or not isinstance(capture, dict): + raise ValueError("inventory and capture must be JSON objects") + if type(inventory.get("schema_version")) is not int or type(capture.get("schema_version")) is not int or inventory["schema_version"] != 1 or capture["schema_version"] != 1: + raise ValueError("unsupported inventory or capture schema_version") + pages = inventory.get("pages") + if not isinstance(pages, list) or not pages or any(not isinstance(p, dict) for p in pages): + raise ValueError("inventory needs a nonempty pages array") + paths = [p.get("path") for p in pages] + if any(not isinstance(p, str) for p in paths) or len(set(paths)) != len(paths): + raise ValueError("inventory page paths must be unique strings") + rebuilt = make_inventory(inventory.get("repository", ""), inventory.get("revision", ""), + {p["path"]: p["source_text"] for p in pages}) + if inventory != rebuilt: + raise ValueError("inventory does not match its embedded source bytes/expression inventory") + for field in ("repository", "revision", "renderer_profile"): + if capture.get(field) != inventory[field]: + failures.append(f"capture {field} mismatch") + try: + timestamp = datetime.fromisoformat(capture.get("captured_at", "").replace("Z", "+00:00")) + if timestamp.tzinfo is None: + raise ValueError() + except (ValueError, AttributeError, TypeError): + failures.append("capture needs captured_at with a timezone") + if not isinstance(capture.get("capture_method"), str) or not capture["capture_method"].strip(): + failures.append("capture needs a nonempty capture_method") + captured_pages = capture.get("pages") + if not isinstance(captured_pages, list) or any(not isinstance(p, dict) for p in captured_pages): + raise ValueError("capture pages must be an array of objects") + captured_paths = [p.get("path") for p in captured_pages] + if captured_paths != paths: + failures.append("capture page paths/order differ from inventory (missing, extra or duplicate page)") + + contract = {"schema_version": 1, "expressions": []} if contract is None else contract + if not isinstance(contract, dict) or type(contract.get("schema_version")) is not int or contract["schema_version"] != 1 or not isinstance(contract.get("expressions"), list): + raise ValueError("invalid text contract schema") + rules: dict[tuple, dict] = {} + known = {(p["path"], e["index"]): e for p in pages for e in p["expressions"]} + for rule in contract["expressions"]: + if not isinstance(rule, dict): + raise ValueError("contract expressions must be objects") + key = (rule.get("path"), rule.get("index")) + if not isinstance(key[0], str) or type(key[1]) is not int or key not in known or key in rules or rule.get("source_sha256") != known[key]["source_sha256"]: + raise ValueError("unknown, duplicate or stale expression contract") + allowed = {"path", "index", "source_sha256", "required_text", "expected_text", "relation_override", + "allow_html_like_inequality", "reason", "evidence"} + if set(rule) - allowed: + raise ValueError("unknown contract field (contracts cannot skip checks)") + if "expected_text" in rule and (not isinstance(rule["expected_text"], str) or not compact(rule["expected_text"])): + raise ValueError("expected_text must be nonempty text") + if not isinstance(rule.get("required_text", []), list) or any( + not isinstance(v, str) or not compact(v) for v in rule.get("required_text", [])): + raise ValueError("required_text must be an array of nonempty text") + if "expected_text" not in rule and not rule.get("required_text"): + raise ValueError("each expression contract needs expected_text or required_text") + if "allow_html_like_inequality" in rule and not isinstance(rule["allow_html_like_inequality"], bool): + raise ValueError("allow_html_like_inequality must be boolean") + if "relation_override" in rule: + override = rule["relation_override"] + if not isinstance(override, dict) or any(k not in RELATION_SYMBOLS or type(v) is not int or v < 0 + for k, v in override.items()): + raise ValueError("relation_override must map known symbols to nonnegative integer counts") + if "relation_override" in rule or rule.get("allow_html_like_inequality"): + if not all(isinstance(rule.get(k), str) and rule[k].strip() for k in ("expected_text", "reason", "evidence")): + raise ValueError("renderer exception requires expected_text, reason and evidence") + exceptions.append(rule) + rules[key] = rule + + by_path = {p.get("path"): p for p in captured_pages if isinstance(p.get("path"), str)} + checked = 0 + for page in pages: + path = page["path"] + current = by_path.get(path) + if current is None: + continue + boundaries.append({"path": path, "source_sha256": page["source_sha256"], "url": current.get("url"), + "revision": current.get("revision"), "source_expressions": len(page["expressions"]), + "source_spans": [{k: e[k] for k in ("index", "line_start", "line_end", "source_sha256")} + for e in page["expressions"]]}) + for field, expected in (("url", page["url"]), ("revision", inventory["revision"]), ("source_sha256", page["source_sha256"])): + if current.get(field) != expected: + failures.append(f"{path}: captured {field} mismatch") + if current.get("errors") != []: + failures.append(f"{path}: renderer errors present or error evidence missing") + hosts = current.get("math") + if not isinstance(hosts, list): + failures.append(f"{path}: missing math-host array") + continue + boundaries[-1]["captured_hosts"] = len(hosts) + if len(hosts) != len(page["expressions"]): + failures.append(f"{path}: {len(page['expressions'])} source expressions, {len(hosts)} captured hosts") + for expr, host in zip(page["expressions"], hosts): + label = f"{path}:{expr['line_start']} expression {expr['index']}" + rule = rules.get((path, expr["index"]), {}) + if not isinstance(host, dict) or host.get("rendered") is not True or host.get("errors") != []: + failures.append(f"{label}: missing/unrendered host or renderer-error evidence") + continue + if host.get("text_source") not in TEXT_SOURCES or not isinstance(host.get("text"), str) or not compact(host["text"]): + failures.append(f"{label}: missing full accessible mathematical text/source") + continue + checked += 1 + text = compact(host["text"]) + expected = {k: v for k, v in rule.get("relation_override", expr["relations"]).items() if v} + actual = dict(sorted(Counter(c for c in text if c in RELATION_SYMBOLS).items())) + if expected != actual: + failures.append(f"{label}: relation mismatch; expected {expected}, captured {actual}") + for equation_label in expr["labels"]: + if equation_label not in text: + failures.append(f"{label}: missing equation label {equation_label}") + if re.search(r"<\s*[A-Za-z]", tex_body(expr["tex"])) and not rule.get("allow_html_like_inequality"): + failures.append(f"{label}: GitHub HTML-like inequality hazard; use supported syntax or a traced exact-text exception") + if "expected_text" in rule and compact(rule["expected_text"]) != text: + failures.append(f"{label}: full expected_text mismatch") + for required in rule.get("required_text", []): + if compact(required) not in text: + failures.append(f"{label}: missing required_text {required!r}") + return {"schema_version": 1, "status": "fail" if failures else "pass", + "repository": inventory["repository"], "revision": inventory["revision"], + "renderer_profile": inventory["renderer_profile"], "captured_at": capture.get("captured_at"), + "capture_method": capture.get("capture_method"), "boundaries": boundaries, + "expressions_checked": checked, "text_contracts": len(rules), "renderer_exceptions": exceptions, + "failures": failures, "visual_review_required": True, + "limits": "Counts, supported relations/visible labels and explicit text contracts only. No arbitrary TeX equivalence, scientific correctness, capture authentication or visual-layout certification."} + + +def read_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + commands = parser.add_subparsers(dest="command", required=True) + inv = commands.add_parser("inventory", help="read math source from an exact local Git commit") + inv.add_argument("--root", type=Path, required=True) + inv.add_argument("--repository", required=True) + inv.add_argument("--revision", required=True) + inv.add_argument("--page", action="append", required=True) + inv.add_argument("--output", type=Path, required=True) + check = commands.add_parser("check", help="check pinned extracted capture; does not fetch or render") + check.add_argument("--inventory", type=Path, required=True) + check.add_argument("--capture", type=Path, required=True) + check.add_argument("--contract", type=Path) + check.add_argument("--output", type=Path) + args = parser.parse_args(argv) + try: + if args.command == "inventory": + if not SHA.fullmatch(args.revision) or len(set(args.page)) != len(args.page) or not all(safe_path(p) for p in args.page): + raise ValueError("use an exact commit SHA and unique safe page paths") + commit = subprocess.check_output(["git", "--no-replace-objects", "rev-parse", f"{args.revision}^{{commit}}"], cwd=args.root, text=True).strip() + if commit != args.revision: + raise ValueError("revision does not identify the supplied commit") + sources = {p: subprocess.check_output(["git", "--no-replace-objects", "show", f"{commit}:{p}"], cwd=args.root).decode("utf-8") for p in args.page} + result = make_inventory(args.repository, commit, sources) + else: + result = validate(read_json(args.inventory), read_json(args.capture), read_json(args.contract) if args.contract else None) + output = json.dumps(result, indent=2, ensure_ascii=False) + "\n" + if args.output: + args.output.write_text(output, encoding="utf-8") + else: + print(output, end="") + return 1 if result.get("status") == "fail" else 0 + except (OSError, UnicodeError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as error: + print(f"ERROR: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/verification/hosted_math/probe_hosted_math.cjs b/verification/hosted_math/probe_hosted_math.cjs new file mode 100644 index 0000000..f83ea9d --- /dev/null +++ b/verification/hosted_math/probe_hosted_math.cjs @@ -0,0 +1,146 @@ +#!/usr/bin/env node +'use strict'; +// Representative read-only diagnostic, not release-readiness evidence. +// Importing this module neither starts a browser nor visits a site. +const fs = require('node:fs'); +const path = require('node:path'); +const cp = require('node:child_process'); +const crypto = require('node:crypto'); +const collector = require('./capture_hosted_math.cjs'); +const sha256 = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); + +function argumentsFor(argv) { + if (argv.includes('--resume-from')) throw new Error('A diagnostic does not resume captures; use the full collector for that operation'); + const args = collector.argumentsFor(argv); + if (args.help) return args; + if (args.pages.length !== 1) throw new Error('Choose exactly one representative --page for the early diagnostic'); + return args; +} + +function sourceAdvisories(source, page) { + const warnings = []; + let fence = null; + for (const [index, line] of source.split(/\r?\n/).entries()) { + const mark = line.match(/^\s{0,3}(`{3,}|~{3,})/); + if (mark) { + if (!fence) fence = mark[1]; + else if (mark[1][0] === fence[0] && mark[1].length >= fence.length) fence = null; + continue; + } + if (fence) continue; + const inline = [...line.matchAll(/(? warnings.push({code, path:page, line:index+1, message}); + if (tex.includes('<')) add('raw_inline_less_than', 'Inspect raw < in inline mathematics on GitHub; use an appropriate TeX relation if the host truncates it.'); + if (/_[A-Za-z0-9]+_/.test(tex)) add('repeated_unbraced_subscript', 'Inspect a possible repeated unbraced subscript; braces may be needed to express the intended indices.'); + if (/^\s*\|/.test(line) && /(? message.includes(category) || collector.classifyFailure(message) === category)) return category; + } + return messages.length ? 'verification_failure' : null; +} + +function dependencies(args, services = {}) { + const execute = services.execFileSync || cp.execFileSync; + const resolve = services.resolve || require.resolve; + const result = {node:process.version}; + if (Number(process.versions.node.split('.')[0]) < 18) throw new Error('capability_unavailable: Node.js 18 or later is required'); + for (const [key, command, flags] of [['git','git',['--version']], ['python',args.python,['--version']]]) { + try { + result[key] = String(execute(command, flags, {encoding:'utf8',stdio:'pipe'})).trim(); + } catch (error) { + throw new Error('capability_unavailable: Cannot execute '+key+': '+String(error)); + } + } + const pythonVersion = result.python.match(/Python\s+(\d+)\.(\d+)/); + if (!pythonVersion || Number(pythonVersion[1]) < 3 || (Number(pythonVersion[1]) === 3 && Number(pythonVersion[2]) < 10)) + throw new Error('capability_unavailable: Python 3.10 or later is required; observed '+result.python); + for (const name of ['playwright','mathjax-full']) { + try { result[name] = resolve(name+'/package.json'); } + catch (error) { throw new Error('capability_unavailable: Cannot find module '+name+': '+String(error)); } + } + return result; +} + +function emptyOutput(directory) { + const resolved = path.resolve(directory); + if (fs.existsSync(resolved)) { + if (fs.lstatSync(resolved).isSymbolicLink() || !fs.statSync(resolved).isDirectory()) throw new Error('Output must be a regular directory'); + if (fs.readdirSync(resolved).length) throw new Error('Use an empty output directory; preserve earlier diagnostic evidence'); + } + return resolved; +} + +async function run(args, services = {}) { + if (args.pages?.length !== 1 || args['resume-from'] || args.resumeFrom) throw new Error('Diagnostic requires exactly one page and no resumed evidence'); + const output = emptyOutput(args.output); + const at = (services.now || (() => new Date().toISOString()))(); + const execute = services.execFileSync || cp.execFileSync; + const inspectPinned = services.pinnedPages || collector.pinnedPages; + const capture = services.capture || collector.run; + const failures = []; + let pinned, runtime = {}, sourceHash = null, advisories = [], captureReport = null, captureExit = null; + try { + runtime = dependencies(args, services); + pinned = inspectPinned(args); + if (pinned.pages.length !== 1 || pinned.pages[0] !== args.pages[0]) throw new Error('Pinned diagnostic scope differs from the requested page'); + const source = execute('git', ['--no-replace-objects','show',args.revision+':'+args.pages[0]], {cwd:args.root,encoding:'utf8',maxBuffer:32*1024*1024}); + sourceHash = sha256(source); + advisories = sourceAdvisories(String(source), args.pages[0]); + const log = console.log; + // The diagnostic emits one summary of its own; raw collector records remain on disk. + try { console.log = () => {}; captureExit = await capture({...args,output,diagnosticOnly:true}); } + finally { console.log = log; } + const filename = path.join(output,'hosted-report.json'); + if (!fs.existsSync(filename)) throw new Error('Collector did not produce its report'); + const bytes = fs.readFileSync(filename); + captureReport = JSON.parse(bytes); + if (captureReport.repository !== args.repository || captureReport.revision !== args.revision || + captureReport.tree !== pinned.tree || JSON.stringify(captureReport.required_pages) !== JSON.stringify(args.pages)) + throw new Error('Collector diagnostic report identity/scope mismatch'); + if (captureReport.diagnostic_only !== true) throw new Error('Collector did not mark its representative capture as diagnostic-only; use the matching current helper bundle'); + failures.push(...(captureReport.failures || [])); + if (captureExit !== 0 || captureReport.status !== 'pass') { + if (!failures.length) failures.push('Representative hosted comparison did not pass'); + } + } catch (error) { failures.push(String(error)); } + fs.mkdirSync(output,{recursive:true}); + const category = categoryFor(failures); + const filename = path.join(output,'hosted-report.json'); + const report = { + schema_version:1,kind:'hosted_probe',repository:args.repository,revision:args.revision, + tree:pinned?.tree || null,page:args.pages[0],source_sha256:sourceHash, + observed_at:at,status:failures.length?'fail':'pass',failure_category:category,failures, + runtime,advisories,diagnostic_only:true,release_ready:false,release_evidence:false, + capture_report:fs.existsSync(filename)?{path:'hosted-report.json',sha256:sha256(fs.readFileSync(filename))}:null, + limits:'One representative page at the collector\'s two viewports only. This early diagnostic is not full repository review, visual approval, scientific validation, or release-readiness evidence. Source advisories are heuristic and do not prove a rendering defect.', + next_action:!failures.length ? 'Continue furnishing; perform the complete final source-bound hosted and visual review later.' : + category === 'policy_denied' ? 'Record the denial and continue unaffected work; retry only after applicable access evidence changes, without routing around the denial.' : + category === 'access_required' ? 'Identify the actual missing access requirement and resolve it through an authorized flow; preserve the named grant and continue unaffected work.' : + category === 'capability_unavailable' ? 'Use or provision a permitted compatible runtime within the actual grant, then repeat the diagnostic; no access-setting change is implied.' : + category === 'transport_failure' ? 'Preserve this failed attempt and retry the same authorized operation after the transient transport condition changes.' : + 'Inspect the pinned source and captured representative page, repair demonstrated defects within scope, and repeat the diagnostic.' + }; + fs.writeFileSync(path.join(output,'probe-report.json'),JSON.stringify(report,null,2)+'\n'); + return {code:report.status==='pass'?0:1,report}; +} + +module.exports = {argumentsFor,sourceAdvisories,categoryFor,dependencies,emptyOutput,run}; +if (require.main === module) { + (async () => { + const args = argumentsFor(process.argv.slice(2)); + if (args.help) { console.log('probe_hosted_math.cjs --root REPO --repository owner/name --revision FULLSHA --page REPRESENTATIVE.md --output EMPTY_DIR [--contract JSON] [--python python3]'); return; } + const result = await run(args); + console.log(JSON.stringify({status:result.report.status,category:result.report.failure_category,report:path.join(path.resolve(args.output),'probe-report.json'),release_ready:false})); + process.exitCode = result.code; + })().catch(error => {console.error(String(error));process.exitCode=2;}); +} From 17126153e8f1ff13e7818eacce81431389e8485e Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sun, 15 Nov 2026 11:52:59 +0800 Subject: [PATCH 2/5] Repair mathematics delimiters and macros demonstrated by the GitHub renderer --- README.md | 24 +++--- learning/anchor.md | 26 +++---- learning/milestones.md | 52 ++++++------- learning/story.md | 76 +++++++++--------- references/related_work.md | 20 ++--- science/README.md | 2 +- science/interpretation.md | 24 +++--- science/model.md | 60 +++++++------- science/moment_frontier.md | 134 ++++++++++++++++---------------- science/passive_frontier.md | 112 +++++++++++++------------- science/replay_and_resources.md | 52 ++++++------- verification/README.md | 10 +-- 12 files changed, 296 insertions(+), 296 deletions(-) diff --git a/README.md b/README.md index 7523cc1..b54959e 100644 --- a/README.md +++ b/README.md @@ -2,17 +2,17 @@ **How does the accuracy of a nonlinear quantum training loss change the number of examples needed when inputs cannot be replayed?** -This project establishes an accuracy-dependent sample exponent for selecting among a fixed finite collection of known measurement hypotheses. Each passive example supplies a classical context, sampled uniformly from a known set of size $M$, and one fresh copy of its unknown conditional quantum state. The state table is fixed throughout the experiment. +This project establishes an accuracy-dependent sample exponent for selecting among a fixed finite collection of known measurement hypotheses. Each passive example supplies a classical context, sampled uniformly from a known set of size $`M`$, and one fresh copy of its unknown conditional quantum state. The state table is fixed throughout the experiment. -For loss $\ell_h(x)=1-\operatorname{Tr}[\Pi_h(x)\rho_x]$ and fixed tilt $a>0$, minimize +For loss $`\ell_h(x)=1-\mathrm{Tr}[\Pi_h(x)\rho_x]`$ and fixed tilt $`a>0`$, minimize ```math R_a(h)=\frac{1}{a}\log\left(\frac{1}{M}\sum_{x=1}^{M}e^{a\ell_h(x)}\right). ``` -Let $\kappa_r(a)$ be the largest ratio between exponential moments of two distributions on $[0,1]$ whose first $r$ moments agree, and set $\Gamma_r(a)=a^{-1}\log\kappa_r(a)$. Equivalently, $\kappa_r(a)$ is the best multiplicative distortion of a degree-$r$ polynomial envelope of $e^{au}$; the scalar approximation duality is inherited and credited in the [moment account](science/moment_frontier.md). +Let $`\kappa_r(a)`$ be the largest ratio between exponential moments of two distributions on $`[0,1]`$ whose first $`r`$ moments agree, and set $`\Gamma_r(a)=a^{-1}\log\kappa_r(a)`$. Equivalently, $`\kappa_r(a)`$ is the best multiplicative distortion of a degree-$`r`$ polynomial envelope of $`e^{au}`$; the scalar approximation duality is inherited and credited in the [moment account](science/moment_frontier.md). -For every fixed integer $k\ge1$, at accuracies strictly between adjacent thresholds, +For every fixed integer $`k\ge1`$, at accuracies strictly between adjacent thresholds, ```math \Gamma_k(a)<\varepsilon<\Gamma_{k-1}(a) @@ -21,14 +21,14 @@ N_{\mathrm{worst}}(M) =\Theta_{a,\varepsilon,H,\delta}\!\left(M^{1-1/k}\right). ``` -Here $H\ge2$ is a fixed finite cap on the number of hypotheses, the failure target satisfies $0<\delta<1/2$, and $M$ tends to infinity while the other parameters remain fixed. The upper bound holds for every such class; a particular two-hypothesis class on two-qubit outputs witnesses the worst-case lower bound. Arbitrary collective quantum measurements are allowed. +Here $`H\ge2`$ is a fixed finite cap on the number of hypotheses, the failure target satisfies $`0\lt \delta\lt 1/2`$, and $`M`$ tends to infinity while the other parameters remain fixed. The upper bound holds for every such class; a particular two-hypothesis class on two-qubit outputs witnesses the worst-case lower bound. Arbitrary collective quantum measurements are allowed. | Same-context observations that become necessary | Passive source exponent | |---|---:| -| One | $0$ | -| Two | $1/2$ | -| Three | $2/3$ | -| $k$ | $1-1/k$ | +| One | $`0`$ | +| Two | $`1/2`$ | +| Three | $`2/3`$ | +| $`k`$ | $`1-1/k`$ | The first threshold is explicit: @@ -38,7 +38,7 @@ The first threshold is explicit: =\frac{a}{8}+O(a^3). ``` -At $a=1$, the first three thresholds are approximately $0.12330156$, $0.01029531$ and $0.00064456$. These values are checked numerically; the theorem uses the exact variational thresholds. +At $`a=1`$, the first three thresholds are approximately $`0.12330156`$, $`0.01029531`$ and $`0.00064456`$. These values are checked numerically; the theorem uses the exact variational thresholds. ## Read the science @@ -52,9 +52,9 @@ The [learning route](learning/README.md) starts with a concrete two-context exam A nonlinear objective depends on within-context outcome probabilities, rather than only their mean across contexts. Better accuracy can require higher same-context occupancies. Passive sampling must wait for these coincidences; selected-input replay supplies them directly and removes the support-size factor. -The lower bound rules out bypassing this repetition cost with collective quantum processing. For fixed $H$, matching source exponents also admit immediate per-hypothesis measurements and classical storage of their outcomes. This is a data-access law, with a classical latent-variable core. It establishes no processing-time speedup or hardware crossover. +The lower bound rules out bypassing this repetition cost with collective quantum processing. For fixed $`H`$, matching source exponents also admit immediate per-hypothesis measurements and classical storage of their outcomes. This is a data-access law, with a classical latent-variable core. It establishes no processing-time speedup or hardware crossover. -The theorem concerns proper selection from the supplied hypothesis class, uniform contexts, independent source draws, arbitrary fixed conditional states, fixed parameters and strict threshold gaps. It does not determine the critical accuracies $\varepsilon=\Gamma_r(a)$, joint precision/support limits, or nonuniform-context rates. Source preparation, classical caching, quantum storage when used, and known measurement circuits are accounted for separately. +The theorem concerns proper selection from the supplied hypothesis class, uniform contexts, independent source draws, arbitrary fixed conditional states, fixed parameters and strict threshold gaps. It does not determine the critical accuracies $`\varepsilon=\Gamma_r(a)`$, joint precision/support limits, or nonuniform-context rates. Source preparation, classical caching, quantum storage when used, and known measurement circuits are accounted for separately. ## Reproduce the finite checks diff --git a/learning/anchor.md b/learning/anchor.md index 92c9d9a..d81bfaa 100644 --- a/learning/anchor.md +++ b/learning/anchor.md @@ -23,31 +23,31 @@ Watrous uses matrix notation rather than Dirac notation. The project uses both. | Book notation | Project notation or role | | --- | --- | -| A complex Euclidean space such as $\mathcal X$ | A finite-dimensional register space, here $\mathsf Q\cong\mathbb C^d$ | -| $\mathrm D(\mathcal X)$ | The density operators, written $\mathcal D(\mathsf Q)$ here | -| $u u^*$ and $E_{x,x}=e_xe_x^*$ | $\lvert u\rangle\langle u\rvert$ and $\lvert x\rangle\langle x\rvert$ | -| A measurement $\mu$ with outcome operator $\mu(1)$ | The loss outcome operator $I-\Pi_h(x)$ | -| $\langle A,\rho\rangle=\operatorname{Tr}(A^*\rho)$ | $\operatorname{Tr}[(I-\Pi_h(x))\rho_x]=\ell_h(x)$ for the Hermitian loss projector | -| $\lVert A\rVert_1$ | The same trace norm; our trace distance is $D(\rho,\sigma)=\tfrac12\lVert\rho-\sigma\rVert_1$ | +| A complex Euclidean space such as $`\mathcal X`$ | A finite-dimensional register space, here $`\mathsf Q\cong\mathbb C^d`$ | +| $`\mathrm D(\mathcal X)`$ | The density operators, written $`\mathcal D(\mathsf Q)`$ here | +| $`u u^{*}`$ and $`E_{x,x}=e_xe_x^{*}`$ | $`\lvert u\rangle\langle u\rvert`$ and $`\lvert x\rangle\langle x\rvert`$ | +| A measurement $`\mu`$ with outcome operator $`\mu(1)`$ | The loss outcome operator $`I-\Pi_h(x)`$ | +| $`\langle A,\rho\rangle=\mathrm{Tr}(A^{*}\rho)`$ | $`\mathrm{Tr}[(I-\Pi_h(x))\rho_x]=\ell_h(x)`$ for the Hermitian loss projector | +| $`\lVert A\rVert_1`$ | The same trace norm; our trace distance is $`D(\rho,\sigma)=\tfrac12\lVert\rho-\sigma\rVert_1`$ | ## From registers to the source -The context is a readable classical register. A table $x\mapsto\rho_x$ defines +The context is a readable classical register. A table $`x\mapsto\rho_x`$ defines $$ \Omega_\rho=\frac1M\sum_{x=1}^M \lvert x\rangle\langle x\rvert\otimes\rho_x. $$ -Its block-diagonal form means a context label is sampled with probability $1/M$ and its associated state is supplied. The table is unknown but fixed. Receiving another example means another independent source preparation, not a coherent query to that table. Reading the context does not supply a preparation circuit or the ability to choose the next context. These are local modeling assumptions, made explicit in [the model](../science/model.md); they are not consequences of the density-operator formalism. +Its block-diagonal form means a context label is sampled with probability $`1/M`$ and its associated state is supplied. The table is unknown but fixed. Receiving another example means another independent source preparation, not a coherent query to that table. Reading the context does not supply a preparation circuit or the ability to choose the next context. These are local modeling assumptions, made explicit in [the model](../science/model.md); they are not consequences of the density-operator formalism. -Measuring $I-\Pi_h(x)$ produces a bit $Y$ with conditional mean $\ell_h(x)$. If the same context supplies $j$ independent specimens, the product of the $j$ loss bits has conditional mean $\ell_h(x)^j$. This is the first bridge from tensor-product copies to the classical moments required by the nonlinear objective. +Measuring $`I-\Pi_h(x)`$ produces a bit $`Y`$ with conditional mean $`\ell_h(x)`$. If the same context supplies $`j`$ independent specimens, the product of the $`j`$ loss bits has conditional mean $`\ell_h(x)^j`$. This is the first bridge from tensor-product copies to the classical moments required by the nonlinear objective. ## From indistinguishable states to a learning converse -The lower bound constructs two priors over fixed tables. Under either prior, consider the density operator of **all** labeled training registers. When no context occurs $k$ times, matching moments make these operators exactly equal. This statement concerns the complete quantum input, not just the outcomes of a preferred hypothesis measurement. +The lower bound constructs two priors over fixed tables. Under either prior, consider the density operator of **all** labeled training registers. When no context occurs $`k`$ times, matching moments make these operators exactly equal. This statement concerns the complete quantum input, not just the outcomes of a preferred hypothesis measurement. -If the exceptional collision event has probability $q$, the two averaged training states $\omega_0,\omega_1$ satisfy +If the exceptional collision event has probability $`q`$, the two averaged training states $`\omega_0,\omega_1`$ satisfy $$ D(\omega_0,\omega_1)\le q. @@ -68,9 +68,9 @@ An entire adaptive learning computation ending in a binary hypothesis choice def The exponential-loss approximation problem and the generalized birthday calculation are additional **classical** machinery. The bridge is: 1. Repeated loss measurements estimate moments of the conditional probability. -2. A degree-$k$ envelope $e^{au}\le P(u)\le\kappa_k(a)e^{au}$ turns those moments into a surrogate risk with distortion $\Gamma_k(a)$. +2. A degree-$`k`$ envelope $`e^{au}\le P(u)\le\kappa_k(a)e^{au}`$ turns those moments into a surrogate risk with distortion $`\Gamma_k(a)`$. 3. The dual moment pair makes a larger gap invisible below the necessary repetition level. -4. Uniform-context occupancy supplies, and limits, that repetition level at $M^{1-1/k}$ samples. +4. Uniform-context occupancy supplies, and limits, that repetition level at $`M^{1-1/k}`$ samples. 5. Concentration and proper hypothesis selection connect these facts to a PAC guarantee for each fixed table. The complete derivations are [the moment frontier](../science/moment_frontier.md) and [the passive frontier](../science/passive_frontier.md), corresponding to M14–M27 in [the map](milestones.md). This machinery is not attributed to Watrous. diff --git a/learning/milestones.md b/learning/milestones.md index 7484c84..c0f764a 100644 --- a/learning/milestones.md +++ b/learning/milestones.md @@ -18,7 +18,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Dependencies and story role:** This is the local starting point; no earlier milestone is required. It introduces the object that remains fixed whenever its context is revisited. -**Conceptual connection:** The table entry $\rho_x$ is a physical statistical object, not a classical list of its matrix entries given to the learner. +**Conceptual connection:** The table entry $`\rho_x`$ is a physical statistical object, not a classical list of its matrix entries given to the learner. **Sources:** Watrous, Chapter 2, “Basic notions of quantum information,” for states; [model](../science/model.md), “Source and hypotheses.” @@ -28,11 +28,11 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** How does a known measurement hypothesis assign a loss to an unknown state? -**Understanding target:** Read $\ell_h(x)=1-\operatorname{Tr}[\Pi_h(x)\rho_x]$ as a probability in $[0,1]$. Distinguish knowledge of a hypothesis measurement from knowledge of its probability on the unknown source. +**Understanding target:** Read $`\ell_h(x)=1-\mathrm{Tr}[\Pi_h(x)\rho_x]`$ as a probability in $`[0,1]`$. Distinguish knowledge of a hypothesis measurement from knowledge of its probability on the unknown source. **Dependencies and story role:** Uses M01 and adds the local measurement through which a hypothesis is evaluated. -**Conceptual connection:** Projector-valued hypotheses make the learning task concrete without giving the learner a preparation oracle or a description of $\rho_x$. +**Conceptual connection:** Projector-valued hypotheses make the learning task concrete without giving the learner a preparation oracle or a description of $`\rho_x`$. **Sources:** Watrous, Chapters 1–2, for operators, trace, and measurements; [model](../science/model.md), “Source and hypotheses” and “Tilted population risk.” @@ -42,7 +42,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** Which information does one binary measurement outcome supply about its context? -**Understanding target:** Separate the observed bit $Y$ from the conditional probability $\ell_h(x)=\mathbb E[Y\mid X=x]$. Explain why applying a nonlinear function to the bit need not estimate that function of the probability. +**Understanding target:** Separate the observed bit $`Y`$ from the conditional probability $`\ell_h(x)=\mathbb E[Y\mid X=x]`$. Explain why applying a nonlinear function to the bit need not estimate that function of the probability. **Dependencies and story role:** Uses M02. It isolates the local statistical distinction that eventually creates the repetition cost. @@ -56,7 +56,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** What changes when the source supplies several independent specimens at the same context? -**Understanding target:** Interpret $\rho_x^{\otimes r}$ as repeated independent preparation. Distinguish this access from one specimen, a correlated multi-system state, or a procedure that clones an unknown received state. +**Understanding target:** Interpret $`\rho_x^{\otimes r}`$ as repeated independent preparation. Distinguish this access from one specimen, a correlated multi-system state, or a procedure that clones an unknown received state. **Dependencies and story role:** Uses M01–M03. It joins the state and outcome descriptions into the local repeated-observation experiment. @@ -70,7 +70,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** How are random context labels and their fixed conditional states combined into training data? -**Understanding target:** Read the classical-quantum source $M^{-1}\sum_x|x\rangle\langle x|\otimes\rho_x$ and its independent repetitions. Explain that the table is fixed even though the sampled label changes, and that revisiting a label does not redraw its hidden table entry. +**Understanding target:** Read the classical-quantum source $`M^{-1}\sum_x|x\rangle\langle x|\otimes\rho_x`$ and its independent repetitions. Explain that the table is fixed even though the sampled label changes, and that revisiting a label does not redraw its hidden table entry. **Dependencies and story role:** Uses M01 and M04. It moves from one context to the full source without yet specifying a learning objective. @@ -98,7 +98,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** What does a positive tilt ask the learner to resolve beyond the mean loss? -**Understanding target:** Interpret $R_a(h)=a^{-1}\log\mathbb E_x e^{a\ell_h(x)}$ for $a>0$, its mean-loss limit, and its emphasis on larger conditional losses. Preserve the order of the conditional mean, exponential, context average, and logarithm. +**Understanding target:** Interpret $`R_a(h)=a^{-1}\log\mathbb E_x e^{a\ell_h(x)}`$ for $`a>0`$, its mean-loss limit, and its emphasis on larger conditional losses. Preserve the order of the conditional mean, exponential, context average, and logarithm. **Dependencies and story role:** Uses M03 and M05. It connects the local measurement probability to the global objective. @@ -126,7 +126,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** Why do repeated conditional observations supply powers of a probability? -**Understanding target:** Explain $\mathbb E[\prod_{i=1}^{j}Y_i\mid x]=\ell_h(x)^j$ under conditional independence, then average over contexts. Recognize the first $r$ loss moments as accessible from grouped $r$-copy examples. +**Understanding target:** Explain $`\mathbb E[\prod_{i=1}^{j}Y_i\mid x]=\ell_h(x)^j`$ under conditional independence, then average over contexts. Recognize the first $`r`$ loss moments as accessible from grouped $`r`$-copy examples. **Dependencies and story role:** Uses M03–M04 and M07. It converts physical repetition into the scalar information used by approximation theory. @@ -154,11 +154,11 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** How can finitely many moments control a nonlinear exponential mean? -**Understanding target:** Interpret a degree-$r$ polynomial as a linear combination of the moments in M09. Understand the pointwise envelope $e^{au}\le p(u)\le K e^{au}$ as a multiplicative comparison that survives averaging. +**Understanding target:** Interpret a degree-$`r`$ polynomial as a linear combination of the moments in M09. Understand the pointwise envelope $`e^{au}\le p(u)\le K e^{au}`$ as a multiplicative comparison that survives averaging. **Dependencies and story role:** Uses M07 and M09. It introduces the classical approximation interface that links repetition to risk accuracy. -**Conceptual connection:** The envelope's positivity is a statement about its values on $[0,1]$; it does not assert that every coefficient or every associated measurement operator is positive. +**Conceptual connection:** The envelope's positivity is a statement about its values on $`[0,1]`$; it does not assert that every coefficient or every associated measurement operator is positive. **Sources:** Watrous, Chapter 1, for linear functionals, norms, and convexity foundations; [moment frontier](../science/moment_frontier.md), “Equivalent positive polynomial envelope” and “Relative approximation, strictness, and convergence.” The project supplies the approximation argument. @@ -184,7 +184,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** What does the smallest useful example reveal about nonlinear risk? -**Understanding target:** Compare a hypothesis with losses $0$ and $1$ at equally likely contexts to one with constant loss $1/2$. Explain why their means agree while positive-tilt risks differ, and why the single-outcome substitution from M03 misses this distinction. +**Understanding target:** Compare a hypothesis with losses $`0`$ and $`1`$ at equally likely contexts to one with constant loss $`1/2`$. Explain why their means agree while positive-tilt risks differ, and why the single-outcome substitution from M03 misses this distinction. **Dependencies and story role:** Uses M07, M11–M12. It begins the narrative with a concrete need for information beyond the first moment. @@ -196,9 +196,9 @@ Each milestone records a conceptual target and its source dependencies. The map **Phase:** Narrative/innovation. -**Central question:** How large can a tilted-risk difference remain when the first $r$ moments agree? +**Central question:** How large can a tilted-risk difference remain when the first $`r`$ moments agree? -**Understanding target:** Interpret $\kappa_r(a)$ as the largest ratio of exponential means over matching-moment laws and $\Gamma_r(a)=a^{-1}\log\kappa_r(a)$ as the corresponding risk gap. Explain why exchanging the two laws removes a sign ambiguity. +**Understanding target:** Interpret $`\kappa_r(a)`$ as the largest ratio of exponential means over matching-moment laws and $`\Gamma_r(a)=a^{-1}\log\kappa_r(a)`$ as the corresponding risk gap. Explain why exchanging the two laws removes a sign ambiguity. **Dependencies and story role:** Uses M09, M11 and M13. It replaces an isolated example by the exact scalar quantity that will control the theorem. @@ -216,7 +216,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Dependencies and story role:** Uses M11 and M14. It makes one exact threshold serve both the lower and upper proofs. -**Conceptual connection:** Matching moments erase every degree-$r$ polynomial difference, while a positive envelope bounds what remains of the exponential objective. +**Conceptual connection:** Matching moments erase every degree-$`r`$ polynomial difference, while a positive envelope bounds what remains of the exponential objective. **Sources:** Watrous, Chapter 1, for finite-dimensional linear and convex foundations; [moment frontier](../science/moment_frontier.md), Theorem 1 and its explicit attribution; [related work](../references/related_work.md), “Classical conditional learning and approximation theory.” @@ -226,7 +226,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** What accuracy can first-moment information support at a fixed tilt? -**Understanding target:** Explain the extremal constant-loss and endpoint-Bernoulli laws at a common mean, the maximizing mean, and the explicit value of $\Gamma_1(a)$. Recognize its logarithmic Specht-ratio origin and its leading behavior $a/8$. +**Understanding target:** Explain the extremal constant-loss and endpoint-Bernoulli laws at a common mean, the maximizing mean, and the explicit value of $`\Gamma_1(a)`$. Recognize its logarithmic Specht-ratio origin and its leading behavior $`a/8`$. **Dependencies and story role:** Uses M13–M15. It turns the abstract frontier into a concrete scale for the first change in passive sample behavior. @@ -240,7 +240,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** How do successive repetition levels change the threshold sequence? -**Understanding target:** Explain positivity, strict decrease, and convergence of $\Gamma_r(a)$, and the role of relative approximation in those properties. Interpret the fixed-degree small-tilt asymptotic while keeping that limit separate from the fixed-parameter support-size limit. +**Understanding target:** Explain positivity, strict decrease, and convergence of $`\Gamma_r(a)`$, and the role of relative approximation in those properties. Interpret the fixed-degree small-tilt asymptotic while keeping that limit separate from the fixed-parameter support-size limit. **Dependencies and story role:** Uses M14–M16. It establishes that adjacent accuracy intervals form a genuine ordered hierarchy. @@ -268,7 +268,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** How does minimizing a surrogate yield the required proper-risk decision? -**Understanding target:** Follow the chain comparing the selected exponential mean, its polynomial mean, and the optimal hypothesis's polynomial mean. Explain why the distortion enters once as $\Gamma_r(a)$, with a separate estimation slack, rather than twice. +**Understanding target:** Follow the chain comparing the selected exponential mean, its polynomial mean, and the optimal hypothesis's polynomial mean. Explain why the distortion enters once as $`\Gamma_r(a)`$, with a separate estimation slack, rather than twice. **Dependencies and story role:** Uses M08, M15 and M18. It connects local estimation to the actual learning output. @@ -296,7 +296,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** Why can no collective quantum measurement distinguish the two worlds before sufficient repetitions occur? -**Understanding target:** Explain why entries of an $s$-copy conditional state are degree-$s$ polynomials in its latent probability. Use the matching moments and independence between frozen context entries to obtain equality of the complete prior-averaged training states when every occupancy is small enough. +**Understanding target:** Explain why entries of an $`s`$-copy conditional state are degree-$`s`$ polynomials in its latent probability. Use the matching moments and independence between frozen context entries to obtain equality of the complete prior-averaged training states when every occupancy is small enough. **Dependencies and story role:** Uses M04, M10 and M20. It provides the measurement-independent core of the lower bound. @@ -310,7 +310,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** At what sample scale can a context first occur often enough to expose the hidden distinction? -**Understanding target:** Interpret the bound $\Pr(\text{a k-fold repeat})\leq\binom nk M^{1-k}$ for $k\geq2$. Derive the scale $M^{1-1/k}$ and explain how a rare bad-label event bounds distinguishing advantage. +**Understanding target:** Interpret the bound $`\Pr(\text{a k-fold repeat})\leq\binom nk M^{1-k}`$ for $`k\geq2`$. Derive the scale $`M^{1-1/k}`$ and explain how a rare bad-label event bounds distinguishing advantage. **Dependencies and story role:** Uses M05, M10 and M21. It turns full-state equality into a support-dependent information bound. @@ -324,7 +324,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** Why does the argument establish a failure for a fixed unknown source, rather than a different resampling model? -**Understanding target:** Combine concentration of the table's exponential means, a strict risk gap above $\epsilon$, and the world-identification bound. Explain how averaging a purported guarantee over table priors leads to a contradiction and therefore to a violating deterministic table. +**Understanding target:** Combine concentration of the table's exponential means, a strict risk gap above $`\epsilon`$, and the world-identification bound. Explain how averaging a purported guarantee over table priors leads to a contradiction and therefore to a violating deterministic table. **Dependencies and story role:** Uses M08 and M20–M22. It closes the lower proof under the original task's quantifiers. @@ -338,7 +338,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** Is the lower collision scale also enough to obtain a useful repeated context? -**Understanding target:** Follow the first- and second-moment calculation for the number of equal-label $k$-subsets in a batch of order $M^{1-1/k}$. Explain why overlap terms vanish at fixed $k$ and why the chance of success stays bounded away from zero. +**Understanding target:** Follow the first- and second-moment calculation for the number of equal-label $`k`$-subsets in a batch of order $`M^{1-1/k}`$. Explain why overlap terms vanish at fixed $`k`$ and why the chance of success stays bounded away from zero. **Dependencies and story role:** Uses M22. It begins the constructive half at the same support exponent as the converse. @@ -370,7 +370,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Dependencies and story role:** Uses M18–M19 and M24–M25. It completes the upper construction as a fixed-budget learning algorithm rather than an expected waiting-time argument. -**Conceptual connection:** The theorem's constant may depend on the tilt, class cap, confidence, degree, and threshold margin even though its power of $M$ is sharp. +**Conceptual connection:** The theorem's constant may depend on the tilt, class cap, confidence, degree, and threshold margin even though its power of $`M`$ is sharp. **Sources:** Watrous, Chapter 1, for probability notation; [passive frontier](../science/passive_frontier.md), “Finite estimates and a fixed sample budget,” for bounded-variable concentration and confidence bookkeeping; [replay and resources](../science/replay_and_resources.md), “Physical and computational resources.” @@ -380,7 +380,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** How do the exact thresholds and the collision scale combine into one theorem? -**Understanding target:** Explain why $\Gamma_k(a)<\epsilon<\Gamma_{k-1}(a)$ gives worst-case sample complexity $\Theta(M^{1-1/k})$. State the fixed-parameter limiting order, the confidence and proper-selection conditions, and the distinction between an upper bound for every finite class and a lower bound witnessed by one two-hypothesis class. +**Understanding target:** Explain why $`\Gamma_k(a)\lt \epsilon\lt \Gamma_{k-1}(a)`$ gives worst-case sample complexity $`\Theta(M^{1-1/k})`$. State the fixed-parameter limiting order, the confidence and proper-selection conditions, and the distinction between an upper bound for every finite class and a lower bound witnessed by one two-hypothesis class. **Dependencies and story role:** Integrates M14–M26. It is the global synthesis of the main scientific proof. @@ -392,9 +392,9 @@ Each milestone records a conceptual target and its source dependencies. The map **Phase:** Narrative/innovation. -**Central question:** What remains ambiguous when each random arrival already supplies $r$ copies? +**Central question:** What remains ambiguous when each random arrival already supplies $`r`$ copies? -**Understanding target:** Explain the support-independent PAC boundary at $\Gamma_r(a)$, why later natural visits prevent it from being an eternal impossibility for a fixed finite support, and why the worst-case expected-regret factor $1-1/H$ describes a different guarantee. +**Understanding target:** Explain the support-independent PAC boundary at $`\Gamma_r(a)`$, why later natural visits prevent it from being an eternal impossibility for a fixed finite support, and why the worst-case expected-regret factor $`1-1/H`$ describes a different guarantee. **Dependencies and story role:** Uses M06, M08, M15, M19 and M23. It places the passive staircase inside the broader access comparison without changing the output metric silently. @@ -408,7 +408,7 @@ Each milestone records a conceptual target and its source dependencies. The map **Central question:** What does deliberate repetition remove, and which preparation costs remain? -**Understanding target:** Explain how replay bypasses collision waiting, how the Poisson product identity estimates the exponential with random depth, and why a finite expected count differs from a hard copy cap. Account for the initial specimen even when the random depth is zero, giving expected preparations $a+e^{-a}$ under the stated natural-event interface. +**Understanding target:** Explain how replay bypasses collision waiting, how the Poisson product identity estimates the exponential with random depth, and why a finite expected count differs from a hard copy cap. Account for the initial specimen even when the random depth is zero, giving expected preparations $`a+e^{-a}`$ under the stated natural-event interface. **Dependencies and story role:** Uses M04, M06, M09 and M28. It completes the source-access comparison with its physical preparation obligations. diff --git a/learning/story.md b/learning/story.md index 710bf58..3a920e4 100644 --- a/learning/story.md +++ b/learning/story.md @@ -1,17 +1,17 @@ # When learning accuracy requires repeated contexts -An experiment has two equally likely settings. Two candidate measurements each have mean loss $1/2$. The first works perfectly at one setting and always fails at the other; the second has loss probability $1/2$ at both settings. +An experiment has two equally likely settings. Two candidate measurements each have mean loss $`1/2`$. The first works perfectly at one setting and always fails at the other; the second has loss probability $`1/2`$ at both settings. -| Context | Loss of $h_1$ | Loss of $h_2$ | +| Context | Loss of $`h_1`$ | Loss of $`h_2`$ | | --- | ---: | ---: | -| $x=1$ | $0$ | $1/2$ | -| $x=2$ | $1$ | $1/2$ | +| $`x=1`$ | $`0`$ | $`1/2`$ | +| $`x=2`$ | $`1`$ | $`1/2`$ | -Mean loss ties them. A criterion that puts extra weight on settings with high loss prefers $h_2$. This small example introduces the question: how much conditional information must a data source supply before a learner can resolve that preference at a specified accuracy? +Mean loss ties them. A criterion that puts extra weight on settings with high loss prefers $`h_2`$. This small example introduces the question: how much conditional information must a data source supply before a learner can resolve that preference at a specified accuracy? ## A complete quantum realization -Write $\tau_u=\operatorname{diag}(1-u,u)$ for a qubit state. Use the two-qubit source table +Write $`\tau_u=\mathrm{diag}(1-u,u)`$ for a qubit state. Use the two-qubit source table $$ \rho_1=\tau_0\otimes\tau_{1/2},\qquad @@ -25,15 +25,15 @@ $$ \Pi_2=I\otimes\lvert0\rangle\langle0\rvert. $$ -For hypothesis $h$, the loss at context $x$ is +For hypothesis $`h`$, the loss at context $`x`$ is $$ -\ell_h(x)=1-\operatorname{Tr}[\Pi_h(x)\rho_x]. +\ell_h(x)=1-\mathrm{Tr}[\Pi_h(x)\rho_x]. $$ -The state table and projectors give exactly the displayed losses. Measuring the complementary projector $I-\Pi_h(x)$ produces a loss bit with that probability. These notions connect to Watrous's states and measurements through [the anchor bridge](anchor.md). +The state table and projectors give exactly the displayed losses. Measuring the complementary projector $`I-\Pi_h(x)`$ produces a loss bit with that probability. These notions connect to Watrous's states and measurements through [the anchor bridge](anchor.md). -For positive tilt $a$, define the population risk +For positive tilt $`a`$, define the population risk $$ R_a(h)=\frac1a\log\left(\frac12 @@ -47,20 +47,20 @@ R_a(h_2)=\frac12,\qquad R_a(h_1)=\frac12+\frac1a\log\cosh(a/2). $$ -At $a=1$ the gap is about $0.12011451$. The extra cost comes from variation between contexts, despite equal means. This example illustrates the objective; the support-size lower bound below uses many contexts and specially matched frozen-table priors. +At $`a=1`$ the gap is about $`0.12011451`$. The extra cost comes from variation between contexts, despite equal means. This example illustrates the objective; the support-size lower bound below uses many contexts and specially matched frozen-table priors. ## A probability and one observed bit are different objects -Suppose an arrival at context $x$ gives one state, and measuring it gives a bit $Y$ with mean $\ell_h(x)$. Exponentiating that bit yields +Suppose an arrival at context $`x`$ gives one state, and measuring it gives a bit $`Y`$ with mean $`\ell_h(x)`$. Exponentiating that bit yields $$ \mathbb E[e^{aY}\mid x] =1+(e^a-1)\ell_h(x). $$ -The target instead contains $e^{a\ell_h(x)}$. The first quantity is affine in the loss probability, and the second is nonlinear. Exponentiating an outcome therefore does not solve the conditional-probability estimation problem. +The target instead contains $`e^{a\ell_h(x)}`$. The first quantity is affine in the loss probability, and the second is nonlinear. Exponentiating an outcome therefore does not solve the conditional-probability estimation problem. -If the source prepares $j$ independent specimens at the same context, their loss bits satisfy +If the source prepares $`j`$ independent specimens at the same context, their loss bits satisfy $$ \mathbb E[Y_1\cdots Y_j\mid x]=\ell_h(x)^j. @@ -70,7 +70,7 @@ Repeated preparations reveal higher moments. Passive data can supply such repeti ## A scalar threshold measures the missing information -Let $\mu$ and $\nu$ be probability distributions of a loss value $u\in[0,1]$. Matching their first $r$ moments means +Let $`\mu`$ and $`\nu`$ be probability distributions of a loss value $`u\in[0,1]`$. Matching their first $`r`$ moments means $$ \int u^j\,d\mu(u)=\int u^j\,d\nu(u) @@ -87,29 +87,29 @@ $$ \Gamma_r(a)=\frac1a\log\kappa_r(a). $$ -Thus $\Gamma_r(a)$ is the largest possible tilted-risk gap that remains compatible with those moments. An inherited approximation duality gives an equivalent envelope: +Thus $`\Gamma_r(a)`$ is the largest possible tilted-risk gap that remains compatible with those moments. An inherited approximation duality gives an equivalent envelope: $$ -\kappa_r(a)=\min\left\{K:\ \exists P,\ \deg P\le r,\quad -e^{au}\le P(u)\le K e^{au}\quad(0\le u\le1)\right\}. +\kappa_r(a)=\min\left\lbraceK:\ \exists P,\ \deg P\le r,\quad +e^{au}\le P(u)\le K e^{au}\quad(0\le u\le1)\right\rbrace. $$ One scalar quantity controls both sides of the argument: indistinguishable moment pairs give a lower bound, and a polynomial envelope gives a learner. The local derivation and attribution are in [the moment frontier](../science/moment_frontier.md). -The thresholds satisfy $1=\Gamma_0(a)>\Gamma_1(a)>\cdots>0$ and tend to zero. The first value is the classical logarithmic Specht ratio, +The thresholds satisfy $`1=\Gamma_0(a)>\Gamma_1(a)>\cdots>0`$ and tend to zero. The first value is the classical logarithmic Specht ratio, $$ \Gamma_1(a)=\frac1a\log\frac{e^a-1}{a} -\frac1a+\frac1{e^a-1}. $$ -It is approximately $a/8$ at small tilt. The two-context example does not attain this maximum for every $a$: the sharp value optimizes over all admissible loss distributions with the same mean. +It is approximately $`a/8`$ at small tilt. The two-context example does not attain this maximum for every $`a`$: the sharp value optimizes over all admissible loss distributions with the same mean. ## The accuracy–support theorem -Now let the source have a known uniform support of $M$ contexts and an arbitrary unknown **fixed** state $\rho_x$ at each context. Each draw independently supplies a uniformly random label $x$ and one fresh specimen of $\rho_x$. There are at most $H$ known projector hypotheses. The learner must return one of those hypotheses: this is proper selection. +Now let the source have a known uniform support of $`M`$ contexts and an arbitrary unknown **fixed** state $`\rho_x`$ at each context. Each draw independently supplies a uniformly random label $`x`$ and one fresh specimen of $`\rho_x`$. There are at most $`H`$ known projector hypotheses. The learner must return one of those hypotheses: this is proper selection. -Fix $a>0$, $H\ge2$, $0<\delta<1/2$ and an integer $k\ge1$. If +Fix $`a>0`$, $`H\ge2`$, $`0\lt \delta\lt 1/2`$ and an integer $`k\ge1`$. If $$ \Gamma_k(a)<\varepsilon<\Gamma_{k-1}(a), @@ -126,57 +126,57 @@ $$ is $$ -\mathsf N^*(M) +\mathsf N^{*}(M) =\Theta_{a,\varepsilon,H,\delta,k}(M^{1-1/k}) \qquad(M\to\infty). $$ -The upper bound holds for every supplied class of size at most $H$. One particular pair of commuting projectors on two qubits witnesses the lower bound. It is not a lower bound for every class. All displayed parameters except $M$ are fixed; constants need not be uniform near a threshold or when other parameters grow. +The upper bound holds for every supplied class of size at most $`H`$. One particular pair of commuting projectors on two qubits witnesses the lower bound. It is not a lower bound for every class. All displayed parameters except $`M`$ are fixed; constants need not be uniform near a threshold or when other parameters grow. -At $a=1$, the strict tolerance intervals illustrate the staircase: +At $`a=1`$, the strict tolerance intervals illustrate the staircase: | Tolerance | Source-cost dependence | | --- | --- | -| $0.12330156\ldots<\varepsilon<1$ | $\Theta(1)$ | -| $0.01029531\ldots<\varepsilon<0.12330156\ldots$ | $\Theta(M^{1/2})$ | -| $0.00064456\ldots<\varepsilon<0.01029531\ldots$ | $\Theta(M^{2/3})$ | +| $`0.12330156\ldots\lt \varepsilon\lt 1`$ | $`\Theta(1)`$ | +| $`0.01029531\ldots\lt \varepsilon\lt 0.12330156\ldots`$ | $`\Theta(M^{1/2})`$ | +| $`0.00064456\ldots\lt \varepsilon\lt 0.01029531\ldots`$ | $`\Theta(M^{2/3})`$ | Endpoint equalities are not covered. These decimal values illustrate the analytically defined thresholds; numerical grids are not the proof. ## Why collective quantum processing cannot remove the cost -For the lower bound, choose loss distributions that match through degree $k-1$ but have a tilted-risk gap greater than $\varepsilon$. Draw latent loss parameters independently at each context and freeze them. One world makes the first coordinate better; the other swaps the coordinate priors. +For the lower bound, choose loss distributions that match through degree $`k-1`$ but have a tilted-risk gap greater than $`\varepsilon`$. Draw latent loss parameters independently at each context and freeze them. One world makes the first coordinate better; the other swaps the coordinate priors. -For a diagonal qubit $\tau_u$, every entry of $\tau_u^{\otimes s}$ is a polynomial of degree at most $s$ in $u$. Until a context occurs $k$ times, moment matching therefore makes the **complete prior-averaged training state** identical between the two worlds. This is stronger than saying the learner's chosen measurement has equal mean. +For a diagonal qubit $`\tau_u`$, every entry of $`\tau_u^{\otimes s}`$ is a polynomial of degree at most $`s`$ in $`u`$. Until a context occurs $`k`$ times, moment matching therefore makes the **complete prior-averaged training state** identical between the two worlds. This is stronger than saying the learner's chosen measurement has equal mean. -With $n$ passive draws, a union bound gives +With $`n`$ passive draws, a union bound gives $$ \Pr[\text{some context appears at least }k\text{ times}] \le {n\choose k}M^{1-k}. $$ -Below the scale $M^{1-1/k}$, the two full input states are almost indistinguishable. Watrous's binary discrimination theorem then limits every possible final hypothesis choice, including one produced by collective measurements and adaptive processing. Concentration of the frozen-table risks makes the preferred hypotheses genuinely opposite with high prior probability. Averaging any claimed guarantee over these fixed-table priors yields a contradiction. The source is fixed after its initial draw; the construction does not redraw its hidden parameters on each visit. +Below the scale $`M^{1-1/k}`$, the two full input states are almost indistinguishable. Watrous's binary discrimination theorem then limits every possible final hypothesis choice, including one produced by collective measurements and adaptive processing. Concentration of the frozen-table risks makes the preferred hypotheses genuinely opposite with high prior probability. Averaging any claimed guarantee over these fixed-table priors yields a contradiction. The source is fixed after its initial draw; the construction does not redraw its hidden parameters on each visit. ## Why the same power is sufficient -For one hypothesis at a time, measure every arriving specimen immediately and cache its context and loss bit. A batch of order $M^{1-1/k}$ draws contains a $k$-fold repeat with probability bounded away from zero. Select a repeated context using only its labels, symmetrically across labels, and retain its first $k$ outcomes. +For one hypothesis at a time, measure every arriving specimen immediately and cache its context and loss bit. A batch of order $`M^{1-1/k}`$ draws contains a $`k`$-fold repeat with probability bounded away from zero. Select a repeated context using only its labels, symmetrically across labels, and retain its first $`k`$ outcomes. -Uniform context sampling makes the selected context exactly uniform. Independent successful batches give independent effective repeated-context examples. A degree-$k$ envelope can be estimated by products of their loss bits. Its coefficients may be signed; boundedness permits statistical estimation even though the estimator is not a binary effect. +Uniform context sampling makes the selected context exactly uniform. Independent successful batches give independent effective repeated-context examples. A degree-$`k`$ envelope can be estimated by products of their loss bits. Its coefficients may be signed; boundedness permits statistical estimation even though the estimator is not a binary effect. -Minimizing the estimated envelope surrogate loses at most $\Gamma_k(a)$ plus statistical slack. The strict inequality $\Gamma_k(a)<\varepsilon$ leaves room for that slack. A fixed number of independent batches, with their failures included in $\delta$, proves the matching fixed-budget upper bound. [The passive proof](../science/passive_frontier.md) gives the extraction and concentration details. +Minimizing the estimated envelope surrogate loses at most $`\Gamma_k(a)`$ plus statistical slack. The strict inequality $`\Gamma_k(a)\lt \varepsilon`$ leaves room for that slack. A fixed number of independent batches, with their failures included in $`\delta`$, proves the matching fixed-budget upper bound. [The passive proof](../science/passive_frontier.md) gives the extraction and concentration details. ## Replay and the meaning of the resource -If the source can deliberately prepare $k$ independent copies at a sampled context, the learner obtains effective groups directly. For fixed tolerance above $\Gamma_k(a)$, the number of groups can be independent of $M$. Every initial and repeated specimen is still charged. This capability is independent preparation from the source, not cloning a received unknown state. +If the source can deliberately prepare $`k`$ independent copies at a sampled context, the learner obtains effective groups directly. For fixed tolerance above $`\Gamma_k(a)`$, the number of groups can be independent of $`M`$. Every initial and repeated specimen is still charged. This capability is independent preparation from the source, not cloning a received unknown state. -Random replica depth is another interface choice. With $K\sim\operatorname{Poisson}(a)$, the loss-bit product has mean $e^{a(\ell_h(x)-1)}$. The identity is inherited Bernoulli-factory machinery. If a natural arrival always prepares an initial specimen, the physical count is $\max\{1,K\}$, with mean $a+e^{-a}$, rather than $a$. A finite expected count with an unbounded tail is different from a deterministic cap. +Random replica depth is another interface choice. With $`K\sim\mathrm{Poisson}(a)`$, the loss-bit product has mean $`e^{a(\ell_h(x)-1)}`$. The identity is inherited Bernoulli-factory machinery. If a natural arrival always prepares an initial specimen, the physical count is $`\max\{1,K\}`$, with mean $`a+e^{-a}`$, rather than $`a`$. A finite expected count with an unbounded tail is different from a deterministic cap. The [resource account](../science/replay_and_resources.md) also charges discarded passive arrivals, classical caches, measurement circuits and any quantum waiting memory. ## What the result establishes -This is a quantum-data access theorem with a classical statistical core. Commuting states already force the lower bound, and immediate individual measurements attain the support exponent for fixed $H$. It establishes no quantum processing advantage or general runtime speedup. +This is a quantum-data access theorem with a classical statistical core. Commuting states already force the lower bound, and immediate individual measurements attain the support exponent for fixed $`H`$. It establishes no quantum processing advantage or general runtime speedup. The PAC requirement concerns the excess of the hypothesis actually returned. Expected regret is a different criterion and has a different sharp moment-limited factor. Improper predictions outside the supplied class, nonuniform contexts, evolving or smooth state tables, critical threshold equalities and joint parameter limits require separate analysis. diff --git a/references/related_work.md b/references/related_work.md index 78b58c1..3a9ab49 100644 --- a/references/related_work.md +++ b/references/related_work.md @@ -1,6 +1,6 @@ # Related work and scope of the comparison -The result studied here is an accuracy-dependent sample law for **proper selection from a fixed finite hypothesis class**, with passive examples from a fixed, arbitrary conditional-state table on a known uniform support of size $M$. For fixed $a,\epsilon,H,\delta$, the strict interval $\Gamma_k(a)<\epsilon<\Gamma_{k-1}(a)$ determines the exponent $M^{1-1/k}$. The lower bound permits arbitrary collective quantum processing; a procedure that measures arrivals individually already achieves this support exponent for fixed $H$. +The result studied here is an accuracy-dependent sample law for **proper selection from a fixed finite hypothesis class**, with passive examples from a fixed, arbitrary conditional-state table on a known uniform support of size $`M`$. For fixed $`a,\epsilon,H,\delta`$, the strict interval $`\Gamma_k(a)\lt \epsilon\lt \Gamma_{k-1}(a)`$ determines the exponent $`M^{1-1/k}`$. The lower bound permits arbitrary collective quantum processing; a procedure that measures arrivals individually already achieves this support exponent for fixed $`H`$. The moment duality, polynomial-copy correspondence, collision exponents, and distinction between passive data and repeated observations all have substantial precedents. The contribution claimed here is their precise connection to the **proper tilted-risk decision** and its accuracy thresholds in this source model. This is a focused comparison, not a claim that the underlying methods or the general need for repeated observations are new. @@ -9,7 +9,7 @@ The moment duality, polynomial-copy correspondence, collision exponents, and dis | Primary source | Established result used in the comparison | Relationship to this account | | --- | --- | --- | | Fanizza, Quek and Rosati, [*Learning Quantum Processes Without Input Control*](https://doi.org/10.1103/PRXQuantum.5.020367), PRX Quantum **5**, 020367 (2024), Theorems 1, 4 and 10 | Learns projector-valued hypotheses from random classical inputs and quantum outputs without chosen-input access. Its finite-list selector handles known projector lists on nonidentical product examples, with dimension-independent quantum sample bounds. | This supplies an optional quantum ERM component after effective repeated-context examples have been constructed. Its projector loss is linear in the conditional state. The support-dependent cost of obtaining the nonlinear conditional information is an additional step. Their other learning results, including trace-distance guarantees, are not ruled out by the present lower bound. | -| Qiu, Pira and Rebentrost, [*Quantum learning with tunable loss functions*](https://doi.org/10.1038/s41534-026-01259-2), npj Quantum Information **12**, 131 (2026), access description, Eqs. (4), (10), and Theorems 1–2 | Studies tilted quantum learning while disallowing requests for repeated copies of a particular sampled conditional state. The published Theorem 1 imposes the small-tilt condition $\lvert\gamma\rvert\leq\epsilon$; its subsequent learnability statements also tie tilt to the stated tolerance. | The present fixed-tilt accuracy frontier calibrates the additional information needed when resolving nonlinear risk more finely. It does **not** contradict the published theorem in its stated small-tilt regime. Their convention tilts acceptance probability; positive tilt of our loss $1-p$ corresponds to negative acceptance tilt. | +| Qiu, Pira and Rebentrost, [*Quantum learning with tunable loss functions*](https://doi.org/10.1038/s41534-026-01259-2), npj Quantum Information **12**, 131 (2026), access description, Eqs. (4), (10), and Theorems 1–2 | Studies tilted quantum learning while disallowing requests for repeated copies of a particular sampled conditional state. The published Theorem 1 imposes the small-tilt condition $`\lvert\gamma\rvert\leq\epsilon`$; its subsequent learnability statements also tie tilt to the stated tolerance. | The present fixed-tilt accuracy frontier calibrates the additional information needed when resolving nonlinear risk more finely. It does **not** contradict the published theorem in its stated small-tilt regime. Their convention tilts acceptance probability; positive tilt of our loss $`1-p`$ corresponds to negative acceptance tilt. | | McGinley, [*Postselection-Free Learning of Measurement-Induced Quantum Dynamics*](https://doi.org/10.1103/PRXQuantum.5.020347), PRX Quantum **5**, 020347 (2024), Secs. III A–B | Explains the no-coincidence obstruction: measurement statistics from singly observed conditional states access linear ensemble functionals. Develops quantum–classical correlators and bounds on nonlinear properties using classical descriptions. | The basic obstruction is prior work. Here it is quantified by an exact sequence of tilted-risk tolerances and the corresponding uniform-context collision exponents. The theorem concerns arbitrary unknown tables; it does not exclude useful nonlinear-property bounds when additional descriptions or structure are available. | | Du, Cheng, Zhao, Ma and Yuan, [*No cloning of quantum ensembles*](https://doi.org/10.1038/s41467-026-74924-x), Nature Communications **17**, 8052 (2026), Theorems 1–3 | Theorem 1 gives exponential sample hardness for ensemble cloning and certain nonlinear ensemble observables, even with copies of an unknown purification and arbitrary collective processing. Theorem 2 gives a contrasting bounded-preparation-complexity result. | Their access is stronger and their target is different. The present result is a narrower, unconditional passive-data law for choosing among specified hypotheses, with an explicit accuracy staircase. It is not a strengthening of their general no-cloning theorem or a computational-hardness result. | @@ -19,24 +19,24 @@ These comparisons concern the access models and theorem scopes of the published | Primary source | Relevant established mechanism | Exact boundary of the present comparison | | --- | --- | --- | -| Frongillo, Mehta, Morgan and Waggoner, [*Multi-Observation Regression*](https://proceedings.mlr.press/v89/frongillo19a.html), AISTATS 2019, Secs. 2–5 and Theorems 1–3 | Learns higher-order conditional targets from ordinary examples by constructing multi-observation examples from nearby inputs. Explicitly distinguishes passive or pool-based access from fully active access permitting repeated labels at a chosen input. | Its main regression results use regularity assumptions on conditional distributions over continuous inputs. Our source is an arbitrary fixed table with a known uniform finite support. The inspected results do not state the $\Gamma_k(a)$-indexed strict-accuracy staircase for proper finite-class selection; they already establish the broader conditional-learning and repeated-observation viewpoint. | +| Frongillo, Mehta, Morgan and Waggoner, [*Multi-Observation Regression*](https://proceedings.mlr.press/v89/frongillo19a.html), AISTATS 2019, Secs. 2–5 and Theorems 1–3 | Learns higher-order conditional targets from ordinary examples by constructing multi-observation examples from nearby inputs. Explicitly distinguishes passive or pool-based access from fully active access permitting repeated labels at a chosen input. | Its main regression results use regularity assumptions on conditional distributions over continuous inputs. Our source is an arbitrary fixed table with a known uniform finite support. The inspected results do not state the $`\Gamma_k(a)`$-indexed strict-accuracy staircase for proper finite-class selection; they already establish the broader conditional-learning and repeated-observation viewpoint. | | Casalaina-Martin, Frongillo, Morgan and Waggoner, [*Multi-Observation Elicitation*](https://proceedings.mlr.press/v65/casalaina-martin17a.html), COLT 2017, Definitions 2 and 5, Theorem 7, Corollaries 10 and 13 | Formalizes losses receiving several independent outcomes from the same distribution and proves tradeoffs between observation count and report dimension. Polynomial properties and variance give basic examples. | An observation hierarchy is inherited. Our proper decision has two actions in the lower-bound construction and a nonzero error tolerance; its thresholds are expectation-ratio gaps, rather than polynomial degree alone or exact elicitation complexity. | -| Adibi and Krysta, [*Optimal Rényi and Logarithmic Additive Functional Entropy Estimation*](https://arxiv.org/abs/2610.28999), arXiv:2610.28999v1 (2026), Appendix I, Theorem I.1 and Corollary I.2 | Gives exact weighted relative-approximation duality: an annihilating signed measure yields matching-moment probability laws with expectation ratio $(1+d)/(1-d)$. | This is the scalar duality behind the two equivalent definitions of $\Gamma_r(a)$; it is explicitly inherited. The additional steps here are the two-action quantum-state embedding, concentration for a frozen finite table, and matching passive-context extraction. | +| Adibi and Krysta, [*Optimal Rényi and Logarithmic Additive Functional Entropy Estimation*](https://arxiv.org/abs/2610.28999), arXiv:2610.28999v1 (2026), Appendix I, Theorem I.1 and Corollary I.2 | Gives exact weighted relative-approximation duality: an annihilating signed measure yields matching-moment probability laws with expectation ratio $`(1+d)/(1-d)`$. | This is the scalar duality behind the two equivalent definitions of $`\Gamma_r(a)`$; it is explicitly inherited. The additional steps here are the two-action quantum-state embedding, concentration for a frozen finite table, and matching passive-context extraction. | -Adibi–Krysta's main Theorem 2.2 concerns a fixed scalar function with a specified leading power at zero. It should not simply be substituted for the present theorem: writing the classical diagonal witness as $q_{x,1}=p_x/M$ makes its target involve $e^{aM q_{x,1}}$, with a known uniform context marginal and an $M$-dependent rescaling. This observation identifies a difference in the stated models; it is not a claim that classical functional-estimation methods cannot prove the present law. +Adibi–Krysta's main Theorem 2.2 concerns a fixed scalar function with a specified leading power at zero. It should not simply be substituted for the present theorem: writing the classical diagonal witness as $`q_{x,1}=p_x/M`$ makes its target involve $`e^{aM q_{x,1}}`$, with a known uniform context marginal and an $`M`$-dependent rescaling. This observation identifies a difference in the stated models; it is not a claim that classical functional-estimation methods cannot prove the present law. Other methodological ancestors are important. Tian, Kong and Valiant's [*Learning Populations of Parameters*](https://arxiv.org/abs/1709.02707) (NeurIPS 2017) develops moment-based inference for populations of coins observed several times. Acharya, Orlitsky, Suresh and Tyagi's [*The Complexity of Estimating Rényi Entropy*](https://arxiv.org/abs/1408.1000) gives the familiar integer-order collision exponent. Brun's [*Measuring Polynomial Functions of States*](https://arxiv.org/abs/quant-ph/0401067) establishes the use of several copies to measure polynomial state functionals. None of these ingredients is presented here as a new quantum effect. -Similarly, Poisson repetition gives the standard identity $\mathbb E[p^K]=e^{a(p-1)}$ for $K\sim\mathrm{Poisson}(a)$. Bernoulli-factory constructions and their use in exponential transformations predate this account; see Dughmi, Hartline, Kleinberg and Niazadeh, [*Bernoulli Factories and Black-Box Reductions in Mechanism Design*](https://arxiv.org/abs/1703.04143). A random repetition count with finite expectation must be distinguished from a deterministic maximum number of copies per context. +Similarly, Poisson repetition gives the standard identity $`\mathbb E[p^K]=e^{a(p-1)}`$ for $`K\sim\mathrm{Poisson}(a)`$. Bernoulli-factory constructions and their use in exponential transformations predate this account; see Dughmi, Hartline, Kleinberg and Niazadeh, [*Bernoulli Factories and Black-Box Reductions in Mechanism Design*](https://arxiv.org/abs/1703.04143). A random repetition count with finite expectation must be distinguished from a deterministic maximum number of copies per context. ## Public related source-model analyses -The public [Quantum-Example-Entropy frozen-source analysis](https://github.com/GoGoKo699/Quantum-Example-Entropy/blob/d1077fac179d33972a63f57d60d54b822721b328/science/frozen_sources.md), Theorem S1, supplies a related frozen-table mechanism. Its coherent-example simulation error includes the address-collision term $\binom{T}{2}\sum_x p_x^2$, alongside a label-collision term. The present result uses higher occupancy levels and moment twins to determine a proper nonlinear-risk decision threshold. The two tasks and access models differ; the frozen-source and collision reasoning are material prior context. +The public [Quantum-Example-Entropy frozen-source analysis](https://github.com/GoGoKo699/Quantum-Example-Entropy/blob/d1077fac179d33972a63f57d60d54b822721b328/science/frozen_sources.md), Theorem S1, supplies a related frozen-table mechanism. Its coherent-example simulation error includes the address-collision term $`\binom{T}{2}\sum_x p_x^2`$, alongside a label-collision term. The present result uses higher occupancy levels and moment twins to determine a proper nonlinear-risk decision threshold. The two tasks and access models differ; the frozen-source and collision reasoning are material prior context. -The public [Quantum-Trajectory-Cloning-Cost analysis](https://github.com/GoGoKo699/Quantum-Trajectory-Cloning-Cost/blob/94798b20a91637dbbed6ddfb0b9d0dd92560040e/science/analysis.md) proves a repeat-label protocol with $M+1$ expected source copies that produces two conditional states while preserving the original label law. That full-output requirement differs from scalar risk selection and from uniformly selecting a repeated context. Its proposed matching lower bound and known-assignment separation are explicitly marked unverified there and are not used as established results here. +The public [Quantum-Trajectory-Cloning-Cost analysis](https://github.com/GoGoKo699/Quantum-Trajectory-Cloning-Cost/blob/94798b20a91637dbbed6ddfb0b9d0dd92560040e/science/analysis.md) proves a repeat-label protocol with $`M+1`$ expected source copies that produces two conditional states while preserving the original label law. That full-output requirement differs from scalar risk selection and from uniformly selecting a repeated context. Its proposed matching lower bound and known-assignment separation are explicitly marked unverified there and are not used as established results here. ## Scope and limitation -The strongest limitation is the classical core of the lower-bound example. Commuting two-qubit states already force the staircase, and separate measurements attain its support exponent for fixed $H$. The result therefore concerns the information supplied by the source and the precision of the learning objective. It establishes no quantum processing advantage, no new general collision exponent, and no unrestricted learnability obstruction for all nonlinear quantum losses. +The strongest limitation is the classical core of the lower-bound example. Commuting two-qubit states already force the staircase, and separate measurements attain its support exponent for fixed $`H`$. The result therefore concerns the information supplied by the source and the precision of the learning objective. It establishes no quantum processing advantage, no new general collision exponent, and no unrestricted learnability obstruction for all nonlinear quantum losses. -The comparison is restricted to the sources and theorem locations identified above. [BibTeX records](bibliography.bib) give structured citations for the principal external sources. Critical accuracies $\epsilon=\Gamma_r(a)$, nonuniform context laws, smooth conditional-state families, and joint limits in class size, tilt, precision or degree require additional analysis. +The comparison is restricted to the sources and theorem locations identified above. [BibTeX records](bibliography.bib) give structured citations for the principal external sources. Critical accuracies $`\epsilon=\Gamma_r(a)`$, nonuniform context laws, smooth conditional-state families, and joint limits in class size, tilt, precision or degree require additional analysis. diff --git a/science/README.md b/science/README.md index 78e01ca..eb113b7 100644 --- a/science/README.md +++ b/science/README.md @@ -3,7 +3,7 @@ The problem is to select a known measurement hypothesis by a nonlinear risk from passive classical–quantum examples. The same input context need not recur quickly, and the learner cannot request a fresh specimen at a chosen context. 1. [Model and precise task](model.md): source, hypotheses, loss convention, proper selection, accuracy and resource definitions. -2. [Moment frontier](moment_frontier.md): the exact thresholds $\Gamma_r$, inherited polynomial duality, explicit first threshold and limiting behavior. +2. [Moment frontier](moment_frontier.md): the exact thresholds $`\Gamma_r`$, inherited polynomial duality, explicit first threshold and limiting behavior. 3. [Passive frontier](passive_frontier.md): the matching fixed-parameter exponent, quantum indistinguishability lower bound and collision-based upper bound. 4. [Replay and resources](replay_and_resources.md): what a repeatable source supplies, how measurements implement the surrogate loss, and which preparation, storage and circuit costs remain. 5. [Interpretation](interpretation.md): scientific consequence, examples and limits. diff --git a/science/interpretation.md b/science/interpretation.md index 898332a..82297dc 100644 --- a/science/interpretation.md +++ b/science/interpretation.md @@ -3,7 +3,7 @@ The learning objective determines which features of a quantum-data source must be accessible. For a known projector-valued hypothesis, write $$ -\ell_h(x)=1-\operatorname{Tr}[\Pi_h(x)\rho(x)],\qquad +\ell_h(x)=1-\mathrm{Tr}[\Pi_h(x)\rho(x)],\qquad R_a(h)=\frac1a\log\mathbb E_x e^{a\ell_h(x)},\qquad a>0. $$ @@ -11,9 +11,9 @@ Ordinary mean loss depends linearly on each conditional state. Tilted risk also ## Accuracy determines the required repetition level -Let $\Gamma_r(a)$ be the largest $a^{-1}$-scaled log expectation-ratio gap between probability laws on $[0,1]$ whose moments through degree $r$ agree, as defined in [the moment frontier](moment_frontier.md). Equivalently, it is the smallest $a^{-1}$-scaled logarithmic multiplicative error of a degree-$r$ polynomial envelope of $e^{ap}$. These are inherited approximation-theoretic descriptions of the same scalar quantity. +Let $`\Gamma_r(a)`$ be the largest $`a^{-1}`$-scaled log expectation-ratio gap between probability laws on $`[0,1]`$ whose moments through degree $`r`$ agree, as defined in [the moment frontier](moment_frontier.md). Equivalently, it is the smallest $`a^{-1}`$-scaled logarithmic multiplicative error of a degree-$`r`$ polynomial envelope of $`e^{ap}`$. These are inherited approximation-theoretic descriptions of the same scalar quantity. -For every fixed integer $k\geq1$, the strict interval +For every fixed integer $`k\geq1`$, the strict interval $$ \Gamma_k(a)<\epsilon<\Gamma_{k-1}(a) @@ -25,21 +25,21 @@ $$ N_{\min}(M)=\Theta_{a,\epsilon,H,\delta}\!\left(M^{1-1/k}\right). $$ -Here the input distribution is uniform on a known $M$-point support, the conditional-state table is unknown and fixed, the finite class size $H\geq2$ and failure probability $0<\delta<1/2$ are fixed, and $M$ grows. The upper bound holds for each fixed finite class. The lower bound is witnessed by a particular two-hypothesis class on a four-dimensional output space; it is not a lower bound for every class. +Here the input distribution is uniform on a known $`M`$-point support, the conditional-state table is unknown and fixed, the finite class size $`H\geq2`$ and failure probability $`0\lt \delta\lt 1/2`$ are fixed, and $`M`$ grows. The upper bound holds for each fixed finite class. The lower bound is witnessed by a particular two-hypothesis class on a four-dimensional output space; it is not a lower bound for every class. -For example, at $a=1$, the first thresholds give the following strict intervals. Decimal values are numerical evaluations, not exact endpoint statements. +For example, at $`a=1`$, the first thresholds give the following strict intervals. Decimal values are numerical evaluations, not exact endpoint statements. | Excess-risk tolerance | Needed collision level | Dependence on support size | | --- | --- | --- | -| $0.12330156\ldots<\epsilon<1$ | One observation per effective example | $\Theta(1)$ | -| $0.01029531\ldots<\epsilon<0.12330156\ldots$ | Two observations of one context | $\Theta(M^{1/2})$ | -| $0.00064456\ldots<\epsilon<0.01029531\ldots$ | Three observations of one context | $\Theta(M^{2/3})$ | +| $`0.12330156\ldots\lt \epsilon\lt 1`$ | One observation per effective example | $`\Theta(1)`$ | +| $`0.01029531\ldots\lt \epsilon\lt 0.12330156\ldots`$ | Two observations of one context | $`\Theta(M^{1/2})`$ | +| $`0.00064456\ldots\lt \epsilon\lt 0.01029531\ldots`$ | Three observations of one context | $`\Theta(M^{2/3})`$ | -The exponent changes because a new moment becomes necessary to separate decisions at the requested accuracy. A $k$-fold repeated context first becomes available at the scale $M^{1-1/k}$. A polynomial envelope shows that this much conditional information is sufficient, up to the strict accuracy margin. Matching moments show it is necessary in the worst case. Constants can grow strongly as a tolerance approaches a threshold; the theorem does not locate finite-$M$ crossover points. +The exponent changes because a new moment becomes necessary to separate decisions at the requested accuracy. A $`k`$-fold repeated context first becomes available at the scale $`M^{1-1/k}`$. A polynomial envelope shows that this much conditional information is sufficient, up to the strict accuracy margin. Matching moments show it is necessary in the worst case. Constants can grow strongly as a tolerance approaches a threshold; the theorem does not locate finite-$`M`$ crossover points. ## The target is a nonlinear function of a probability -A single projector measurement gives a Bernoulli loss outcome $B$ with conditional mean $\ell_h(x)$. Exponentiating that outcome does not give an unbiased observation of the target exponential: +A single projector measurement gives a Bernoulli loss outcome $`B`$ with conditional mean $`\ell_h(x)`$. Exponentiating that outcome does not give an unbiased observation of the target exponential: $$ \mathbb E[e^{aB}\mid x] @@ -62,7 +62,7 @@ At tolerances above this threshold, first-moment information is enough for prope ## Replay changes source access -Chosen-input replay supplies fresh preparations of the same conditional state. It permits direct construction of the repeated-context observations without waiting for passive collisions, removing the support-size dependence for fixed parameters. It does not manufacture copies of an unknown received state. A hard cap of $r$ preparations per context and an unbounded random count with finite expectation are also different resources; [replay and resources](replay_and_resources.md) keeps them separate. +Chosen-input replay supplies fresh preparations of the same conditional state. It permits direct construction of the repeated-context observations without waiting for passive collisions, removing the support-size dependence for fixed parameters. It does not manufacture copies of an unknown received state. A hard cap of $`r`$ preparations per context and an unbounded random count with finite expectation are also different resources; [replay and resources](replay_and_resources.md) keeps them separate. Uniform contexts play a substantive role in the passive upper bound. A context-label-symmetric collision rule selects an exactly uniform repeated context. Independent batches therefore yield independent effective examples for every fixed state table. For a nonuniform law, ordinary collision selection reweights a context according to a higher power of its probability, so this argument does not transfer unchanged. @@ -72,6 +72,6 @@ Every consumed source output is counted, including samples that do not contribut The model allows quantum outputs, incompatible hypothesis measurements, and arbitrary collective processing. The lower bound excludes a collective quantum shortcut around the need for repeated contexts. Its witness nevertheless uses commuting two-qubit states, so the obstruction already exists in a classical population of conditional Bernoulli variables. -For a fixed finite class, one can allocate independent sample batches to hypotheses, measure every arrival immediately, and keep classical context/outcome records until suitable repetitions appear. This achieves the same power of $M$ as the quantum upper bound. Collective quantum ERM can be an additional tool for class-size dependence, but that ingredient and its guarantees are inherited. No quantum processing speedup is claimed for the support-size staircase. +For a fixed finite class, one can allocate independent sample batches to hypotheses, measure every arrival immediately, and keep classical context/outcome records until suitable repetitions appear. This achieves the same power of $`M`$ as the quantum upper bound. Collective quantum ERM can be an additional tool for class-size dependence, but that ingredient and its guarantees are inherited. No quantum processing speedup is claimed for the support-size staircase. The exact statement is limited to proper selection, fixed parameters, arbitrary fixed tables, and strict intervals between adjacent thresholds. It does not settle critical equality cases, unrestricted improper prediction, nonuniform or smooth sources, or simultaneous limits in tilt, accuracy, class size and moment degree. Its practical consequence is a quantitative choice: resolve a nonlinear risk only to a tolerance supported by the available conditional information, obtain the required passive repetitions, or explicitly provide replay or additional source structure. diff --git a/science/model.md b/science/model.md index 6bdb613..9359345 100644 --- a/science/model.md +++ b/science/model.md @@ -6,7 +6,7 @@ The objective is a nonlinear function of a conditional Born probability. This di ## 1. Source and hypotheses -Let $M\geq 1$, let $\mathsf Q\cong\mathbb C^d$ be a finite-dimensional quantum register, and write $[M]=\{1,\ldots,M\}$. An unknown source is a fixed table +Let $`M\geq 1`$, let $`\mathsf Q\cong\mathbb C^d`$ be a finite-dimensional quantum register, and write $`[M]=\{1,\ldots,M\}`$. An unknown source is a fixed table $$ \rho:[M]\longrightarrow\mathcal D(\mathsf Q),\qquad x\longmapsto\rho_x. @@ -18,7 +18,7 @@ $$ \Omega_\rho=\frac1M\sum_{x=1}^M |x\rangle\langle x|\otimes\rho_x. $$ -Training data consist of $n$ independent copies of $\Omega_\rho$. Equivalently, $X_1,\ldots,X_n$ are IID uniform on $[M]$, and, conditional on their labels, the supplied quantum state is +Training data consist of $`n`$ independent copies of $`\Omega_\rho`$. Equivalently, $`X_1,\ldots,X_n`$ are IID uniform on $`[M]`$, and, conditional on their labels, the supplied quantum state is $$ \rho_{X_1}\otimes\cdots\otimes\rho_{X_n}. @@ -26,31 +26,31 @@ $$ The table is fixed throughout the experiment. If a label reappears, the source supplies an independent copy of that label's same conditional state. Mixed states are allowed. No preparation circuit, purification, coherent source oracle, or chosen-input interface is supplied. -The learner knows $M$ and a finite hypothesis class +The learner knows $`M`$ and a finite hypothesis class $$ \mathcal H=\{h_1,\ldots,h_m\},\qquad 1\leq m\leq H,\quad H\geq2. $$ -Here $H$ is the fixed class-size cap; $m$ is the size of the supplied class. Each hypothesis specifies known projectors $\Pi_h(x)$ on $\mathsf Q$. Its conditional loss is +Here $`H`$ is the fixed class-size cap; $`m`$ is the size of the supplied class. Each hypothesis specifies known projectors $`\Pi_h(x)`$ on $`\mathsf Q`$. Its conditional loss is $$ -\ell_h(x)=1-\operatorname{Tr}\!\left(\Pi_h(x)\rho_x\right)\in[0,1]. +\ell_h(x)=1-\mathrm{Tr}\!\left(\Pi_h(x)\rho_x\right)\in[0,1]. $$ This is agnostic learning: the unknown table need not belong to the hypothesis class. The lower bounds use constant projectors on a fixed number of qubits, so they do not rely on difficult hypothesis evaluation or a growing quantum output dimension. ## 2. Tilted population risk -Fix a positive tilt $a>0$. The canonical risk is +Fix a positive tilt $`a>0`$. The canonical risk is $$ R_a(h;\rho)=\frac1a\log\left(\frac1M\sum_{x=1}^M e^{a\ell_h(x)}\right). $$ -The task is to minimize this quantity over $h\in\mathcal H$. It lies in $[0,1]$. As $a\to0$, it tends to the mean loss $M^{-1}\sum_x\ell_h(x)$; a positive tilt gives more weight to contexts with larger conditional loss. +The task is to minimize this quantity over $`h\in\mathcal H`$. It lies in $`[0,1]`$. As $`a\to0`$, it tends to the mean loss $`M^{-1}\sum_x\ell_h(x)`$; a positive tilt gives more weight to contexts with larger conditional loss. -Let $Y_h\in\{0,1\}$ be the loss outcome obtained by measuring $\{\Pi_h(x),I-\Pi_h(x)\}$ on one copy at context $x$, with $Y_h=1$ for the second outcome. Then +Let $`Y_h\in\{0,1\}`$ be the loss outcome obtained by measuring $`\{\Pi_h(x),I-\Pi_h(x)\}`$ on one copy at context $`x`$, with $`Y_h=1`$ for the second outcome. Then $$ \mathbb E[Y_h\mid X=x]=\ell_h(x). @@ -63,19 +63,19 @@ $$ =1+(e^a-1)\mathbb E[\ell_h(X)], $$ -whereas the desired exponential mean is $\mathbb E[e^{a\ell_h(X)}]$. Replacing the conditional mean by one observed outcome therefore changes the learning objective. +whereas the desired exponential mean is $`\mathbb E[e^{a\ell_h(X)}]`$. Replacing the conditional mean by one observed outcome therefore changes the learning objective. -All main statements use $a>0$. For comparison with a signed tilt $\gamma$, the identity +All main statements use $`a>0`$. For comparison with a signed tilt $`\gamma`$, the identity $$ R_{-a}(\ell)=1-R_a(1-\ell) $$ -converts minimization at negative tilt into maximization of the complemented positive-tilt risk. Reflection $u\mapsto1-u$ leaves the distortion constants in [the moment frontier](moment_frontier.md) unchanged. The direction of optimization must still be reversed when using this identity. +converts minimization at negative tilt into maximization of the complemented positive-tilt risk. Reflection $`u\mapsto1-u`$ leaves the distortion constants in [the moment frontier](moment_frontier.md) unchanged. The direction of optimization must still be reversed when using this identity. ## 3. Learning guarantee and quantifiers -A learner is **proper**: on each run it outputs an index $\widehat h\in\mathcal H$. It may use arbitrary classical computation, classical randomness, ancillary systems initially independent of the source, and any collective quantum measurement on all supplied examples. There is no restriction to local measurements or to a bounded number of jointly processed copies. +A learner is **proper**: on each run it outputs an index $`\widehat h\in\mathcal H`$. It may use arbitrary classical computation, classical randomness, ancillary systems initially independent of the source, and any collective quantum measurement on all supplied examples. There is no restriction to local measurements or to a bounded number of jointly processed copies. The excess risk of its realized output is @@ -84,25 +84,25 @@ $$ =R_a(\widehat h;\rho)-\min_{h\in\mathcal H}R_a(h;\rho). $$ -An $(\epsilon,\delta)$ guarantee means +An $`(\epsilon,\delta)`$ guarantee means $$ \Pr\!\left[\mathcal E_a(\widehat h;\rho)\leq\epsilon\right]\geq1-\delta $$ -for every fixed source table $\rho$. Probability is over the sampled labels, measurement outcomes, and learner randomness. +for every fixed source table $`\rho`$. Probability is over the sampled labels, measurement outcomes, and learner randomness. -For a specified class and dimension, let $N^*(M,\mathcal H,d;a,\epsilon,\delta)$ be the least number of passive examples permitting this guarantee. The worst-case finite-class copy complexity is +For a specified class and dimension, let $`N^{*}(M,\mathcal H,d;a,\epsilon,\delta)`$ be the least number of passive examples permitting this guarantee. The worst-case finite-class copy complexity is $$ -\mathsf N^*(M;a,H,\epsilon,\delta) +\mathsf N^{*}(M;a,H,\epsilon,\delta) =\sup_{d,\,\mathcal H:\,1\leq|\mathcal H|\leq H} -N^*(M,\mathcal H,d;a,\epsilon,\delta). +N^{*}(M,\mathcal H,d;a,\epsilon,\delta). $$ -The algorithm may depend on the known class, $M$, and the displayed parameters. In support-size asymptotics, $a,H,\epsilon,\delta$ are fixed and $M\to\infty$. Constants may depend on those fixed parameters. The sharp exponent statements concern $0<\delta<1/2$ and errors strictly between successive moment-frontier values; they do not assert endpoint behavior or uniform constants when the tilt, accuracy, or class size also vary. +The algorithm may depend on the known class, $`M`$, and the displayed parameters. In support-size asymptotics, $`a,H,\epsilon,\delta`$ are fixed and $`M\to\infty`$. Constants may depend on those fixed parameters. The sharp exponent statements concern $`0\lt \delta\lt 1/2`$ and errors strictly between successive moment-frontier values; they do not assert endpoint behavior or uniform constants when the tilt, accuracy, or class size also vary. -A support-independent guarantee uses a number of examples bounded independently of $M$. This is a uniform assertion over all finite context supports, not an assertion that a particular finite table remains unidentifiable with infinitely many examples. +A support-independent guarantee uses a number of examples bounded independently of $`M`$. This is a uniform assertion over all finite context supports, not an assertion that a particular finite table remains unidentifiable with infinitely many examples. ### PAC excess and expected regret are different @@ -112,17 +112,17 @@ $$ \mathbb E\!\left[\mathcal E_a(\widehat h;\rho)\right]. $$ -Randomizing between hypotheses can reduce expected regret while leaving a substantial probability of returning a hypothesis with large excess. Consequently, for a class of size $m$ the sharp interval-based expected-regret factor is $1-1/m$; its worst case under the cap is $1-1/H$. The PAC tolerance floor has no such factor. These statements must not be substituted for one another. +Randomizing between hypotheses can reduce expected regret while leaving a substantial probability of returning a hypothesis with large excess. Consequently, for a class of size $`m`$ the sharp interval-based expected-regret factor is $`1-1/m`$; its worst case under the cap is $`1-1/H`$. The PAC tolerance floor has no such factor. These statements must not be substituted for one another. -Returning an arbitrary POVM or a mixture outside $\mathcal H$ is not proper learning. In particular, the nonlinear risk of an averaged measurement need not equal the average of the hypotheses' risks. The results here do not claim lower bounds for that different output model. +Returning an arbitrary POVM or a mixture outside $`\mathcal H`$ is not proper learning. In particular, the nonlinear risk of an averaged measurement need not equal the average of the hypotheses' risks. The results here do not claim lower bounds for that different output model. ## 4. Three access models | Access | What one arrival supplies | What can happen later | | --- | --- | --- | -| Passive single-copy examples | A random $x$ and one $\rho_x$ | The same label may reappear naturally; it cannot be requested. | -| Grouped $r$-copy examples | A random $x$ and $\rho_x^{\otimes r}$ | A later random group may repeat $x$; the learner cannot ask for an extra group there. | -| Context re-preparation | A random $x$ followed by a requested number of independent copies of $\rho_x$ | The requested copies are an additional source capability, and each is charged. | +| Passive single-copy examples | A random $`x`$ and one $`\rho_x`$ | The same label may reappear naturally; it cannot be requested. | +| Grouped $`r`$-copy examples | A random $`x`$ and $`\rho_x^{\otimes r}`$ | A later random group may repeat $`x`$; the learner cannot ask for an extra group there. | +| Context re-preparation | A random $`x`$ followed by a requested number of independent copies of $`\rho_x`$ | The requested copies are an additional source capability, and each is charged. | For grouped access the source state is @@ -130,9 +130,9 @@ $$ \Omega_\rho^{(r)}=\frac1M\sum_{x=1}^M |x\rangle\langle x|\otimes\rho_x^{\otimes r}. $$ -$G$ groups contain $rG$ physical output copies. A cap of $r$ copies **per arrival** is not a cap of $r$ copies over a context's entire lifetime: natural repeated labels can provide more. Accordingly, the grouped-access distortion floor is a support-independent limit. At a fixed finite $M$, sufficiently many random groups can reveal additional information through repeated labels. +$`G`$ groups contain $`rG`$ physical output copies. A cap of $`r`$ copies **per arrival** is not a cap of $`r`$ copies over a context's entire lifetime: natural repeated labels can provide more. Accordingly, the grouped-access distortion floor is a support-independent limit. At a fixed finite $`M`$, sufficiently many random groups can reveal additional information through repeated labels. -Context re-preparation means obtaining fresh copies from a source, not cloning the one already supplied. A protocol with a finite expected number of re-prepared copies and an unbounded copy-count tail is also distinct from a hard cap of $r$ copies per arrival. +Context re-preparation means obtaining fresh copies from a source, not cloning the one already supplied. A protocol with a finite expected number of re-prepared copies and an unbounded copy-count tail is also distinct from a hard cap of $`r`$ copies per arrival. ## 5. Moments and full quantum information @@ -148,22 +148,22 @@ $$ R_a(h;\rho)=\frac1a\log\int_0^1e^{au}\,d\mu_h^\rho(u). $$ -With $r$ copies at one context, measuring the same hypothesis on those copies gives IID conditional Bernoulli losses. For $j\leq r$, +With $`r`$ copies at one context, measuring the same hypothesis on those copies gives IID conditional Bernoulli losses. For $`j\leq r`$, $$ \mathbb E\!\left[\prod_{i=1}^{j}Y_{h,i}\right] =\int_0^1u^j\,d\mu_h^\rho(u). $$ -This provides an upper-bound method using the first $r$ loss moments. The algebraic fact that an $r$-copy observable has an expectation polynomial of degree at most $r$ in the state, and that polynomial state functionals can be represented on multiple copies, is established background; see [Brun (2004)](https://arxiv.org/abs/quant-ph/0401067). +This provides an upper-bound method using the first $`r`$ loss moments. The algebraic fact that an $`r`$-copy observable has an expectation polynomial of degree at most $`r`$ in the state, and that polynomial state functionals can be represented on multiple copies, is established background; see [Brun (2004)](https://arxiv.org/abs/quant-ph/0401067). Equal scalar loss moments alone do **not** imply indistinguishability against arbitrary quantum measurements. The lower bounds require an explicit source construction whose entire averaged tensor-product state agrees whenever every context has limited occupancy. That stronger equality, rather than a restriction on the learner's measurement choice, is what protects the lower bound against collective processing. ## 6. Resources and scope -The primary complexity is the number of passive output copies. Known hypothesis measurements are operations available to the learner; their circuit cost is not claimed to be constant in a generic implementation. If one measurement costs $T_\Pi$ elementary operations, the direct upper construction incurs that cost for every example it measures, in addition to processing and storing its classical labels and outcomes. Hypothesis descriptions, polynomial coefficients, measurement work registers, and classical records are resources of that implementation. +The primary complexity is the number of passive output copies. Known hypothesis measurements are operations available to the learner; their circuit cost is not claimed to be constant in a generic implementation. If one measurement costs $`T_\Pi`$ elementary operations, the direct upper construction incurs that cost for every example it measures, in addition to processing and storing its classical labels and outcomes. Hypothesis descriptions, polynomial coefficients, measurement work registers, and classical records are resources of that implementation. -For fixed class size and fixed frontier parameters, the collision-based upper construction can measure each example immediately and retain only classical data. It needs no QRAM and no coherent source oracle. In a batch of $n$ examples its label-and-outcome storage is $O(n\log M)$ bits, apart from the known measurement implementation and fixed-parameter coefficient precision. A dictionary implementation takes expected $O(n)$ word operations per batch; bit costs depend on the representation of labels and the dictionary used. +For fixed class size and fixed frontier parameters, the collision-based upper construction can measure each example immediately and retain only classical data. It needs no QRAM and no coherent source oracle. In a batch of $`n`$ examples its label-and-outcome storage is $`O(n\log M)`$ bits, apart from the known measurement implementation and fixed-parameter coefficient precision. A dictionary implementation takes expected $`O(n)`$ word operations per batch; bit costs depend on the representation of labels and the dictionary used. The present results concern proper agnostic learning, uniform IID contexts, arbitrary fixed mixed-state output tables, and finite known classes. They do not establish a computational quantum advantage, a claim for every structured or realizable source family, or a bound for nonuniform and temporally drifting context distributions. diff --git a/science/moment_frontier.md b/science/moment_frontier.md index f0172e4..5cebba1 100644 --- a/science/moment_frontier.md +++ b/science/moment_frontier.md @@ -1,10 +1,10 @@ # The moment frontier for tilted risk -The [learning model](model.md) uses positive tilt $a>0$ and per-context losses in $[0,1]$. This page defines a scalar constant that measures the largest tilted-risk ambiguity compatible with the first $r$ moments. It proves its equivalent polynomial formulation and its operational meaning. The polynomial and moment-duality tools are classical; the learning statements use them with an explicit quantum source construction. +The [learning model](model.md) uses positive tilt $`a>0`$ and per-context losses in $`[0,1]`$. This page defines a scalar constant that measures the largest tilted-risk ambiguity compatible with the first $`r`$ moments. It proves its equivalent polynomial formulation and its operational meaning. The polynomial and moment-duality tools are classical; the learning statements use them with an explicit quantum source construction. ## 1. A sharp moment-ratio constant -Let $\mathcal P([0,1])$ denote the probability measures on $[0,1]$, put $f_a(u)=e^{au}$, and let $r\geq0$ be an integer. Define +Let $`\mathcal P([0,1])`$ denote the probability measures on $`[0,1]`$, put $`f_a(u)=e^{au}`$, and let $`r\geq0`$ be an integer. Define $$ \kappa_r(a)= @@ -15,7 +15,7 @@ $$ \Gamma_r(a)=\frac{\log\kappa_r(a)}a. $$ -The order-zero condition records equal mass. Both measures already have mass one, but retaining it makes the linear-program formulation transparent. Swapping $\mu$ and $\nu$ is allowed, so +The order-zero condition records equal mass. Both measures already have mass one, but retaining it makes the linear-program formulation transparent. Swapping $`\mu`$ and $`\nu`$ is allowed, so $$ \Gamma_r(a)= @@ -26,7 +26,7 @@ $$ \right|. $$ -The maximum exists. The space of probability measures on the compact interval is weakly compact; the moment constraints are closed; the exponential integrals are continuous; and the denominator is at least one. In particular, $1\leq\kappa_r(a)\leq e^a$. +The maximum exists. The space of probability measures on the compact interval is weakly compact; the moment constraints are closed; the exponential integrals are continuous; and the denominator is at least one. In particular, $`1\leq\kappa_r(a)\leq e^a`$. The measures can be chosen with finite support. Indeed, the vector @@ -34,19 +34,19 @@ $$ \left(\int u\,d\mu,\ldots,\int u^r\,d\mu,\int f_a\,d\mu\right) $$ -lies in the convex hull of the curve $(u,\ldots,u^r,f_a(u))\in\mathbb R^{r+1}$. Carathéodory's theorem replaces it by a measure on at most $r+2$ points. Applying this separately to an optimal pair preserves its moments and exponential integrals. +lies in the convex hull of the curve $`(u,\ldots,u^r,f_a(u))\in\mathbb R^{r+1}`$. Carathéodory's theorem replaces it by a measure on at most $`r+2`$ points. Applying this separately to an optimal pair preserves its moments and exponential integrals. ## 2. Equivalent positive polynomial envelope -**Theorem 1 — moment ratio and polynomial envelope.** For every $a>0$ and integer $r\geq0$, +**Theorem 1 — moment ratio and polynomial envelope.** For every $`a>0`$ and integer $`r\geq0`$, $$ \kappa_r(a)= -\min\left\{K:\ \exists p\in\mathbb R[u],\ \deg p\leq r, -\quad f_a(u)\leq p(u)\leq Kf_a(u)\quad(0\leq u\leq1)\right\}. +\min\left\lbraceK:\ \exists p\in\mathbb R[u],\ \deg p\leq r, +\quad f_a(u)\leq p(u)\leq Kf_a(u)\quad(0\leq u\leq1)\right\rbrace. $$ -The polynomial minimum is attained. Equivalently, over strictly positive polynomials of degree at most $r$, +The polynomial minimum is attained. Equivalently, over strictly positive polynomials of degree at most $`r`$, $$ \kappa_r(a)= @@ -55,7 +55,7 @@ $$ {\min_{u\in[0,1]}p(u)/f_a(u)}. $$ -**Proof.** First suppose $f_a\leq p\leq Kf_a$ and $\mu,\nu$ match moments through $r$. Then +**Proof.** First suppose $`f_a\leq p\leq Kf_a`$ and $`\mu,\nu`$ match moments through $`r`$. Then $$ \int f_a\,d\mu @@ -66,7 +66,7 @@ $$ Thus every feasible envelope bounds the moment ratio from above. -For the converse, take nested finite sets $G_N\subset[0,1]$ whose union is dense and that all contain $r+1$ fixed distinct points. When $r=0$, one fixed point suffices. On a finite grid, scale a moment-matched pair of probability measures by the reciprocal of its denominator. The ratio problem becomes the finite linear program +For the converse, take nested finite sets $`G_N\subset[0,1]`$ whose union is dense and that all contain $`r+1`$ fixed distinct points. When $`r=0`$, one fixed point suffices. On a finite grid, scale a moment-matched pair of probability measures by the reciprocal of its denominator. The ratio problem becomes the finite linear program $$ \begin{aligned} @@ -77,29 +77,29 @@ $$ \end{aligned} $$ -Conversely, feasible finite measures $\alpha,\beta$ have the same nonzero mass; normalizing both by that mass recovers probability measures with the same objective ratio. The feasible set is nonempty and bounded: $f_a\geq1$ bounds the mass of $\beta$ by one, and the order-zero constraint gives the same bound for $\alpha$. +Conversely, feasible finite measures $`\alpha,\beta`$ have the same nonzero mass; normalizing both by that mass recovers probability measures with the same objective ratio. The feasible set is nonempty and bounded: $`f_a\geq1`$ bounds the mass of $`\beta`$ by one, and the order-zero constraint gives the same bound for $`\alpha`$. -The dual has a real polynomial $p_N$ of degree at most $r$ for the moment constraints and a scalar $K_N$ for the exponential normalization. Its inequalities are exactly +The dual has a real polynomial $`p_N`$ of degree at most $`r`$ for the moment constraints and a scalar $`K_N`$ for the exponential normalization. Its inequalities are exactly $$ f_a(u)\leq p_N(u)\leq K_Nf_a(u)\qquad(u\in G_N). $$ -Finite-dimensional linear-program duality therefore gives an attained grid optimum $K_N$, equal to the grid moment ratio. Since grid-supported pairs are admissible in the full problem, +Finite-dimensional linear-program duality therefore gives an attained grid optimum $`K_N`$, equal to the grid moment ratio. Since grid-supported pairs are admissible in the full problem, $$ 1\leq K_N\leq\kappa_r(a)\leq e^a. $$ -At the $r+1$ fixed nodes, the values of $p_N$ are uniformly bounded. The inverse of their fixed Vandermonde matrix consequently bounds every coefficient of $p_N$. Pass to a subsequence on which its coefficients and $K_N$ converge, obtaining a polynomial $p$ and $K\leq\kappa_r(a)$. At any $u\in[0,1]$, choose grid points tending to $u$. Uniform convergence of the polynomials and continuity of $f_a$ give +At the $`r+1`$ fixed nodes, the values of $`p_N`$ are uniformly bounded. The inverse of their fixed Vandermonde matrix consequently bounds every coefficient of $`p_N`$. Pass to a subsequence on which its coefficients and $`K_N`$ converge, obtaining a polynomial $`p`$ and $`K\leq\kappa_r(a)`$. At any $`u\in[0,1]`$, choose grid points tending to $`u`$. Uniform convergence of the polynomials and continuity of $`f_a`$ give $$ f_a(u)\leq p(u)\leq Kf_a(u). $$ -The first part of the proof now gives $\kappa_r(a)\leq K$, establishing equality and attainment. Finally, a positive polynomial can be scaled so that its minimum ratio $p/f_a$ is one; the smallest resulting $K$ is its maximum-to-minimum ratio. This proves the equivalent formula. $\square$ +The first part of the proof now gives $`\kappa_r(a)\leq K`$, establishing equality and attainment. Finally, a positive polynomial can be scaled so that its minimum ratio $`p/f_a`$ is one; the smallest resulting $`K`$ is its maximum-to-minimum ratio. This proves the equivalent formula. $`\square`$ -This scalar identity is inherited. In particular, [Adibi and Krysta, Appendix I, Theorem I.1 and Corollary I.2](https://arxiv.org/abs/2610.28999), give the exact weighted relative-approximation duality and matching-moment expectation ratio $(1+d)/(1-d)$ used here. The finite-grid proof above specializes that identity to the exponential and fixes the notation needed for the learning theorem. Related polynomial-approximation and moment-matching methods appear in [discrete functional estimation](https://arxiv.org/abs/1406.6956) and [population-parameter learning](https://arxiv.org/abs/1709.02707). The duality itself is not a new quantum principle. +This scalar identity is inherited. In particular, [Adibi and Krysta, Appendix I, Theorem I.1 and Corollary I.2](https://arxiv.org/abs/2610.28999), give the exact weighted relative-approximation duality and matching-moment expectation ratio $`(1+d)/(1-d)`$ used here. The finite-grid proof above specializes that identity to the exponential and fixes the notation needed for the learning theorem. Related polynomial-approximation and moment-matching methods appear in [discrete functional estimation](https://arxiv.org/abs/1406.6956) and [population-parameter learning](https://arxiv.org/abs/1709.02707). The duality itself is not a new quantum principle. ## 3. Relative approximation, strictness, and convergence @@ -110,7 +110,7 @@ E_r(a)=\min_{\deg q\leq r}\max_{0\leq u\leq1} \left|q(u)e^{-au}-1\right|. $$ -The minimum exists by the same coefficient-compactness argument as above, and $E_r(a)<1$: a suitable positive constant already gives error $\tanh(a/2)<1$. Scaling an envelope to balance its upper and lower relative errors, and conversely scaling a relative approximant upward, gives +The minimum exists by the same coefficient-compactness argument as above, and $`E_r(a)\lt 1`$: a suitable positive constant already gives error $`\tanh(a/2)\lt 1`$. Scaling an envelope to balance its upper and lower relative errors, and conversely scaling a relative approximant upward, gives $$ E_r(a)=\frac{\kappa_r(a)-1}{\kappa_r(a)+1}, @@ -118,9 +118,9 @@ E_r(a)=\frac{\kappa_r(a)-1}{\kappa_r(a)+1}, \Gamma_r(a)=\frac1a\log\frac{1+E_r(a)}{1-E_r(a)}. $$ -In detail, $f_a\leq p\leq Kf_a$ implies that $q=2p/(K+1)$ has relative error at most $(K-1)/(K+1)$. If $q$ has relative error $E<1$, then $p=q/(1-E)$ satisfies $f_a\leq p\leq[(1+E)/(1-E)]f_a$. Taking the optima proves both identities. +In detail, $`f_a\leq p\leq Kf_a`$ implies that $`q=2p/(K+1)`$ has relative error at most $`(K-1)/(K+1)`$. If $`q`$ has relative error $`E\lt 1`$, then $`p=q/(1-E)`$ satisfies $`f_a\leq p\leq[(1+E)/(1-E)]f_a`$. Taking the optima proves both identities. -**Proposition 2 — a strictly decreasing frontier.** For every fixed $a>0$, +**Proposition 2 — a strictly decreasing frontier.** For every fixed $`a>0`$, $$ 1=\Gamma_0(a)>\Gamma_1(a)>\Gamma_2(a)>\cdots>0, @@ -128,21 +128,21 @@ $$ \lim_{r\to\infty}\Gamma_r(a)=0. $$ -**Proof.** Moment matching becomes more restrictive with $r$, so the sequence is nonincreasing. If a finite-degree value had $\kappa_r=1$, Theorem 1 would give a polynomial identical to $e^{au}$, which is impossible for $a>0$. Thus each finite-degree value is positive. +**Proof.** Moment matching becomes more restrictive with $`r`$, so the sequence is nonincreasing. If a finite-degree value had $`\kappa_r=1`$, Theorem 1 would give a polynomial identical to $`e^{au}`$, which is impossible for $`a>0`$. Thus each finite-degree value is positive. -For strictness, use the standard weighted Chebyshev alternation theorem: a best degree-$s$ approximation to $f_a$ with positive weight $e^{-au}$ has $s+2$ alternating extrema of its weighted error. If $E_{r+1}=E_r$, an optimal degree-$r$ polynomial $q_r$ would also be optimal at degree $r+1$. Its error +For strictness, use the standard weighted Chebyshev alternation theorem: a best degree-$`s`$ approximation to $`f_a`$ with positive weight $`e^{-au}`$ has $`s+2`$ alternating extrema of its weighted error. If $`E_{r+1}=E_r`$, an optimal degree-$`r`$ polynomial $`q_r`$ would also be optimal at degree $`r+1`$. Its error $$ e(u)=q_r(u)e^{-au}-1 $$ -would then have $r+3$ alternating extreme points. Their $r+1$ middle points are interior extrema, so $e'$ would have at least $r+1$ distinct zeros. But +would then have $`r+3`$ alternating extreme points. Their $`r+1`$ middle points are interior extrema, so $`e'`$ would have at least $`r+1`$ distinct zeros. But $$ e'(u)=e^{-au}\big(q'_r(u)-a q_r(u)\big), $$ -and the factor in parentheses is a nonzero polynomial of degree at most $r$. It is nonzero because a nonzero polynomial cannot satisfy $q'=aq$ for $a>0$, while the zero approximant has error one and is not optimal. This contradiction proves strictness. +and the factor in parentheses is a nonzero polynomial of degree at most $`r`$. It is nonzero because a nonzero polynomial cannot satisfy $`q'=aq`$ for $`a>0`$, while the zero approximant has error one and is not optimal. This contradiction proves strictness. For convergence, put @@ -156,25 +156,25 @@ $$ p_r(u)=\sum_{j=0}^{r}\frac{(au)^j}{j!}+T_r(a) $$ -satisfies $f_a\leq p_r\leq f_a+T_r(a)\leq(1+T_r(a))f_a$. Therefore +satisfies $`f_a\leq p_r\leq f_a+T_r(a)\leq(1+T_r(a))f_a`$. Therefore $$ 0\leq\Gamma_r(a)\leq\frac1a\log\big(1+T_r(a)\big)\longrightarrow0. $$ -For $r=0$, the largest ratio of unconstrained exponential means is $e^a$, attained by $\delta_1$ and $\delta_0$, so $\Gamma_0=1$. $\square$ +For $`r=0`$, the largest ratio of unconstrained exponential means is $`e^a`$, attained by $`\delta_1`$ and $`\delta_0`$, so $`\Gamma_0=1`$. $`\square`$ The alternation theorem used here is the usual best-approximation theorem for a positive weight on an interval. Its role is only to establish strictness; the dual characterization and the learning bounds do not depend on inferring strictness from numerical grids. ## 4. The one-copy value and small-tilt hierarchy -**Proposition 3 — the first frontier value.** Let $b=e^a-1$ and +**Proposition 3 — the first frontier value.** Let $`b=e^a-1`$ and $$ -m_*(a)=\frac1a-\frac1b. +m_{*}(a)=\frac1a-\frac1b. $$ -Then $m_*\in(0,1)$ and +Then $`m_{*}\in(0,1)`$ and $$ \kappa_1(a)=\frac ba\exp\left(-1+\frac ab\right), @@ -182,36 +182,36 @@ $$ \Gamma_1(a)=\frac1a\log\frac ba-\frac1a+\frac1b. $$ -**Proof.** Among probability measures with mean $m$, convexity gives +**Proof.** Among probability measures with mean $`m`$, convexity gives $$ e^{am}\leq\int e^{au}\,d\mu(u)\leq1+m(e^a-1). $$ -The lower endpoint is attained by $\delta_m$, and the upper by $(1-m)\delta_0+m\delta_1$. Hence +The lower endpoint is attained by $`\delta_m`$, and the upper by $`(1-m)\delta_0+m\delta_1`$. Hence $$ \kappa_1(a)=\max_{0\leq m\leq1}(1+bm)e^{-am}. $$ -The derivative of its logarithm is $b/(1+bm)-a$. It is positive at zero and negative at one, and is strictly decreasing. The unique maximizer is $m_*$; substitution gives the displayed formula. $\square$ +The derivative of its logarithm is $`b/(1+bm)-a`$. It is positive at zero and negative at one, and is strictly decreasing. The unique maximizer is $`m_{*}`$; substitution gives the displayed formula. $`\square`$ -Writing $S(h)=(h-1)h^{1/(h-1)}/(e\log h)$, this is $\Gamma_1(a)=a^{-1}\log S(e^a)$. The function $S$ is the classical [Specht ratio](https://www.kurims.kyoto-u.ac.jp/~kyodo/kokyuroku/contents/pdf/1259-1.pdf), a sharp reverse arithmetic-geometric mean constant. The constant is inherited; its operational interpretation is supplied below. +Writing $`S(h)=(h-1)h^{1/(h-1)}/(e\log h)`$, this is $`\Gamma_1(a)=a^{-1}\log S(e^a)`$. The function $`S`$ is the classical [Specht ratio](https://www.kurims.kyoto-u.ac.jp/~kyodo/kokyuroku/contents/pdf/1259-1.pdf), a sharp reverse arithmetic-geometric mean constant. The constant is inherited; its operational interpretation is supplied below. -**Proposition 4 — fixed-degree small-tilt asymptotics.** For each fixed integer $r\geq1$, +**Proposition 4 — fixed-degree small-tilt asymptotics.** For each fixed integer $`r\geq1`$, $$ \Gamma_r(a)\sim\frac{a^r}{(r+1)!\,4^r}\qquad(a\downarrow0). $$ -**Proof.** Let $P_r(u)=\sum_{j=0}^{r}(au)^j/j!$. Uniformly on $[0,1]$, +**Proof.** Let $`P_r(u)=\sum_{j=0}^{r}(au)^j/j!`$. Uniformly on $`[0,1]`$, $$ \frac{f_a(u)-P_r(u)}{a^{r+1}} \longrightarrow\frac{u^{r+1}}{(r+1)!}. $$ -Subtracting $P_r$ does not change distance from the degree-$r$ polynomial space. After rescaling, the relative weight $e^{-au}$ converges uniformly to one and lies between $e^{-a}$ and one. Uniform approximation distance is Lipschitz in its target. Consequently, +Subtracting $`P_r`$ does not change distance from the degree-$`r`$ polynomial space. After rescaling, the relative weight $`e^{-au}`$ converges uniformly to one and lies between $`e^{-a}`$ and one. Uniform approximation distance is Lipschitz in its target. Consequently, $$ \frac{E_r(a)}{a^{r+1}} @@ -219,53 +219,53 @@ $$ \frac1{(r+1)!}\inf_{\deg q\leq r}\|u^{r+1}-q(u)\|_\infty. $$ -The last infimum is $2^{-(2r+1)}$. Indeed, the monic shifted Chebyshev polynomial $2^{-(2r+1)}\mathrm T_{r+1}(2u-1)$ has exactly that norm. A monic polynomial with smaller norm would differ from it by a degree-$r$ polynomial with at least $r+1$ sign changes between its alternating extreme points, a contradiction. Finally, +The last infimum is $`2^{-(2r+1)}`$. Indeed, the monic shifted Chebyshev polynomial $`2^{-(2r+1)}\mathrm T_{r+1}(2u-1)`$ has exactly that norm. A monic polynomial with smaller norm would differ from it by a degree-$`r`$ polynomial with at least $`r+1`$ sign changes between its alternating extreme points, a contradiction. Finally, $$ \log\frac{1+E_r}{1-E_r}\sim2E_r, $$ -and division by $a$ yields the stated constant. $\square$ +and division by $`a`$ yields the stated constant. $`\square`$ -In particular, $\Gamma_1(a)\sim a/8$, $\Gamma_2(a)\sim a^2/96$, and $\Gamma_3(a)\sim a^3/1536$. These are fixed-degree limits; they do not assert uniformity when $r$ grows with $1/a$. +In particular, $`\Gamma_1(a)\sim a/8`$, $`\Gamma_2(a)\sim a^2/96`$, and $`\Gamma_3(a)\sim a^3/1536`$. These are fixed-degree limits; they do not assert uniformity when $`r`$ grows with $`1/a`$. ## 5. From an envelope to a learning guarantee -Let $p(u)=\sum_{j=0}^{r}c_ju^j$ be an optimal envelope. In a grouped $r$-copy example, measure hypothesis $h$ on its copies to obtain conditional IID Bernoulli losses $Y_1,\ldots,Y_r$. The statistic +Let $`p(u)=\sum_{j=0}^{r}c_ju^j`$ be an optimal envelope. In a grouped $`r`$-copy example, measure hypothesis $`h`$ on its copies to obtain conditional IID Bernoulli losses $`Y_1,\ldots,Y_r`$. The statistic $$ Z_h=c_0+\sum_{j=1}^{r}c_j\prod_{i=1}^{j}Y_i $$ -is unbiased for $P_h=\mathbb E[p(\ell_h(X))]$ and obeys $|Z_h|\leq\sum_{j=0}^{r}|c_j|$. Let $A_h=\mathbb E[e^{a\ell_h(X)}]$. The envelope gives +is unbiased for $`P_h=\mathbb E[p(\ell_h(X))]`$ and obeys $`|Z_h|\leq\sum_{j=0}^{r}|c_j|`$. Let $`A_h=\mathbb E[e^{a\ell_h(X)}]`$. The envelope gives $$ A_h\leq P_h\leq\kappa_r(a)A_h. $$ -If all $P_h$ are estimated to additive error at most $\eta$ and the learner minimizes those estimates, then for a true risk minimizer $h^*$, +If all $`P_h`$ are estimated to additive error at most $`\eta`$ and the learner minimizes those estimates, then for a true risk minimizer $`h^{*}`$, $$ A_{\widehat h}\leq P_{\widehat h} -\leq P_{h^*}+2\eta -\leq\kappa_r(a)A_{h^*}+2\eta. +\leq P_{h^{*}}+2\eta +\leq\kappa_r(a)A_{h^{*}}+2\eta. $$ -Since $A_{h^*}\geq1$, +Since $`A_{h^{*}}\geq1`$, $$ -R_a(\widehat h)-R_a(h^*) +R_a(\widehat h)-R_a(h^{*}) \leq\Gamma_r(a)+\frac1a\log\left(1+\frac{2\eta}{\kappa_r(a)}\right) \leq\Gamma_r(a)+\frac{2\eta}{a\kappa_r(a)}. $$ -For fixed $a,r,H,\eta,\delta$, bounded-variable concentration and a union bound estimate all hypotheses with finitely many groups, independently of $M$ and $d$. Separate groups are allocated to different hypotheses, so this construction does not attempt incompatible measurements on one copy. Every supplied copy is charged. The polynomial representation is a direct instance of established multi-copy polynomial estimation, not a new state-preparation assumption. +For fixed $`a,r,H,\eta,\delta`$, bounded-variable concentration and a union bound estimate all hypotheses with finitely many groups, independently of $`M`$ and $`d`$. Separate groups are allocated to different hypotheses, so this construction does not attempt incompatible measurements on one copy. Every supplied copy is charged. The polynomial representation is a direct instance of established multi-copy polynomial estimation, not a new state-preparation assumption. -Thus every tolerance strictly above $\Gamma_r(a)$ admits a support-independent grouped-access PAC guarantee. A finite known $M$ may permit better tolerances after sufficiently many natural repeated groups; the statement is uniform over unbounded supports. +Thus every tolerance strictly above $`\Gamma_r(a)`$ admits a support-independent grouped-access PAC guarantee. A finite known $`M`$ may permit better tolerances after sufficiently many natural repeated groups; the statement is uniform over unbounded supports. ## 6. Why the same constant is unavoidable -Choose an optimal pair $\mu_-,\mu_+$ matching moments through $r$, oriented so that +Choose an optimal pair $`\mu_-,\mu_+`$ matching moments through $`r`$, oriented so that $$ \frac1a\log\int f_a\,d\mu_+ @@ -273,7 +273,7 @@ $$ =\Gamma_r(a). $$ -To witness the worst case under the class-size cap $H$, use exactly $H$ hypotheses. For each world $j\in[H]$ and each context $x$, independently draw latent probabilities $U_{x,j}\sim\mu_-$ and $U_{x,h}\sim\mu_+$ for $h\ne j$. Freeze these draws, and define +To witness the worst case under the class-size cap $`H`$, use exactly $`H`$ hypotheses. For each world $`j\in[H]`$ and each context $`x`$, independently draw latent probabilities $`U_{x,j}\sim\mu_-`$ and $`U_{x,h}\sim\mu_+`$ for $`h\ne j`$. Freeze these draws, and define $$ \tau_u=\begin{pmatrix}1-u&0\\0&u\end{pmatrix}, @@ -281,41 +281,41 @@ $$ \rho_x=\bigotimes_{h=1}^{H}\tau_{U_{x,h}}. $$ -Hypothesis $h$ uses the projector $|0\rangle\langle0|$ on coordinate $h$, tensored with identities elsewhere. Hence $\ell_h(x)=U_{x,h}$. This is a valid source on $H$ qubits; for two hypotheses, two qubits suffice, independently of $M$. +Hypothesis $`h`$ uses the projector $`|0\rangle\langle0|`$ on coordinate $`h`$, tensored with identities elsewhere. Hence $`\ell_h(x)=U_{x,h}`$. This is a valid source on $`H`$ qubits; for two hypotheses, two qubits suffice, independently of $`M`$. -For any $s\leq r$, each entry of $\tau_u^{\otimes s}$ is a polynomial in $u$ of degree at most $s$. Therefore +For any $`s\leq r`$, each entry of $`\tau_u^{\otimes s}`$ is a polynomial in $`u`$ of degree at most $`s`$. Therefore $$ \int\tau_u^{\otimes s}\,d\mu_-(u) =\int\tau_u^{\otimes s}\,d\mu_+(u). $$ -Regrouping tensor factors by hypothesis coordinate proves that the averaged $s$-copy state at a context is identical in every world. Conditional on a sequence of distinct grouped-example labels, the complete averaged training state is consequently identical across worlds, even when the learner is allowed a collective measurement on all groups. With $G$ groups, the probability of a repeated group label is at most $G(G-1)/(2M)$. +Regrouping tensor factors by hypothesis coordinate proves that the averaged $`s`$-copy state at a context is identical in every world. Conditional on a sequence of distinct grouped-example labels, the complete averaged training state is consequently identical across worlds, even when the learner is allowed a collective measurement on all groups. With $`G`$ groups, the probability of a repeated group label is at most $`G(G-1)/(2M)`$. -For each fixed world, the table averages of $f_a(U_{x,h})\in[1,e^a]$ concentrate around their prior means as $M\to\infty$. The log is $1$-Lipschitz on $[1,\infty)$, so the actual frozen-table risks concentrate as well. With probability tending to one over the table construction, world $j$ has unique optimal hypothesis $j$, and every other hypothesis has excess tending to $\Gamma_r(a)$. +For each fixed world, the table averages of $`f_a(U_{x,h})\in[1,e^a]`$ concentrate around their prior means as $`M\to\infty`$. The log is $`1`$-Lipschitz on $`[1,\infty)`$, so the actual frozen-table risks concentrate as well. With probability tending to one over the table construction, world $`j`$ has unique optimal hypothesis $`j`$, and every other hypothesis has excess tending to $`\Gamma_r(a)`$. -Suppose a fixed finite number of groups gave a uniform guarantee at $\epsilon<\Gamma_r(a)$ and confidence $1-\delta>1/H$. Average that guarantee over a uniformly random world and its frozen-table prior. As $M\to\infty$, label collisions and atypical tables vanish, while all training states become identical across worlds. No learner can then output the correct world index with average probability greater than $1/H$. This contradicts the claimed guarantee. Since a guarantee for every fixed table also holds after averaging over any table prior, the argument supplies a worst-case fixed source rather than assuming a freshly randomized process on every use. +Suppose a fixed finite number of groups gave a uniform guarantee at $`\epsilon\lt \Gamma_r(a)`$ and confidence $`1-\delta>1/H`$. Average that guarantee over a uniformly random world and its frozen-table prior. As $`M\to\infty`$, label collisions and atypical tables vanish, while all training states become identical across worlds. No learner can then output the correct world index with average probability greater than $`1/H`$. This contradicts the claimed guarantee. Since a guarantee for every fixed table also holds after averaging over any table prior, the argument supplies a worst-case fixed source rather than assuming a freshly randomized process on every use. -Together with the envelope upper bound, this proves the worst-case support-independent PAC boundary over classes of size at most $H$, with strict inequalities: +Together with the envelope upper bound, this proves the worst-case support-independent PAC boundary over classes of size at most $`H`$, with strict inequalities: -- $\epsilon>\Gamma_r(a)$: finitely many grouped examples suffice uniformly in $M$; -- $\epsilon<\Gamma_r(a)$ and $\delta<1-1/H$: no finite uniform bound exists. +- $`\epsilon>\Gamma_r(a)`$: finitely many grouped examples suffice uniformly in $`M`$; +- $`\epsilon\lt \Gamma_r(a)`$ and $`\delta\lt 1-1/H`$: no finite uniform bound exists. -No claim at $\epsilon=\Gamma_r(a)$ follows from these statements. The lower-bound states commute, and the quantum measurement class is unrestricted. The obstruction is unavailable conditional repetition, not a computational separation between quantum and classical processors. +No claim at $`\epsilon=\Gamma_r(a)`$ follows from these statements. The lower-bound states commute, and the quantum measurement class is unrestricted. The obstruction is unavailable conditional repetition, not a computational separation between quantum and classical processors. ## 7. Expected regret has a different exact floor The following elementary decision lemma identifies the metric distinction. -**Lemma 5 — interval uncertainty.** Suppose each of $H$ action risks lies in a known interval $[l_h,l_h+W]$. A randomized action can guarantee worst-case expected regret at most $(1-1/H)W$ over the product of these intervals. +**Lemma 5 — interval uncertainty.** Suppose each of $`H`$ action risks lies in a known interval $`[l_h,l_h+W]`$. A randomized action can guarantee worst-case expected regret at most $`(1-1/H)W`$ over the product of these intervals. -**Proof.** By the finite-action compact-game minimax theorem, it suffices to bound the Bayes regret under every distribution of admissible risk vectors. Choose a measurable minimizing action $J$ for each vector, breaking ties deterministically, and let $p_h=\Pr(J=h)$. Pointwise, +**Proof.** By the finite-action compact-game minimax theorem, it suffices to bound the Bayes regret under every distribution of admissible risk vectors. Choose a measurable minimizing action $`J`$ for each vector, breaking ties deterministically, and let $`p_h=\Pr(J=h)`$. Pointwise, $$ R_h-R_J\leq l_h-l_J+W\,\mathbf1\{h\ne J\}. $$ -Averaging its expectation over a fixed random action with probabilities $p_h$ cancels the $l$ terms, giving +Averaging its expectation over a fixed random action with probabilities $`p_h`$ cancels the $`l`$ terms, giving $$ \sum_h p_h\mathbb E[R_h-R_J] @@ -323,19 +323,19 @@ $$ \leq W(1-1/H). $$ -Some fixed action has Bayes regret at most this weighted average. Minimax gives the result. $\square$ +Some fixed action has Bayes regret at most this weighted average. Minimax gives the result. $`\square`$ -If the first $r$ moments of every loss distribution were known exactly, each risk would lie in an interval of width at most $\Gamma_r(a)$. The lemma gives expected regret at most $(1-1/H)\Gamma_r(a)$. The $H$ indistinguishable worlds above attain that value in the large-support limit. +If the first $`r`$ moments of every loss distribution were known exactly, each risk would lie in an interval of width at most $`\Gamma_r(a)`$. The lemma gives expected regret at most $`(1-1/H)\Gamma_r(a)`$. The $`H`$ indistinguishable worlds above attain that value in the large-support limit. -This ideal-moment statement also has a statistical version with arbitrarily small slack. For $\xi\geq0$, let $\Gamma_r(a;\xi)$ be the largest risk difference between two probability measures whose moments of orders $1,\ldots,r$ differ by at most $\xi$. Compactness gives +This ideal-moment statement also has a statistical version with arbitrarily small slack. For $`\xi\geq0`$, let $`\Gamma_r(a;\xi)`$ be the largest risk difference between two probability measures whose moments of orders $`1,\ldots,r`$ differ by at most $`\xi`$. Compactness gives $$ \Gamma_r(a;\xi)\downarrow\Gamma_r(a)\qquad(\xi\downarrow0). $$ -Indeed, any sequence of approximate maximizers with $\xi\downarrow0$ has a subsequence converging to an exactly moment-matched pair. Estimate every moment within $\xi/2$, form the corresponding feasible moment intervals for each action, and use the interval decision rule. On the estimation event the risk intervals have width at most $\Gamma_r(a;\xi)$. Its complement contributes at most its probability because excess risk is bounded by one. Thus finite grouped samples achieve expected regret arbitrarily close to $(1-1/H)\Gamma_r(a)$, uniformly in $M$. +Indeed, any sequence of approximate maximizers with $`\xi\downarrow0`$ has a subsequence converging to an exactly moment-matched pair. Estimate every moment within $`\xi/2`$, form the corresponding feasible moment intervals for each action, and use the interval decision rule. On the estimation event the risk intervals have width at most $`\Gamma_r(a;\xi)`$. Its complement contributes at most its probability because excess risk is bounded by one. Thus finite grouped samples achieve expected regret arbitrarily close to $`(1-1/H)\Gamma_r(a)`$, uniformly in $`M`$. -This expected value does not give a PAC guarantee below $\Gamma_r(a)$: under an indistinguishable world, randomization still returns a wrong, high-excess hypothesis with substantial probability. +This expected value does not give a PAC guarantee below $`\Gamma_r(a)`$: under an indistinguishable world, randomization still returns a wrong, high-excess hypothesis with substantial probability. ## 8. What the frontier does and does not establish diff --git a/science/passive_frontier.md b/science/passive_frontier.md index ade5be9..f7b2008 100644 --- a/science/passive_frontier.md +++ b/science/passive_frontier.md @@ -4,17 +4,17 @@ This file proves the fixed-parameter sample exponent for proper selection from a ## Statement and scope -An unknown, fixed table assigns a density matrix $\rho_x$ to each identifiable context $x\in[M]$. A passive source independently draws $X$ uniformly from $[M]$ and supplies one fresh specimen of $\rho_X$. The learner cannot choose $X$ or request another specimen at that context. Different visits to a context prepare independent copies of its same fixed state. +An unknown, fixed table assigns a density matrix $`\rho_x`$ to each identifiable context $`x\in[M]`$. A passive source independently draws $`X`$ uniformly from $`[M]`$ and supplies one fresh specimen of $`\rho_X`$. The learner cannot choose $`X`$ or request another specimen at that context. Different visits to a context prepare independent copies of its same fixed state. -There are $m\le H$ known projector-valued hypotheses $\Pi_h(x)$. Write +There are $`m\le H`$ known projector-valued hypotheses $`\Pi_h(x)`$. Write $$ -\ell_h(x)=1-\operatorname{Tr}[\Pi_h(x)\rho_x],\qquad +\ell_h(x)=1-\mathrm{Tr}[\Pi_h(x)\rho_x],\qquad A_h=\frac1M\sum_{x=1}^M e^{a\ell_h(x)},\qquad R_a(h)=\frac1a\log A_h, $$ -where $a>0$. A proper learner returns an index $\widehat h$ in the supplied class. Its guarantee is +where $`a>0`$. A proper learner returns an index $`\widehat h`$ in the supplied class. Its guarantee is $$ \Pr\!\left[R_a(\widehat h)-\min_h R_a(h)\le\varepsilon\right] @@ -23,7 +23,7 @@ $$ for every fixed source table and supplied class. The learner may otherwise process all supplied specimens jointly and adaptively. -For $r\ge0$, let +For $`r\ge0`$, let $$ K_r(a)=\sup_{\mu,\nu} @@ -32,35 +32,35 @@ K_r(a)=\sup_{\mu,\nu} \Gamma_r(a)=\frac1a\log K_r(a), $$ -where $\mu,\nu$ are probability measures with equal moments of degrees $0,\ldots,r$. Thus $K_r(a)$ is the same constant denoted $\kappa_r(a)$ in the moment account. The moment-frontier theorem gives the equivalent attained envelope problem +where $`\mu,\nu`$ are probability measures with equal moments of degrees $`0,\ldots,r`$. Thus $`K_r(a)`$ is the same constant denoted $`\kappa_r(a)`$ in the moment account. The moment-frontier theorem gives the equivalent attained envelope problem $$ -K_r(a)=\min\left\{K: +K_r(a)=\min\left\lbraceK: \exists P\in\mathbb R[u],\ \deg P\le r,\quad -e^{au}\le P(u)\le K e^{au}\quad(0\le u\le1)\right\}. +e^{au}\le P(u)\le K e^{au}\quad(0\le u\le1)\right\rbrace. $$ -**Theorem.** Fix $a>0$, an integer $H\ge2$, confidence $0<\delta<1/2$, and an integer $k\ge1$. If +**Theorem.** Fix $`a>0`$, an integer $`H\ge2`$, confidence $`0\lt \delta\lt 1/2`$, and an integer $`k\ge1`$. If $$ \Gamma_k(a)<\varepsilon<\Gamma_{k-1}(a), $$ -then the worst-case fixed-budget passive sample complexity, over classes of size at most $H$ and fixed source tables, satisfies +then the worst-case fixed-budget passive sample complexity, over classes of size at most $`H`$ and fixed source tables, satisfies $$ -N^*(M)=\Theta_{a,\varepsilon,H,\delta,k} +N^{*}(M)=\Theta_{a,\varepsilon,H,\delta,k} \!\left(M^{1-1/k}\right) \qquad(M\to\infty). $$ -The upper bound holds for every such finite class. The lower bound is witnessed by one class of two constant commuting projectors on two qubits. It is not a lower bound for every class with two hypotheses. Constants can depend on the displayed fixed parameters and the distances from the two threshold values. Critical accuracies $\varepsilon=\Gamma_r(a)$, growing $H$ or $k$, and joint limits involving $a$, $\varepsilon$, and $M$ are not covered by this statement. +The upper bound holds for every such finite class. The lower bound is witnessed by one class of two constant commuting projectors on two qubits. It is not a lower bound for every class with two hypotheses. Constants can depend on the displayed fixed parameters and the distances from the two threshold values. Critical accuracies $`\varepsilon=\Gamma_r(a)`$, growing $`H`$ or $`k`$, and joint limits involving $`a`$, $`\varepsilon`$, and $`M`$ are not covered by this statement. ## Lower bound against arbitrary quantum processing ### Two moment-matched worlds -First suppose $k\ge2$, and put $r=k-1$. Because $\varepsilon<\Gamma_r(a)$, choose moment-matched probability measures $\mu,\nu$ such that +First suppose $`k\ge2`$, and put $`r=k-1`$. Because $`\varepsilon\lt \Gamma_r(a)`$, choose moment-matched probability measures $`\mu,\nu`$ such that $$ u=\int e^{ap}\,d\mu(p),\qquad @@ -68,16 +68,16 @@ v=\int e^{ap}\,d\nu(p),\qquad g=\frac1a\log\frac vu>\varepsilon. $$ -The measures may be swapped to arrange $v>u$. An approximate maximizing pair with this strict gap is enough; no numerical approximation of an optimizer is used in the proof. +The measures may be swapped to arrange $`v>u`$. An approximate maximizing pair with this strict gap is enough; no numerical approximation of an optimizer is used in the proof. -For each context independently freeze two latent probabilities. In world $0$, draw $p_x\sim\mu$ and $q_x\sim\nu$, independently, and set +For each context independently freeze two latent probabilities. In world $`0`$, draw $`p_x\sim\mu`$ and $`q_x\sim\nu`$, independently, and set $$ \rho_x=\tau_{p_x}\otimes\tau_{q_x},\qquad -\tau_p=\operatorname{diag}(1-p,p). +\tau_p=\mathrm{diag}(1-p,p). $$ -World $1$ swaps the two priors. The fixed class consists of +World $`1`$ swaps the two priors. The fixed class consists of $$ \Pi_1=|0\rangle\langle0|\otimes I, @@ -85,13 +85,13 @@ $$ \Pi_2=I\otimes|0\rangle\langle0|. $$ -Their losses are $p_x$ and $q_x$. These are valid supervised examples with a constant reference label, if labels are included in the source notation. Only proper selection between the two supplied measurements is claimed: an unrestricted improper classifier would be a different task. +Their losses are $`p_x`$ and $`q_x`$. These are valid supervised examples with a constant reference label, if labels are included in the source notation. Only proper selection between the two supplied measurements is claimed: an unrestricted improper classifier would be a different task. -The random tables are priors for a lower-bound argument. Once drawn, each table is fixed throughout all sampling; the source does not redraw $p_x$ or $q_x$ when a context is revisited. +The random tables are priors for a lower-bound argument. Once drawn, each table is fixed throughout all sampling; the source does not redraw $`p_x`$ or $`q_x`$ when a context is revisited. -### Equality before a $k$-fold repeat +### Equality before a $`k`$-fold repeat -Condition on the entire sequence of sampled context labels. If context $x$ occurs $s$ times, its specimens have state $\rho_x^{\otimes s}$. After regrouping tensor factors by coordinate, +Condition on the entire sequence of sampled context labels. If context $`x`$ occurs $`s`$ times, its specimens have state $`\rho_x^{\otimes s}`$. After regrouping tensor factors by coordinate, $$ \mathbb E[\rho_x^{\otimes s}] @@ -99,11 +99,11 @@ $$ \otimes\mathbb E[\tau_{q_x}^{\otimes s}]. $$ -Every matrix entry of $\tau_p^{\otimes s}$ is a polynomial in $p$ of degree at most $s$. Therefore the two worlds have exactly the same prior-averaged state whenever $s\le r$. Independence of the frozen parameters at distinct contexts makes the *entire* prior-averaged training state identical whenever every context count is at most $k-1$. +Every matrix entry of $`\tau_p^{\otimes s}`$ is a polynomial in $`p`$ of degree at most $`s`$. Therefore the two worlds have exactly the same prior-averaged state whenever $`s\le r`$. Independence of the frozen parameters at distinct contexts makes the *entire* prior-averaged training state identical whenever every context count is at most $`k-1`$. This equality is at the level of the supplied quantum registers, with their classical context labels. Consequently it survives every collective measurement, intermediate measurement, adaptive control, and classical postprocessing allowed to the learner. It does not depend on a restriction to a particular measurement strategy. -For $n$ iid uniform context draws, let $E$ be the event that no context occurs $k$ times. A union bound over subsets of $k$ sample positions gives +For $`n`$ iid uniform context draws, let $`E`$ be the event that no context occurs $`k`$ times. A union bound over subsets of $`k`$ sample positions gives $$ q_n:=\Pr(E^c) @@ -111,23 +111,23 @@ q_n:=\Pr(E^c) \le\frac{n^k}{k!M^{k-1}}. $$ -If $\omega_0,\omega_1$ are the prior-averaged classical-quantum training states, their trace distance obeys +If $`\omega_0,\omega_1`$ are the prior-averaged classical-quantum training states, their trace distance obeys $$ \frac12\|\omega_0-\omega_1\|_1\le q_n. $$ -Indeed their contributions on $E$ are equal, and the remaining subnormalized states each have trace $q_n$. With equal world priors, no procedure can identify the world with average probability greater than $(1+q_n)/2$. +Indeed their contributions on $`E`$ are equal, and the remaining subnormalized states each have trace $`q_n`$. With equal world priors, no procedure can identify the world with average probability greater than $`(1+q_n)/2`$. ### Fixed-table risks and the PAC contradiction -It remains to relate the annealed gap $g$ to a source with a fixed deterministic table. Define +It remains to relate the annealed gap $`g`$ to a source with a fixed deterministic table. Define $$ \zeta=\frac{a(g-\varepsilon)}4>0. $$ -Both coordinate exponential moments are averages of $M$ independent random variables in $[1,e^a]$. Hoeffding's inequality and a union bound show that, in either world, with probability at least $1-\eta_M$, +Both coordinate exponential moments are averages of $`M`$ independent random variables in $`[1,e^a]`$. Hoeffding's inequality and a union bound show that, in either world, with probability at least $`1-\eta_M`$, $$ \left|\frac1M\sum_xe^{ap_x}-\mathbb E e^{ap_x}\right|\le\zeta, @@ -141,81 +141,81 @@ $$ \eta_M=4\exp\!\left(-\frac{2M\zeta^2}{(e^a-1)^2}\right). $$ -All exponential moments are at least one, so $\log$ is 1-Lipschitz on their range. On this good-table event the two actual risks differ, in the intended direction, by at least +All exponential moments are at least one, so $`\log`$ is 1-Lipschitz on their range. On this good-table event the two actual risks differ, in the intended direction, by at least $$ g-\frac{2\zeta}{a} =\frac{g+\varepsilon}{2}>\varepsilon. $$ -Thus, on every good table, an $(\varepsilon,\delta)$-PAC proper learner must select the corresponding world's unique better hypothesis with probability at least $1-\delta$. Averaging over the table prior would identify the world with probability at least $1-\delta-\eta_M$. +Thus, on every good table, an $`(\varepsilon,\delta)`$-PAC proper learner must select the corresponding world's unique better hypothesis with probability at least $`1-\delta`$. Averaging over the table prior would identify the world with probability at least $`1-\delta-\eta_M`$. -For explicit constants put $w=1-2\delta>0$. Take $M$ large enough that $\eta_M\le w/8$, and take +For explicit constants put $`w=1-2\delta>0`$. Take $`M`$ large enough that $`\eta_M\le w/8`$, and take $$ n\le c\,M^{1-1/k},\qquad c=\left(\frac{wk!}{4}\right)^{1/k}. $$ -Then $q_n\le w/4$. The learning guarantee would give world-identification success at least $1/2+3w/8$, whereas the trace-distance bound permits at most $1/2+w/8$. This contradiction proves the lower bound. In particular, some deterministic fixed table violates the proposed learning guarantee; a random-table prior is not being substituted for the original task. +Then $`q_n\le w/4`$. The learning guarantee would give world-identification success at least $`1/2+3w/8`$, whereas the trace-distance bound permits at most $`1/2+w/8`$. This contradiction proves the lower bound. In particular, some deterministic fixed table violates the proposed learning guarantee; a random-table prior is not being substituted for the original task. -When $k=1$, the asserted exponent is zero. Since $\varepsilon<\Gamma_0(a)=1$, two deterministic tables with opposite optimal hypotheses and risk gap one rule out a zero-sample learner at $\delta<1/2$. Hence $N^*(M)\ge1=\Omega(M^0)$. The preceding collision argument is unnecessary in this case. +When $`k=1`$, the asserted exponent is zero. Since $`\varepsilon\lt \Gamma_0(a)=1`$, two deterministic tables with opposite optimal hypotheses and risk gap one rule out a zero-sample learner at $`\delta\lt 1/2`$. Hence $`N^{*}(M)\ge1=\Omega(M^0)`$. The preceding collision argument is unnecessary in this case. ## Upper bound from uniformly selected collision groups -The upper proof requires no coherent quantum memory for fixed $H$. It uses separate data batches for different hypotheses, measures each specimen immediately, and stores only classical context labels and measurement outcomes. +The upper proof requires no coherent quantum memory for fixed $`H`$. It uses separate data batches for different hypotheses, measures each specimen immediately, and stores only classical context labels and measurement outcomes. -### A constant-probability $k$-collision +### A constant-probability $`k`$-collision -For fixed $k\ge2$, take a batch of +For fixed $`k\ge2`$, take a batch of $$ b_M=\left\lceil M^{1-1/k}\right\rceil $$ -iid contexts. Let $C$ count subsets of $k$ positions having the same context. Then +iid contexts. Let $`C`$ count subsets of $`k`$ positions having the same context. Then $$ \mathbb EC={b_M\choose k}M^{1-k}\longrightarrow\lambda_k=\frac1{k!}. $$ -In $\mathbb EC^2$, disjoint pairs of subsets contribute asymptotically $\lambda_k^2$, identical subsets contribute $\lambda_k$, and pairs overlapping in $j\in\{1,\ldots,k-1\}$ positions contribute +In $`\mathbb EC^2`$, disjoint pairs of subsets contribute asymptotically $`\lambda_k^2`$, identical subsets contribute $`\lambda_k`$, and pairs overlapping in $`j\in\{1,\ldots,k-1\}`$ positions contribute $$ {b_M\choose k}{k\choose j}{b_M-k\choose k-j} M^{1-2k+j}=O_k(M^{-1+j/k})=o(1). $$ -Consequently $\mathbb EC^2\to\lambda_k^2+\lambda_k$. The second-moment bound gives a constant $\alpha_k>0$ such that, for all sufficiently large $M$, +Consequently $`\mathbb EC^2\to\lambda_k^2+\lambda_k`$. The second-moment bound gives a constant $`\alpha_k>0`$ such that, for all sufficiently large $`M`$, $$ \Pr(C>0)\ge\frac{(\mathbb EC)^2}{\mathbb EC^2}\ge\alpha_k. $$ -For example $\alpha_k=1/[2(k!+1)]$ works after increasing the finite lower cutoff on $M$. For $k=1$, use $b_M=1$ and $\alpha_1=1$. +For example $`\alpha_k=1/[2(k!+1)]`$ works after increasing the finite lower cutoff on $`M`$. For $`k=1`$, use $`b_M=1`$ and $`\alpha_1=1`$. ### Uniformity and independence are preserved -In a successful batch select uniformly from the set of contexts occurring at least $k$ times, and retain the first $k$ associated outcomes. The selection uses only the context labels and independent random coins. Label-permutation symmetry gives +In a successful batch select uniformly from the set of contexts occurring at least $`k`$ times, and retain the first $`k`$ associated outcomes. The selection uses only the context labels and independent random coins. Label-permutation symmetry gives $$ \Pr(X_{\mathrm{selected}}=x\mid\text{batch succeeds})=\frac1M $$ -for every $x$, for every fixed source table. No symmetry of the unknown states is assumed. Choosing the first $k$ occurrences also uses no measurement outcome. +for every $`x`$, for every fixed source table. No symmetry of the unknown states is assumed. Choosing the first $`k`$ occurrences also uses no measurement outcome. -Independent batches give independent selected groups. More precisely, a successful batch has a fixed conditional distribution: a uniform context and $k$ independent outcomes from its conditional state. This distribution does not depend on which batch succeeded. Therefore the first $L$ successful batches supply iid groups, independently of the event that a prescribed number of batches contains at least $L$ successes. Repeated selected labels across different batches do not spoil independence: source visits are independent preparations from the same fixed table. +Independent batches give independent selected groups. More precisely, a successful batch has a fixed conditional distribution: a uniform context and $`k`$ independent outcomes from its conditional state. This distribution does not depend on which batch succeeded. Therefore the first $`L`$ successful batches supply iid groups, independently of the event that a prescribed number of batches contains at least $`L`$ successes. Repeated selected labels across different batches do not spoil independence: source visits are independent preparations from the same fixed table. ### A signed polynomial is an observable, not automatically an effect -Choose an optimal degree-$k$ envelope +Choose an optimal degree-$`k`$ envelope $$ e^{au}\le P(u)=\sum_{j=0}^k c_j u^j \le K_k(a)e^{au}. $$ -Fix hypothesis $h$ for a batch. Upon receiving $(x,\rho_x)$, measure the loss projector $I-\Pi_h(x)$, producing $Y\in\{0,1\}$ with mean $\ell_h(x)$. For a selected collision group define +Fix hypothesis $`h`$ for a batch. Upon receiving $`(x,\rho_x)`$, measure the loss projector $`I-\Pi_h(x)`$, producing $`Y\in\{0,1\}`$ with mean $`\ell_h(x)`$. For a selected collision group define $$ Z_h=\sum_{j=0}^k c_j\prod_{i=1}^jY_i, @@ -228,9 +228,9 @@ $$ |Z_h|\le A_P:=\sum_{j=0}^k|c_j|. $$ -The coefficients need not be positive. Pointwise positivity of $P$ does not make this estimator a binary outcome or its associated operator a positive effect. Its bounded range is sufficient for the following classical estimate. +The coefficients need not be positive. Pointwise positivity of $`P`$ does not make this estimator a binary outcome or its associated operator a positive effect. Its bounded range is sufficient for the following classical estimate. -Equivalently, on $k$ quantum copies one may use the Hermitian observable +Equivalently, on $`k`$ quantum copies one may use the Hermitian observable $$ O_h(x)=\sum_{j=0}^k c_j @@ -238,7 +238,7 @@ O_h(x)=\sum_{j=0}^k c_j \qquad \|O_h(x)\|\le A_P. $$ -If a binary effect is needed by another learning primitive, $(O_h+A_PI)/(2A_P)$ lies between zero and identity and admits a standard projector dilation. This shift and rescaling, including its effect on accuracy and gate costs, must be retained. +If a binary effect is needed by another learning primitive, $`(O_h+A_PI)/(2A_P)`$ lies between zero and identity and admits a standard projector dilation. This shift and rescaling, including its effect on accuracy and gate costs, must be retained. ### Finite estimates and a fixed sample budget @@ -251,7 +251,7 @@ L=\left\lceil\frac{2A_P^2}{\eta^2} \log\frac{4H}{\delta}\right\rceil. $$ -For each hypothesis, average $Z_h$ over $L$ successful independent batches. Hoeffding's inequality gives, simultaneously for all $m\le H$, with probability at least $1-\delta/2$, +For each hypothesis, average $`Z_h`$ over $`L`$ successful independent batches. Hoeffding's inequality gives, simultaneously for all $`m\le H`$, with probability at least $`1-\delta/2`$, $$ |\widehat S_h-S_h|\le\eta, @@ -266,35 +266,35 @@ B=\left\lceil \frac{2L+8\log(2H/\delta)}{\alpha_k}\right\rceil $$ -independent batches. Their success indicators are iid with probability at least $\alpha_k$. A Chernoff bound shows that fewer than $L$ successes occurs with probability at most $\delta/(2H)$. If there are too few successes the learner may return any index; this event is included in its failure probability. The complete budget is +independent batches. Their success indicators are iid with probability at least $`\alpha_k`$. A Chernoff bound shows that fewer than $`L`$ successes occurs with probability at most $`\delta/(2H)`$. If there are too few successes the learner may return any index; this event is included in its failure probability. The complete budget is $$ N\le H B b_M =O_{a,\varepsilon,H,\delta,k}(M^{1-1/k}). $$ -Choose $\widehat h$ minimizing $\widehat S_h$, and let $h_*$ minimize the true tilted risk. On the simultaneous good event, +Choose $`\widehat h`$ minimizing $`\widehat S_h`$, and let $`h_{*}`$ minimize the true tilted risk. On the simultaneous good event, $$ A_{\widehat h}\le S_{\widehat h} -\le S_{h_*}+2\eta -\le K_k(a)A_{h_*}+2\eta. +\le S_{h_{*}}+2\eta +\le K_k(a)A_{h_{*}}+2\eta. $$ -Since $A_{h_*}\ge1$, +Since $`A_{h_{*}}\ge1`$, $$ -R_a(\widehat h)-R_a(h_*) +R_a(\widehat h)-R_a(h_{*}) \le\frac1a\log\bigl(K_k(a)+2\eta\bigr) <\varepsilon. $$ -The envelope distortion enters once, as $\Gamma_k(a)$, rather than twice. Combining the statistical and batch-failure probabilities proves the upper bound. +The envelope distortion enters once, as $`\Gamma_k(a)`$, rather than twice. Combining the statistical and batch-failure probabilities proves the upper bound. ## What the theorem establishes For fixed parameters in a strict threshold interval, increasing the required nonlinear-risk accuracy changes which repeat order the passive stream must supply. That repeat order determines the power of the context support in the sample budget. Even unrestricted quantum processing cannot recover moments absent from the prior-averaged input states. -The matching exponent is already achievable by immediate single-copy measurements and classical collision bookkeeping for fixed $H$. Thus the theorem is a data-access and statistical-accuracy frontier. It asserts no quantum-processing speedup, no advantage over a matched classical latent-Bernoulli experiment, and no lower bound for every hypothesis class. The resources behind the upper construction and the stronger repeated-input model are described in [replay and resources](replay_and_resources.md). +The matching exponent is already achievable by immediate single-copy measurements and classical collision bookkeeping for fixed $`H`$. Thus the theorem is a data-access and statistical-accuracy frontier. It asserts no quantum-processing speedup, no advantage over a matched classical latent-Bernoulli experiment, and no lower bound for every hypothesis class. The resources behind the upper construction and the stronger repeated-input model are described in [replay and resources](replay_and_resources.md). The proof uses established moment matching, polynomial-observable estimation, and generalized-birthday methods. Its scalar relative-approximation duality and closest scientific comparisons are credited in [the moment frontier](moment_frontier.md) and the repository's related-work account. diff --git a/science/replay_and_resources.md b/science/replay_and_resources.md index 3139750..ca2438b 100644 --- a/science/replay_and_resources.md +++ b/science/replay_and_resources.md @@ -1,10 +1,10 @@ # Repeated-input access and resource charges -The passive theorem counts naturally occurring one-copy examples. Controlled repetition changes that source interface. This file specifies the stronger interface and records what the constructive bounds cost. The central convention is the positive-loss tilt in [the model](model.md): $R_a(h)=a^{-1}\log\mathbb E e^{a\ell_h(X)}$, with $a>0$. +The passive theorem counts naturally occurring one-copy examples. Controlled repetition changes that source interface. This file specifies the stronger interface and records what the constructive bounds cost. The central convention is the positive-loss tilt in [the model](model.md): $`R_a(h)=a^{-1}\log\mathbb E e^{a\ell_h(X)}`$, with $`a>0`$. ## Conditional replay is an additional source capability -A natural source event first draws $X$ from its prescribed distribution and supplies $(X,\rho_X)$. In the replay model the learner may then request further independent preparations of that *same* $\rho_X$. The source table is unchanged. The learner need not be allowed to select an arbitrary context before the natural draw. +A natural source event first draws $`X`$ from its prescribed distribution and supplies $`(X,\rho_X)`$. In the replay model the learner may then request further independent preparations of that *same* $`\rho_X`$. The source table is unchanged. The learner need not be allowed to select an arbitrary context before the natural draw. This is independent preparation by a source capable of repeating the underlying input or experiment. It is not cloning the received unknown specimen, inferring an unknown preparation circuit, or assuming free coherent access to classical data. Every initial specimen, repeated preparation, and known hypothesis-measurement operation is charged. @@ -12,9 +12,9 @@ If the physical source cannot repeat an event—such as a unique uncontrolled tr ## A finite replica cap removes the support dependence above its threshold -Suppose each natural source event can provide exactly $k$ independent copies of its sampled conditional state. Let $P$ be a degree-$k$ relative envelope from [the moment frontier](moment_frontier.md), and use the bounded estimator $Z_h$ from [the passive proof](passive_frontier.md). Independent natural events are already iid groups, so no collision search is needed. +Suppose each natural source event can provide exactly $`k`$ independent copies of its sampled conditional state. Let $`P`$ be a degree-$`k`$ relative envelope from [the moment frontier](moment_frontier.md), and use the bounded estimator $`Z_h`$ from [the passive proof](passive_frontier.md). Independent natural events are already iid groups, so no collision search is needed. -For every fixed tolerance $\varepsilon>\Gamma_k(a)$, the same estimates and surrogate minimization give a proper learner with a finite number of source groups independent of the context support. One explicit per-hypothesis group count is +For every fixed tolerance $`\varepsilon>\Gamma_k(a)`$, the same estimates and surrogate minimization give a proper learner with a finite number of source groups independent of the context support. One explicit per-hypothesis group count is $$ L=\left\lceil\frac{2A_P^2}{\eta^2} @@ -24,22 +24,22 @@ L=\left\lceil\frac{2A_P^2}{\eta^2} \qquad A_P=\sum_{j=0}^k|c_j|, $$ -where $P(u)=\sum_{j=0}^kc_ju^j$. Using independent groups for each of $m\le H$ hypotheses costs at most $H L$ natural source events and $kHL$ physical specimens. The coefficients and therefore the constants can grow with $a$ and $k$; this formula does not hide an optimized joint limit. +where $`P(u)=\sum_{j=0}^kc_ju^j`$. Using independent groups for each of $`m\le H`$ hypotheses costs at most $`H L`$ natural source events and $`kHL`$ physical specimens. The coefficients and therefore the constants can grow with $`a`$ and $`k`$; this formula does not hide an optimized joint limit. -Conversely, a hard cap of $k$ copies per natural event cannot uniformly support error below $\Gamma_k(a)$ using a number of events independent of unrestricted context support. Matching $k$-moment priors make the first group at each context identical between two lower-bound worlds. A second visit can supply more copies, but for any fixed number of events its probability can be made arbitrarily small by increasing the uniform support. Fixed-table concentration then gives the same proper-selection obstruction as in the passive proof. +Conversely, a hard cap of $`k`$ copies per natural event cannot uniformly support error below $`\Gamma_k(a)`$ using a number of events independent of unrestricted context support. Matching $`k`$-moment priors make the first group at each context identical between two lower-bound worlds. A second visit can supply more copies, but for any fixed number of events its probability can be made arbitrarily small by increasing the uniform support. Fixed-table concentration then gives the same proper-selection obstruction as in the passive proof. This is a support-independent accuracy statement, not a claim that a fixed finite support remains unlearnable forever. Nor is a cap per source event the same as a lifetime cap on the total number of visits to one context. ## An exact exponential estimator with random replica depth -There is a useful alternative to choosing a deterministic cap. Draw $K\sim\operatorname{Poisson}(a)$, independently of the sampled context. For a fixed hypothesis, measure its loss projector $I-\Pi_h(X)$ on $K$ copies and let +There is a useful alternative to choosing a deterministic cap. Draw $`K\sim\mathrm{Poisson}(a)`$, independently of the sampled context. For a fixed hypothesis, measure its loss projector $`I-\Pi_h(X)`$ on $`K`$ copies and let $$ B_h=\prod_{j=1}^K Y_j, \qquad \prod_{j=1}^0Y_j=1. $$ -Conditional on $X=x$, +Conditional on $`X=x`$, $$ \mathbb E[B_h\mid x] @@ -55,48 +55,48 @@ $$ R_a(h)=1+\frac1a\log\beta_h. $$ -Thus minimizing the true risk is equivalent to minimizing $\beta_h$. The block operator $(I-\Pi_h(x))^{\otimes K}$, with its empty-product convention, is a projector. If a learning primitive maximizes acceptance, use its complementary projector. +Thus minimizing the true risk is equivalent to minimizing $`\beta_h`$. The block operator $`(I-\Pi_h(x))^{\otimes K}`$, with its empty-product convention, is a projector. If a learning primitive maximizes acceptance, use its complementary projector. The identity is the classical Poisson probability-generating-function/exponential Bernoulli-factory construction. Its use here must be credited as inherited; it is not a nonlinear measurement on one unknown quantum specimen. For example, Dughmi, Hartline, Kleinberg, and Niazadeh describe the Poisson-exponential factory and expected-payoff applications in [their Bernoulli-factory account](https://www.sigecom.org/exchanges/volume_16/1/DUGHMI.pdf). ### The initial specimen is still charged -Under the natural-source interface, the first specimen is prepared even when $K=0$. The physical number prepared for an untruncated event is therefore +Under the natural-source interface, the first specimen is prepared even when $`K=0`$. The physical number prepared for an untruncated event is therefore $$ \max\{1,K\},\qquad \mathbb E\max\{1,K\}=a+e^{-a}\le 1+a. $$ -When $K=0$ this initial specimen is unused. An expected cost of exactly $a$ is valid only under an explicitly stronger interface that can reveal the context while preparing no quantum output on zero-copy events. That interface is not assumed here. +When $`K=0`$ this initial specimen is unused. An expected cost of exactly $`a`$ is valid only under an explicitly stronger interface that can reveal the context while preparing no quantum output on zero-copy events. That interface is not assumed here. An exact bounded Bernoulli-factory lower bound on expected coin flips is a statement about that primitive. It is not automatically a lower bound on every tilted-risk learning algorithm. ### Finite-depth truncation -For a hard cap $r\ge1$, if $K>r$ discard the natural initial specimen, make no further requests, and set the estimator to zero. Otherwise use the preceding product estimator. Writing $t_r=\Pr(K>r)$, its mean $\beta_h^{(r)}$ satisfies +For a hard cap $`r\ge1`$, if $`K>r`$ discard the natural initial specimen, make no further requests, and set the estimator to zero. Otherwise use the preceding product estimator. Writing $`t_r=\Pr(K>r)`$, its mean $`\beta_h^{(r)}`$ satisfies $$ 0\le\beta_h-\beta_h^{(r)}\le t_r, \qquad \beta_h\ge e^{-a}. $$ -Every event prepares at most $r$ specimens. Its expected count is at most $a+e^{-a}$, since truncation discards rather than prepares the oversized groups. Padding with known ancillas is bookkeeping for a learning algorithm, not an extra unknown-state preparation. +Every event prepares at most $`r`$ specimens. Its expected count is at most $`a+e^{-a}`$, since truncation discards rather than prepares the oversized groups. Padding with known ancillas is bookkeeping for a learning algorithm, not an extra unknown-state preparation. -Suppose estimates of $\beta_h^{(r)}$ have uniform additive error at most $\eta$. Selecting a minimizer then gives +Suppose estimates of $`\beta_h^{(r)}`$ have uniform additive error at most $`\eta`$. Selecting a minimizer then gives $$ -\beta_{\widehat h}\le\beta_{h_*}+2\eta+t_r, +\beta_{\widehat h}\le\beta_{h_{*}}+2\eta+t_r, $$ and hence $$ -R_a(\widehat h)-R_a(h_*) +R_a(\widehat h)-R_a(h_{*}) \le\frac1a\log\!\left(1+e^a(2\eta+t_r)\right). $$ -For instance it suffices to choose $2\eta+t_r\le e^{-a}(e^{a\varepsilon}-1)$. Independent estimation per hypothesis uses +For instance it suffices to choose $`2\eta+t_r\le e^{-a}(e^{a\varepsilon}-1)`$. Independent estimation per hypothesis uses $$ L\ge\frac{1}{2\eta^2}\log\frac{2H}{\delta} @@ -104,9 +104,9 @@ $$ groups per hypothesis by Hoeffding's inequality. This supplies a valid support-independent finite-class learner without any quantum collective-search theorem. Optimizing its dependence on tilt or hypothesis count is a separate question. -For fixed $a$, the Poisson tail admits caps of order $\log(1/\varepsilon)/\log\log(1/\varepsilon)$ as $\varepsilon\to0$. The matching necessity requires the moment-approximation lower bound at the same error convention; it is not inferred from this upper-tail calculation alone. This asymptotic is distinct from the passive theorem, which fixes $a$, $\varepsilon$, and $k$ before taking $M\to\infty$. +For fixed $`a`$, the Poisson tail admits caps of order $`\log(1/\varepsilon)/\log\log(1/\varepsilon)`$ as $`\varepsilon\to0`$. The matching necessity requires the moment-approximation lower bound at the same error convention; it is not inferred from this upper-tail calculation alone. This asymptotic is distinct from the passive theorem, which fixes $`a`$, $`\varepsilon`$, and $`k`$ before taking $`M\to\infty`$. -For a negative tilt $-a$, use acceptance rather than loss bits: $\prod_{j=1}^K(1-Y_j)$ has mean $\mathbb E e^{-a\ell_h(X)}$. Minimizing $R_{-a}$ then means *maximizing* this mean. Copy charges and tail estimates are unchanged; the optimization direction must be reversed. +For a negative tilt $`-a`$, use acceptance rather than loss bits: $`\prod_{j=1}^K(1-Y_j)`$ has mean $`\mathbb E e^{-a\ell_h(X)}`$. Minimizing $`R_{-a}`$ then means *maximizing* this mean. Copy charges and tail estimates are unchanged; the optimization direction must be reversed. ## Physical and computational resources @@ -114,20 +114,20 @@ The following accounting describes the constructions, rather than an optimized u | Construction | Natural source events | Physical specimens | Persistent storage | Hypothesis operations | |---|---:|---:|---|---| -| Passive fixed-$H$ frontier | $O(M^{1-1/k})$ at fixed parameters | One per event | Classical context/outcome cache for one batch | One known single-copy measurement per received specimen | -| Deterministic $k$-copy replay, separate hypotheses | $\le HL$ | $\le kHL$ | Classical running estimates; source may prepare copies sequentially | At most $k$ known measurements per group | -| Capped Poisson replay, separate hypotheses | $\le HL$ | At most $rHL$; expectation at most $(a+e^{-a})HL$ | Classical running estimates | At most $r$ known measurements per group | +| Passive fixed-$`H`$ frontier | $`O(M^{1-1/k})`$ at fixed parameters | One per event | Classical context/outcome cache for one batch | One known single-copy measurement per received specimen | +| Deterministic $`k`$-copy replay, separate hypotheses | $`\le HL`$ | $`\le kHL`$ | Classical running estimates; source may prepare copies sequentially | At most $`k`$ known measurements per group | +| Capped Poisson replay, separate hypotheses | $`\le HL`$ | At most $`rHL`$; expectation at most $`(a+e^{-a})HL`$ | Classical running estimates | At most $`r`$ known measurements per group | | Shared quantum collision blocks with joint QERM | Depends on the inherited QERM group count | Includes all specimens consumed while finding collision groups | Quantum cache of unknown specimens plus classical context records | Block-projector/dilation and threshold-search operations must be implemented | ### Passive storage and processing -For the memoryless-measurement upper bound, each batch can maintain a dictionary indexed by observed contexts, with counts capped at $k$ and the first $k$ binary outcomes. There are at most $b_M$ entries. A conservative peak classical-memory charge is +For the memoryless-measurement upper bound, each batch can maintain a dictionary indexed by observed contexts, with counts capped at $`k`$ and the first $`k`$ binary outcomes. There are at most $`b_M`$ entries. A conservative peak classical-memory charge is $$ O\!\left(b_M(\log M+k+\log(k+1))\right)\text{ bits}. $$ -Hypotheses and batches can be processed sequentially, reusing this cache. Uniform selection among eligible contexts can use reservoir sampling when a context first reaches count $k$. This selection is independent of all quantum measurement outcomes. Hash-table processing has expected linear word-operation cost per batch; bit operations, reading context labels, and implementing $\Pi_h(x)$ have their usual additional costs. +Hypotheses and batches can be processed sequentially, reusing this cache. Uniform selection among eligible contexts can use reservoir sampling when a context first reaches count $`k`$. This selection is independent of all quantum measurement outcomes. Hash-table processing has expected linear word-operation cost per batch; bit operations, reading context labels, and implementing $`\Pi_h(x)`$ have their usual additional costs. The source Hilbert-space dimension does not appear in the sample exponent. The cost of realizing its hypothesis measurements does: this work assumes those known measurements are implementable and does not replace their circuits with free oracles. No QRAM is required by the immediate-measurement construction. @@ -135,12 +135,12 @@ The source Hilbert-space dimension does not appear in the sample exponent. The c Fanizza, Quek, and Rosati's [QERM theorem](https://doi.org/10.1103/PRXQuantum.5.020367) provides dimension-independent sample bounds with polylogarithmic dependence on the size of a finite projector class. Applying that theorem to the lifted replay projectors, or to a shifted/rescaled polynomial observable with a projector dilation, is an inherited route to improving hypothesis-count dependence. -It requires quantum data availability appropriate to that learning primitive. To use a collision group for several noncommuting hypotheses, one cannot first measure every incoming specimen with a chosen hypothesis and then treat its classical outcome as the untouched quantum state. A straightforward collision extractor retains unknown quantum specimens until the repeated context is identified, charging up to $O(b_M\log d)$ quantum bits for a batch of $d$-dimensional outputs, as well as the retained accepted groups and QERM workspace. Replay blocks likewise consume their full conditional-state copy count. +It requires quantum data availability appropriate to that learning primitive. To use a collision group for several noncommuting hypotheses, one cannot first measure every incoming specimen with a chosen hypothesis and then treat its classical outcome as the untouched quantum state. A straightforward collision extractor retains unknown quantum specimens until the repeated context is identified, charging up to $`O(b_M\log d)`$ quantum bits for a batch of $`d`$-dimensional outputs, as well as the retained accepted groups and QERM workspace. Replay blocks likewise consume their full conditional-state copy count. A block product projector needs the constituent known hypothesis tests and conjunction/complement controls; a signed polynomial surrogate additionally needs its shift, scale, and dilation. The QERM sample theorem does not imply a polylogarithmic gate count in the number of hypotheses. Threshold search and hypothesis-circuit evaluation can be expensive. These costs cannot be replaced by the sample count. ## Interpretation limits -The fixed-$H$ matching passive exponent already has a classical latent-Bernoulli realization. The result therefore does not establish a quantum processing advantage, a time speedup, a practical crossover, or a benefit from a particular hardware implementation. Its operational conclusion is which repeated conditional observations the selected nonlinear-risk accuracy requires, and what changes when the physical source can supply them deliberately. +The fixed-$`H`$ matching passive exponent already has a classical latent-Bernoulli realization. The result therefore does not establish a quantum processing advantage, a time speedup, a practical crossover, or a benefit from a particular hardware implementation. Its operational conclusion is which repeated conditional observations the selected nonlinear-risk accuracy requires, and what changes when the physical source can supply them deliberately. Nonuniform or unknown context probabilities, an evolving state table, restrictions on quantum or classical memory, improper hypothesis outputs, and the exact threshold endpoints require their own analysis. They are not obtained by silently extending the displayed asymptotic. diff --git a/verification/README.md b/verification/README.md index 94de734..cc39da6 100644 --- a/verification/README.md +++ b/verification/README.md @@ -38,22 +38,22 @@ The dependencies are pinned to the versions used for the recorded run. The scrip The source checks use $$ -\rho(p,q)=\operatorname{diag}(1-p,p)\otimes -\operatorname{diag}(1-q,q). +\rho(p,q)=\mathrm{diag}(1-p,p)\otimes +\mathrm{diag}(1-q,q). $$ -One world draws the frozen coordinates independently from $\mu,\nu$; the other swaps these priors. Each averaged state is diagonal, so half the $\ell_1$ distance of its diagonal is its quantum half trace distance. This verifies an actual quantum input family, while keeping the finite calculation small. It does not restrict the learner's processing to measurements in that diagonal basis. +One world draws the frozen coordinates independently from $`\mu,\nu`$; the other swaps these priors. Each averaged state is diagonal, so half the $`\ell_1`$ distance of its diagonal is its quantum half trace distance. This verifies an actual quantum input family, while keeping the finite calculation small. It does not restrict the learner's processing to measurements in that diagonal basis. ## Recorded thresholds -$\Gamma_r(a)$ is the logarithmic moment ambiguity divided by $a$. +$`\Gamma_r(a)`$ is the logarithmic moment ambiguity divided by $`a`$. | (a) | (Gamma_0) | (Gamma_1) | (Gamma_2) | (Gamma_3) | |---:|---:|---:|---:|---:| | 1 | 1 | 0.123301561482 | 0.010295312342 | 0.000644562136 | | 2 | 1 | 0.237237323535 | 0.039761060549 | 0.005003925480 | -The recorded run passed all checks. Matched source-block half trace distances were below $1.3\times10^{-16}$. The refined moment and continuum-envelope residuals were below the script's $10^{-10}$ tolerance; exact values are retained in the result file. The collision calculation also records finite examples at $T\approx M^{1-1/k}$, alongside the fixed-(k) Poisson limit. Those examples illustrate the scaling and are not used to certify an asymptotic theorem. +The recorded run passed all checks. Matched source-block half trace distances were below $`1.3\times10^{-16}`$. The refined moment and continuum-envelope residuals were below the script's $`10^{-10}`$ tolerance; exact values are retained in the result file. The collision calculation also records finite examples at $`T\approx M^{1-1/k}`$, alongside the fixed-(k) Poisson limit. Those examples illustrate the scaling and are not used to certify an asymptotic theorem. ## Limits From 1ed5af9c7e7bb0fc194dec27f8b34f7435e34f48 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sun, 15 Nov 2026 11:58:41 +0800 Subject: [PATCH 3/5] Preserve mathematical punctuation through the hosted Markdown parser --- README.md | 2 +- learning/anchor.md | 4 +-- learning/story.md | 10 +++--- science/interpretation.md | 2 +- science/model.md | 26 +++++++-------- science/moment_frontier.md | 59 +++++++++++++++++---------------- science/passive_frontier.md | 40 +++++++++++----------- science/replay_and_resources.md | 12 +++---- 8 files changed, 78 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index b54959e..08e2e3f 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ For every fixed integer $`k\ge1`$, at accuracies strictly between adjacent thres \Gamma_k(a)<\varepsilon<\Gamma_{k-1}(a) \quad\Longrightarrow\quad N_{\mathrm{worst}}(M) -=\Theta_{a,\varepsilon,H,\delta}\!\left(M^{1-1/k}\right). +=\Theta_{a,\varepsilon,H,\delta}\left(M^{1-1/k}\right). ``` Here $`H\ge2`$ is a fixed finite cap on the number of hypotheses, the failure target satisfies $`0\lt \delta\lt 1/2`$, and $`M`$ tends to infinity while the other parameters remain fixed. The upper bound holds for every such class; a particular two-hypothesis class on two-qubit outputs witnesses the worst-case lower bound. Arbitrary collective quantum measurements are allowed. diff --git a/learning/anchor.md b/learning/anchor.md index d81bfaa..cc9e0dd 100644 --- a/learning/anchor.md +++ b/learning/anchor.md @@ -25,9 +25,9 @@ Watrous uses matrix notation rather than Dirac notation. The project uses both. | --- | --- | | A complex Euclidean space such as $`\mathcal X`$ | A finite-dimensional register space, here $`\mathsf Q\cong\mathbb C^d`$ | | $`\mathrm D(\mathcal X)`$ | The density operators, written $`\mathcal D(\mathsf Q)`$ here | -| $`u u^{*}`$ and $`E_{x,x}=e_xe_x^{*}`$ | $`\lvert u\rangle\langle u\rvert`$ and $`\lvert x\rangle\langle x\rvert`$ | +| $`u u^{\ast }`$ and $`E_{x,x}=e_xe_x^{\ast }`$ | $`\lvert u\rangle\langle u\rvert`$ and $`\lvert x\rangle\langle x\rvert`$ | | A measurement $`\mu`$ with outcome operator $`\mu(1)`$ | The loss outcome operator $`I-\Pi_h(x)`$ | -| $`\langle A,\rho\rangle=\mathrm{Tr}(A^{*}\rho)`$ | $`\mathrm{Tr}[(I-\Pi_h(x))\rho_x]=\ell_h(x)`$ for the Hermitian loss projector | +| $`\langle A,\rho\rangle=\mathrm{Tr}(A^{\ast }\rho)`$ | $`\mathrm{Tr}[(I-\Pi_h(x))\rho_x]=\ell_h(x)`$ for the Hermitian loss projector | | $`\lVert A\rVert_1`$ | The same trace norm; our trace distance is $`D(\rho,\sigma)=\tfrac12\lVert\rho-\sigma\rVert_1`$ | ## From registers to the source diff --git a/learning/story.md b/learning/story.md index 3a920e4..fb90413 100644 --- a/learning/story.md +++ b/learning/story.md @@ -73,7 +73,7 @@ Repeated preparations reveal higher moments. Passive data can supply such repeti Let $`\mu`$ and $`\nu`$ be probability distributions of a loss value $`u\in[0,1]`$. Matching their first $`r`$ moments means $$ -\int u^j\,d\mu(u)=\int u^j\,d\nu(u) +\int u^j\thinspace d\mu(u)=\int u^j\thinspace d\nu(u) \quad(0\le j\le r). $$ @@ -82,8 +82,8 @@ Define $$ \kappa_r(a)= \max_{\mu,\nu\ \mathrm{matching\ through}\ r} -\frac{\int e^{au}\,d\mu(u)} -{\int e^{au}\,d\nu(u)},\qquad +\frac{\int e^{au}\thinspace d\mu(u)} +{\int e^{au}\thinspace d\nu(u)},\qquad \Gamma_r(a)=\frac1a\log\kappa_r(a). $$ @@ -126,7 +126,7 @@ $$ is $$ -\mathsf N^{*}(M) +\mathsf N^{\ast }(M) =\Theta_{a,\varepsilon,H,\delta,k}(M^{1-1/k}) \qquad(M\to\infty). $$ @@ -170,7 +170,7 @@ Minimizing the estimated envelope surrogate loses at most $`\Gamma_k(a)`$ plus s If the source can deliberately prepare $`k`$ independent copies at a sampled context, the learner obtains effective groups directly. For fixed tolerance above $`\Gamma_k(a)`$, the number of groups can be independent of $`M`$. Every initial and repeated specimen is still charged. This capability is independent preparation from the source, not cloning a received unknown state. -Random replica depth is another interface choice. With $`K\sim\mathrm{Poisson}(a)`$, the loss-bit product has mean $`e^{a(\ell_h(x)-1)}`$. The identity is inherited Bernoulli-factory machinery. If a natural arrival always prepares an initial specimen, the physical count is $`\max\{1,K\}`$, with mean $`a+e^{-a}`$, rather than $`a`$. A finite expected count with an unbounded tail is different from a deterministic cap. +Random replica depth is another interface choice. With $`K\sim\mathrm{Poisson}(a)`$, the loss-bit product has mean $`e^{a(\ell_h(x)-1)}`$. The identity is inherited Bernoulli-factory machinery. If a natural arrival always prepares an initial specimen, the physical count is $`\max\lbrace 1,K\rbrace `$, with mean $`a+e^{-a}`$, rather than $`a`$. A finite expected count with an unbounded tail is different from a deterministic cap. The [resource account](../science/replay_and_resources.md) also charges discarded passive arrivals, classical caches, measurement circuits and any quantum waiting memory. diff --git a/science/interpretation.md b/science/interpretation.md index 82297dc..3181e8b 100644 --- a/science/interpretation.md +++ b/science/interpretation.md @@ -22,7 +22,7 @@ $$ has worst-case proper-learning source cost $$ -N_{\min}(M)=\Theta_{a,\epsilon,H,\delta}\!\left(M^{1-1/k}\right). +N_{\min}(M)=\Theta_{a,\epsilon,H,\delta}\left(M^{1-1/k}\right). $$ Here the input distribution is uniform on a known $`M`$-point support, the conditional-state table is unknown and fixed, the finite class size $`H\geq2`$ and failure probability $`0\lt \delta\lt 1/2`$ are fixed, and $`M`$ grows. The upper bound holds for each fixed finite class. The lower bound is witnessed by a particular two-hypothesis class on a four-dimensional output space; it is not a lower bound for every class. diff --git a/science/model.md b/science/model.md index 9359345..33b341e 100644 --- a/science/model.md +++ b/science/model.md @@ -6,7 +6,7 @@ The objective is a nonlinear function of a conditional Born probability. This di ## 1. Source and hypotheses -Let $`M\geq 1`$, let $`\mathsf Q\cong\mathbb C^d`$ be a finite-dimensional quantum register, and write $`[M]=\{1,\ldots,M\}`$. An unknown source is a fixed table +Let $`M\geq 1`$, let $`\mathsf Q\cong\mathbb C^d`$ be a finite-dimensional quantum register, and write $`[M]=\lbrace 1,\ldots,M\rbrace `$. An unknown source is a fixed table $$ \rho:[M]\longrightarrow\mathcal D(\mathsf Q),\qquad x\longmapsto\rho_x. @@ -29,13 +29,13 @@ The table is fixed throughout the experiment. If a label reappears, the source s The learner knows $`M`$ and a finite hypothesis class $$ -\mathcal H=\{h_1,\ldots,h_m\},\qquad 1\leq m\leq H,\quad H\geq2. +\mathcal H=\lbrace h_1,\ldots,h_m\rbrace ,\qquad 1\leq m\leq H,\quad H\geq2. $$ Here $`H`$ is the fixed class-size cap; $`m`$ is the size of the supplied class. Each hypothesis specifies known projectors $`\Pi_h(x)`$ on $`\mathsf Q`$. Its conditional loss is $$ -\ell_h(x)=1-\mathrm{Tr}\!\left(\Pi_h(x)\rho_x\right)\in[0,1]. +\ell_h(x)=1-\mathrm{Tr}\left(\Pi_h(x)\rho_x\right)\in[0,1]. $$ This is agnostic learning: the unknown table need not belong to the hypothesis class. The lower bounds use constant projectors on a fixed number of qubits, so they do not rely on difficult hypothesis evaluation or a growing quantum output dimension. @@ -50,7 +50,7 @@ $$ The task is to minimize this quantity over $`h\in\mathcal H`$. It lies in $`[0,1]`$. As $`a\to0`$, it tends to the mean loss $`M^{-1}\sum_x\ell_h(x)`$; a positive tilt gives more weight to contexts with larger conditional loss. -Let $`Y_h\in\{0,1\}`$ be the loss outcome obtained by measuring $`\{\Pi_h(x),I-\Pi_h(x)\}`$ on one copy at context $`x`$, with $`Y_h=1`$ for the second outcome. Then +Let $`Y_h\in\lbrace 0,1\rbrace `$ be the loss outcome obtained by measuring $`\lbrace \Pi_h(x),I-\Pi_h(x)\rbrace `$ on one copy at context $`x`$, with $`Y_h=1`$ for the second outcome. Then $$ \mathbb E[Y_h\mid X=x]=\ell_h(x). @@ -87,17 +87,17 @@ $$ An $`(\epsilon,\delta)`$ guarantee means $$ -\Pr\!\left[\mathcal E_a(\widehat h;\rho)\leq\epsilon\right]\geq1-\delta +\Pr\left[\mathcal E_a(\widehat h;\rho)\leq\epsilon\right]\geq1-\delta $$ for every fixed source table $`\rho`$. Probability is over the sampled labels, measurement outcomes, and learner randomness. -For a specified class and dimension, let $`N^{*}(M,\mathcal H,d;a,\epsilon,\delta)`$ be the least number of passive examples permitting this guarantee. The worst-case finite-class copy complexity is +For a specified class and dimension, let $`N^{\ast }(M,\mathcal H,d;a,\epsilon,\delta)`$ be the least number of passive examples permitting this guarantee. The worst-case finite-class copy complexity is $$ -\mathsf N^{*}(M;a,H,\epsilon,\delta) -=\sup_{d,\,\mathcal H:\,1\leq|\mathcal H|\leq H} -N^{*}(M,\mathcal H,d;a,\epsilon,\delta). +\mathsf N^{\ast }(M;a,H,\epsilon,\delta) +=\sup_{d,\thinspace \mathcal H:\thinspace 1\leq|\mathcal H|\leq H} +N^{\ast }(M,\mathcal H,d;a,\epsilon,\delta). $$ The algorithm may depend on the known class, $`M`$, and the displayed parameters. In support-size asymptotics, $`a,H,\epsilon,\delta`$ are fixed and $`M\to\infty`$. Constants may depend on those fixed parameters. The sharp exponent statements concern $`0\lt \delta\lt 1/2`$ and errors strictly between successive moment-frontier values; they do not assert endpoint behavior or uniform constants when the tilt, accuracy, or class size also vary. @@ -109,7 +109,7 @@ A support-independent guarantee uses a number of examples bounded independently The PAC condition above bounds the excess of the hypothesis actually returned. A different criterion is expected regret, $$ -\mathbb E\!\left[\mathcal E_a(\widehat h;\rho)\right]. +\mathbb E\left[\mathcal E_a(\widehat h;\rho)\right]. $$ Randomizing between hypotheses can reduce expected regret while leaving a substantial probability of returning a hypothesis with large excess. Consequently, for a class of size $`m`$ the sharp interval-based expected-regret factor is $`1-1/m`$; its worst case under the cap is $`1-1/H`$. The PAC tolerance floor has no such factor. These statements must not be substituted for one another. @@ -145,14 +145,14 @@ $$ Then $$ -R_a(h;\rho)=\frac1a\log\int_0^1e^{au}\,d\mu_h^\rho(u). +R_a(h;\rho)=\frac1a\log\int_0^1e^{au}\thinspace d\mu_h^\rho(u). $$ With $`r`$ copies at one context, measuring the same hypothesis on those copies gives IID conditional Bernoulli losses. For $`j\leq r`$, $$ -\mathbb E\!\left[\prod_{i=1}^{j}Y_{h,i}\right] -=\int_0^1u^j\,d\mu_h^\rho(u). +\mathbb E\left[\prod_{i=1}^{j}Y_{h,i}\right] +=\int_0^1u^j\thinspace d\mu_h^\rho(u). $$ This provides an upper-bound method using the first $`r`$ loss moments. The algebraic fact that an $`r`$-copy observable has an expectation polynomial of degree at most $`r`$ in the state, and that polynomial state functionals can be represented on multiple copies, is established background; see [Brun (2004)](https://arxiv.org/abs/quant-ph/0401067). diff --git a/science/moment_frontier.md b/science/moment_frontier.md index 5cebba1..797083c 100644 --- a/science/moment_frontier.md +++ b/science/moment_frontier.md @@ -9,8 +9,8 @@ Let $`\mathcal P([0,1])`$ denote the probability measures on $`[0,1]`$, put $`f_ $$ \kappa_r(a)= \max_{\substack{\mu,\nu\in\mathcal P([0,1])\\ -\int u^j\,d\mu=\int u^j\,d\nu\ (0\leq j\leq r)}} -\frac{\int f_a\,d\mu}{\int f_a\,d\nu}, +\int u^j\thinspace d\mu=\int u^j\thinspace d\nu\ (0\leq j\leq r)}} +\frac{\int f_a\thinspace d\mu}{\int f_a\thinspace d\nu}, \qquad \Gamma_r(a)=\frac{\log\kappa_r(a)}a. $$ @@ -20,10 +20,10 @@ The order-zero condition records equal mass. Both measures already have mass one $$ \Gamma_r(a)= \max_{\mu,\nu\text{ matching through }r} -\left| -\frac1a\log\int f_a\,d\mu- -\frac1a\log\int f_a\,d\nu -\right|. +\left\lvert +\frac1a\log\int f_a\thinspace d\mu- +\frac1a\log\int f_a\thinspace d\nu +\right\rvert. $$ The maximum exists. The space of probability measures on the compact interval is weakly compact; the moment constraints are closed; the exponential integrals are continuous; and the denominator is at least one. In particular, $`1\leq\kappa_r(a)\leq e^a`$. @@ -31,7 +31,7 @@ The maximum exists. The space of probability measures on the compact interval is The measures can be chosen with finite support. Indeed, the vector $$ -\left(\int u\,d\mu,\ldots,\int u^r\,d\mu,\int f_a\,d\mu\right) +\left(\int u\thinspace d\mu,\ldots,\int u^r\thinspace d\mu,\int f_a\thinspace d\mu\right) $$ lies in the convex hull of the curve $`(u,\ldots,u^r,f_a(u))\in\mathbb R^{r+1}`$. Carathéodory's theorem replaces it by a measure on at most $`r+2`$ points. Applying this separately to an optimal pair preserves its moments and exponential integrals. @@ -58,10 +58,10 @@ $$ **Proof.** First suppose $`f_a\leq p\leq Kf_a`$ and $`\mu,\nu`$ match moments through $`r`$. Then $$ -\int f_a\,d\mu -\leq\int p\,d\mu -=\int p\,d\nu -\leq K\int f_a\,d\nu. +\int f_a\thinspace d\mu +\leq\int p\thinspace d\mu +=\int p\thinspace d\nu +\leq K\int f_a\thinspace d\nu. $$ Thus every feasible envelope bounds the moment ratio from above. @@ -107,7 +107,7 @@ Define the best relative approximation error $$ E_r(a)=\min_{\deg q\leq r}\max_{0\leq u\leq1} -\left|q(u)e^{-au}-1\right|. +\left\lvertq(u)e^{-au}-1\right\rvert. $$ The minimum exists by the same coefficient-compactness argument as above, and $`E_r(a)\lt 1`$: a suitable positive constant already gives error $`\tanh(a/2)\lt 1`$. Scaling an envelope to balance its upper and lower relative errors, and conversely scaling a relative approximant upward, gives @@ -171,10 +171,10 @@ The alternation theorem used here is the usual best-approximation theorem for a **Proposition 3 — the first frontier value.** Let $`b=e^a-1`$ and $$ -m_{*}(a)=\frac1a-\frac1b. +m_{\ast }(a)=\frac1a-\frac1b. $$ -Then $`m_{*}\in(0,1)`$ and +Then $`m_{\ast }\in(0,1)`$ and $$ \kappa_1(a)=\frac ba\exp\left(-1+\frac ab\right), @@ -185,7 +185,7 @@ $$ **Proof.** Among probability measures with mean $`m`$, convexity gives $$ -e^{am}\leq\int e^{au}\,d\mu(u)\leq1+m(e^a-1). +e^{am}\leq\int e^{au}\thinspace d\mu(u)\leq1+m(e^a-1). $$ The lower endpoint is attained by $`\delta_m`$, and the upper by $`(1-m)\delta_0+m\delta_1`$. Hence @@ -194,14 +194,14 @@ $$ \kappa_1(a)=\max_{0\leq m\leq1}(1+bm)e^{-am}. $$ -The derivative of its logarithm is $`b/(1+bm)-a`$. It is positive at zero and negative at one, and is strictly decreasing. The unique maximizer is $`m_{*}`$; substitution gives the displayed formula. $`\square`$ +The derivative of its logarithm is $`b/(1+bm)-a`$. It is positive at zero and negative at one, and is strictly decreasing. The unique maximizer is $`m_{\ast }`$; substitution gives the displayed formula. $`\square`$ Writing $`S(h)=(h-1)h^{1/(h-1)}/(e\log h)`$, this is $`\Gamma_1(a)=a^{-1}\log S(e^a)`$. The function $`S`$ is the classical [Specht ratio](https://www.kurims.kyoto-u.ac.jp/~kyodo/kokyuroku/contents/pdf/1259-1.pdf), a sharp reverse arithmetic-geometric mean constant. The constant is inherited; its operational interpretation is supplied below. **Proposition 4 — fixed-degree small-tilt asymptotics.** For each fixed integer $`r\geq1`$, $$ -\Gamma_r(a)\sim\frac{a^r}{(r+1)!\,4^r}\qquad(a\downarrow0). +\Gamma_r(a)\sim\frac{a^r}{(r+1)!\thinspace 4^r}\qquad(a\downarrow0). $$ **Proof.** Let $`P_r(u)=\sum_{j=0}^{r}(au)^j/j!`$. Uniformly on $`[0,1]`$, @@ -216,7 +216,7 @@ Subtracting $`P_r`$ does not change distance from the degree-$`r`$ polynomial sp $$ \frac{E_r(a)}{a^{r+1}} \longrightarrow -\frac1{(r+1)!}\inf_{\deg q\leq r}\|u^{r+1}-q(u)\|_\infty. +\frac1{(r+1)!}\inf_{\deg q\leq r}\Vert u^{r+1}-q(u)\Vert _\infty. $$ The last infimum is $`2^{-(2r+1)}`$. Indeed, the monic shifted Chebyshev polynomial $`2^{-(2r+1)}\mathrm T_{r+1}(2u-1)`$ has exactly that norm. A monic polynomial with smaller norm would differ from it by a degree-$`r`$ polynomial with at least $`r+1`$ sign changes between its alternating extreme points, a contradiction. Finally, @@ -243,18 +243,18 @@ $$ A_h\leq P_h\leq\kappa_r(a)A_h. $$ -If all $`P_h`$ are estimated to additive error at most $`\eta`$ and the learner minimizes those estimates, then for a true risk minimizer $`h^{*}`$, +If all $`P_h`$ are estimated to additive error at most $`\eta`$ and the learner minimizes those estimates, then for a true risk minimizer $`h^{\ast }`$, $$ A_{\widehat h}\leq P_{\widehat h} -\leq P_{h^{*}}+2\eta -\leq\kappa_r(a)A_{h^{*}}+2\eta. +\leq P_{h^{\ast }}+2\eta +\leq\kappa_r(a)A_{h^{\ast }}+2\eta. $$ -Since $`A_{h^{*}}\geq1`$, +Since $`A_{h^{\ast }}\geq1`$, $$ -R_a(\widehat h)-R_a(h^{*}) +R_a(\widehat h)-R_a(h^{\ast }) \leq\Gamma_r(a)+\frac1a\log\left(1+\frac{2\eta}{\kappa_r(a)}\right) \leq\Gamma_r(a)+\frac{2\eta}{a\kappa_r(a)}. $$ @@ -268,15 +268,16 @@ Thus every tolerance strictly above $`\Gamma_r(a)`$ admits a support-independent Choose an optimal pair $`\mu_-,\mu_+`$ matching moments through $`r`$, oriented so that $$ -\frac1a\log\int f_a\,d\mu_+ --\frac1a\log\int f_a\,d\mu_- +\frac1a\log\int f_a\thinspace d\mu_+ +-\frac1a\log\int f_a\thinspace d\mu_- =\Gamma_r(a). $$ To witness the worst case under the class-size cap $`H`$, use exactly $`H`$ hypotheses. For each world $`j\in[H]`$ and each context $`x`$, independently draw latent probabilities $`U_{x,j}\sim\mu_-`$ and $`U_{x,h}\sim\mu_+`$ for $`h\ne j`$. Freeze these draws, and define $$ -\tau_u=\begin{pmatrix}1-u&0\\0&u\end{pmatrix}, +\tau_u=\begin{pmatrix}1-u&0\\ +0&u\end{pmatrix}, \qquad \rho_x=\bigotimes_{h=1}^{H}\tau_{U_{x,h}}. $$ @@ -286,8 +287,8 @@ Hypothesis $`h`$ uses the projector $`|0\rangle\langle0|`$ on coordinate $`h`$, For any $`s\leq r`$, each entry of $`\tau_u^{\otimes s}`$ is a polynomial in $`u`$ of degree at most $`s`$. Therefore $$ -\int\tau_u^{\otimes s}\,d\mu_-(u) -=\int\tau_u^{\otimes s}\,d\mu_+(u). +\int\tau_u^{\otimes s}\thinspace d\mu_-(u) +=\int\tau_u^{\otimes s}\thinspace d\mu_+(u). $$ Regrouping tensor factors by hypothesis coordinate proves that the averaged $`s`$-copy state at a context is identical in every world. Conditional on a sequence of distinct grouped-example labels, the complete averaged training state is consequently identical across worlds, even when the learner is allowed a collective measurement on all groups. With $`G`$ groups, the probability of a repeated group label is at most $`G(G-1)/(2M)`$. @@ -312,7 +313,7 @@ The following elementary decision lemma identifies the metric distinction. **Proof.** By the finite-action compact-game minimax theorem, it suffices to bound the Bayes regret under every distribution of admissible risk vectors. Choose a measurable minimizing action $`J`$ for each vector, breaking ties deterministically, and let $`p_h=\Pr(J=h)`$. Pointwise, $$ -R_h-R_J\leq l_h-l_J+W\,\mathbf1\{h\ne J\}. +R_h-R_J\leq l_h-l_J+W\thinspace \mathbf1\lbrace h\ne J\rbrace . $$ Averaging its expectation over a fixed random action with probabilities $`p_h`$ cancels the $`l`$ terms, giving diff --git a/science/passive_frontier.md b/science/passive_frontier.md index f7b2008..e0fffd2 100644 --- a/science/passive_frontier.md +++ b/science/passive_frontier.md @@ -17,7 +17,7 @@ $$ where $`a>0`$. A proper learner returns an index $`\widehat h`$ in the supplied class. Its guarantee is $$ -\Pr\!\left[R_a(\widehat h)-\min_h R_a(h)\le\varepsilon\right] +\Pr\left[R_a(\widehat h)-\min_h R_a(h)\le\varepsilon\right] \ge 1-\delta $$ @@ -27,7 +27,7 @@ For $`r\ge0`$, let $$ K_r(a)=\sup_{\mu,\nu} -\frac{\int_0^1e^{au}\,d\mu(u)}{\int_0^1e^{au}\,d\nu(u)}, +\frac{\int_0^1e^{au}\thinspace d\mu(u)}{\int_0^1e^{au}\thinspace d\nu(u)}, \qquad \Gamma_r(a)=\frac1a\log K_r(a), $$ @@ -49,8 +49,8 @@ $$ then the worst-case fixed-budget passive sample complexity, over classes of size at most $`H`$ and fixed source tables, satisfies $$ -N^{*}(M)=\Theta_{a,\varepsilon,H,\delta,k} -\!\left(M^{1-1/k}\right) +N^{\ast }(M)=\Theta_{a,\varepsilon,H,\delta,k} +\left(M^{1-1/k}\right) \qquad(M\to\infty). $$ @@ -63,8 +63,8 @@ The upper bound holds for every such finite class. The lower bound is witnessed First suppose $`k\ge2`$, and put $`r=k-1`$. Because $`\varepsilon\lt \Gamma_r(a)`$, choose moment-matched probability measures $`\mu,\nu`$ such that $$ -u=\int e^{ap}\,d\mu(p),\qquad -v=\int e^{ap}\,d\nu(p),\qquad +u=\int e^{ap}\thinspace d\mu(p),\qquad +v=\int e^{ap}\thinspace d\nu(p),\qquad g=\frac1a\log\frac vu>\varepsilon. $$ @@ -114,7 +114,7 @@ $$ If $`\omega_0,\omega_1`$ are the prior-averaged classical-quantum training states, their trace distance obeys $$ -\frac12\|\omega_0-\omega_1\|_1\le q_n. +\frac12\Vert \omega_0-\omega_1\Vert _1\le q_n. $$ Indeed their contributions on $`E`$ are equal, and the remaining subnormalized states each have trace $`q_n`$. With equal world priors, no procedure can identify the world with average probability greater than $`(1+q_n)/2`$. @@ -130,15 +130,15 @@ $$ Both coordinate exponential moments are averages of $`M`$ independent random variables in $`[1,e^a]`$. Hoeffding's inequality and a union bound show that, in either world, with probability at least $`1-\eta_M`$, $$ -\left|\frac1M\sum_xe^{ap_x}-\mathbb E e^{ap_x}\right|\le\zeta, +\left\lvert\frac1M\sum_xe^{ap_x}-\mathbb E e^{ap_x}\right\rvert\le\zeta, \qquad -\left|\frac1M\sum_xe^{aq_x}-\mathbb E e^{aq_x}\right|\le\zeta, +\left\lvert\frac1M\sum_xe^{aq_x}-\mathbb E e^{aq_x}\right\rvert\le\zeta, $$ where $$ -\eta_M=4\exp\!\left(-\frac{2M\zeta^2}{(e^a-1)^2}\right). +\eta_M=4\exp\left(-\frac{2M\zeta^2}{(e^a-1)^2}\right). $$ All exponential moments are at least one, so $`\log`$ is 1-Lipschitz on their range. On this good-table event the two actual risks differ, in the intended direction, by at least @@ -153,13 +153,13 @@ Thus, on every good table, an $`(\varepsilon,\delta)`$-PAC proper learner must s For explicit constants put $`w=1-2\delta>0`$. Take $`M`$ large enough that $`\eta_M\le w/8`$, and take $$ -n\le c\,M^{1-1/k},\qquad +n\le c\thinspace M^{1-1/k},\qquad c=\left(\frac{wk!}{4}\right)^{1/k}. $$ Then $`q_n\le w/4`$. The learning guarantee would give world-identification success at least $`1/2+3w/8`$, whereas the trace-distance bound permits at most $`1/2+w/8`$. This contradiction proves the lower bound. In particular, some deterministic fixed table violates the proposed learning guarantee; a random-table prior is not being substituted for the original task. -When $`k=1`$, the asserted exponent is zero. Since $`\varepsilon\lt \Gamma_0(a)=1`$, two deterministic tables with opposite optimal hypotheses and risk gap one rule out a zero-sample learner at $`\delta\lt 1/2`$. Hence $`N^{*}(M)\ge1=\Omega(M^0)`$. The preceding collision argument is unnecessary in this case. +When $`k=1`$, the asserted exponent is zero. Since $`\varepsilon\lt \Gamma_0(a)=1`$, two deterministic tables with opposite optimal hypotheses and risk gap one rule out a zero-sample learner at $`\delta\lt 1/2`$. Hence $`N^{\ast }(M)\ge1=\Omega(M^0)`$. The preceding collision argument is unnecessary in this case. ## Upper bound from uniformly selected collision groups @@ -179,7 +179,7 @@ $$ \mathbb EC={b_M\choose k}M^{1-k}\longrightarrow\lambda_k=\frac1{k!}. $$ -In $`\mathbb EC^2`$, disjoint pairs of subsets contribute asymptotically $`\lambda_k^2`$, identical subsets contribute $`\lambda_k`$, and pairs overlapping in $`j\in\{1,\ldots,k-1\}`$ positions contribute +In $`\mathbb EC^2`$, disjoint pairs of subsets contribute asymptotically $`\lambda_k^2`$, identical subsets contribute $`\lambda_k`$, and pairs overlapping in $`j\in\lbrace 1,\ldots,k-1\rbrace `$ positions contribute $$ {b_M\choose k}{k\choose j}{b_M-k\choose k-j} @@ -215,7 +215,7 @@ e^{au}\le P(u)=\sum_{j=0}^k c_j u^j \le K_k(a)e^{au}. $$ -Fix hypothesis $`h`$ for a batch. Upon receiving $`(x,\rho_x)`$, measure the loss projector $`I-\Pi_h(x)`$, producing $`Y\in\{0,1\}`$ with mean $`\ell_h(x)`$. For a selected collision group define +Fix hypothesis $`h`$ for a batch. Upon receiving $`(x,\rho_x)`$, measure the loss projector $`I-\Pi_h(x)`$, producing $`Y\in\lbrace 0,1\rbrace `$ with mean $`\ell_h(x)`$. For a selected collision group define $$ Z_h=\sum_{j=0}^k c_j\prod_{i=1}^jY_i, @@ -235,7 +235,7 @@ Equivalently, on $`k`$ quantum copies one may use the Hermitian observable $$ O_h(x)=\sum_{j=0}^k c_j \bigl(I-\Pi_h(x)\bigr)^{\otimes j}\otimes I^{\otimes(k-j)}, -\qquad \|O_h(x)\|\le A_P. +\qquad \Vert O_h(x)\Vert \le A_P. $$ If a binary effect is needed by another learning primitive, $`(O_h+A_PI)/(2A_P)`$ lies between zero and identity and admits a standard projector dilation. This shift and rescaling, including its effect on accuracy and gate costs, must be retained. @@ -273,18 +273,18 @@ N\le H B b_M =O_{a,\varepsilon,H,\delta,k}(M^{1-1/k}). $$ -Choose $`\widehat h`$ minimizing $`\widehat S_h`$, and let $`h_{*}`$ minimize the true tilted risk. On the simultaneous good event, +Choose $`\widehat h`$ minimizing $`\widehat S_h`$, and let $`h_{\ast }`$ minimize the true tilted risk. On the simultaneous good event, $$ A_{\widehat h}\le S_{\widehat h} -\le S_{h_{*}}+2\eta -\le K_k(a)A_{h_{*}}+2\eta. +\le S_{h_{\ast }}+2\eta +\le K_k(a)A_{h_{\ast }}+2\eta. $$ -Since $`A_{h_{*}}\ge1`$, +Since $`A_{h_{\ast }}\ge1`$, $$ -R_a(\widehat h)-R_a(h_{*}) +R_a(\widehat h)-R_a(h_{\ast }) \le\frac1a\log\bigl(K_k(a)+2\eta\bigr) <\varepsilon. $$ diff --git a/science/replay_and_resources.md b/science/replay_and_resources.md index ca2438b..ff7bac5 100644 --- a/science/replay_and_resources.md +++ b/science/replay_and_resources.md @@ -64,8 +64,8 @@ The identity is the classical Poisson probability-generating-function/exponentia Under the natural-source interface, the first specimen is prepared even when $`K=0`$. The physical number prepared for an untruncated event is therefore $$ -\max\{1,K\},\qquad -\mathbb E\max\{1,K\}=a+e^{-a}\le 1+a. +\max\lbrace 1,K\rbrace ,\qquad +\mathbb E\max\lbrace 1,K\rbrace =a+e^{-a}\le 1+a. $$ When $`K=0`$ this initial specimen is unused. An expected cost of exactly $`a`$ is valid only under an explicitly stronger interface that can reveal the context while preparing no quantum output on zero-copy events. That interface is not assumed here. @@ -86,14 +86,14 @@ Every event prepares at most $`r`$ specimens. Its expected count is at most $`a+ Suppose estimates of $`\beta_h^{(r)}`$ have uniform additive error at most $`\eta`$. Selecting a minimizer then gives $$ -\beta_{\widehat h}\le\beta_{h_{*}}+2\eta+t_r, +\beta_{\widehat h}\le\beta_{h_{\ast }}+2\eta+t_r, $$ and hence $$ -R_a(\widehat h)-R_a(h_{*}) -\le\frac1a\log\!\left(1+e^a(2\eta+t_r)\right). +R_a(\widehat h)-R_a(h_{\ast }) +\le\frac1a\log\left(1+e^a(2\eta+t_r)\right). $$ For instance it suffices to choose $`2\eta+t_r\le e^{-a}(e^{a\varepsilon}-1)`$. Independent estimation per hypothesis uses @@ -124,7 +124,7 @@ The following accounting describes the constructions, rather than an optimized u For the memoryless-measurement upper bound, each batch can maintain a dictionary indexed by observed contexts, with counts capped at $`k`$ and the first $`k`$ binary outcomes. There are at most $`b_M`$ entries. A conservative peak classical-memory charge is $$ -O\!\left(b_M(\log M+k+\log(k+1))\right)\text{ bits}. +O\left(b_M(\log M+k+\log(k+1))\right)\text{ bits}. $$ Hypotheses and batches can be processed sequentially, reusing this cache. Uniform selection among eligible contexts can use reservoir sampling when a context first reaches count $`k`$. This selection is independent of all quantum measurement outcomes. Hash-table processing has expected linear word-operation cost per batch; bit operations, reading context labels, and implementing $`\Pi_h(x)`$ have their usual additional costs. From 281fe924097ec69a495ee3346552a9287ebf9e9b Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sun, 15 Nov 2026 12:00:56 +0800 Subject: [PATCH 4/5] Separate named delimiter commands from their operands --- learning/story.md | 2 +- science/moment_frontier.md | 4 ++-- science/passive_frontier.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/learning/story.md b/learning/story.md index fb90413..4b8ae93 100644 --- a/learning/story.md +++ b/learning/story.md @@ -90,7 +90,7 @@ $$ Thus $`\Gamma_r(a)`$ is the largest possible tilted-risk gap that remains compatible with those moments. An inherited approximation duality gives an equivalent envelope: $$ -\kappa_r(a)=\min\left\lbraceK:\ \exists P,\ \deg P\le r,\quad +\kappa_r(a)=\min\left\lbrace K:\ \exists P,\ \deg P\le r,\quad e^{au}\le P(u)\le K e^{au}\quad(0\le u\le1)\right\rbrace. $$ diff --git a/science/moment_frontier.md b/science/moment_frontier.md index 797083c..ce02cd4 100644 --- a/science/moment_frontier.md +++ b/science/moment_frontier.md @@ -42,7 +42,7 @@ lies in the convex hull of the curve $`(u,\ldots,u^r,f_a(u))\in\mathbb R^{r+1}`$ $$ \kappa_r(a)= -\min\left\lbraceK:\ \exists p\in\mathbb R[u],\ \deg p\leq r, +\min\left\lbrace K:\ \exists p\in\mathbb R[u],\ \deg p\leq r, \quad f_a(u)\leq p(u)\leq Kf_a(u)\quad(0\leq u\leq1)\right\rbrace. $$ @@ -107,7 +107,7 @@ Define the best relative approximation error $$ E_r(a)=\min_{\deg q\leq r}\max_{0\leq u\leq1} -\left\lvertq(u)e^{-au}-1\right\rvert. +\left\lvert q(u)e^{-au}-1\right\rvert. $$ The minimum exists by the same coefficient-compactness argument as above, and $`E_r(a)\lt 1`$: a suitable positive constant already gives error $`\tanh(a/2)\lt 1`$. Scaling an envelope to balance its upper and lower relative errors, and conversely scaling a relative approximant upward, gives diff --git a/science/passive_frontier.md b/science/passive_frontier.md index e0fffd2..a6e007d 100644 --- a/science/passive_frontier.md +++ b/science/passive_frontier.md @@ -35,7 +35,7 @@ $$ where $`\mu,\nu`$ are probability measures with equal moments of degrees $`0,\ldots,r`$. Thus $`K_r(a)`$ is the same constant denoted $`\kappa_r(a)`$ in the moment account. The moment-frontier theorem gives the equivalent attained envelope problem $$ -K_r(a)=\min\left\lbraceK: +K_r(a)=\min\left\lbrace K: \exists P\in\mathbb R[u],\ \deg P\le r,\quad e^{au}\le P(u)\le K e^{au}\quad(0\le u\le1)\right\rbrace. $$ From d256f4e31356c8bc6611bdb15bf4f1e45f07ee14 Mon Sep 17 00:00:00 2001 From: Ruge Lin Date: Sun, 15 Nov 2026 12:08:27 +0800 Subject: [PATCH 5/5] Polish verification tables and add unobstructed hosted screenshots --- .github/workflows/hosted-math.yml | 6 ++ science/interpretation.md | 2 +- verification/README.md | 20 +++---- .../hosted_math/capture_top_screenshots.cjs | 56 +++++++++++++++++++ 4 files changed, 73 insertions(+), 11 deletions(-) create mode 100644 verification/hosted_math/capture_top_screenshots.cjs diff --git a/.github/workflows/hosted-math.yml b/.github/workflows/hosted-math.yml index a8c9ae1..d4997a5 100644 --- a/.github/workflows/hosted-math.yml +++ b/.github/workflows/hosted-math.yml @@ -53,6 +53,11 @@ jobs: --repository "$GITHUB_REPOSITORY" \ --revision "$CAPTURE_REVISION" \ --output "$RUNNER_TEMP/hosted-math" + - name: Capture settled top-scroll screenshots + run: | + export NODE_PATH="$RUNNER_TEMP/math-runtime/node_modules" + node verification/hosted_math/capture_top_screenshots.cjs \ + "$RUNNER_TEMP/hosted-math" "$RUNNER_TEMP/hosted-visual" - name: Retain the actual captures and comparison report if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 @@ -61,5 +66,6 @@ jobs: path: | ${{ runner.temp }}/hosted-math ${{ runner.temp }}/hosted-probe + ${{ runner.temp }}/hosted-visual if-no-files-found: error retention-days: 14 diff --git a/science/interpretation.md b/science/interpretation.md index 3181e8b..983f2c3 100644 --- a/science/interpretation.md +++ b/science/interpretation.md @@ -62,7 +62,7 @@ At tolerances above this threshold, first-moment information is enough for prope ## Replay changes source access -Chosen-input replay supplies fresh preparations of the same conditional state. It permits direct construction of the repeated-context observations without waiting for passive collisions, removing the support-size dependence for fixed parameters. It does not manufacture copies of an unknown received state. A hard cap of $`r`$ preparations per context and an unbounded random count with finite expectation are also different resources; [replay and resources](replay_and_resources.md) keeps them separate. +Chosen-input replay supplies fresh preparations of the same conditional state. It permits direct construction of the repeated-context observations without waiting for passive collisions, removing the support-size dependence for fixed parameters. It does not manufacture copies of an unknown received state. A hard cap of $`r`$ preparations per source event and an unbounded random count with finite expectation are also different resources; [replay and resources](replay_and_resources.md) keeps them separate. Uniform contexts play a substantive role in the passive upper bound. A context-label-symmetric collision rule selects an exactly uniform repeated context. Independent batches therefore yield independent effective examples for every fixed state table. For a nonuniform law, ordinary collision selection reweights a context according to a higher power of its probability, so this argument does not transfer unchanged. diff --git a/verification/README.md b/verification/README.md index cc39da6..cbfc0a7 100644 --- a/verification/README.md +++ b/verification/README.md @@ -25,15 +25,15 @@ The dependencies are pinned to the versions used for the recorded run. The scrip | Check | Computation | Scope | |---|---|---| -| Moment/envelope duality | Independently solve the normalized ratio primal and polynomial-envelope dual on 4,001 points, for eight cases | (a=1,2), degrees (r=0,1,2,3); numerical agreement on the grid | -| Continuum envelope | Refine alternating contacts and inspect every real stationary point of (P(p)e^{-ap}), plus both endpoints | The eight displayed numerical cases; floating-point root calculations | -| Matching moment witnesses | Solve for positive atomic weights, compare moments through degree (r), and evaluate the tilted risk ratio | Explicit finite priors, independently checked against each envelope | -| First threshold | Compare the degree-one value with the analytic Specht expression | (a=1,2) | -| Quantum source blocks | Construct the full diagonal of each averaged two-qubit state for repeated contexts | Twenty blocks: repetitions through (r) agree; the next repetition distinguishes the selected witness | -| Several contexts | Tensor three independently assigned context blocks using explicit arrival words | Six words whose maximum multiplicity is at most (r); registers may be regrouped by a common permutation | -| Copy observable | Evaluate the falling-factorial estimator from the count of (r) independent Bernoulli outcomes | Eight envelope polynomials, tested on 101 loss probabilities each | +| Moment/envelope duality | Independently solve the normalized ratio primal and polynomial-envelope dual on 4,001 points, for eight cases | $`a=1,2`$, degrees $`r=0,1,2,3`$; numerical agreement on the grid | +| Continuum envelope | Refine alternating contacts and inspect every real stationary point of $`P(p)e^{-ap}`$, plus both endpoints | The eight displayed numerical cases; floating-point root calculations | +| Matching moment witnesses | Solve for positive atomic weights, compare moments through degree $`r`$, and evaluate the tilted risk ratio | Explicit finite priors, independently checked against each envelope | +| First threshold | Compare the degree-one value with the analytic Specht expression | $`a=1,2`$ | +| Quantum source blocks | Construct the full diagonal of each averaged two-qubit state for repeated contexts | Twenty blocks: repetitions through $`r`$ agree; the next repetition distinguishes the selected witness | +| Several contexts | Tensor three independently assigned context blocks using explicit arrival words | Six words whose maximum multiplicity is at most $`r`$; registers may be regrouped by a common permutation | +| Copy observable | Evaluate the falling-factorial estimator from the count of $`r`$ independent Bernoulli outcomes | Eight envelope polynomials, tested on 101 loss probabilities each | | Collision law | Count assignments exactly with integer dynamic programming before converting to probabilities | 126 finite cases, the union bound, monotonicity and the pigeonhole endpoint | -| Independent occupancy check | Enumerate every context word for small supports and compare with the dynamic program; also compare (k=2) with the ordinary birthday formula | 42 exhaustive cases, plus the two-fold collision cases above | +| Independent occupancy check | Enumerate every context word for small supports and compare with the dynamic program; also compare $`k=2`$ with the ordinary birthday formula | 42 exhaustive cases, plus the two-fold collision cases above | The source checks use @@ -48,12 +48,12 @@ One world draws the frozen coordinates independently from $`\mu,\nu`$; the other $`\Gamma_r(a)`$ is the logarithmic moment ambiguity divided by $`a`$. -| (a) | (Gamma_0) | (Gamma_1) | (Gamma_2) | (Gamma_3) | +| $`a`$ | $`\Gamma_0`$ | $`\Gamma_1`$ | $`\Gamma_2`$ | $`\Gamma_3`$ | |---:|---:|---:|---:|---:| | 1 | 1 | 0.123301561482 | 0.010295312342 | 0.000644562136 | | 2 | 1 | 0.237237323535 | 0.039761060549 | 0.005003925480 | -The recorded run passed all checks. Matched source-block half trace distances were below $`1.3\times10^{-16}`$. The refined moment and continuum-envelope residuals were below the script's $`10^{-10}`$ tolerance; exact values are retained in the result file. The collision calculation also records finite examples at $`T\approx M^{1-1/k}`$, alongside the fixed-(k) Poisson limit. Those examples illustrate the scaling and are not used to certify an asymptotic theorem. +The recorded run passed all checks. Matched source-block half trace distances were below $`1.3\times10^{-16}`$. The refined moment and continuum-envelope residuals were below the script's $`10^{-10}`$ tolerance; exact values are retained in the result file. The collision calculation also records finite examples at $`T\approx M^{1-1/k}`$, alongside the fixed-$`k`$ Poisson limit. Those examples illustrate the scaling and are not used to certify an asymptotic theorem. ## Limits diff --git a/verification/hosted_math/capture_top_screenshots.cjs b/verification/hosted_math/capture_top_screenshots.cjs new file mode 100644 index 0000000..7bf4753 --- /dev/null +++ b/verification/hosted_math/capture_top_screenshots.cjs @@ -0,0 +1,56 @@ +'use strict'; +// Supplementary visual evidence; the canonical mathematical comparison is separate. +const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'); +const {chromium}=require('playwright'); +const {waitForHostedMath}=require('./capture_hosted_math.cjs'); +const sha256=b=>crypto.createHash('sha256').update(b).digest('hex'); +(async()=>{ + const [input,output]=process.argv.slice(2); + if(!input || !output) throw new Error('Use INPUT_CAPTURE_DIRECTORY EMPTY_OUTPUT_DIRECTORY'); + const report=JSON.parse(fs.readFileSync(path.join(input,'hosted-report.json'))); + const source=JSON.parse(fs.readFileSync(path.join(input,'math-source.json'))); + if(report.status!=='pass' || source.revision!==report.revision) throw new Error('A passing bound mathematical capture is required'); + if(fs.existsSync(output) && fs.readdirSync(output).length) throw new Error('Use an empty output directory'); + fs.mkdirSync(output,{recursive:true}); + const browser=await chromium.launch({headless:true}); + const observations=[]; + try{ + for(const width of [1440,760]){ + const context=await browser.newContext({viewport:{width,height:1000},deviceScaleFactor:1,colorScheme:'light'}); + try{ + for(const [index,item] of source.pages.entries()){ + const page=await context.newPage(); + try{ + const response=await page.goto(item.url,{waitUntil:'domcontentloaded',timeout:60000}); + if(response.status()!==200 || page.url()!==item.url) throw new Error('Exact source URL unavailable'); + const article=page.locator('article.markdown-body').first(); + await article.waitFor({state:'visible',timeout:30000}); + await page.evaluate(async()=>{ + for(let y=0,n=0;ysetTimeout(r,50)); + } + window.scrollTo(0,0); + }); + await waitForHostedMath(article,item.expressions.length); + await page.evaluate(async()=>{ + window.scrollTo(0,0); + await new Promise(r=>setTimeout(r,750)); + await new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r))); + }); + if(await page.evaluate(()=>window.scrollY)!==0) throw new Error('Page did not settle at the top'); + const name=String(index+1).padStart(4,'0')+'-'+width+'.png'; + await page.screenshot({path:path.join(output,name),fullPage:true,timeout:30000}); + const bytes=fs.readFileSync(path.join(output,name)); + observations.push({path:item.path,source_sha256:item.source_sha256,width,scroll_y:0, + screenshot:name,size_bytes:bytes.length,sha256:sha256(bytes),observed_at:new Date().toISOString()}); + }finally{await page.close();} + } + }finally{await context.close();} + } + }finally{await browser.close();} + fs.writeFileSync(path.join(output,'visual-report.json'),JSON.stringify({schema_version:1, + kind:'hosted_visual_supplement',repository:report.repository,revision:report.revision,tree:report.tree, + mathematical_report_sha256:sha256(fs.readFileSync(path.join(input,'hosted-report.json'))), + observations,limits:'Additional actual-host screenshots after settled top scrolling; requires visual inspection and does not replace the mathematical structural report.'},null,2)+'\n'); + process.stdout.write(JSON.stringify({screenshots:observations.length,output})+'\n'); +})().catch(e=>{process.stderr.write(String(e)+'\n');process.exitCode=1;});