diff --git a/.github/workflows/nor19-streamed-cached-verifier.yml b/.github/workflows/nor19-streamed-cached-verifier.yml new file mode 100644 index 000000000..75f5062f5 --- /dev/null +++ b/.github/workflows/nor19-streamed-cached-verifier.yml @@ -0,0 +1,141 @@ +name: NOR-19 bounded-buffer cached public verifier CPU and memory + +on: + push: + paths: + - 'research/nor19_streamed_verifier/**' + - '.github/workflows/nor19-streamed-cached-verifier.yml' + pull_request: + paths: + - 'research/nor19_streamed_verifier/**' + - '.github/workflows/nor19-streamed-cached-verifier.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + streamed-exact-parity-and-public-source-safety: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Test all five algorithms against original exact native public masks + run: python -m unittest research.nor19_streamed_verifier.test_streamed -v + + original-hosted-public-fixture-and-memory-independent-audit: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Independently audit 64 native masks, 2240 original timing samples, 640 memory profiles and bigint products + run: | + python research/nor19_streamed_verifier/receipt_audit.py --check \ + --archive research/nor19_streamed_verifier/results/nor19_original_hosted.zip + + previously-unbenchmarked-public-fixture-and-memory: + needs: streamed-exact-parity-and-public-source-safety + runs-on: ubuntu-latest + timeout-minutes: 55 + env: + PYTHONHASHSEED: '0' + OPENBLAS_NUM_THREADS: '1' + OMP_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Regenerate NOR-18 source and hash-lock every original public input + run: | + python research/nor19_streamed_verifier/benchmark.py \ + --make-fixture /tmp/nor19_public_fixture.json --check + - name: Benchmark five modes with seven measured repetitions and isolated memory passes + run: | + python research/nor19_streamed_verifier/benchmark.py \ + --fixture /tmp/nor19_public_fixture.json \ + --repetitions 7 --warmups 2 \ + --check --out /tmp/nor19_full.json + - name: Independent policy mask, memory, timing and source-integrity audit + run: | + python - <<'PY' + from pathlib import Path + from hashlib import sha256 + from collections import Counter + import json,math,statistics + fixture=Path('/tmp/nor19_public_fixture.json').read_bytes() + raw=Path('/tmp/nor19_full.json').read_bytes() + pub=json.loads(fixture) + x=json.loads(raw) + assert pub['schema']=='nor19.previously_untimed_public_source_64.v1' + assert pub['public_only'] and pub['private_program_identities_and_query_outputs_absent'] + assert pub['previously_timed_NOR18R_source_indices_excluded'] + assert pub['source_original_NOR18_sha256']=='9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b' + assert len(pub['cases'])==64 + assert len(set(z['original_full_public_sha256'] for z in pub['cases']))==64 + assert x['schema']=='nor19.streaming_memory_bounded_public_verifier.v1' + assert x['fixture_schema']==pub['schema'] + assert x['fixture_sha256']==sha256(fixture).hexdigest() + assert x['case_count']==len(x['records'])==64 + assert x['cohorts']==4 + assert x['source_families']=={'late_source':32,'signed':16,'rational':16} + assert x['measured_repetitions']==7 and x['warmups']==2 + assert x['algorithms']==['independent16','cached16','stream16_queryfirst','stream16_verifyfirst','chunk4_verifyfirst'] + assert x['primary']=='stream16_verifyfirst' + assert len(set(z['public_sha256'] for z in x['records']))==64 + assert all(z['exact_mask_and_certificate_parity'] for z in x['records']) + assert all(x['scope'][f] for f in ( + 'complete_public_original_masks_and_certificates_unchanged', + 'previous_NOR18R_measured_cases_excluded', + 'all_fixture_sources_match_original_NOR18_byte_locked_archive', + 'all_five_query_simulations_recomputed_independently', + 'withheld_true_future_and_program_identity_absent_from_fixture')) + for obs,public in zip(x['records'],pub['cases']): + assert obs['original_index']==public['original_index'] + assert obs['public_sha256']==public['original_full_public_sha256'] + assert obs['reference_mask']==public['original_exact_full_accept_mask'] + assert obs['reference_unanimous']==public['original_public_future_output_identifiable'] + assert len(obs['mode_samples_ns'])==5 + for mode in x['algorithms']: + samples=obs['mode_samples_ns'][mode] + assert len(samples)==7 + for s in samples: + assert s['total_ns']==s['query_ns']+s['verification_ns']+s['certificate_ns'] + assert s['query_ns']>0 and s['verification_ns']>0 + assert obs['complete_tracemalloc'][mode]['mask']==public['original_exact_full_accept_mask'] + assert obs['verifier_only_tracemalloc'][mode]['mask']==public['original_exact_full_accept_mask'] + assert obs['reciprocal_bigint_work'][mode]['R_integer_products']>0 + assert x['materialized_demo_candidate_buffers_at_once_design']['stream16_verifyfirst']==0 + assert x['materialized_demo_candidate_buffers_at_once_design']['chunk4_verifyfirst']==4 + assert x['materialized_demo_candidate_buffers_at_once_design']['cached16']==32 + assert x['primary_memory_block_bootstrap']['draws']==4096 + assert x['primary_speed_block_bootstrap']['draws']==4096 + assert x['primary_median_peak_ratio_threshold']==0.8 + assert x['primary_faster_than_native_threshold']==2.0 + assert x['primary_memory_win_case_threshold']==48 + assert len(x['isolated_process_RSS_KiB'])==5 + print('NOR19 HOST',x['host']) + print('NOR19 PRIMARY MEDIAN TRACEMALLOC PEAK RATIO STREAM/CACHE',x['primary_median_complete_peak_ratio_vs_cached']) + print('NOR19 LOWER PEAK CASES',x['primary_lower_peak_cases'],'/64') + print('NOR19 PRIMARY MEDIAN PAIRED CPU SPEEDUP NATIVE/STREAM',x['primary_median_total_native_over_stream_speedup']) + print('NOR19 FIRST PREREGISTERED PASS',x['primary_passed']) + print('NOR19 COHORT MEMORY BOOTSTRAP',x['primary_memory_block_bootstrap']) + print('NOR19 COHORT SPEED BOOTSTRAP',x['primary_speed_block_bootstrap']) + print('NOR19 MEDIAN AND BIGINT RESULTS',x['summary_all']) + print('NOR19 PER FAMILY',x['summary_by_family']) + print('NOR19 PROCESS RSS',x['isolated_process_RSS_KiB']) + print('NOR19 PUBLIC FIXTURE BYTES SHA256',len(fixture),sha256(fixture).hexdigest()) + print('NOR19 FULL BENCHMARK BYTES SHA256',len(raw),sha256(raw).hexdigest()) + PY + - uses: actions/upload-artifact@v4 + with: + name: nor19-new64-public-fixture-and-five-mode-cpu-memory-results + path: | + /tmp/nor19_public_fixture.json + /tmp/nor19_full.json diff --git a/research/nor19_streamed_verifier/README.md b/research/nor19_streamed_verifier/README.md new file mode 100644 index 000000000..595486399 --- /dev/null +++ b/research/nor19_streamed_verifier/README.md @@ -0,0 +1,101 @@ +# NOR-19: bounded candidate-output buffers in the cached exact verifier + +**Preregistered 16 November 2026 before any NOR-19 CPU or memory measurement.** Extends [NOR-18R #178](https://github.com/MoralityLabAI/Compactification-Theory/pull/178) and [MathCan reciprocal reuse #98](https://github.com/patrickdugan/MathCan/pull/98). + +The NOR-18R verifier reuses the four unary public-series transforms per degree-192 demonstration, achieving a measured **4.33× median paired complete CPU speedup** over sixteen independent checks. Its Python-traced peak temporary allocation was larger than the native checker (128.2 versus 74.1 KiB on the original 64 sources), partly because the cache materialized all sixteen complete candidate outputs for both demonstrations while their public query predictions were also live. NOR-19 tests reducing the number of materialized public demonstration candidate-output arrays while retaining the same exact public acceptance masks and certified future outputs. + +## Source lock and disjoint confirmation fixture + +The exact original NOR-18 288-case public source stream remains SHA-256 \`9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b\`; its RRC25 trained GRU checksum is \`54f225f2a61c52fee5a740576eaab3bcbc5280a595fc1ac1ac115ec8ac26c41b\`. + +Regenerate the complete 288-case NOR-18 roster and independently verify **every** regenerated public source digest against the original archived JSON, before extracting any timing fixture. Choose the next 64 source entries, which NOR-18R's [first timing fixture](https://github.com/MoralityLabAI/Compactification-Theory/blob/main/research/nor18r_runtime/results/nor18r_original_hosted.zip) did **not** time: for each of four source cohorts, late_source cases at positions 8–15, signed at 52–55 and rational at 64–67. This provides **32 late_source + 16 signed + 16 rational**, all distinct complete-public inputs, with no overlap with NOR-18R's original 64-case benchmark. The sources originate from the same frozen NOR-18 generator and source split; confirmation is across **previously unbenchmarked cases**, not across a new generator distribution. + +The new public fixture stores only two degree-192 input/output demonstration pairs, the degree-256 public query INPUT, the public header, family, original source index, and the frozen exact acceptance-mask and output-unanimity receipts. **No planted program identities or withheld query OUTPUTS are serialized.** All five verifiers must match the original sixteen-bit acceptance mask and output-unanimity certificate for every source. An independent audit must rederive these masks using the original exact RRC25 checker. + +## Registered implementations + +All implementations perform one complete **sixteen-candidate public query-input simulation** and account for its time, then check all sixteen exact degree-192 public demonstration templates. They differ in how those template outputs are materialized and in the ordering of query/verification work: + +| Implementation | Materialized demonstration outputs | Peak design bound | Query ordering | +| --- | --- | --- | --- | +| \`independent16\` | Native exact checker, one candidate per call | Native control | Query first | +| \`cached16\` | Original NOR-18R cached two-demo sixteen-output batch | 32 candidate-output vectors | Query first | +| \`stream16_queryfirst\` | Four unary transforms once per demo; compare each candidate coefficient by coefficient, abort on first mismatch | **Zero** complete candidate-output vectors | Query first | +| \`stream16_verifyfirst\` | Same coefficient-streamed exact checker, process demo 1 then demo 2 and release each workspace | **Zero** complete candidate-output vectors | Verify first | +| \`chunk4_verifyfirst\` | Four shared unary transforms per demo, materialize at most four complete candidate outputs at a time, discard after comparing | **Four** candidate-output vectors | Verify first | + +Every cached/streamed implementation evaluates four unary transforms on each of the two demonstrations, including one reciprocal transform R, retaining the full exact integer recurrence semantics. Query simulation is recomputed per algorithm and never reused across modes. The abstract materialized-output count is an **algorithmic workspace model**, not a measured count of Python allocation or total live series (which also include the four unary transforms and query predictions). The pointwise streaming predicate must be provably equal to full finite-series equality. Each implementation's public mask/certificate must match all four other implementations and the original NOR-18 reference. + +## Timing and memory protocol + +Run on a hosted Linux x86-64 CPython 3.12 CPU. Per public source and algorithm: **two warmups and seven measured repetitions**, each mode presented in a deterministically shuffled order per repetition. Collect garbage before each timing, disable the collector within the timed segment and measure with \`perf_counter_ns\`. Time the query simulation, exact public verification, certificate selection and combined operation, recording the execution order for the verify-first methods. + +Measure peak temporary Python allocation using \`tracemalloc\` **in a separate untimed complete execution** for each source/algorithm, starting after fixture loading and stopping afterward. Also measure Python-traced peak for each verifier-only phase separately and record isolated worker \`ru_maxrss\` for all five algorithms. A zero increase over the process baseline on the small fixture is interpreted as a measurement-resolution limit, not evidence of identical temporary allocations. + +Quantify total R reciprocal invocation counts from the frozen four-op grammar: one query inversion common to all methods, one R per public demonstration for each cached/streamed/checker variant, and 8+16 if the base operator is R for every native independent demonstration. Compare the exact big-integer operand-width products recorded by the prior NOR-18R audit on the public sources. + +## Primary success rule and controls + +The **predeclared primary implementation** is \`stream16_verifyfirst\`. It succeeds on this fixed source benchmark only if: + +1. Every public acceptance mask and certificate exactly matches the original native checker and the original source-locked NOR-18 JSON for all 64 cases. +2. The **median of per-case ratios of untimed Python \`tracemalloc\` complete-operation peaks**, streamed / cached, is at most **0.80**, and streamed has a lower peak on at least **48/64** cases. +3. The median of paired complete-operation runtime ratios, independent16 / streamed, is at least **2.0×**, so the new memory-bounded checker retains substantial measured CPU acceleration over the original repeated-check implementation. + +Report actual means/medians, the paired runtime and peak-allocation ratios, per-family results, and a deterministic 4096-draw four-source-cohort block-bootstrap percentile interval for each ratio. The chunked implementation and query-first streaming control are secondary, and any hindsight-best mode may be described only as exploratory. A failure on any primary threshold is reported as a failed preregistered result even if another variant performs better. + +This test measures one CPython/GitHub-hosted CPU environment. Peak allocation may vary with Python's allocator, source coefficient bit widths, and generated source family. The result does not establish a zero-memory verifier, constant total series memory, GPU improvement, or production theorem-prover safety. + +## Reproduction + +\`\`\`sh +python -m unittest research.nor19_streamed_verifier.test_streamed -v +python research/nor19_streamed_verifier/benchmark.py \ + --make-fixture /tmp/nor19_public_fixture.json --check +python research/nor19_streamed_verifier/benchmark.py \ + --fixture /tmp/nor19_public_fixture.json \ + --repetitions 7 --warmups 2 --check --out /tmp/nor19_full.json +\`\`\` + +The first completed CI will freeze the original full benchmark and public-only source fixture SHA-256 checksums. Each new result must pass an independent source/semantic, timing and allocation audit before merging. + + +## First hosted execution: exact parity and measured memory reduction + +The originally registered NOR-19 CPU and memory benchmark completed on 16 November 2026 in [GitHub Actions run 43804264372](https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43804264372), artifact ID 14198011159. The original public-only fixture and measured results are frozen in the source-controlled [nor19_original_hosted.zip](results/nor19_original_hosted.zip), and pinned separately by the [NOR-19 first-run receipt](results/nor19_first_frozen_receipt.json): + +- Public source fixture: **1,290,607 bytes**, SHA-256 \`97fc9ccd3830bc666e6af6d0a86d3b000ef2b8d0a7a29a406ff38fbd08707f3f\`. +- Full measured result: **680,861 bytes**, SHA-256 \`16d6ce9acb042aff76d48f46b7d07ff76a4efca1ade26314cdc52926eb0e1a16\`. +- Original NOR-18 held-out source manifest: \`9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b\`. + +The 64 new public inputs are distinct from NOR-18R's first 64 benchmark inputs, with 32 late_source, 16 signed and 16 rational cases spread across four frozen original source cohorts. All five algorithms matched the native exact sixteen-candidate acceptance mask and the candidate-output unanimity certificate for every public source. Every policy uses the same complete set of public query-output simulations, and the fixture excludes all private future outputs and planted program identities. + +### Measured CPU and Python allocation + +CPython 3.12.16, GCC 15.2.0, Linux 7.0.0-1019-azure x86_64, four logical CPUs. Each case/mode was warmed twice and then timed seven times in deterministic shuffled order with garbage collection disabled during measured executions. Peak allocation was measured using separate untimed tracemalloc passes. + +| Public algorithm | Median per-case complete CPU | Median complete Python-traced temporary allocation | Median verifier-only temporary allocation | +| --- | ---: | ---: | ---: | +| Native sixteen independent exact checks | 19.420 ms | 67.13 KiB | 16.89 KiB | +| Original NOR-18R eager cached sixteen-output batch | 4.240 ms | 119.43 KiB | 72.98 KiB | +| Streaming coefficients, public query simulation first | 4.268 ms | 61.47 KiB | 8.92 KiB | +| **Streaming coefficients, verifier first (primary)** | **4.235 ms** | **61.49 KiB** | **8.92 KiB** | +| Four-candidate chunked outputs, verifier first | 4.059 ms | 62.99 KiB | 19.18 KiB | + +The **median paired complete peak allocation ratio** of primary streaming versus original eager caching was **0.474714**, a measured reduction of approximately 52.5% under the Python-traced memory metric, with lower allocation in **64/64 source cases**. The fixed four-cohort block-bootstrap 95% percentile interval for this *ratio* was **0.46918 to 0.48832**. The median paired complete CPU speedup from original native independent checks to the primary streaming implementation was **4.33448×**, with a block-bootstrap percentile interval **4.32170× to 4.35296×**. This meets all three preregistered success criteria, including 20% memory reduction, a 48/64 lower-allocation threshold, and a 2× or better native-to-streaming speedup. + +The verifier-only tracemalloc median fell from **72.98 KiB to 8.92 KiB** when sixteen full candidate-output series were replaced with coefficient-by-coefficient exact comparison, while preserving the same four shared public unary transforms per demonstration. The query-first streaming negative control achieved almost the same allocation reduction, indicating that removing the eager candidate-output arrays accounts for most observed savings. The four-output chunked control also reduced allocation and had slightly lower sample median CPU time, but it was explicitly secondary and was not selected as the registered primary. + +### Integer and RSS accounting + +All four cached variants used the same original public reciprocal-transform computations: **4,476,928 exact R recurrence multiplications** across 64 sources, including query prediction. The independently computed native sixteen-check baseline executed **28,192,768**, a difference that follows from repeating R eight or twenty-four times per demonstration. Thus the streaming design achieves its allocation reduction without giving up the cache's reciprocal-reuse advantage. + +Isolated subprocess peak \`ru_maxrss\` measured 28,888 KiB for all five variants, with zero measurable increase over the fixture-loaded process baseline. That coarse process-level peak cannot resolve the differences detected by Python tracemalloc and cannot be used to claim identical physical resident memory. + +### Reproducibility and scope + +The permanent independent [NOR-19 receipt auditor](receipt_audit.py) checks the source-controlled fixture and full-result SHA-256, reconstructs all **64 exact native masks and output certificates**, verifies **2,240 original nanosecond timing samples**, **640 independently measured complete/verifier-only memory records**, **320 reciprocal operand-work ledgers**, and replays **8,192 deterministic source-cohort bootstrap draws**. It imports no new NOR-19 streaming benchmark implementation. + +The companion [MathCan NOR-19 theorem #101](https://github.com/patrickdugan/MathCan/pull/101) proves sequential coefficient equality is equivalent to full finite-vector equality, and distinguishes the abstract workspace count of 32 candidate-output buffers for eager caching, at most four for chunking and zero complete candidate-output buffers for streaming. These are algebraic materialization counts; the observed CPU, Python allocation and RSS values come solely from the original hosted experiment. + +The result establishes a memory-bounded public verifier implementation on the fixed synthetic RRC25 source family and one measured CPython runner. It does not prove a general constant-space theorem prover, portability to a GPU or NPU, or cross-machine timing reproducibility. A new source generator or a different host needs an independently pinned confirmation. diff --git a/research/nor19_streamed_verifier/benchmark.py b/research/nor19_streamed_verifier/benchmark.py new file mode 100644 index 000000000..5f258967f --- /dev/null +++ b/research/nor19_streamed_verifier/benchmark.py @@ -0,0 +1,608 @@ +"""NOR-19: public-only streaming / chunked cached verifier benchmarks. + +The primary implementation streams *coefficients* through the exact +RRC25 two-branch delayed-series expression, retains the four unary +transforms for one public demo at a time, and never creates any candidate +output series for demo verification. + +Compare the original NOR18R native and cached algorithms against two +streamed execution orders and a bounded four-output chunk checker. +Independent fixture source is the previously UNBENCHMARKED half of the +same NOR18 frozen 288-case heldout corpus, with every source digest +rechecked against its original public first-run JSON. +""" +from __future__ import annotations + +import argparse +from collections import Counter,defaultdict +import gc +from hashlib import sha256 +import json +import math +import os +from pathlib import Path +import platform +import random +import statistics +import subprocess +import sys +import time +import tracemalloc + +HERE=Path(__file__).resolve().parent +ROOT=HERE.parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0,str(ROOT)) + +from research.rrc_compactification import compound25 as corpus +from research.nor11_attractor_controller import controller as nor11 +from research.nor12_task_readout import readout as nor12 +from research.nor16_public_query_consensus import experiment as nor16 +from research.nor17_prefix_certificates import experiment as nor17 +from research.nor18_costed_prefix import experiment as nor18 +from research.nor18r_runtime import benchmark as old + +SCHEMA="nor19.streaming_memory_bounded_public_verifier.v1" +FIXTURE_SCHEMA="nor19.previously_untimed_public_source_64.v1" +OLD_FULL_SHA=old.NOR18_SHA +CHECKPOINT_SHA=old.CHECKPOINT_SHA +SOURCE_MODELS=("independent16","cached16","stream16_queryfirst", + "stream16_verifyfirst","chunk4_verifyfirst") +WARMUPS=2 +TIMED_REPS=7 +SOURCES=64 +BOOTSTRAP_DRAWS=4096 +BOOT_SEED=202611191900 +PRIMARY="stream16_verifyfirst" +PRIMARY_MEMORY_RATIO_MAX=.80 +PRIMARY_SPEEDUP_NATIVE_MIN=2.0 +PRIMARY_MEMORY_WINS_MIN=48 + + +def json_bytes(obj): + return (json.dumps(obj,indent=2,sort_keys=True)+"\n").encode() + + +def make_fixture(): + archive=old.read_nor18() + roster=nor11.sample_cohorts(nor12.SPLIT_COUNTS) + batches=nor18.fresh_cohorts(roster) + assert len(batches)==4 + records=[] + for rep,batch in enumerate(batches): + assert len(batch)==72 + assert sha256("\n".join(nor16.full_public_digest(c) + for c,h,d in batch).encode()).hexdigest()==archive["cohorts"][rep][ + "public_manifest_sha256"] + for i,(c,h,model_hash) in enumerate(batch): + source=archive["records"][rep*72+i] + assert source["family"]==c.family + assert source["full_public_input_sha256"]==nor16.full_public_digest(c) + assert source["model_visible_sha256"]==model_hash + # Original NOR18R used 0:8, 48:52, 60:64. Keep these new. + indices=list(range(8,16))+list(range(52,56))+list(range(64,68)) + assert len(indices)==16 + assert Counter(batch[i][0].family for i in indices)=={ + "late_source":8,"signed":4,"rational":4} + for i in indices: + c,h,model_hash=batch[i] + source=archive["records"][rep*72+i] + records.append({ + "cohort":rep, + "original_index":rep*72+i, + "family":c.family, + "original_full_public_sha256":source["full_public_input_sha256"], + "original_model_input_sha256":model_hash, + "public_header":{"base":h.base,"delay":h.delay, + "spacing":h.spacing,"amplitude":h.amplitude}, + "demos":[[list(f[:193]),list(y[:193])] for f,y in c.demos], + "public_query_input":list(c.query), + "original_exact_full_accept_mask":source["retro_full_accepted_mask"], + "original_public_future_output_identifiable":source[ + "certificate_possible_from_complete_public_mask"], + }) + assert len(records)==SOURCES + assert len({r["original_full_public_sha256"] for r in records})==SOURCES + assert Counter(x["family"] for x in records)=={ + "late_source":32,"signed":16,"rational":16} + return { + "schema":FIXTURE_SCHEMA, + "source_original_NOR18_sha256":OLD_FULL_SHA, + "original_RRC25_checkpoint_sha256":CHECKPOINT_SHA, + "selection_rule":"each of four NOR18 cohorts, indices 8:16+52:56+64:68", + "previously_timed_NOR18R_source_indices_excluded":True, + "public_only":True, + "private_program_identities_and_query_outputs_absent":True, + "cases":records, + } + + +def load_fixture(path): + raw=Path(path).read_bytes() + o=json.loads(raw) + assert o["schema"]==FIXTURE_SCHEMA + assert o["source_original_NOR18_sha256"]==OLD_FULL_SHA + assert o["original_RRC25_checkpoint_sha256"]==CHECKPOINT_SHA + assert o["previously_timed_NOR18R_source_indices_excluded"] + assert o["public_only"] and o["private_program_identities_and_query_outputs_absent"] + assert len(o["cases"])==SOURCES + assert Counter(z["family"] for z in o["cases"])=={ + "late_source":32,"signed":16,"rational":16} + assert len({r["original_full_public_sha256"] for r in o["cases"]})==64 + return o + + +def public_case(row): + # Original NOR18R loader checks source digest, feature hash and exact + # public degree192 / query input degree256 without a secret future. + return old.unpack_case(row) + + +def streamed_mask(c,h): + """Four unary transforms cached per demo; no candidate output vectors. + + Short-circuit on the first mismatching exact integer coefficient. + The two demos are checked sequentially so only one demo's unary + transform workspace is live. The candidate sets form an exact + intersection, preserving native full-template acceptance. + """ + mask=65535 + k=h.delay + d=h.spacing + amp=h.amplitude + for source,observed in c.demos: + # Match native verify_template's fixed degree-192 truncation even + # when a unit-test source carries additional unpublished suffixes. + source=source[:corpus.OBSERVED+1] + observed=observed[:corpus.OBSERVED+1] + maps={op:corpus.d.operate(source,op) for op in corpus.OPS} + base=maps[h.base] + for j in range(16): + if not mask&(1<=k+d: + x+=amp*u[n-k-d] + if n>=k+2*d: + x+=amp*v[n-k-2*d] + if x!=observed[n]: + mask &= ~(1<=end>=mid>=start + times={ + "query_ns":query_ns, + "verification_ns":verify_ns, + "certificate_ns":last-end, + "total_ns":last-start, + } + assert sum(times[k] for k in ("query_ns","verification_ns", + "certificate_ns"))==times["total_ns"] + return {"mask":mask,"unanimous":unanimous, + "chosen_class":chosen,"times":times} + return {"mask":mask,"unanimous":unanimous,"chosen_class":chosen} + + +def allocation_profile(c,h,mode): + gc.collect() + tracemalloc.start() + try: + result=complete(c,h,mode) + current,peak=tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + return { + "python_peak_allocation_bytes":peak, + "python_current_allocation_bytes":current, + "mask":result["mask"], + } + + +def verifier_only_profile(c,h,mode): + gc.collect() + tracemalloc.start() + try: + mask=public_mask(c,h,mode) + current,peak=tracemalloc.get_traced_memory() + finally: + tracemalloc.stop() + return {"python_verifier_only_peak_bytes":peak, + "python_verifier_only_current_bytes":current, + "mask":mask} + + +def get_rss_kib(): + return old.get_rss_kib() + + +def rss_worker(fixture_path,mode): + fixture=load_fixture(fixture_path) + before=get_rss_kib() + for row in fixture["cases"]: + c,h=public_case(row) + complete(c,h,mode) + after=get_rss_kib() + return { + "mode":mode, + "cases":SOURCES, + "baseline_peak_RSS_KiB":before, + "peak_RSS_after_all_cases_KiB":after, + "additional_max_RSS_KiB":(max(0,after-before) + if before is not None and after is not None + else None), + "separate_process":True, + } + + +def rss_by_mode(fixture_path): + results={} + for mode in SOURCE_MODELS: + res=subprocess.run([ + sys.executable,str(Path(__file__).resolve()), + "--fixture",str(fixture_path),"--rss-worker",mode], + check=True,capture_output=True,text=True) + parsed=json.loads(res.stdout.strip().splitlines()[-1]) + assert parsed["mode"]==mode and parsed["cases"]==SOURCES + results[mode]=parsed + return results + + +def inverse_invocations(h,mode): + if mode=="independent16": + return 8+16*int(h.base=="R") + assert mode in SOURCE_MODELS + return 1 + + +def observed_bigint_work(c,h,mode,inverses=None): + """Exact inverse recurrence multiplicity times observed operand width. + + All methods simulate one public query inverse. The four cached modes + compute exactly one inverse per public demonstration. Native computes + 8 or 24 inverse recurrences per demonstration. + """ + if inverses is None: + inverses=[old.exact_inverse_operand_ledger(f) for f,y in c.demos] + inverses.append(old.exact_inverse_operand_ledger(c.query)) + assert len(inverses)==3 + mult=inverse_invocations(h,mode) + q=inverses[2] + inverse_products=sum(r["multiplications"] for r in inverses[:2]) + inverse_width=sum(r["operand_bitwidth_products"] for r in inverses[:2]) + return { + "R_full_public_demo_invocations":2*mult, + "R_public_query_invocations":1, + "R_integer_products":q["multiplications"]+mult*inverse_products, + "R_operand_bitwidth_product_proxy":q["operand_bitwidth_products"]+ + mult*inverse_width, + } + + +def bootstrap_ratio(records,key,draws=BOOTSTRAP_DRAWS): + groups=defaultdict(list) + for row in records: + groups[row["cohort"]].append(row) + assert set(groups)=={0,1,2,3} + assert all(len(group)==16 for group in groups.values()) + rng=random.Random(BOOT_SEED+13) + values=[] + for _ in range(draws): + sample=[x for rep in (rng.randrange(4) for k in range(4)) + for x in groups[rep]] + values.append(statistics.median(x[key] for x in sample)) + values.sort() + return { + "draws":draws, + "unit":"NOR18 original source cohort of 16 previously unbenchmarked cases", + "percentile_2_5":values[int(.025*(draws-1))], + "percentile_97_5":values[int(.975*(draws-1))], + } + + +def env_info(): + return { + "python":sys.version, + "implementation":platform.python_implementation(), + "compiler":platform.python_compiler(), + "platform":platform.platform(), + "machine":platform.machine(), + "cpu_logical":os.cpu_count(), + "time_clock":"time.perf_counter_ns", + "measurement_gc":"collect before samples, disable during sample", + "tracemalloc":"each mode/case separate untimed profile", + "RSS":"isolated subprocess per algorithm, whole fixture", + } + + +def run(fixture_path,timed_reps=TIMED_REPS,warmups=WARMUPS): + if timed_reps!=TIMED_REPS or warmups!=WARMUPS: + raise ValueError("preregistered sample counts changed") + fixture=load_fixture(fixture_path) + observations=[] + for position,row in enumerate(fixture["cases"]): + c,h=public_case(row) + expected=(row["original_exact_full_accept_mask"], + row["original_public_future_output_identifiable"]) + assert all((z["mask"],z["unanimous"])==expected + for z in (complete(c,h,mode) for mode in SOURCE_MODELS)) + samples={name:[] for name in SOURCE_MODELS} + rng=random.Random(BOOT_SEED+position*100003) + for rep in range(WARMUPS+TIMED_REPS): + modes=list(SOURCE_MODELS) + rng.shuffle(modes) + for mode in modes: + gc.collect() + enabled=gc.isenabled() + gc.disable() + try: + result=complete(c,h,mode,measure=True) + finally: + if enabled: + gc.enable() + assert (result["mask"],result["unanimous"])==expected + if rep>=WARMUPS: + samples[mode].append(result["times"]) + assert all(len(x)==TIMED_REPS for x in samples.values()) + medians={mode:{key:float(statistics.median(s[key] for s in ss)) + for key in ("query_ns","verification_ns","certificate_ns", + "total_ns")} + for mode,ss in samples.items()} + allocation={mode:allocation_profile(c,h,mode) for mode in SOURCE_MODELS} + verifier_peak={mode:verifier_only_profile(c,h,mode) + for mode in SOURCE_MODELS} + assert all(z["mask"]==expected[0] for z in allocation.values()) + assert all(z["mask"]==expected[0] for z in verifier_peak.values()) + inv=[old.exact_inverse_operand_ledger(f) for f,y in c.demos] + inv.append(old.exact_inverse_operand_ledger(c.query)) + bigint={mode:observed_bigint_work(c,h,mode,inv) + for mode in SOURCE_MODELS} + primary_peak=allocation[PRIMARY]["python_peak_allocation_bytes"] + cached_peak=allocation["cached16"]["python_peak_allocation_bytes"] + primary_time=medians[PRIMARY]["total_ns"] + baseline_time=medians["independent16"]["total_ns"] + observations.append({ + "cohort":row["cohort"], + "original_index":row["original_index"], + "family":row["family"], + "public_sha256":row["original_full_public_sha256"], + "source_header":row["public_header"], + "reference_mask":expected[0], + "reference_unanimous":expected[1], + "exact_mask_and_certificate_parity":True, + "mode_samples_ns":samples, + "mode_medians_ns":medians, + "complete_tracemalloc":allocation, + "verifier_only_tracemalloc":verifier_peak, + "reciprocal_bigint_work":bigint, + "primary_peak_ratio_vs_cached":primary_peak/cached_peak, + "primary_native_speedup":baseline_time/max(1,primary_time), + "streaming_lower_peak_than_cached":primary_peak=PRIMARY_SPEEDUP_NATIVE_MIN) and ( + wins>=PRIMARY_MEMORY_WINS_MIN) and all( + o["exact_mask_and_certificate_parity"] for o in observations) + def summarize(sample): + return { + "cases":len(sample), + "median_streamed_peak_vs_cached_ratio":statistics.median( + r["primary_peak_ratio_vs_cached"] for r in sample), + "streamed_lower_peak_cases":sum( + r["streaming_lower_peak_than_cached"] for r in sample), + "median_native_over_primary_streamed_total_speedup":statistics.median( + r["primary_native_speedup"] for r in sample), + "median_complete_ms":{mode:statistics.median( + r["mode_medians_ns"][mode]["total_ns"] for r in sample)/1e6 + for mode in SOURCE_MODELS}, + "median_verifier_ms":{mode:statistics.median( + r["mode_medians_ns"][mode]["verification_ns"] for r in sample)/1e6 + for mode in SOURCE_MODELS}, + "median_complete_peak_KiB":{mode:statistics.median( + r["complete_tracemalloc"][mode]["python_peak_allocation_bytes"] + for r in sample)/1024 for mode in SOURCE_MODELS}, + "median_verifier_only_peak_KiB":{mode:statistics.median( + r["verifier_only_tracemalloc"][mode][ + "python_verifier_only_peak_bytes"] for r in sample)/1024 + for mode in SOURCE_MODELS}, + "reciprocal_bigint_products":{mode:sum( + r["reciprocal_bigint_work"][mode]["R_integer_products"] + for r in sample) for mode in SOURCE_MODELS}, + } + return { + "schema":SCHEMA, + "original_NOR18_full_SHA256":OLD_FULL_SHA, + "fixture_schema":FIXTURE_SCHEMA, + "fixture_sha256":sha256(Path(fixture_path).read_bytes()).hexdigest(), + "case_count":64, + "cohorts":4, + "source_families":{"late_source":32,"signed":16,"rational":16}, + "measured_repetitions":TIMED_REPS, + "warmups":WARMUPS, + "algorithms":list(SOURCE_MODELS), + "primary":"stream16_verifyfirst", + "host":env_info(), + "records":observations, + "summary_all":summarize(observations), + "summary_by_family":{family:summarize([ + row for row in observations if row["family"]==family]) + for family in ("late_source","signed","rational")}, + "primary_median_complete_peak_ratio_vs_cached":memory_ratio, + "primary_median_total_native_over_stream_speedup":speedup, + "primary_lower_peak_cases":wins, + "primary_median_peak_ratio_threshold":PRIMARY_MEMORY_RATIO_MAX, + "primary_faster_than_native_threshold":PRIMARY_SPEEDUP_NATIVE_MIN, + "primary_memory_win_case_threshold":PRIMARY_MEMORY_WINS_MIN, + "primary_passed":passed, + "primary_memory_block_bootstrap":bootstrap_ratio(observations, + "primary_peak_ratio_vs_cached"), + "primary_speed_block_bootstrap":bootstrap_ratio(observations, + "primary_native_speedup"), + "isolated_process_RSS_KiB":rss_by_mode(fixture_path), + "materialized_demo_candidate_buffers_at_once_design":{ + "cached16":32,"stream16_queryfirst":0, + "stream16_verifyfirst":0,"chunk4_verifyfirst":4, + "independent16":"native temporary per candidate"}, + "scope":{ + "complete_public_original_masks_and_certificates_unchanged":True, + "previous_NOR18R_measured_cases_excluded":True, + "all_fixture_sources_match_original_NOR18_byte_locked_archive":True, + "all_five_query_simulations_recomputed_independently":True, + "withheld_true_future_and_program_identity_absent_from_fixture":True, + "full_measured_times_include_query_and_verification":True, + "tracemalloc_is_separate_untimed_execution":True, + "memory_buffer_counts_are_design_bounds_not_bytes":True, + "block_bootstrap_is_conditional_on_four_existing_source_cohorts":True, + "hosted_CPU_is_not_cross_platform_guarantee":True, + }, + } + + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument("--make-fixture",type=Path) + parser.add_argument("--fixture",type=Path) + parser.add_argument("--out",type=Path) + parser.add_argument("--repetitions",type=int,default=TIMED_REPS) + parser.add_argument("--warmups",type=int,default=WARMUPS) + parser.add_argument("--rss-worker",choices=SOURCE_MODELS) + parser.add_argument("--check",action="store_true") + args=parser.parse_args() + if args.make_fixture: + source=make_fixture() + args.make_fixture.parent.mkdir(parents=True,exist_ok=True) + args.make_fixture.write_bytes(json_bytes(source)) + print("NOR19 VERIFIED NEW UNTIMERD PUBLIC FIXTURE", + len(source["cases"]), + sha256(args.make_fixture.read_bytes()).hexdigest()) + return + if not args.fixture: + parser.error("pass --make-fixture or --fixture") + if args.rss_worker: + print(json.dumps(rss_worker(args.fixture,args.rss_worker), + sort_keys=True)) + return + result=run(args.fixture,args.repetitions,args.warmups) + if args.check: + assert result["case_count"]==64 + assert len(result["records"])==64 + assert result["measured_repetitions"]==7 + assert all(r["exact_mask_and_certificate_parity"] for r in result["records"]) + rendered=json_bytes(result) + if args.out: + args.out.parent.mkdir(parents=True,exist_ok=True) + args.out.write_bytes(rendered) + else: + print(rendered.decode(),end="") + + +if __name__=="__main__": + main() diff --git a/research/nor19_streamed_verifier/receipt_audit.py b/research/nor19_streamed_verifier/receipt_audit.py new file mode 100644 index 000000000..493c4368b --- /dev/null +++ b/research/nor19_streamed_verifier/receipt_audit.py @@ -0,0 +1,404 @@ +"""NOR-19 independent original source, timing and memory receipt audit. + +Does not import the NOR-19 benchmark or any new streaming implementation. +Reconstructs all exact public accepted masks and unique hypothetical future +certificates using the original RRC25 public checker, checks all first- +hosted nanosecond samples and untimed allocation profiles, independently +replays bigint source coefficient operand widths, and regenerates the +four-cohort bootstrap over original source records. + +Measured times and traced allocations remain observations; this audit +cannot prove that another CPU will reproduce identical values. +""" +from __future__ import annotations + +import argparse +from collections import Counter,defaultdict +from hashlib import sha256 +import json +import math +from pathlib import Path +import random +import statistics +import sys +from zipfile import ZipFile + +HERE=Path(__file__).resolve().parent +ROOT=HERE.parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0,str(ROOT)) + +from research.rrc_compactification import compound25 as corpus +from research.nor11_attractor_controller import controller as nor11 + +RECEIPT=HERE/"results"/"nor19_first_frozen_receipt.json" +FULL_SHA="16d6ce9acb042aff76d48f46b7d07ff76a4efca1ade26314cdc52926eb0e1a16" +FIXTURE_SHA="97fc9ccd3830bc666e6af6d0a86d3b000ef2b8d0a7a29a406ff38fbd08707f3f" +OLD_SHA="9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b" +MODEL_SHA="54f225f2a61c52fee5a740576eaab3bcbc5280a595fc1ac1ac115ec8ac26c41b" +SEED=202611191900 +MODES=("independent16","cached16","stream16_queryfirst", + "stream16_verifyfirst","chunk4_verifyfirst") +PRIMARY="stream16_verifyfirst" + + +def eq_num(a,b): + return math.isclose(a,b,rel_tol=1e-11,abs_tol=1e-8) + + +def receipt(): + r=json.loads(RECEIPT.read_text()) + assert r["schema"]=="nor19.frozen_first_hosted_streamed_memory_cpu_receipt.v1" + assert r["original_fixture_sha256"]==FIXTURE_SHA + assert r["original_full_result_sha256"]==FULL_SHA + assert r["original_fixture_bytes"]==1290607 + assert r["original_full_result_bytes"]==680861 + assert r["source_original_NOR18_sha256"]==OLD_SHA + assert r["source_RRC25_checkpoint_sha256"]==MODEL_SHA + assert r["source_cases"]==64 and r["source_cohorts"]==4 + assert r["timed_repetitions_per_mode"]==7 + assert r["warmups_per_mode"]==2 + assert r["algorithms"]==list(MODES) + assert r["primary"]==PRIMARY + assert r["primary_registered_pass"] + assert r["primary_lower_peak_cases"]==64 + assert r["bootstrap_draws"]==4096 + return r + + +def source_from_public_only(row): + allowed={"cohort","original_index","family","original_full_public_sha256", + "original_model_input_sha256","public_header","demos", + "public_query_input","original_exact_full_accept_mask", + "original_public_future_output_identifiable"} + assert set(row)==allowed + rep=row["cohort"] + assert rep in (0,1,2,3) + ix=row["original_index"] + assert ix//72==rep + pos=ix%72 + assert ((row["family"]=="late_source" and 8<=pos<16) + or (row["family"]=="signed" and 52<=pos<56) + or (row["family"]=="rational" and 64<=pos<68)) + h=row["public_header"] + assert set(h)=={"base","delay","spacing","amplitude"} + assert h["base"] in corpus.OPS + assert h["delay"] in corpus.DELAYS and h["spacing"] in corpus.SPACINGS + assert h["amplitude"] in corpus.AMPLITUDES + demos=tuple((tuple(f),tuple(y)) for f,y in row["demos"]) + assert len(demos)==2 and all(len(f)==len(y)==193 and f[0]==1 for f,y in demos) + query=tuple(row["public_query_input"]) + assert len(query)==257 and query[0]==1 + c=corpus.Case(f"nor19-independent-{ix}",row["family"], + demos,query,(),None) + header=corpus.Header(h["base"],h["delay"],h["spacing"],h["amplitude"]) + public_digest=sha256(json.dumps([c.visible,c.query], + separators=(",",":")).encode()).hexdigest() + assert public_digest==row["original_full_public_sha256"] + assert nor11.public_digest(c,header)==row["original_model_input_sha256"] + assert c.future==() and c.program is None + return c,header + + +def public_native_mask_and_output(c,h): + accepted=0 + futures=[] + for j in range(16): + program=(h.base,h.delay,h.spacing,h.amplitude, + corpus.OPS[j//4],corpus.OPS[j%4]) + future=corpus.execute(c.query,program) + futures.append(future) + if corpus.verify_template(c,h,corpus.OPS[j//4],corpus.OPS[j%4]): + accepted|=1<=1 + return { + "R_full_public_demo_invocations":2*repetitions, + "R_public_query_invocations":1, + "R_integer_products":q[0]+repetitions*sum(z[0] for z in costs), + "R_operand_bitwidth_product_proxy": + q[1]+repetitions*sum(z[1] for z in costs), + } + + +def bootstrap(source,key,draws=4096): + blocks=defaultdict(list) + for entry in source: + blocks[entry["cohort"]].append(entry) + assert set(blocks)=={0,1,2,3} + assert all(len(v)==16 for v in blocks.values()) + rng=random.Random(SEED+13) + estimates=[] + for _ in range(draws): + selected=[z for i in (rng.randrange(4) for k in range(4)) + for z in blocks[i]] + estimates.append(statistics.median(x[key] for x in selected)) + estimates.sort() + return { + "draws":draws, + "unit":"NOR18 original source cohort of 16 previously unbenchmarked cases", + "percentile_2_5":estimates[int(.025*(draws-1))], + "percentile_97_5":estimates[int(.975*(draws-1))], + } + + +def median_from(source,fn): + return statistics.median(fn(x) for x in source) + + +def audit(fixture_raw,result_raw,frozen): + fixture=json.loads(fixture_raw) + result=json.loads(result_raw) + assert fixture["schema"]=="nor19.previously_untimed_public_source_64.v1" + assert fixture["source_original_NOR18_sha256"]==OLD_SHA + assert fixture["original_RRC25_checkpoint_sha256"]==MODEL_SHA + assert fixture["previously_timed_NOR18R_source_indices_excluded"] + assert fixture["public_only"] + assert fixture["private_program_identities_and_query_outputs_absent"] + assert result["schema"]=="nor19.streaming_memory_bounded_public_verifier.v1" + assert result["original_NOR18_full_SHA256"]==OLD_SHA + assert result["fixture_schema"]==fixture["schema"] + assert result["fixture_sha256"]==FIXTURE_SHA + assert result["case_count"]==len(result["records"])==64 + assert result["cohorts"]==4 + assert result["source_families"]=={"late_source":32,"signed":16,"rational":16} + assert result["measured_repetitions"]==7 and result["warmups"]==2 + assert result["algorithms"]==list(MODES) + assert result["primary"]==PRIMARY + assert result["primary_median_peak_ratio_threshold"]==.8 + assert result["primary_faster_than_native_threshold"]==2. + assert result["primary_memory_win_case_threshold"]==48 + assert result["primary_passed"] + assert set(result["materialized_demo_candidate_buffers_at_once_design"])==set(MODES) + assert result["materialized_demo_candidate_buffers_at_once_design"]["cached16"]==32 + assert result["materialized_demo_candidate_buffers_at_once_design"]["stream16_verifyfirst"]==0 + assert result["materialized_demo_candidate_buffers_at_once_design"]["chunk4_verifyfirst"]==4 + assert len(fixture["cases"])==64 + assert len({r["original_full_public_sha256"] for r in fixture["cases"]})==64 + assert Counter(r["family"] for r in fixture["cases"])=={ + "late_source":32,"signed":16,"rational":16} + assert len({z["public_sha256"] for z in result["records"]})==64 + for flag in ( + "complete_public_original_masks_and_certificates_unchanged", + "previous_NOR18R_measured_cases_excluded", + "all_fixture_sources_match_original_NOR18_byte_locked_archive", + "all_five_query_simulations_recomputed_independently", + "withheld_true_future_and_program_identity_absent_from_fixture", + "full_measured_times_include_query_and_verification", + "tracemalloc_is_separate_untimed_execution", + "memory_buffer_counts_are_design_bounds_not_bytes", + "block_bootstrap_is_conditional_on_four_existing_source_cohorts", + "hosted_CPU_is_not_cross_platform_guarantee", + ): + assert result["scope"][flag],flag + for item,record in zip(fixture["cases"],result["records"],strict=True): + c,h=source_from_public_only(item) + assert item["original_full_public_sha256"]==record["public_sha256"] + assert record["source_header"]==item["public_header"] + assert record["cohort"]==item["cohort"] + assert record["family"]==item["family"] + assert record["original_index"]==item["original_index"] + native_mask,unanimity=public_native_mask_and_output(c,h) + assert native_mask==item["original_exact_full_accept_mask"] + assert unanimity==item["original_public_future_output_identifiable"] + assert record["reference_mask"]==native_mask + assert record["reference_unanimous"]==unanimity + assert record["exact_mask_and_certificate_parity"] + assert set(record["mode_samples_ns"])==set(MODES) + assert set(record["mode_medians_ns"])==set(MODES) + assert set(record["complete_tracemalloc"])==set(MODES) + assert set(record["verifier_only_tracemalloc"])==set(MODES) + assert set(record["reciprocal_bigint_work"])==set(MODES) + for mode in MODES: + assert record["reciprocal_bigint_work"][mode]==original_bigint_work(c,h,mode) + samples=record["mode_samples_ns"][mode] + assert len(samples)==7 + for sample in samples: + assert set(sample)=={ + "query_ns","verification_ns","certificate_ns","total_ns"} + assert all(type(v) is int and v>=0 for v in sample.values()) + assert sample["total_ns"]==( + sample["query_ns"]+sample["verification_ns"]+ + sample["certificate_ns"]) + assert sample["query_ns"]>0 and sample["verification_ns"]>0 + for field in ("query_ns","verification_ns","certificate_ns","total_ns"): + expected=median_from(samples,lambda x:x[field]) + assert eq_num(record["mode_medians_ns"][mode][field],expected) + mem=record["complete_tracemalloc"][mode] + assert mem["mask"]==native_mask + assert (0<=mem["python_current_allocation_bytes"]<= + mem["python_peak_allocation_bytes"]) + assert mem["python_peak_allocation_bytes"]>0 + only=record["verifier_only_tracemalloc"][mode] + assert only["mask"]==native_mask + assert (0<=only["python_verifier_only_current_bytes"]<= + only["python_verifier_only_peak_bytes"]) + ratio=(record["complete_tracemalloc"][PRIMARY][ + "python_peak_allocation_bytes"]/ + record["complete_tracemalloc"]["cached16"][ + "python_peak_allocation_bytes"]) + speed=(record["mode_medians_ns"]["independent16"]["total_ns"]/ + record["mode_medians_ns"][PRIMARY]["total_ns"]) + assert eq_num(ratio,record["primary_peak_ratio_vs_cached"]) + assert eq_num(speed,record["primary_native_speedup"]) + assert record["streaming_lower_peak_than_cached"]==(ratio<1) + rows=result["records"] + ratios=[r["primary_peak_ratio_vs_cached"] for r in rows] + speeds=[r["primary_native_speedup"] for r in rows] + median_ratio=statistics.median(ratios) + median_speed=statistics.median(speeds) + wins=sum(x<1 for x in ratios) + assert eq_num(median_ratio,result[ + "primary_median_complete_peak_ratio_vs_cached"]) + assert eq_num(median_ratio,frozen[ + "primary_median_complete_python_peak_ratio_stream_vs_cache"]) + assert eq_num(median_speed,result[ + "primary_median_total_native_over_stream_speedup"]) + assert eq_num(median_speed,frozen[ + "primary_median_native_over_streamed_cpu_speedup"]) + assert wins==result["primary_lower_peak_cases"]==frozen["primary_lower_peak_cases"] + assert (median_ratio<=.8 and median_speed>=2. and wins>=48)==result[ + "primary_passed"] + for field,receipt_key in ( + ("primary_peak_ratio_vs_cached","block_bootstrap_95_stream_over_cached_python_peak_ratio"), + ("primary_native_speedup","block_bootstrap_95_native_over_streamed_cpu_speedup"), + ): + recomputed=bootstrap(rows,field) + original=result[ + "primary_memory_block_bootstrap" if field.startswith("primary_peak") + else "primary_speed_block_bootstrap"] + assert recomputed["draws"]==original["draws"]==4096 + for quant in ("percentile_2_5","percentile_97_5"): + assert eq_num(recomputed[quant],original[quant]) + assert eq_num(recomputed["percentile_2_5"],frozen[receipt_key][0]) + assert eq_num(recomputed["percentile_97_5"],frozen[receipt_key][1]) + summaries={"all":rows} + summaries.update({fam:[x for x in rows if x["family"]==fam] + for fam in ("late_source","signed","rational")}) + for name,group in summaries.items(): + summary=(result["summary_all"] if name=="all" else + result["summary_by_family"][name]) + assert summary["cases"]==len(group) + assert eq_num(summary["median_streamed_peak_vs_cached_ratio"], + median_from(group,lambda x:x["primary_peak_ratio_vs_cached"])) + assert eq_num(summary["median_native_over_primary_streamed_total_speedup"], + median_from(group,lambda x:x["primary_native_speedup"])) + assert summary["streamed_lower_peak_cases"]==sum( + x["primary_peak_ratio_vs_cached"]<1 for x in group) + for mode in MODES: + for key,src,scale in ( + ("median_complete_ms","mode_medians_ns",1e6), + ("median_verifier_ms","mode_medians_ns",1e6), + ("median_complete_peak_KiB","complete_tracemalloc",1024), + ("median_verifier_only_peak_KiB","verifier_only_tracemalloc",1024), + ): + if key=="median_complete_ms": + val=median_from(group,lambda x:x[src][mode]["total_ns"])/scale + elif key=="median_verifier_ms": + val=median_from(group,lambda x:x[src][mode]["verification_ns"])/scale + elif key=="median_complete_peak_KiB": + val=median_from(group,lambda x:x[src][mode][ + "python_peak_allocation_bytes"])/scale + else: + val=median_from(group,lambda x:x[src][mode][ + "python_verifier_only_peak_bytes"])/scale + assert eq_num(summary[key][mode],val) + if name=="all": + receipt_key={ + "median_complete_ms":"per_mode_median_complete_ms", + "median_verifier_ms":"per_mode_median_public_verification_ms", + "median_complete_peak_KiB":"per_mode_median_complete_tracemalloc_KiB", + "median_verifier_only_peak_KiB":"per_mode_median_verifier_only_tracemalloc_KiB"}[key] + assert eq_num(val,frozen[receipt_key][mode]) + assert summary["reciprocal_bigint_products"][mode]==sum( + entry["reciprocal_bigint_work"][mode]["R_integer_products"] + for entry in group) + for mode in MODES: + rss=result["isolated_process_RSS_KiB"][mode] + assert rss["mode"]==mode and rss["cases"]==64 + assert rss["separate_process"] + assert rss["peak_RSS_after_all_cases_KiB"]==frozen[ + "per_mode_separate_process_peak_RSS_KiB"][mode] + assert rss["baseline_peak_RSS_KiB"]==frozen[ + "per_mode_separate_process_baseline_RSS_KiB"][mode] + assert rss["additional_max_RSS_KiB"]>=0 + return { + "public_only_unused_source_cases_checked":64, + "exact_native_masks_and_output_unanimity_recomputed":64, + "first_hosted_timing_samples_recomputed":64*5*7, + "separate_memory_profiles_checked":64*5*2, + "reciprocal_bigint_work_profiles_replayed":64*5, + "bootstrap_resamples_recomputed":2*4096, + "primary_complete_streaming_peak_ratio":median_ratio, + "primary_native_to_streaming_speedup":median_speed, + "first_preregistered_primary_success":True, + } + + +def main(): + p=argparse.ArgumentParser() + input_group=p.add_mutually_exclusive_group() + input_group.add_argument("--archive",type=Path) + p.add_argument("--fixture",type=Path) + p.add_argument("--full",type=Path) + p.add_argument("--check",action="store_true") + args=p.parse_args() + frozen=receipt() + public_bytes=result_bytes=None + if args.archive: + with ZipFile(args.archive) as z: + assert sorted(z.namelist())==[ + "nor19_full.json","nor19_public_fixture.json"] + assert z.testzip() is None + public_bytes=z.read("nor19_public_fixture.json") + result_bytes=z.read("nor19_full.json") + elif args.fixture and args.full: + public_bytes=args.fixture.read_bytes() + result_bytes=args.full.read_bytes() + elif args.fixture or args.full: + p.error("requires both --fixture and --full") + else: + print("NOR19 ORIGINAL HOSTED FIRST-RESULT SOURCE RECEIPT VALID") + return + assert len(public_bytes)==frozen["original_fixture_bytes"] + assert len(result_bytes)==frozen["original_full_result_bytes"] + assert sha256(public_bytes).hexdigest()==FIXTURE_SHA + assert sha256(result_bytes).hexdigest()==FULL_SHA + result=audit(public_bytes,result_bytes,frozen) + print("NOR19 INDEPENDENT EXACT PUBLIC MASK / CPU / MEMORY AUDIT PASSED",result) + if args.check: + assert result["first_hosted_timing_samples_recomputed"]==2240 + assert result["first_preregistered_primary_success"] + + +if __name__=="__main__": + main() diff --git a/research/nor19_streamed_verifier/results/nor19_first_frozen_receipt.json b/research/nor19_streamed_verifier/results/nor19_first_frozen_receipt.json new file mode 100644 index 000000000..490e37300 --- /dev/null +++ b/research/nor19_streamed_verifier/results/nor19_first_frozen_receipt.json @@ -0,0 +1,113 @@ +{ + "schema": "nor19.frozen_first_hosted_streamed_memory_cpu_receipt.v1", + "execution_date": "2026-11-16", + "first_hosted_run": "https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43804264372", + "first_artifact_id": 14198011159, + "artifact_name": "nor19-new64-public-fixture-and-five-mode-cpu-memory-results", + "original_fixture_bytes": 1290607, + "original_fixture_sha256": "97fc9ccd3830bc666e6af6d0a86d3b000ef2b8d0a7a29a406ff38fbd08707f3f", + "original_full_result_bytes": 680861, + "original_full_result_sha256": "16d6ce9acb042aff76d48f46b7d07ff76a4efca1ade26314cdc52926eb0e1a16", + "source_original_NOR18_sha256": "9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b", + "source_RRC25_checkpoint_sha256": "54f225f2a61c52fee5a740576eaab3bcbc5280a595fc1ac1ac115ec8ac26c41b", + "host": "CPython 3.12.16, GCC 15.2.0, Linux 7.0.0-1019-azure x86_64, 4 logical CPUs", + "source_cases": 64, + "source_cohorts": 4, + "source_families": { + "late_source": 32, + "signed": 16, + "rational": 16 + }, + "excluded_original_NOR18R_source_indices": true, + "warmups_per_mode": 2, + "timed_repetitions_per_mode": 7, + "algorithms": [ + "independent16", + "cached16", + "stream16_queryfirst", + "stream16_verifyfirst", + "chunk4_verifyfirst" + ], + "primary": "stream16_verifyfirst", + "primary_median_complete_python_peak_ratio_stream_vs_cache": 0.4747144851523367, + "primary_lower_peak_cases": 64, + "primary_median_native_over_streamed_cpu_speedup": 4.33448367178092, + "primary_registered_memory_ratio_threshold": 0.8, + "primary_registered_memory_wins_threshold": 48, + "primary_registered_native_cpu_speedup_threshold": 2, + "primary_registered_pass": true, + "block_bootstrap_95_stream_over_cached_python_peak_ratio": [ + 0.4691818567189487, + 0.4883155173662138 + ], + "block_bootstrap_95_native_over_streamed_cpu_speedup": [ + 4.321700561218259, + 4.352961976758831 + ], + "bootstrap_draws": 4096, + "per_mode_median_complete_ms": { + "cached16": 4.239884, + "chunk4_verifyfirst": 4.059071, + "independent16": 19.420255, + "stream16_queryfirst": 4.2679905, + "stream16_verifyfirst": 4.2351955 + }, + "per_mode_median_public_verification_ms": { + "cached16": 2.2436975, + "chunk4_verifyfirst": 2.1001115, + "independent16": 17.19884, + "stream16_queryfirst": 2.2704875, + "stream16_verifyfirst": 2.2809185 + }, + "per_mode_median_complete_tracemalloc_KiB": { + "cached16": 119.43359375, + "chunk4_verifyfirst": 62.9921875, + "independent16": 67.134765625, + "stream16_queryfirst": 61.47265625, + "stream16_verifyfirst": 61.48828125 + }, + "per_mode_median_verifier_only_tracemalloc_KiB": { + "cached16": 72.98046875, + "chunk4_verifyfirst": 19.181640625, + "independent16": 16.88671875, + "stream16_queryfirst": 8.91796875, + "stream16_verifyfirst": 8.91796875 + }, + "total_observed_reciprocal_bigint_products": { + "cached16": 4476928, + "chunk4_verifyfirst": 4476928, + "independent16": 28192768, + "stream16_queryfirst": 4476928, + "stream16_verifyfirst": 4476928 + }, + "per_family_paired_cpu_speedup_native_over_primary": { + "late_source": 4.216325186916773, + "signed": 4.530794378959993, + "rational": 4.416034050901056 + }, + "per_family_paired_complete_peak_ratio_primary_over_cache": { + "late_source": 0.4673133661648893, + "signed": 0.5280373458238543, + "rational": 0.5213008158663146 + }, + "per_mode_separate_process_peak_RSS_KiB": { + "cached16": 28888, + "chunk4_verifyfirst": 28888, + "independent16": 28888, + "stream16_queryfirst": 28888, + "stream16_verifyfirst": 28888 + }, + "per_mode_separate_process_baseline_RSS_KiB": { + "cached16": 28888, + "chunk4_verifyfirst": 28888, + "independent16": 28888, + "stream16_queryfirst": 28888, + "stream16_verifyfirst": 28888 + }, + "semantics": { + "all_64_full_masks_and_certificates_identical_to_original": true, + "zero_hidden_program_or_future_in_fixture": true, + "query_simulation_computed_by_each_mode": true + }, + "scope": "First hosted CPU run, four frozen source cohorts from original NOR18 generator, but disjoint with NOR18R timing subset. Memory traced in separate untimed mode/case operations, not process RSS. 7 measured timing samples each. Cohort-bootstrap conditional on this one machine/source. Streaming holds four shared unary transforms per demonstration and does not materialize full demonstration candidate outputs. Bigint invocation counts arithmetic only; no universal cross-platform or theorem-prover claim." +} diff --git a/research/nor19_streamed_verifier/results/nor19_original_hosted.zip b/research/nor19_streamed_verifier/results/nor19_original_hosted.zip new file mode 100644 index 000000000..4749a4673 Binary files /dev/null and b/research/nor19_streamed_verifier/results/nor19_original_hosted.zip differ diff --git a/research/nor19_streamed_verifier/test_streamed.py b/research/nor19_streamed_verifier/test_streamed.py new file mode 100644 index 000000000..6b9291858 --- /dev/null +++ b/research/nor19_streamed_verifier/test_streamed.py @@ -0,0 +1,132 @@ +"""NOR-19 semantic, buffer and source-isolation tests. + +No benchmark timing result is exposed to the selection logic. +""" +from __future__ import annotations + +from collections import Counter +from dataclasses import replace +import random +import statistics +import unittest + +from research.nor19_streamed_verifier import benchmark as n +from research.rrc_compactification import compound25 as corpus + + +class NOR19StreamedCheckerTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + rng=random.Random(202611191916) + cls.examples=[] + for family in ("late_source","signed","rational","product","sparse","squared"): + for trial in range(200): + c=corpus.make_case(rng,family,f"nor19-unit-{family}-{trial}") + heads=corpus.possible_headers(c) + if len(heads)==1: + cls.examples.append((c,heads[0])) + break + else: + raise AssertionError("could not find uniquely identified source header") + assert len(cls.examples)==6 + + def test_all_five_exact_public_masks_and_certificates_match(self): + for case,h in self.examples: + ref=n.public_mask(case,h,"independent16") + self.assertGreater(ref,0) + for mode in n.SOURCE_MODELS: + self.assertEqual(n.public_mask(case,h,mode),ref) + receipt=n.complete(case,h,mode) + self.assertEqual(receipt["mask"],ref) + self.assertEqual(receipt["unanimous"], + n.complete(case,h,"cached16")["unanimous"]) + self.assertEqual(receipt["chosen_class"], + n.complete(case,h,"cached16")["chosen_class"]) + + def test_one_complete_candidate_matches_original_exact_interpreter(self): + for case,h in self.examples: + for source,observed in case.demos: + source=source[:corpus.OBSERVED+1] + unary={op:corpus.d.operate(source,op) for op in corpus.OPS} + for j in range(16): + expected=corpus.execute(source,n.old.nor17.program(h,j)) + got=n.build_one_candidate(h,unary,j) + self.assertEqual(got,expected) + with self.assertRaises(ValueError): + # Candidate source indexing is exact: no invented class. + n.public_mask(case,h,"unknown") + + def test_no_private_source_program_or_future_observed_by_any_mode(self): + for case,h in self.examples: + altered=replace(case,program=None, + future=tuple(17_000_001 for _ in case.future)) + for mode in n.SOURCE_MODELS: + self.assertEqual(n.complete(case,h,mode), + n.complete(altered,h,mode)) + self.assertEqual(n.SOURCES,64) + + def test_staged_timing_is_accounted_for_both_execution_orders(self): + case,h=self.examples[0] + for mode in n.SOURCE_MODELS: + z=n.complete(case,h,mode,measure=True) + values=z["times"] + self.assertEqual(values["total_ns"], + values["query_ns"]+values["verification_ns"]+ + values["certificate_ns"]) + self.assertGreater(values["verification_ns"],0) + self.assertGreater(values["query_ns"],0) + self.assertGreater(values["total_ns"],0) + + def test_streamed_and_chunked_peak_memory_measured_separately(self): + case,h=self.examples[0] + for mode in n.SOURCE_MODELS: + out=n.allocation_profile(case,h,mode) + ver=n.verifier_only_profile(case,h,mode) + self.assertEqual(out["mask"],ver["mask"]) + self.assertLessEqual(out["python_current_allocation_bytes"], + out["python_peak_allocation_bytes"]) + self.assertGreater(out["python_peak_allocation_bytes"],0) + self.assertGreater(ver["python_verifier_only_peak_bytes"],0) + + def test_bigint_operation_count_is_exact_for_streamed_cache(self): + for case,h in self.examples: + original=n.observed_bigint_work(case,h,"independent16") + cached=n.observed_bigint_work(case,h,"cached16") + self.assertEqual(n.inverse_invocations(h,"independent16"), + 8+16*int(h.base=="R")) + for mode in ("cached16","stream16_queryfirst", + "stream16_verifyfirst","chunk4_verifyfirst"): + self.assertEqual(n.observed_bigint_work(case,h,mode),cached) + self.assertEqual(n.inverse_invocations(h,mode),1) + self.assertGreater(original["R_integer_products"], + cached["R_integer_products"]) + self.assertGreater(original["R_operand_bitwidth_product_proxy"], + cached["R_operand_bitwidth_product_proxy"]) + + def test_source_selection_frozen_no_overlap(self): + indexes=[i for i in range(8,16)] + indexes+=list(range(52,56))+list(range(64,68)) + old=list(range(8))+list(range(48,52))+list(range(60,64)) + self.assertEqual(len(indexes),len(old)) + self.assertFalse(set(indexes)&set(old)) + self.assertEqual(n.TIMED_REPS,7) + self.assertEqual(n.WARMUPS,2) + self.assertEqual(n.PRIMARY_MEMORY_RATIO_MAX,.80) + self.assertEqual(n.PRIMARY_SPEEDUP_NATIVE_MIN,2.0) + self.assertEqual(n.PRIMARY_MEMORY_WINS_MIN,48) + + def test_four_cohort_block_bootstrap(self): + records=[{"cohort":i,"primary_peak_ratio_vs_cached":.5+.1*i, + "primary_native_speedup":3+i*.25} + for i in range(4) for _ in range(16)] + a=n.bootstrap_ratio(records,"primary_peak_ratio_vs_cached",draws=80) + b=n.bootstrap_ratio(records,"primary_native_speedup",draws=80) + for r in (a,b): + self.assertEqual(r["draws"],80) + self.assertLessEqual(r["percentile_2_5"],r["percentile_97_5"]) + self.assertEqual(len(n.SOURCE_MODELS),5) + self.assertEqual(n.BOOTSTRAP_DRAWS,4096) + + +if __name__=="__main__": + unittest.main()